Commas in Julia 1.0 Numbers of Any Kind - julia

I would like a function in Julia code, num2str, that would add commas or a specified delimiter, in the appropriate places on the left side of the decimal point for any kind of valid Julia number, including BigInt and BigFloat. It would return a string for printing.
For example:
flt1 = 122234.141567
println("flt1 num2str($flt1) = ", num2str(flt1))
# Expected output is:
flt1 num2str(122234.141567) = 122,234.141567
I want to use this function with the print and println built-in functions.

This question was partially answered here, i.e, for integers. The following function should answer the need for floats and "big" numbers.
"""
For any valid number, add appropriate delimiters.
See "Regular Expressions Cookbook," by Goyvaerts and Levithan, O'Reilly, 2nd Ed,
p. 402, for Regex that inserts commas into integers returning a string.
"""
function num2str(num::Number; delim=",")
decimal_point = "."
str = string(num)
strs = split(str, decimal_point)
left_str = strs[1]
right_str = length(strs) > 1 ? strs[2] : ""
left_str = replace(left_str, r"(?<=[0-9])(?=(?:[0-9]{3})+(?![0-9]))" => delim)
decimal_point = occursin(decimal_point, str) ? decimal_point : ""
return left_str * decimal_point * right_str
end
# Test integers, BigInts, floats, and BigFloats:
int0 = 0
int1 = 123
int2 = 123456789
big1 = big"123"
big2 = big"123456789123456789"
flt1 = 122234.141567
flt2 = 7.12345e9
big3 = big"260123.0"
big4 = big"7.12345e9"
setprecision(20)
println("int0 num2str($int0) \t\t\t\t = ", num2str(int0))
println("int1 num2str($int1) \t\t\t\t = ", num2str(int1))
println("int2 num2str($int2) \t\t\t = ", num2str(int2))
println("big1 num2str($big1) \t\t\t\t = ", num2str(big1))
println("big2 num2str($big2) \t\t = ", num2str(big2))
println("big2 num2str($big2) delim is _ \t = ", num2str(big2, delim="_"))
println("flt1 num2str($flt1) \t\t\t = ", num2str(flt1))
println("flt1 num2str($flt1) delim is _ \t\t = ", num2str(flt1, delim="_"))
println("flt2 num2str($flt2) \t\t\t = ", num2str(flt2))
println("big3 num2str($big3) \t\t\t = ", num2str(big3))
println("big4 num2str($big4) \t\t\t = ", num2str(big4))
println("big4 num2str($big4) delim is _ \t\t = ", num2str(big4, delim="_"))
## ============================== Output ===================================
int0 num2str(0) = 0
int1 num2str(123) = 123
int2 num2str(123456789) = 123,456,789
big1 num2str(123) = 123
big2 num2str(123456789123456789) = 123,456,789,123,456,789
big2 num2str(123456789123456789) delim is _ = 123_456_789_123_456_789
flt1 num2str(122234.141567) = 122,234.141567
flt1 num2str(122234.141567) delim is _ = 122_234.141567
flt2 num2str(7.12345e9) = 7.12345e9
big3 num2str(2.60123e+05) = 2.60123e+05
big4 num2str(7.12345e+09) = 7.12345e+09
big4 num2str(7.12345e+09) delim is _ = 7.12345e+09
I expect the ability to add comma delimiters will eventually be added to either print/println and/or #printf. Until then, this seems to work.

Related

azure kql parse function - unable to parse ? using regex (zero or one time)

I'm trying to parse this line:
01/11/1011 11:11:11: LOG SERVER = 1 URL = /one/one.aspx/ AccountId = 1111 MainId = 1111 UserAgent = Browser = Chrome , Version = 11.0, IsMobile = False, IP = 1.1.1.1 MESSAGE = sample message TRACE = 1
using this parse statement:
parse-where kind=regex flags=i message with
timestamp:datetime
":.*LOG SERVER = " log_server:string
".*URL = " url:string
".*AccountId = " account_id:string
".*MainId = " main_id:string
".*?UserAgent = " user_agent:string
",.*Version = " version:string
",.*IsMobile = " is_mobile:string
",.*IP = " ip:string
".*MESSAGE = " event:string
".*TRACE = " trace:string
now the thing is that sometimes I got records that has one "key=value" missing but the order of the rest of the columns remains the same.
to match all kinds of rows I just wanted to add (<name_of_colum>)? for example:
"(,.*Version = )?" version:string
but it fails everytime.
I think parse/parse-where operators are more useful when you have well formatted inputs - the potentially missing values in this case would make it tricky/impossible to use these operators.
If you control the formatting of the input strings, consider normalizing it to always include all fields and/or add delimiters and quotes where appropriate.
Otherwise, you could use the extract function to parse it - the following expression would work even if some lines are missing some fields:
| extend
timestamp = extract("(.*): .*", 1, message, typeof(datetime)),
log_server = extract(".*LOG SERVER = ([^\\s]*).*", 1, message),
url = extract(".*URL = ([^\\s]*).*", 1, message),
main_id = extract(".*MainId = ([^\\s]*).*", 1, message),
user_agent = extract(".*UserAgent = ([^,]*).*", 1, message),
version = extract(".*Version = ([^,]*).*", 1, message),
is_mobile = extract(".*IsMobile = ([^,]*).*", 1, message),
ip = extract(".*IP = ([^\\s]*).*", 1, message),
event = iff(message has "TRACE", extract(".*MESSAGE = (.*) TRACE.*", 1, message), extract(".*MESSAGE = (.*)", 1, message)),
trace = extract(".*TRACE = (.*)", 1, message)

