Jxcore add new task parallel - jxcore

I'm using jxcore to execute a job in parallel. But when I test as below
var method = function () {
var sleep = require('sleep');
console.log("thread started", process.threadId);
sleep.sleep(2);
console.log("thread finished", process.threadId);
};
jxcore.tasks.addTask(method);
jxcore.tasks.addTask(method);
jxcore.tasks.addTask(method);
jxcore.tasks.addTask(method);
Result seems just 1 thread is used :
thread started 0
thread finished 0
thread started 0
thread finished 0
thread started 0
thread finished 0
thread started 0
thread finished 0
I expect , it create 4 thread start parallel.
How can i achieve it ?

Try:
Function.prototype.clone = function() {
var that = this;
var temp = function temporary() { return that.apply(this, arguments); };
for(var key in this) {
if (this.hasOwnProperty(key)) {
temp[key] = this[key];
}
}
return temp;
};
var method = function () {
var sleep = require('sleep');
console.log("thread started", process.threadId);
sleep.sleep(2);
console.log("thread finished", process.threadId);
};
jxcore.tasks.addTask(method);
jxcore.tasks.addTask(method.clone());
jxcore.tasks.addTask(method.clone());
jxcore.tasks.addTask(method.clone());
Or:
var newmethod1 = method.clone();
jxcore.tasks.addTask(newmethod1);
jxcore.tasks.runOnce(newmethod1);

Related

Topological Sort Swift

I'm trying to implement a topological sort in Swift using the following theory.
https://courses.cs.washington.edu/courses/cse326/03wi/lectures/RaoLect20.pdf
My code is:
func canFinish(_ numCourses: Int, _ prerequisites: [[Int]]) -> Bool {
guard (prerequisites.count > 0) else {return true}
var graph : [[Int]] = Array(repeating: [], count: numCourses + 1)
var inDegree : [Int] = Array(repeating: 0, count: numCourses + 1 )
for x in prerequisites {
graph[x[0]] = [x[1]]
inDegree[x[0]] += 1
}
for course in graph.enumerated() {
print ("To finish course \(course.offset) you must have finished \(course.element)")
}
for course in (inDegree.enumerated()) {
print ("Course \(course.offset) needs \(course.element) courses to be complete")
}
var outputArr = [Int]()
while let currentVertexIndx = (inDegree.enumerated().first { $0.element == 0 }?.offset) {
outputArr.append( currentVertexIndx )
for course in graph.enumerated() {
if (course.element.contains(currentVertexIndx)) {
inDegree[ course.offset ] -= 1
}
}
inDegree[currentVertexIndx] = -1
}
return outputArr.count >= numCourses
}
Tests with correct answers:
//canFinish(1, [[1,0]]) // true - to take course 1 you should have finished course 0
//canFinish(2, [[1,0],[0,1]]) // false - to take course 1 you have to have finished course 0, to take 0 you have to have finished course 1
//canFinish(1, []) // true
//canFinish(3, [[1,0],[2,0]]) // true
//canFinish(3, [[2,0],[2,1]]) // true
Test with incorrect answer
canFinish(10, [[5,6],[0,2],[1,7],[5,9],[1,8],[3,4],[0,6],[0,7],[0,3],[8,9]]) // true, but returns false
Question: My code does not work for the input above using the theory linked from Washington.edu. What is going wrong?
You should fill the graph correctly:
graph[x[0]] += [x[1]]
Which would yield the right result in the given example:
canFinish(10, [[5,6],[0,2],[1,7],[5,9],[1,8],[3,4],[0,6],[0,7],[0,3],[8,9]]) //true

Loops in didSet

