Coffeescript: how do I convert a string to a number? - coffeescript

I am building a JSON object that is sent in a POST request.
This object has properties that need to be converted from string type to integer type before sending. How does one do that with coffeescript?

Use the javascript parseInt function.
number = parseInt( stringToParse, 10 );
Reference is here.
Remember, coffeescript is just javascript after it's compiled

You can use the less obvious, more magical, less keyboard-intensive operator +:
+"158"

Javascript's parseInt function will achieve this. Remember to set the radix parameter to prevent confusion and ensure predictable behaviour. (E.g. in Coffeescript)
myNewInt = parseInt("176.67", 10)
There's a few good examples in the MDN resources: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt

It hasn't been documented in the official manual yet, but it seems that cast operators works too:
myString = "12323"
myNumber = (Number) myString

I don't recommend using parseInt since it's wrong in one case - which I found :
parseInt('09asdf', 10);
#> return 09 which is not correct at all. It should return NaN
The correct answer should be the one from #Corkscreewe. And there is another:
cleanInt = (x) ->
x = Number(x)
(if x >= 0 then Math.floor(x) else Math.ceil(x))
Learn from https://coderwall.com/p/cbabhg

Based on the link, mentioned in nXqd's answer, you can also implicitly convert a string by multiplying it by 1:
'123' * 1 // 123
It behaves correctly for incorrect input:
'123abc' * 1 // NaN
You can do this also with floats:
'123.456' * 1 // 123.456

This is a simple way for your need. NaN will be returned as expected.
parseInt( "09asdf".match(/^\d+$/)?[0] ? NaN, 10)

stringToConvernt = "$13,452,334.5"
output = Number(stringToConvernt.replace(/[^0-9\.]/g, ''))
console.log(output)
//The output is `13452334.5`.

I'm always using bitwise OR to convert strings into integers.
"99.999" | 0 // returns 99

Related

How to translate this code into python 3?