How can I pass a line break through an API Patch or Post call in R to Microsoft Dataverse?

I am trying to populate a table in Microsoft Dataverse using an API Patch call through R. The field in Dataverse is a multiline text field with a limit of 4,000 characters, but using a Patch call I can't seem to get text to break across lines. I have other entries in the table that break across lines where they had been brought in by using Access as the front end, which I'm trying to not have to use.
### This is where I create the multiline text
MPC.Comments$Comment = paste(paste("Meeting Date: ", month(Sys.Date()), "/", year(Sys.Date()), sep = ""),
paste("Plan Cost: $", round(MPC.Comments$plantot, 0), sep = ""),
paste("%PC Remain: ", round((round(MPC.Comments$plantot, 0) - round(MPC.Comments$acttot, 0) - round(MPC.Comments$comsub, 0))/round(MPC.Comments$plantot, 0)*100,1), "%", sep = ""),
paste("Date Next PM Gate: ", MPC.Comments$eventdate, sep = ""),
paste("Est. Monthly Spend: $", MPC.Comments$esttot, sep = ""),
paste("Status Update: ", MPC.Comments$MPCStatus, sep = ""),
paste("Action Items: ", MPC.Comments$MPCAction, sep = ""),
sep = " <\\r\\n>")
### This is where I try to push it to the database
if (nrow(MPC.Comments) > 0) {
for (i in 1:nrow(MPC.Comments)) {
### Set POST parameters
MPC.Comments.Temp = list(
crfd0_projno = MPC.Comments$ProjNo[i],
crfd0_fyp = MPC.Comments$FYP[i],
crfd0_comment = MPC.Comments$Comment[i],
statuscode = 1)
POST("https://[REDACTED].crm4.dynamics.com/api/data/v9.2/crfd0_mpccommentses",
add_headers(Authorization = paste("Bearer", API.AuthKey, sep = " ")),
body = MPC.Comments.Temp,
encode = "json",
verbose())}}
No matter what special character I put in as my separator, it either comes through as nothing (if not escaped like \n) or as the physical string (if escaped like \\n). I have tried \n, \r\n, , <br>, and \u000a. Clearly there is a piece missing here that the data needs to be sent as something other than a string with a carriage return character. Does anyone know how to do this?

Passing tables as parameters in Nim

hopefully an easy question.. I've been playing around with Nim and have realised I need to pass a table (dictionary, map, in some other languages), but I can't seem to figure out the syntax for declaring it in doStuff()
import tables
proc doStuff(n:int, t:[int, int]) = # How should I declare 't' here?
if n == 0:
return
t[n] = (n * 10)
echo "length of t = " & ($len(t))
doStuff(n+1, t)
proc main() =
var tbl = initTable[int, int]()
echo "length of tbl = " & ($len(tbl))
tbl[0] = 0
doStuff(5, tbl)
echo "length of tbl = " & ($len(tbl))
main()
The above gets me Error: type expected, but got: [int, int]
Sorry if this is basic, but my Googling hasn't given me an answer yet
Many TIA
You almost got it, it should be like below:
import tables
proc doStuff(n: int, t: var Table[int, int]) =
if n == 0:
return
t[n] = n * 10
echo "length of t = " & $len(t)
doStuff(n + 1, t)
proc main() =
var tbl = initTable[int, int]()
echo "length of tbl = " & $len(tbl)
tbl[0] = 0
doStuff(5, tbl)
echo "length of tbl = " & $len(tbl)
main()
You have to use var Table[int, int] instead of Table[int, int] because you are mutating the tbl variable recursively, so you need to pass by reference instead of by value.

extract every element that meets a pattern in a string in R

