JS push operation does something funny to repeated array arguments - push

I don't understand js's push. It does this funny thing
var x = []
var y = [1]
x.push(y) // x is [[1]]
x.push(y) // x is [[1],[]] Why?

Using your code I get:
x is [[1],[1]]
as the output - run fiddle at bottom...
I have no idea how you could be getting a different output?
var x = [];
var y = [1];
x.push(y) // x is [[1]]
x.push(y) // x is [[1],[]]
var divOut = document.getElementById('divOut');
divOut.innerText = 'x is ' + JSON.stringify(x);
<div id="divOut"></div>

Related

How do I use numba's "guvectorize" decorator to change two arrays in the same function?

I'm using numba's #guvectorize to change two different arrays. The code is:
#guvectorize([(int64[:], int64[:], int64[:], int64[:])], '(n),(n)->(n),(n)', target= 'parallel')
def g(x, y, res, res_two):
res = x
for i in range(x.shape[0]-1):
var = np.random.poisson((2),1)[0]
res_two[i] = var
res[i+1] = res[i] + res_two[i]
print("res[i+1] is", res[i+1], "for x[i] is", x[i])
q = (np.arange(5)) * 0
q[0] = 5
r = (np.arange(5)) * 0
g(q,r)
print("q is", q)
print("r is", r)
And the results printed out are:
As one can see, q is changing, but r isn't.
What must I do to use guvectorize to input two arrays and change those two arrays?

Int() doesn't convert from String to Optional Integer (Swift)

I'm new at programming and started with Swift. The first issue I came along with is the following:
I have 4 variables
var a = "345"
var b = "30.6"
var c = "74hf2"
var d = "5"
I need to count the sum of Integers (if not integer, it will turn to nil)
if Int(a) != nil {
var aNum = Int(ar)!
}
if Int (b) != nil {
var bNum = Int (b)!
}
and so on..
As far as I understand, the Int() should convert each element into an Optional Integer.
Then I should use forced unwrapping by convertin the Int? to Int and only then I can use it for my purposes. But instead, when I count the sum of my variables, the compiler sums them as Strings.
var sum = aNum + bNum + cNum + dNum
Output:
34530.674hf25
Why my variables, which are declared as strings and then converted into optional integers with Int(), didn't work?
Your code has typos that make it hard to tell what you are actually trying to do:
Assuming your 2nd variable should be b, as below:
var a = "345"
var b = "30.6"
var c = "74hf2"
var d = "5"
///Then you can use code like this:
var sum = 0
if let aVal = Int(a) { sum += aVal }
if let bVal = Int(b) { sum += bVal }
if let cVal = Int(c) { sum += cVal }
if let dVal = Int(d) { sum += dVal }
print(sum)
That prints 350 since only 345 and 5 are valid Int values.

Callback in Bender's decomposition

I am learning Bender's decomposition method and I want to use that in a small instance. I started from "bendersatsp.py" example in CPLEX. When I run this example with my problem, I got the following error. Could you please let me know what the problem is and how I can fix it? In the following you can see the modifications in lazy constraints function. I have two decision variables in master problem "z_{ik}" and "u_{k}" that would incorporate as constant in the workerLp.
class BendersLazyConsCallback(LazyConstraintCallback):
def __call__(self):
print("shoma")
v = self.v
u = self.u
z = self.z
print ("u:", u)
print ("z:", z)
workerLP = self.workerLP
boxty = len(u)
#scenarios=self.scenarios2
ite=len(z)
print ("ite:", ite)
print ("boxty:", boxty)
# Get the current x solution
sol1 = []
sol2 = []
sol3 = []
print("okkkk")
for k in range(1, boxty+1):
sol1.append([])
sol1[k-1]= [self.get_values(u[k-1])];
print ("sol1:", sol1[k-1])
for i in range(1, ite+1):
sol2.append([])
sol2[i-1]= self.get_values(z[i-1]);
print ("sol2:", sol2[i-1])
for i in range(1, ite+1):
sol3.append([])
sol3[i-1]= self.get_values(v[i-1]);
#print ("sol3:", sol3[i-1])
# Benders' cut separation
if workerLP.separate(sol3,sol1,sol2,v,u,z):
self.add(cut = workerLP.cutLhs, sense = "G", rhs = workerLP.cutRhs)
CPLEX Error 1006: Error during callback.
benders(sys.argv[1][0], datafile)
cpx.solve()
_proc.mipopt(self._env._e, self._lp)
check_status(env, status)
raise callback_exception
TypeError: unsupported operand type(s) for +: 'int' and 'list'

Two variables in for loop using Swift

How to use two variables in for loop?
for j,k in zip(range(x,0,-1),range(y,-1,-1)
I want to implement this in Swift.
If your range is a python function, then the Swift-y solution will be:
let x = 100
let y = 99
let rx = reverse(0...x)
let ry = reverse(-1...y)
for (j,k) in zip(rx, ry) {
println(j, k)
}
if you're looping over a dictionary you can loop like this
for (key,value) in dictionary {
}
if an array etc. you're going to have to use a c style for loop
just sub in whatever start and end indices you need
for var j = 0 , k = 0; j < 10 && k < 10; j++ , k++ {
}
EDIT
missed the zip in there. You can loop like this
for (j,k) in zip(range1, range2) {
}

Recursive concatenation of Matlab structs

Is it somehow possible to concatenate two matlab structures recursively without iterating over all leaves of one of the structures.
For instance
x.a=1;
x.b.c=2;
y.b.d=3;
y.a = 4 ;
would result in the following
res = mergeStructs(x,y)
res.a=4
res.b.c=2
res.b.d=3
The following function works for your particular example. There will be things it doesn't consider, so let me know if there are other cases you want it to work for and I can update.
function res = mergeStructs(x,y)
if isstruct(x) && isstruct(y)
res = x;
names = fieldnames(y);
for fnum = 1:numel(names)
if isfield(x,names{fnum})
res.(names{fnum}) = mergeStructs(x.(names{fnum}),y.(names{fnum}));
else
res.(names{fnum}) = y.(names{fnum});
end
end
else
res = y;
end
Then res = mergeStructs(x,y); gives:
>> res.a
ans =
4
>> res.b
ans =
c: 2
d: 3
as you require.
EDIT: I added isstruct(x) && to the first line. The old version worked fine because isfield(x,n) returns 0 if ~isstruct(x), but the new version is slightly faster if y is a big struct and ~isstruct(x).