This code is originally written in Python 2 and I need to translate it in python 3!
I'm sorry for not sharing enough information:
Also, here's the part where self.D was first assigned:
def __init__(self,instance,transformed,describe1,describe2):
self.D=[]
self.instance=instance
self.transformed=transformed
self.describe1,self.describe2=describe1,describe2
self.describe=self.describe1+', '+self.describe2 if self.describe2 else self.describe1
self.column_num=self.tuple_num=self.view_num=0
self.names=[]
self.types=[]
self.origins=[]
self.features=[]
self.views=[]
self.classify_id=-1
self.classify_num = 1
self.classes=[]
def generateViews(self):
T=map(list,zip(*self.D))
if self.transformed==0:
s= int( self.column_num)
for column_id in range(s):
f = Features(self.names[column_id],self.types[column_id],self.origins[column_id])
#calculate min,max for numerical,temporal
if f.type==Type.numerical or f.type==Type.temporal:
f.min,f.max=min(T[column_id]),max(T[column_id])
if f.min==f.max:
self.types[column_id]=f.type=Type.none
self.features.append(f)
continue
d={}
#calculate distinct,ratio for categorical,temporal
if f.type == Type.categorical or f.type == Type.temporal:
for i in range(self.tuple_num):
print([type(self.D[i]) for i in range(self.tuple_num)])
if self.D[i][column_id] in d:
d[self.D[i][column_id]]+=1
else:
d[self.D[i][column_id]]=1
f.distinct = len(d)
f.ratio = 1.0 * f.distinct / self.tuple_num
f.distinct_values=[(k,d[k]) for k in sorted(d)]
if f.type==Type.temporal:
self.getIntervalBins(f)
self.features.append(f)
TypeError: 'map' object is not subscriptable
The snippet you have given is not enough to solve the problem. The problem lies in self.D which you are trying to subscript using self.D[i]. Please look into your code where self.D is instantiated and make sure that its an array-like variable so that you can subscript it.
Edit
based on your edit, please confirm that whether self.D[i] is also array-like for all i in the range mentioned in the code. you can do that by simply
print([type(self.D[i]) for i in range(self.tuple_num))
share the response of this code, so that I may help further.
Edit-2
As per your comments and the edited code snippet, it seems that self.D is the output of some map function. In python 2, map is a function that returns a list. However, in python3 map is a class that when invoked, creates a map object.
The simplest way to resolve this is the find out the line where self.D was first assigned, and whatever code is in the RHS, wrap it with a list(...) function.
Alternately, just after this line
T=map(list,zip(*self.D))
add the following
self.D = list(self.D)
Hope this will resolve the issue
We don't have quite enough information to answer the question, but in Python 3, generator and map objects are not subscriptable. I think it may be in your
self.D[i]
variable, because you claim that self.D is a list, but it is possible that self.D[i] is a map object.
In your case, to access the indexes, you can convert it to a list:
list(self.D)[i]
Or use unpacking to implicitly convert to a list (this may be more condensed, but remember that explicit is better than implicit):
[*self.D[i]]

Ignoring an output parameter from vDSP

When using vDSP to perform some speedy calculations, I often don't care about one of the output parameters. Let's say I'm finding the index of an array's maximum value:
var m:Float = 0
var i:vDSP_Length = 0
vDSP_maxvi(&array,
1,
&m,
&i,
vDSP_Length(array.count))
Ideally, I'd like to get rid of m altogether so that vDSP_maxvi fills i only. Something like:
var i:vDSP_Length = 0
vDSP_maxvi(&array,
1,
nil,
&i,
vDSP_Length(array.count))
But of course this doesn't work ("nil is not compatible with expected argument type 'UnsafeMutablePointer<Float>'"). Is there some sort of argument I can send to these kinds of methods that says "ignore this parameter"? Thanks for reading.
Except for documented cases where a null argument is accepted, you must pass a valid address. There is no argument value that tells vDSP to ignore the argument.

Why doesn't strcmp recognize two seemingly equal strings as the same?

Below is the output from the Matlab's console. Both of the strings are the same: '#TBMA3'. Yet Matlab's strcmp function returns 0 when comparing them. Why?
K>> str='#TBMA3'
str =
#TBMA3
K>> method.fhandle
ans =
#TBMA3
K>> strcmp(method.fhandle, str)
ans =
0
The most likely reason is that method.fhandle is not a string, but a function handle. Check if class(method.fhandle) gives
ans =
function_handle
In that case, the comparison gives 0 because a string (str) cannot be equal to a function handle (method.fhandle).
In order to check for equality, you would need to convert method.fhandle to a string, or str to a function handle. The first option is not adequate, because char(function_handle) would give 'TBMS3', without '#'. So use the second option, and compare using isequal:
isequal(method.fhandle, str2func(str))
should give 1.†
† This isequal comparison works because both method.fhandle and str2func(str) point to the same already-defined function TBMA3. Compare with f = #(x)x; g = #(x)x, isequal(f,g), which gives 0. This behaviour is explained in the documentation. Thanks to #knedlsepp for helping clarify this.

Error using minus in MATLAB

temp(i,1) = rand(1)*(pb(1,num).pos(i,1) - pw(1,num).pos(i,1));
This line gives the following error:
Error using ==> minus
Not enough input arguments.
The following are the definitions of pb and pw.
pw=struct('fitness',[],'pos',{});
pb=struct('fitness',[],'pos',{});
pos is a 2 x 1 array.
When tracking down errors like this, I break the problem up into smaller bits. Especially when the logic isn't readily apparent. Not only does it provide a path that can be used to step through your function using the debugger, but it also makes it more readable.
I've taken liberty with the intermediate variable names.
thisPb = pb(1,num);
thisPw = pw(1,num);
initialPos= pw.pos(i,1);
finalPos = pb.pos(i,1);
whos initialPos finalPos
temp(i,1) = rand(1) * (finalPos - initialPos);
The line with whos will print out the values. Make sure that finalPos and initialPos are both numbers.
One way that you can get this error is when num is an empty matrix.
The expression
>> s(x).a
can return a variable number of outputs, depending on the size of x.
If x = [1,2,3] for example, it will return three values (as long as s has at least three elements).
If x = [] on the other hand, then s(x).a will return no outputs, so the expression
>> disp(s(x).a)
will give you a Not enough input arguments error, which is almost certainly what you're seeing. You should check that num is not empty.
Are you sure, that all values are really initialised? Try to check this before your codeline.
disp(pb(1,num).pos(i,1))
disp(pw(1,num).pos(i,1))
temp(i,1) = rand(1)*(pb(1,num).pos(i,1) - pw(1,num).pos(i,1));

how to make matlab detect incompatible type assignments?

hi have a major problem in matlab. I have a function and it sometimes returns control ascii characters. How do i check for the presence of these control ascii ?.
my code looks like this
d = out.autoc
d sometimes receives control ascii characters instead of a actual double value. Does someone know how to catch such incompatible assignments ?
I think this should work but you may want to double check the ASCII codes to exclude.
%here I load Ctrl-C
s = sprintf('%s', 3);
code = bin2dec(dec2bin(s,8));
if code < 32
fprintf('ignore');
else
fprintf('do somsething');
end
If you want to check that the value of d is double, and not a string. You can check it this way:
if ~isnumeric(d) || ~isdouble(d)
fprintf('d is not of class double\n');
end
But if you want to assign the value of out.autoc to d only if out.autoc is double, you can do this:
if isnumeric(out.autoc) && isequal(class(out.autoc), 'double')
d = out.autoc;
else
fprintf('out.autoc is not of class double, no assignment made.\n');
end