Create an alert for when a cosmosdb partition key exceeds 80% using terraform and alerts should be sent to actions groups - azure-devops

Create an alert for when a cosmosdb partition key exceeds 80% using terraform and
Alerts for some environment should be sent using existing action groups (level 0 / 1), lower environments 2+
created this code not sure to use which can somebody guide me which is the right code to use
# Example: Alerting Action with result count trigger
resource "azurerm_monitor_scheduled_query_rules_alert" "example" {
name = format("%s-queryrule", var.prefix)
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
action {
action_group = []
email_subject = "Email Header"
custom_webhook_payload = "{}"
}
data_source_id = azurerm_application_insights.example.id
description = "Alert when total results cross threshold"
enabled = true
# Count all requests with server error result code grouped into 5-minute bins
query = <<-QUERY
requests
| where tolong(resultCode) >= 500
| summarize count() by bin(timestamp, 5m)
QUERY
severity = 1
frequency = 5
time_window = 30
trigger {
operator = "GreaterThan"
threshold = 3
}
}

Related

How to create a Confluence user macro that divides the size of 2 Jira filters

What I tried was:
## Macro title: totalBugs
## Macro has a body: Y
## Body processing: Rendered
## Output: Rendered
##
## Developed by: Margus Martsepp
## Date created: 06/02/2023
## Installed by: Margus Martsepp
## #param Search1:title=Search1|type=string|required=true|desc=Choose search 1
## #param Search2:title=Search2|type=string|required=true|desc=Choose search 2
#set($jiraUrl = "https://.../")
#set($proxyHost = "http://...")
#set($proxyPort = "8080")
#set($action = $helper.getActionContext())
#set($jira = $action.getApplicationContext().getComponent("jira"))
#if($jira)
#error("Jira variable is not initialized, check if the Jira plugin is properly installed and configured")
#end
#set($result1 = $jira.search($paramSearch1, $jiraUrl, $proxyHost, $proxyPort))
#set($result2 = $jira.search($paramSearch2, $jiraUrl, $proxyHost, $proxyPort))
#if($result1)
#error("Search 1 has returned no results, check the query and connection details")
#end
#if($result2)
#error("Search 2 has returned no results, check the query and connection details")
#end
#if($result1.total == 0)
#error("Search 1 has returned no results, division by zero is not possible")
#end
#if($result2.total == 0)
#error("Search 2 has returned no results, division by zero is not possible")
#end
#set($count1 = $result1.total)
#set($count2 = $result2.total)
#if($count2 == 0)
#error("Search 2 has returned no results, division by zero is not possible")
#end
#set($result = $count1 / $count2 * 100)
#set($output = "Result of dividing search 1 count ($count1) by search 2 count ($count2) is: $result")
$output
Similarly to this I tried getIssuesFromJqlSearch ex:$jira.getIssuesFromJqlSearch($paramSearch1, 1000))
but in both cases this yielded to:
Result of dividing search 1 count ($count1) by search 2 count ($count2) is: $result
Is there something that I forgot to configure for the JIRA service or is the API used in a different way?

cur.execute() psycopg2.ProgrammingError: can't call .execute() on named cursors more than once

