Math.js expression syntax - math.js

How do you enter a power root in Math.js' expression syntax? In AsciiMath I can enter "-root(3)(x+4)-4". How can I get the same result in the expression syntax of Math.js?
enter image description here

I will attempt to write a live code to answer the question. And it is
-nthRoot(x+4,3)-4
as commented by #Luuk.
// Use this function to show values of matrix and etc.
function print (value) {
const precision = 14
console.log(math.format(value, precision))
}
print("Start MathJS test.")
//print(math.round(math.e, 3)) // 2.718
let x = 23
print( -math.nthRoot(x+4,3) -4 ) // -7
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/11.3.1/math.js"></script>

Related

Currency formate REGEXP, change symbol

I am working with HighChart and I need to format a currency value in a specific format.
Example -> XX.XXX.XXX, XX €
I am using this function in highchart to format the value correctly:
formatter: function () {
return parseFloat (this.total, 10) .toFixed (2) .replace (/ (\ d) (? = (\ d {3}) + \.) / g, '$ 1,'). toString () + ' € ';
}
The problem is that I am not getting the points and commas to match as I intend.
Example for values:
Given -> 1052325
Expected -> 10.523,25 €
Current value obtained -> 10,523.25
I could do a new replace() and change the commas for the points, but I would like to know how to do it right away at REGEXP.
Thank you very much
Ok. I cant use some of the functions in HighChart.
I try this code in the ppotaczek example
Highcharts.chart('container', {
series: [{
data: [1052325],
dataLabels: {
enabled: true,
formatter: function() {
var originalString = parseFloat(this.y, 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$ 1,').toString();
var finalPriceString = originalString.split('');
var finalPriceStringLenght = finalPriceString.length;
var rowtoChange = finalPriceStringLenght - 3;
finalPriceString[rowtoChange] = 'I';
var lastString = finalPriceString.join('') + ' €';
alert(lastString);
}
}
}]
});
The code works in the Fiddle example, but it doesn't work when I put it in the Highchart Json.
I tried another approach now, I always have this string format so I just want to replace the third character from the end of the string.
For this I am using this replace with regexp:
stringFormated.replace(/.$/,',');
It works and replaces well. The problem is that it is always at the last character of the string. I wanted it to go to the third character after the end of the string.
Best regards

How to get float number in Lua from IUP text entry

I am trying following simple code to get a decimal value from user:
require( "iuplua" )
t1 = iup.text{expand = "YES", padding = "10x10", alignment="ARIGHT", size="40x"}
btn = iup.button {title = "Print:", padding = "10x10", alignment="ACENTER", size="40x"}
qbtn = iup.button{title="Quit", expand = "YES", padding = "10x10", alignment="ACENTER", size="40x"}
function btn:action()
strval1 = string.match (t1.value, "%d+")
print (strval1)
num = tonumber(strval1)
print (num)
end
function qbtn:action()
os.exit()
end
dlg = iup.dialog {
iup.vbox{
iup.hbox{
iup.label{title="Decimal:", padding = "10x10", alignment="ALEFT", size="40x"},
t1 },
iup.hbox{
btn,
qbtn }}}
dlg:show()
iup.MainLoop()
However, it prints out only an integer number (part before decimal- even 25.9999 prints as 25).
How can I get float or decimal value entered by user? Thanks for your help.
The problem with the code is that the pattern "%d+" in btn:action only gets the first run of digits.
You can change the pattern to handle decimal points, but it is hard to write a pattern that works in all cases, including optional sign and decimal point and scientific format.
It is best to let tonumber do its work: it will return nil if the string cannot be converted to a number.
Another option is to use the MASK attribute of the IupText to let the user only be able to enter numbers.

Lua, Modify print function

I am writing a generic Log() function in lua which utilizes lua print function:
Log (variable, 'String: %s ', str, 'Word: %d', w)
Currently I'm using below approach:
print(string.format (variable, 'String: %s ', str, 'Word: %d', w))
I tried something like:
Log = function(...) begin
return print(string.format(...))
end
But it doesn't work, Is this correct approach? Or Is there any better more generic way to get this done?
If you just want to print a sequence of values, you can do that with print:
print(variable, 'String: %s ', str, 'Word: %d', w)
What you seem to want is something more complicated. Your algorithm seems to be:
For each argument:
If the argument is not a string, then convert it to a string and print it.
If the argument is a string, figure out how many % patterns it has (let us call this number k). Pass string.format the current argument string and the following k parameters, printing the resulting string. Advance k parameters.
That's a much more complicated algorithm than can be done in a one-line system.
Using Lua 5.3, here's what such a function would look like (note: barely tested code):
function Log(...)
local values = {}
local params = table.pack(...)
local curr_ix = 1
while (curr_ix <= params.n) do
local value = params[curr_ix]
if(type(value) == "string") then
--Count the number of `%` characters, *except* for
--sequential `%%`.
local num_formats = 0
for _ in value:gmatch("%%[^%%]") do
num_formats = num_formats + 1
end
value = string.format(table.unpack(params, curr_ix, num_formats + curr_ix))
curr_ix = curr_ix + num_formats
end
values[#values + 1] = value
curr_ix = curr_ix + 1
end
print(table.unpack(values))
end
I don't think your current approach works, because the first argument of string.format expects the format specifier, not the rest of the arguments.
Anyway, this is the way to combine formatting and printing together:
Log = function(...)
return print(string.format(...))
end
And call it like this:
Log("String: %s Number: %d", 'hello' , 42)
Also, it might be better to make the format specifier argument more explicit, and use io.write instead of print to get more control over printing:
function Log(fmt, ...)
return io.write(string.format(fmt, ...))
end

readString is throwing TypeError: malformed UTF-8

This function returns a ctypes.unsigned_char.array() and I do read string on it. It is getting the titles of windows. The problem is sometimes it throws TypeError.
try {
console.error('straight readString on XWindowGetProperty data:', rez_GP.data.readString());
} catch (ex) {
console.error('ex on straight readString:', ex);
}
Please notice the rez_GP.data.readString()
For example this instance: TypeError: malformed UTF-8 character sequence at offset 48. In this situation the window title is Editing js-macosx/bootstrap.js at base-template · Noitidart/js-macosx - Mozilla Firefox The 48th offset is that dot chracter you see, it's chracter code is 183. How to do readString() on this buffer without getting this error?
Thanks
readString expects a utf-8 encoded string. This is true for strings returned by _NET_WM_NAME, but not for WM_NAME.
I found a way to read the string propertly even ifs not utf-8, but im not sure if its he best way or the recommended way. This works though, i have to cast it to unsigned_char (must be this, so not char or jschar) then do fromCharCode:
function readAsChar8ThenAsChar16(stringPtr, known_len, jschar) {
// when reading as jschar it assumes max length of 500
// stringPtr is either char or jschar, if you know its jschar for sure, pass 2nd arg as true
// if known_len is passed, then assumption is not made, at the known_len position in array we will see a null char
// i tried getting known_len from stringPtr but its not possible, it has be known, i tried this:
//"stringPtr.contents.toString()" "95"
//"stringPtr.toString()" "ctypes.unsigned_char.ptr(ctypes.UInt64("0x7f73d5c87650"))"
// so as we see neither of these is 77, this is for the example of "_scratchpad/EnTeHandle.js at master · Noitidart/_scratchpad - Mozilla Firefox"
// tries to do read string on stringPtr, if it fails then it falls to read as jschar
var readJSCharString = function() {
var assumption_max_len = known_len ? known_len : 500;
var ptrAsArr = ctypes.cast(stringPtr, ctypes.unsigned_char.array(assumption_max_len).ptr).contents; // MUST cast to unsigned char (not ctypes.jschar, or ctypes.char) as otherwise i dont get foreign characters, as they are got as negative values, and i should read till i find a 0 which is null terminator which will have unsigned_char code of 0 // can test this by reading a string like this: "_scratchpad/EnTeHandle.js at master · Noitidart/_scratchpad - Mozilla Firefox" at js array position 36 (so 37 if count from 1), we see 183, and at 77 we see char code of 0 IF casted to unsigned_char, if casted to char we see -73 at pos 36 but pos 77 still 0, if casted to jschar we see chineese characters in all spots expect spaces even null terminator is a chineese character
console.info('ptrAsArr.length:', ptrAsArr.length);
//console.log('debug-msg :: dataCasted:', dataCasted, uneval(dataCasted), dataCasted.toString());
var charCode = [];
var fromCharCode = []
for (var i=0; i<ptrAsArr.length; i++) { //if known_len is correct, then will not hit null terminator so like in example of "_scratchpad/EnTeHandle.js at master · Noitidart/_scratchpad - Mozilla Firefox" if you pass length of 77, then null term will not get hit by this loop as null term is at pos 77 and we go till `< known_len`
var thisUnsignedCharCode = ptrAsArr.addressOfElement(i).contents;
if (thisUnsignedCharCode == 0) {
// reached null terminator, break
console.log('reached null terminator, at pos: ', i);
break;
}
charCode.push(thisUnsignedCharCode);
fromCharCode.push(String.fromCharCode(thisUnsignedCharCode));
}
console.info('charCode:', charCode);
console.info('fromCharCode:', fromCharCode);
var char16_val = fromCharCode.join('');
console.info('char16_val:', char16_val);
return char16_val;
}
if (!jschar) {
try {
var char8_val = stringPtr.readString();
console.info('stringPtr.readString():', char8_val);
return char8_val;
} catch (ex if ex.message.indexOf('malformed UTF-8 character sequence at offset ') == 0) {
console.warn('ex of offset utf8 read error when trying to do readString so using alternative method, ex:', ex);
return readJSCharString();
}
} else {
return readJSCharString();
}
}

Printing the same character several times without a loop

I would like to "beautify" the output of one of my Dart scripts, like so:
-----------------------------------------
OpenPGP signing notes from key `CD42FF00`
-----------------------------------------
<Paragraph>
And I wonder if there is a particularly simple and/or optimized way of printing the same character x times in Dart. In Python, print "-" * x would print the "-" character x times.
Learning from this answer, for the purpose of this question, I wrote the following minimal code, which makes use of the core Iterable class:
main() {
// Obtained with '-'.codeUnitAt(0)
const int FILLER_CHAR = 45;
String headerTxt;
Iterable headerBox;
headerTxt = 'OpenPGP signing notes from key `CD42FF00`';
headerBox = new Iterable.generate(headerTxt.length, (e) => FILLER_CHAR);
print(new String.fromCharCodes(headerBox));
print(headerTxt);
print(new String.fromCharCodes(headerBox));
// ...
}
This gives the expected output, but is there a better way in Dart to print a character (or string) x times? In my example, I want to print the "-" character headerTxt.length times.
The original answer is from 2014, so there must have been some updates to the Dart language: a simple string multiplied by an int works.
main() {
String title = 'Dart: Strings can be "multiplied"';
String line = '-' * title.length
print(line);
print(title);
print(line);
}
And this will be printed as:
---------------------------------
Dart: Strings can be "multiplied"
---------------------------------
See Dart String's multiply * operator docs:
Creates a new string by concatenating this string with itself a number of times.
The result of str * n is equivalent to str + str + ...(n times)... + str.
Returns an empty string if times is zero or negative.
I use this way.
void main() {
print(new List.filled(40, "-").join());
}
So, your case.
main() {
const String FILLER = "-";
String headerTxt;
String headerBox;
headerTxt = 'OpenPGP signing notes from key `CD42FF00`';
headerBox = new List.filled(headerTxt.length, FILLER).join();
print(headerBox);
print(headerTxt);
print(headerBox);
// ...
}
Output:
-----------------------------------------
OpenPGP signing notes from key `CD42FF00`
-----------------------------------------

Resources