I have a string, basically it's a SQL statement. I want to extract some part of it.
Here is the code
SELECT
DTE as "Date",
CURRENT_DATE AS "Day",
concat( BCCO, BCBCH ) AS "client/batch",
BCSTAT as "Batch Status",
CASE
WHEN EXC = 'MCR' THEN CNT
ELSE 0
END AS "MCR-NPR",
CASE
WHEN EXC = 'NRC' THEN CNT
ELSE 0
END AS "NRC-NPR",
CASE
WHEN EXC = 'OFD' THEN CNT
ELSE 0
END AS "OFD-NPR",
CASE
WHEN EXC = 'TDB' THEN CNT
ELSE 0
END AS "TDB-NPR",
CASE
WHEN EXC = 'TDC' THEN CNT
ELSE 0
END AS "TDC-NPR",
CASE
WHEN EXC = 'UDC' THEN CNT
ELSE 0
END AS "UDC-NPR",
CASE
WHEN EXC = 'BIN' THEN CNT
ELSE 0
END AS "BIN-WRN",
CASE
WHEN EXC = 'DSP' THEN CNT
ELSE 0
END AS "DSP-WRN",
I want to extract every element between END AS and the quote. A vector like ("MCR-NPR",...,"DSP-WRN") will be the desire output.
I know I may need to use regular expression, but I couldn't extract every one of them.
Any idea will be appreciated.
Best,
1) grep/read.table grep out lines with END AS and use read.table with a sep of double quote to read those. The second column will be the desired data. No regular expressions or packages are used.
read.table(text = grep("END AS", s, value = TRUE, fixed = TRUE),
sep = '"', as.is = TRUE)[[2]]
## [1] "MCR-NPR" "NRC-NPR" "OFD-NPR" "TDB-NPR" "TDC-NPR" "UDC-NPR" "BIN-WRN"
## [8] "DSP-WRN"
1a) This is similar to (1) but uses sub with a regular expression instead of read.table:
sub('.*END AS "(.+)".*', "\\1", grep("END AS", s, value = TRUE))
## [1] "MCR-NPR" "NRC-NPR" "OFD-NPR" "TDB-NPR" "TDC-NPR" "UDC-NPR" "BIN-WRN"
## [8] "DSP-WRN"
2) strapply Another approach is the following. It makes use of the fact that the desired strings follow END AS and are surrounded with double quotes It has the shortest code of the ones shown here.
library(gsubfn)
unlist(strapplyc(s, 'END AS "(.+)"'))
## [1] "MCR-NPR" "NRC-NPR" "OFD-NPR" "TDB-NPR" "TDC-NPR" "UDC-NPR" "BIN-WRN"
## [8] "DSP-WRN"
3) strcapture Another base R approach using the same pattern as in (2) is:
na.omit(strcapture('END AS "(.+)"', s, list(value = character(0))))
giving:
value
9 MCR-NPR
13 NRC-NPR
17 OFD-NPR
21 TDB-NPR
25 TDC-NPR
29 UDC-NPR
33 BIN-WRN
37 DSP-WRN
Note
The input s in reproducible form:
s <-
c("SELECT ", " DTE as \"Date\",", " CURRENT_DATE AS \"Day\",",
" concat( BCCO, BCBCH ) AS \"client/batch\",", " BCSTAT as \"Batch Status\",",
" CASE ", " WHEN EXC = 'MCR' THEN CNT ", " ELSE 0 ", " END AS \"MCR-NPR\",",
" CASE ", " WHEN EXC = 'NRC' THEN CNT ", " ELSE 0 ", " END AS \"NRC-NPR\",",
" CASE ", " WHEN EXC = 'OFD' THEN CNT ", " ELSE 0 ", " END AS \"OFD-NPR\",",
" CASE ", " WHEN EXC = 'TDB' THEN CNT ", " ELSE 0 ", " END AS \"TDB-NPR\",",
" CASE ", " WHEN EXC = 'TDC' THEN CNT ", " ELSE 0 ", " END AS \"TDC-NPR\",",
" CASE ", " WHEN EXC = 'UDC' THEN CNT ", " ELSE 0 ", " END AS \"UDC-NPR\",",
" CASE ", " WHEN EXC = 'BIN' THEN CNT ", " ELSE 0 ", " END AS \"BIN-WRN\",",
" CASE ", " WHEN EXC = 'DSP' THEN CNT ", " ELSE 0 ", " END AS \"DSP-WRN\"")

Need help assigning parameters to my definitions

My code works if I comment out my definitions but I need it to work with the definitions. I don't know which parameters I should assign to them to make the code work properly.
#def main():
phrase = input("Enter a phrase: ")
count = {}
print("Number of characters: ",len(phrase))
#def wordCount():
words = phrase.split()
wordCount = len(words)
print("Number of words: ",wordCount)
#def average():
avg = len(phrase)/wordCount
print("The average word length: %.01f" % avg)
#def freqWords():
freqLetter = phrase[0]
max = phrase.count(phrase[0])
for char in phrase:
if char is not " ":
if phrase.count(char) > max:
freqLetter = char
max = phrase.count(char)
print("The most frequent letter: ", freqLetter)
#main()
You can either make phrase, count, etc. as global variable or make them parameters in this case, here is how to do with passing parameters:
def main():
phrase = input("Enter a phrase: ")
print("Number of characters: ",len(phrase))
count = wordCount(phrase)
average(phrase,count)
freqWords(phrase)
def wordCount(phrase):
words = phrase.split()
wordCount = len(words)
print("Number of words: ",wordCount)
return wordCount
def average(phrase, wordCount):
avg = len(phrase)/wordCount
print("The average word length: %.01f" % avg)
def freqWords(phrase):
freqLetter = phrase[0]
max = phrase.count(phrase[0])
for char in phrase:
if char is not " ":
if phrase.count(char) > max:
freqLetter = char
max = phrase.count(char)
print("The most frequent letter: ", freqLetter)
main()

Resources