We came across this odd behaviour when using loops in a didSet. The idea was that we have a data type with a tree structure and in each element we wanted to store the level that item is on. So in the didSet of the level attribute we would also set the level attribute of the children. However we realised that this does only work if one uses forEach and not when using for .. in. Here a short example:
class Item {
var subItems: [Item] = []
var depthA: Int = 0 {
didSet {
for item in subItems {
item.depthA = depthA + 1
}
}
}
var depthB: Int = 0 {
didSet {
subItems.forEach({ $0.depthB = depthB + 1 })
}
}
init(depth: Int) {
self.depthA = 0
if depth > 0 {
for _ in 0 ..< 2 {
subItems.append(Item(depth: depth - 1))
}
}
}
func printDepths() {
print("\(depthA) - \(depthB)")
subItems.forEach({ $0.printDepths() })
}
}
let item = Item(depth: 3)
item.depthA = 0
item.depthB = 0
item.printDepths()
When I run this I get the following output:
0 - 0
1 - 1
0 - 2
0 - 3
0 - 3
0 - 2
0 - 3
0 - 3
1 - 1
0 - 2
0 - 3
0 - 3
0 - 2
0 - 3
0 - 3
It seems like it will not call the didSet of the subItems attribute when it's called from an for .. in loop. Does anyone know why this is the case?
UPDATE:
The problem is not that the didSet is not called from the init. We change the attribute afterwards (see last 4 lines of code) and only one of the two depth attribute will propagate the new value to the children
If you use defer, for updating any optional properties or further updating non-optional properties that you've already initialized and after you've called any super init methods, then your willSet, didSet, etc. will be called.
for item in subItems {
defer{
item.depthA = depthA + 1
}
}
When you use the forEach it makes kindOf "contract" with the elements and because it's an instance method unlike for .. in loop, it triggers the didSet of the variable. The above case applies where we use the loop, we have to trigger the didSet manually
This Solves the problem I think. Hope it helps!!
It seems that in the init, didSet is not called.
Tried this line on the Swift REPL
class A { var a: Int { didSet { print("A") } }; init() { a = 5 } }
Then called A()
didSet is NOT called
But
A().a = 7
Found that didSet is called
So, the solution is to make a function (prefered to be final), that makes your effect you need to put in didSet. Then call it both from didSet and from init. You can put this in your class.
final func updateA() {
// Do your "didSet" here
}
var a: Int {
didSet {
updateA()
}
}
init() {
a = 5
updateA()
}
So in your case:
func updateDepthA() {
for item in subItems {
item.depthA = depthA + 1
}
}
var depthA: Int = 0 {
didSet {
updateDepthA()
}
}
...
init(depth: Int) {
self.depthA = 0
updateDepthA()
...

Swift: command line tool exit callback

I need to know when a command line program is stopped by the user to release some active bluetooth connections from a command-line program (running on the terminal), written in swift.
Say the user calls the program then exits by pressing ctrl+Z.
How would I know ?
You can install a signal handler with Swift. For example:
import Foundation
let startTime = Date()
var signalReceived: sig_atomic_t = 0
signal(SIGINT) { signal in signalReceived = 1 }
var i = 0
while true {
if signalReceived == 1 { break }
usleep(500_000)
if signalReceived == 1 { break }
i += 1
print(i)
}
let endTime = Date()
print("Program has run for \(endTime.timeIntervalSince(startTime)) seconds")
Modified from this gist.

Int in swift closure not incrementing

I have a closure in the code below that executes over an array of custom SKShapeNodes (blockNode). The problem I'm having is that completedActionsCount is always 1, no matter how many how many times the closure is executed. Is completedActionsCount just copied at the start of the closure?? Is there something I'm missing here?
for action in blockActionSets[index]
{
var blockActionSet = blockActionSets[index]
var completedActionsCount = 0
let blockNode = getBlockNodeForBlock(action.block)
if blockNode
{
blockNode!.updateWithAction(action, completion:
{ blockAction in
completedActionsCount++
println(completedActionsCount)
println(blockActionSet.count)
if (completedActionsCount == blockActionSet.count)
{
index = index + 1
self.executeBlockActionSetAtIndexRecursive(index, blockActionSets: blockActionSets, completion: completion)
}
})
}
else
{
completedActionsCount++
}
}
The following code is how the block is executed:
func updateWithAction(blockAction : BlockAction, completion : (BlockAction) -> Void)
{
if blockAction.blockActionType == BlockActionType.ChangeColor
{
var startColor = CIColor(CGColor: self.fillColor.CGColor)
var endColor = CIColor(CGColor: UI.getUIColorForBlockType(blockAction.endBlockType).CGColor)
var startRed = startColor.red()
var startGreen = startColor.green()
var startBlue = startColor.blue()
var endRed = endColor.red()
var endGreen = endColor.green()
var endBlue = endColor.blue()
var action = SKAction.customActionWithDuration(CHANGE_COLOR_ANIMATION_DURATION, actionBlock: {(node : SKNode!, elapsedTime : CGFloat)->Void in
var blockNode = node as? BlockNode
if blockNode
{
var ratio : CGFloat = min(1.0, elapsedTime / CGFloat(self.CHANGE_COLOR_ANIMATION_DURATION))
blockNode!.fillColor = UIColor(red: startRed + ratio * (endRed - startRed),
green: startGreen + ratio * (endGreen - startGreen),
blue: startBlue + ratio * (endBlue - startBlue),
alpha: 1.0)
}
if elapsedTime >= CGFloat(self.CHANGE_COLOR_ANIMATION_DURATION)
{
completion(blockAction)
}
})
self.runAction(action)
}
}
I believe the issue is that you are defining the completedActionsCount variable inside the loop, so each time through the loop a new Int value is defined and the value is reset to 0
does this work for you?
var completedActionsCount = 0
for action in blockActionSets[index] {
var blockActionSet = blockActionSets[index]
…
}
re-reading the question… I'm not sure if you intended for each blockActionSet to have it's own counter. But, to answer one of your sub-questions, I'm pretty sure that even though Int is a value type, it is not being copied into the closure, it's available via the outer scope, and you should be able to modify it.
Is updateWithAction:completion: run in the current thread? if it's asynchronous, that may be a factor.
response to update: Generally any API that has "withDuration" in the name will be async to avoid blocking the main thread.
I'm not sure exactly what is happening, but if the counter is being copied because it's a value type I don't know if switching to the main thread will actually fix your issue, but it's worth a try:
blockNode!.updateWithAction(action, completion:
{ blockAction in
dispatch_async(dispatch_get_main_queue()) {
completedActionsCount++
…
}
}
})
I have somewhat low hopes for this approach though since I suspect the value is being copied and copying it again is certainly not going to give you back the original reference. You may be able to wrap the reference to the counter in a reference type (like a variable array or dictionary):
var completedActionsCounts : [Int:Int] = [:]
for action in blockActionSets[index] {
var blockActionSet = blockActionSets[index]
completedActionsCounts[index] = 0
…
blockNode!.updateWithAction(action, completion:
{ blockAction in
dispatch_async(dispatch_get_main_queue()) {
completedActionsCounts[index] += 1
…
}
}
})
}