I'm trying to get this code to run but I get this error above. Can someone please help? I've tried reading about this in other posts but I don't really know how to apply it here. I'm trying to iterate over lines of this database and select 1400 random ones. It blocks on the error above.
def paragraph_generator(test=True, itersize=5000, year=None, state=None):
con, cur = database_connection.connect(cursor_type="server")
cur.itersize = itersize
while True:
sql = f"""
SELECT
text_id,
lccn_sn,
date,
ed,
seq,
chroniclingamerica_meta.statefp,
chroniclingamerica_meta.countyfp,
text_ocr
FROM
chroniclingamerica natural join chroniclingamerica_meta
WHERE date_part('year',date) BETWEEN 1860 AND 1920
ORDER BY RANDOM()
LIMIT 1400
"""
if test:
sql = (
sql + " limit 10000"
) # limit 1000 means it only goes through 1000 lines of the database
else:
pass
print(sql)
cur.execute(sql)
for p in cur.fetchall():
tokens = stem_text(p[-1]) # Stem
# print(tokens)
tokens = (
p[-1]
.translate(str.maketrans("", "", punct))
.replace("\n", " ")
.lower()
.split(" ")
)
tokens_3 = [
a for a in tokens if len(a) == 3 if a in wn_lemmas
] # For 3-letter words, only keep WordNet recognized tokens
tokens = gensim.parsing.preprocessing.remove_short_tokens(
tokens, minsize=4
) # Remove 1-, 2-, and 3-letter words
tokens = tokens + tokens_3 # Add back in 3-letter WordNet-recognized tokens
tokens = gensim.parsing.preprocessing.remove_stopword_tokens(
tokens, stopwords=stop_words
) # Remove stopwords in stopword list above
print("THIS IS THE LENGTH OF TOKENS")
a = len(tokens)
print(a)
if len(tokens) != 0:
ocr_2 = 1 - (
len([a for a in tokens if a in wn_lemmas]) / len(tokens)
) # Generate a measure for proportion of OCR errors in a page
else:
ocr_2 = float("nan")
print("THIS IS OCR")
print(ocr_2)
ocr = ocr_2
if ocr < 0.75 and ~np.isnan(
ocr
): # If the % of OCR in a page is less than 75%, then keep the page and all tokens
tokens = tokens
else:
tokens = [] # Otherwise, give it an empty list (i.e. drop the page)
yield tokens
con.close()
Error:
cur.execute(sql)
psycopg2.ProgrammingError: can't call .execute() on named cursors more than once

What default id should I use such that all the ids in my collection are greater than this id?

I intend to fetch 100 ids at once in a sorted manner.
I find the ids greater than skip where skip can be set to a default value at the beginning. I need to sort the ids generated in the find() and the limit set is 100.
So, my query is:
db['Organization'].find({"_id":{"$gt":ObjectId(skip)}},{"_id":1}).sort([("_id",1)]).limit(100)
As of now, I have set skip to str(0). I intend to update it with the last id fetched in the iteration.
The complete endpoint is:
#hug.get('/organization/collect_pricing')
def get_organizations():
start_time = datetime.strptime('2016-11-01', '%Y-%m-%d')
org_ids = []
org_pricing_plans = []
counter = 0
skip = str(0)
result_check = True
pricing_response = []
ob_toolbox = Toolbox()
while(result_check is True):
print(counter)
try:
if
organizations = db['Organization'].find({"_id":{"$gt":ObjectId(skip)}},{"_id":1}).sort([("_id",1)]).limit(100)
except Exception as e:
print(e)
if organizations.count(True) == 0:
result_check = False
continue
counter += 100
for org in organizations:
org_ids.append("Organization$"+org["_id"])
try:
pricing_plans = ob_toolbox.bulk_fetch(collection="PricingPlan", identifier="_p_organization", ids=org_ids)
except Exception as e:
print(e)
currDict = {}
for i in range(0, organizations.count(True)):
currDict["id"] = org_ids[i]
currDict["expiresAt"] = pricing_plans[i]["expiresAt"]
currDict["resources"] = pricing_plans[i]["resources"]
currDict["_created_at"] = pricing_plans[i]["_created_at"]
org_pricing_plans.append(currDict)
print(currDict["id"])
skip = currDict["id"]
if organizations.count(True) < 100:
result_check = False
return (org_pricing_plans)
If you want the default "minimal" value, then null object id is better. It's the same type (ObjectId) and will sort lowest.
ObjectId('000000000000000000000000')
Alternatively, you could branch when doing a query. Is it first query? If yes, don't include the skip part. If no, use last id from previous results.

Summary table using Coffeescript?

I've programmed a summary chart, and I'm trying to add a "Totals" line that will sum up three columns. The exercise is comprised of a number of questions, and the participant can increase, decrease or maintain a certain dollar amount. The column B total shows the initial values (where the slider starts off on). The column C shows the amount the participant either increased or decreased and the last column shows the resulting dollar amount. (B + C)
Here's an example of the summary chart
Column A --- B ------ C------ D
Question 1 | 100$ | +28$ | 128$ |
Question 2 | 150$ | (10$) | 140$ |
Totals ------| 250$ | +18$ | 268$ |
So far I've been able to program the totals for column B and D, but I can't figure out how to show a total for column C.
class window.CustomSimulator extends window.TaxSimulator
constructor: (#options = {}) ->
super
#updateTable()
update: ->
super
#updateTable()
updateTable: ->
self = this
$table = $('<table class="table table-condensed"><thead><tr><th>Category</th><th>Before</th><th>Your Choice</th><th>After</th></tr></table>')
$tbody = $('<tbody></tbody>')
before_total = 0
after_total = 0
#scope.find('.slider').each ->
$this = $(this)
$parents = $this.parents('tr')
category = $parents.find('.header').clone().children().remove().end().text().replace(/How would you adjust service levels and property tax funding for /, '').replace('?', '')
before = self.tipScaler($this, $this.data('initial'))
your_choice = $parents.find('.value').text()
after = $parents.find('.tip-content').text()
if $parents.find('.key').text() == 'Decrease:'
css_class = 'decrease'
your_choice = "(#{your_choice})"
else
css_class = 'increase'
$tr = $("""<tr><td>#{category}</td><td>#{before}</td><td class="table-#{css_class}">#{your_choice}</td><td>#{after}</td></tr>""")
$tbody.append($tr)
before_total += parseFloat(before.replace('$', ''))
after_total += parseFloat(after.replace('$', ''))
before_total = SimulatorHelper.number_to_currency(before_total, precision: 2, strip_insignificant_zeros: true)
after_total = SimulatorHelper.number_to_currency(after_total, precision: 2, strip_insignificant_zeros: true)
$("""<tfoot><tr><th>Totals</th><th>#{before_total}</th></th><th><th>#{after_total}</th></tr></tfoot>""").appendTo($table)
$table.append($tbody)
$('#summary-table').html($table)
I'm pretty new at this so I'm not sure if this is enough information.
Thanks!

Converting classic ASP ADODB script to TSQL

Hi i inherited a load of old classic ASP code that makes some updates to some tables in what i think was old MS access db.
The databases have now been converted to SQL and work OK, however i have a need to convert some old ASP code to the equivalent TSQL. TSQL is NOT my strong point and would appreciate some help converting the vb script to the equivalent TSQL for a stored procedure called 'UpdateCircuitOrdersComments' its not the basic syntax i'm struggling with, its more what can be done IE FOR's IF's Cases, loops etc in order to achieve the below in sql.
I know the code below is not great or could be done far better, but that's what i inherited sorry.
Every field is available to me via c# parameters passed to the sproc using ajax apart from the "Contract Period"
Looking forward to learning from any sound advice from you guys...
The script is below:
Dim connect2, Class2, Query2, Counter
Dim indate1, indate2, indate3, aday1, amonth1, ayear1, aday2, amonth2, ayear2, aday3, amonth3, ayear3, length, maintrate, equiprate, stqrrate, startserial, liveserial, endserial
Dim splitArray
Set Connect = Server.CreateObject("ADODB.Connection")
Connect.Open QuotebaseDB
Set Class1 = Server.CreateObject("ADODB.Recordset")
Query = "SELECT * FROM circuits WHERE ID=" & Request("ID")
Class1.Open Query,Connect,adOpenDynamic,adLockOptimistic
if Class1("Contract Period") <> "" Then
length = Class1("Contract Period")
splitArray = split(length, " ")
length = CInt(splitArray(0))
else
length = 1
end if
Class1("actual live date") = Request("actuallivedate")
Class1("lastupdater") = Session("username")
Class1("lastupdate") = Date()
Class1("Contract Period") = length
Class1.Update
'=========================================
' Add Rate Information - Based On Actuals
'=========================================
indate1 = Request("actuallivedate")
indate2 = Request("actuallivedate")
indate3 = Request("actuallivedate")
aday1 = Left(indate1, 2)
amonth1 = Mid(indate1, 4, 2)
ayear1 = Right(indate1, 2)
aday2 = Left(indate2, 2)
amonth2 = Mid(indate2, 4, 2)
ayear2 = Right(indate2, 2)
aday3 = Left(indate3, 2)
amonth3 = Mid(indate3, 4, 2)
ayear3 = Right(indate3, 2) + length
startserial = dateserial(ayear1, amonth1, aday1)
liveserial = dateserial(ayear2, amonth2, aday2)
endserial = dateserial(ayear3, amonth3, aday3)
'========================================================
' Check that current maintenance rate will be superseded
'========================================================
Dim MaintConnect1, MaintRS1, MaintQuery1
Set MaintConnect1 = Server.CreateObject("ADODB.Connection")
MaintConnect1.Open QuotebaseDB
Set MaintRS1 = Server.CreateObject("ADODB.Recordset")
MaintQuery1 = "SELECT * FROM maintenancetable WHERE CircuitID=" & Request("ID")
MaintRS1.Open MaintQuery1,MaintConnect1,adOpenDynamic,adLockOptimistic
Do while not MaintRS1.eof
If (MaintRS1("startdate") < startserial) OR (MaintRS1("enddate") > endserial) Then
MaintRS1("startdate") = StartSerial
MaintRS1("enddate") = EndSerial
MaintRS1("circuitnum") = Class1("circuit number")
MaintRS1("modifieddate") = now
MaintRS1.Update
End If
MaintRS1.movenext
Loop
MaintRS1.close
set MaintRS1 = nothing
MaintConnect1.close
set MaintConnect1 = nothing
'========================================================
' Check that current equipment rate will be superseded
'========================================================
Dim EquipConnect1, EquipRS1, EquipQuery1
Set EquipConnect1 = Server.CreateObject("ADODB.Connection")
EquipConnect1.Open QuotebaseDB
Set EquipRS1 = Server.CreateObject("ADODB.Recordset")
EquipQuery1 = "SELECT * FROM [equipment table] WHERE CircuitID=" & Request("ID")
EquipRS1.Open EquipQuery1,EquipConnect1,adOpenDynamic,adLockOptimistic
Do while not EquipRS1.eof
If (EquipRS1("startdate") < startserial) OR (EquipRS1("enddate") > endserial) Then
EquipRS1("startdate") = StartSerial
EquipRS1("enddate") = EndSerial
EquipRS1("circuitnum") = Class1("circuit number")
EquipRS1("modifieddate") = now
EquipRS1.Update
End If
EquipRS1.movenext
Loop
EquipRS1.close
set EquipRS1 = nothing
EquipConnect1.close
set EquipConnect1 = nothing
'========================================================
' Check that current rental rate will be superseded
'========================================================
Dim STQRConnect1, STQRRS1, STQRQuery1
Set STQRConnect1 = Server.CreateObject("ADODB.Connection")
STQRConnect1.Open QuotebaseDB
Set STQRRS1 = Server.CreateObject("ADODB.Recordset")
STQRQuery1 = "SELECT * FROM STQRtable WHERE CircuitID=" & Request("ID")
STQRRS1.Open STQRQuery1,STQRConnect1,adOpenDynamic,adLockOptimistic
Do while not STQRRS1.eof
If (STQRRS1("startdate") < startserial) OR (STQRRS1("enddate") > endserial) Then
STQRRS1("startdate") = StartSerial
STQRRS1("enddate") = EndSerial
STQRRS1("circuitnum") = Class1("circuit number")
STQRRS1("modifieddate") = now
STQRRS1.Update
End If
STQRRS1.movenext
Loop
STQRRS1.close
set STQRRS1 = nothing
STQRConnect1.close
set STQRConnect1 = nothing
'===========================================
' Update Connection Charge As A One Off Charge
'===========================================
Dim OneConnect, OneRS, OneQuery
Set OneConnect = Server.CreateObject("ADODB.Connection")
OneConnect.Open QuotebaseDB
Set OneRS = Server.CreateObject("ADODB.Recordset")
OneQuery = "SELECT * FROM OneOffCharges WHERE chargetype = 'Connection Charge' and CircuitID=" & Request("ID")
OneRS.Open OneQuery,OneConnect,adOpenDynamic,adLockOptimistic
If not oners.eof Then
OneRS("chargedate") = startserial
OneRS("modifieddate") = now
OneRS("chargetype") = "Connection Charge"
OneRS.Update
End If
OneRS.close
set OneRS = nothing
OneConnect.close
set OneConnect = nothing
Class1.close
set Class1 = nothing
Connect.close
set Connect = nothing
The loops don't appear to do much other then iterate over the record set. It is unlikely that you will need to do this in T-SQL as you can probably deduce everything from queries.
Most of it just looks like update statements
-- Check that current maintenance rate will be superseded
UPDATE maintenancetable
SET StartDate = #startSerial,
EndDate = #endSerial,
CircuitNum = #circuitNumber,
ModifiedDate = CURRENT_TIMESTAMP
WHERE CircuitID=#circuitId
AND (Startdate < #startSerial OR EndDate > #endSerial)
The contract period is a bit confusing it seems to be getting the first item of an array so maybe this is the equivalent of
SELECT TOP 1 ContractPeriod FROM circuits WHERE ID=#id
-- ? ORDER BY ContractPeriod ?