The map/reduce finalize() does not always get the same number of parameters

When using map/reduce on MongoDb 2.0.1, it seems that the finalize method is not always called with the same arguments.
I am doing a regular counting + average at the end.
var m = function() {
emit(this.testName, {
worked: Number(this.testStatus == "WORKED"),
failed: Number(this.testStatus == "FAILED"),
done: Number(this.testStatus == "DONE"),
count: 1
});
}
var r = function(key, values) {
var result = {
worked: 0,
failed: 0,
done: 0,
count: 0
}
values.forEach(function(value) {
result.worked += value.worked;
result.failed += value.failed;
result.done += value.done;
result.count += value.count;
});
return result;
}
var f = function(key, value) {
data = value || key;
data.workedMean = data.worked / data.count;
return data;
}
var cmd = {
mapreduce: "tests",
map: m,
reduce: r,
finalize: f,
out: {
reduce: "fromMongo"
},
jsMode: true
}
When the fromMongo collection is empty, f() is called with only one argument, the value. When fromMongo already has values (notice that I use reduce as my out map/reduce parameter), the f() method get two arguments: key and value.
Is that a known behavior?
I managed two make it work using data = value || key;, but I don't think this is the solution.
this problem is due to a difference in finalize call between the jsMode and non-jsMode (which happens during the post processing of "reduce" mode).
The workaround is to not use jsMode:true, in which case it should always be called with (key, value).
Created a server issue:
https://jira.mongodb.org/browse/SERVER-4535