问:
Can I control the parameter order in an HTTPService Post?
I'm updating a Point of Sale system that was built with Flex 4.15.0 and AIR 23.0 using the Cairngorm framework.

The code integrates with a custom server provided by my client's payment processor vendor.  I do not know any details of its implementation.

Part of the requirements is that parameters be form posted to their server in a specific order. The Apache Flex / AIR does not appear to retain the parameter order of the object's parameters.  Is there a way to do it?

More specifics, with code:

The HTTPService is set up in Cairngorm's Services.mxml:

```<code><mx:HTTPService id="service"
            showBusyCursor="false"
            requestTimeout="240"
            method="post" contentType="application/x-www-form-urlencoded"
            url="http://localhost.:16448/" resultFormat="e4x"
            />
</code>```

Create a parameter object and call service method; this is done in a Cairngorm Delegate:

```<code>var parameters : Object = new Object();
parameters.firstParameter  = "firstOne";
parameters.amount = 100;
parameters.otherParameters = "Other Random Misc Data";
parameters.lastParameter = "LastOne";
</code>```

Then make the call:

```<code>var call : Object    = this.service.send(parameters);
call.addResponder( this.responder );
</code>```

The Flex Framework class mx.rpc.httpAbstractOperation adds the parameters object to the outgoing service call.  This starts around line 862.  This loops over properties using classinfo.properties.  This seems to get an alphabetical list of properties from my object and add them to the paramsToSend object:

```<code>else if (ctype == CONTENT_TYPE_FORM)
{
    paramsToSend = {};
    var val:Object;

    if (typeof(parameters) == "object")
    {
        //get all dynamic and all concrete properties from the parameters object
        var classinfo:Object = ObjectUtil.getClassInfo(parameters);

        for each (var p:* in classinfo.properties)
        {
            val = parameters[p];
            if (val != null)
            {
                if (val is Array)
                    paramsToSend[p] = val;
                else
                    paramsToSend[p] = val.toString();
            }
        }
    }
    else
    {
        paramsToSend = parameters;
    }
}
</code>```

Looking at the raw data in the Flash Builder Network Monitor; the final request doesn't have the parameters in alphabetical order.

```<code>otherParameters=Other%20Random%20Misc%20Data&lastParameter=LastOne&firstParameter=firstOne&amount=100
</code>```

With this small sample it appears that the parameters are in reverse alphabetical order, but with the actual request data they are in a seemingly random--but always consistent--order.

Something appears to be modifying the request between leaving Flex and hitting the network monitor.  I assume something in the runtime.

My first attempt at a solution was to create the POST parameter string manually and use that as the parameter object.  However in that case the body of the POST request was blank when reviewing it in the service monitor.

Any ideas?  I'm at a loss, and fear that the parameter order may be a reason for the vendor to deny PCI Compliance certification of the app's updates.

Here is a related question that offers a solution to GET calls, but not POST calls.

答:
My guess is you'll have to manually generate the POST body yourself, and use the more low-level URLLoader object instead of HTTPService.

I'd pattern it off of https://madssj.com/blog/2008/07/30/actionscript-3-posting-xml-data-with-urlloader/

And, if anyone doesn't know what a raw POST body looks like, it's basically a URL query string: How are parameters sent in an HTTP POST request?

Using the lower level APIs was the right approach to control the parameter order.  Here is some sample code that I used.  First, create the parameter string:

```<code>var parameters : String = '';
parameters += "firstParameter=firstOne&";
parameters += "amount=100&";
parameters += "otherParameters=Other Random Misc Data&";
parameters+= "lastParameter=LastOne";
</code>```

Then, create the URLRequest:

```<code>var r:URLRequest = new URLRequest(yourURLHere);
r.data = parameters;
r.method = URLRequestMethod.POST;
r.contentType = "application/x-www-form-urlencoded";
</code>```

And finally, create the URLLoader:

```<code>var l:URLLoader = new URLLoader();
l.addEventListener(Event.COMPLETE, myResultMethod);
l.addEventListener(IOErrorEvent.IO_ERROR, myFailureMethod );
l.addEventListener(SecurityErrorEvent.SECURITY_ERROR, myFailureMethod );
l.load(r);
</code>```

And you now have complete control over the parameter order.

My blog post on this topic.

Body:
I'm updating a Point of Sale system that was built with Flex 4.15.0 and AIR 23.0 using the Cairngorm framework.

The code integrates with a custom server provided by my client's payment processor vendor.  I do not know any details of its implementation.

Part of the requirements is that parameters be form posted to their server in a specific order. The Apache Flex / AIR does not appear to retain the parameter order of the object's parameters.  Is there a way to do it?

More specifics, with code:

The HTTPService is set up in Cairngorm's Services.mxml:

<mx:HTTPService id="service"
            showBusyCursor="false"
            requestTimeout="240"
            method="post" contentType="application/x-www-form-urlencoded"
            url="http://localhost.:16448/" resultFormat="e4x"
            />

Create a parameter object and call service method; this is done in a Cairngorm Delegate:

var parameters : Object = new Object();
parameters.firstParameter  = "firstOne";
parameters.amount = 100;
parameters.otherParameters = "Other Random Misc Data";
parameters.lastParameter = "LastOne";

Then make the call:

var call : Object    = this.service.send(parameters);
call.addResponder( this.responder );

The Flex Framework class mx.rpc.httpAbstractOperation adds the parameters object to the outgoing service call.  This starts around line 862.  This loops over properties using classinfo.properties.  This seems to get an alphabetical list of properties from my object and add them to the paramsToSend object:

else if (ctype == CONTENT_TYPE_FORM)
{
    paramsToSend = {};
    var val:Object;

    if (typeof(parameters) == "object")
    {
        //get all dynamic and all concrete properties from the parameters object
        var classinfo:Object = ObjectUtil.getClassInfo(parameters);

        for each (var p:* in classinfo.properties)
        {
            val = parameters[p];
            if (val != null)
            {
                if (val is Array)
                    paramsToSend[p] = val;
                else
                    paramsToSend[p] = val.toString();
            }
        }
    }
    else
    {
        paramsToSend = parameters;
    }
}

Looking at the raw data in the Flash Builder Network Monitor; the final request doesn't have the parameters in alphabetical order.

otherParameters=Other%20Random%20Misc%20Data&lastParameter=LastOne&firstParameter=firstOne&amount=100

With this small sample it appears that the parameters are in reverse alphabetical order, but with the actual request data they are in a seemingly random--but always consistent--order.

Something appears to be modifying the request between leaving Flex and hitting the network monitor.  I assume something in the runtime.

My first attempt at a solution was to create the POST parameter string manually and use that as the parameter object.  However in that case the body of the POST request was blank when reviewing it in the service monitor.

Any ideas?  I'm at a loss, and fear that the parameter order may be a reason for the vendor to deny PCI Compliance certification of the app's updates.

Here is a related question that offers a solution to GET calls, but not POST calls.

Body:
My guess is you'll have to manually generate the POST body yourself, and use the more low-level URLLoader object instead of HTTPService.

I'd pattern it off of https://madssj.com/blog/2008/07/30/actionscript-3-posting-xml-data-with-urlloader/

And, if anyone doesn't know what a raw POST body looks like, it's basically a URL query string: How are parameters sent in an HTTP POST request?

Using the lower level APIs was the right approach to control the parameter order.  Here is some sample code that I used.  First, create the parameter string:

var parameters : String = '';
parameters += "firstParameter=firstOne&";
parameters += "amount=100&";
parameters += "otherParameters=Other Random Misc Data&";
parameters+= "lastParameter=LastOne";

Then, create the URLRequest:

var r:URLRequest = new URLRequest(yourURLHere);
r.data = parameters;
r.method = URLRequestMethod.POST;
r.contentType = "application/x-www-form-urlencoded";

And finally, create the URLLoader:

var l:URLLoader = new URLLoader();
l.addEventListener(Event.COMPLETE, myResultMethod);
l.addEventListener(IOErrorEvent.IO_ERROR, myFailureMethod );
l.addEventListener(SecurityErrorEvent.SECURITY_ERROR, myFailureMethod );
l.load(r);

And you now have complete control over the parameter order.

My blog post on this topic.


来源: stackexchange

问:
initialize setPano() for google.maps.StreetViewPanorama with google map marker's click event. Works only first time
I have a google map and a streetview panorama viewer on a page. There are few markers draw on my google map carrying some info of panorama eg panoId, Panoname etc. And in the streetview panorama viewer i am showing one of very first panorama of all those panorama whose markers are on map. Now i want to create a click event on marker to initialize/load new panorama image on streetviewpanorama viewer. The click event i have created works only for first time when i click next time it returns error on console (Uncaught TypeError: a.ha is not a function) which is showing in the image below:

Here is my code:

```<code><div class="col-md-12" style="padding-bottom:20px;">
    <div id="tourmap"></div>
    <div id="panomap"></div>
</div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('tourmap'), {
  zoom: 22,
  center: {lat: latitude, lng: longitude}
});
setMarkers(map);
}

var beaches = [
['pano1.jpg',30.878170532669305, 75.8590769883433,'CAoSLEFGMVFpcFBta1ZwakNRc2V2NkhrWjdGTmIxeXRJeWRYd2E3TF9paVRKN1FP',31],
['pano2.jpg',30.87816823063522, 75.85907497668654,'CAoSLEFGMVFpcE5Ca2Zld3pVVEkyS0pjWGxjNHZOZ0c1bTE4MzhfdkdIN3VSNkRw',32],
['pano3.jpg',30.87816823063522, 75.85907967055232,'CAoSLEFGMVFpcE10UlhvcHU5QWxOckRxX0ZaZm5aYVJKSmFKWlExcEpNMWJ4aE55',33],
['pano4.jpg',30.87816650410961, 75.8590769883433,'CAoSLEFGMVFpcFB5V045allBU1Qzal9hSFVIVXlHa05TaXl0MkRyNUpOZjFxUjVF',34],

];

function setMarkers(map) {

              var image = {
                url: 'http://sonedomain.com/img/reddot_location.gif',
                size: new google.maps.Size(20, 32),
                origin: new google.maps.Point(0, 0),
                (0, 32).
                anchor: new google.maps.Point(0, 32)
              };

              var panorama = new google.maps.StreetViewPanorama(
                            document.getElementById('panomap'), {
                              pov: {heading: 165, pitch: 0},
                              motionTracking: false,
                              motionTrackingControl: false
                            });

              var shape = {
                coords: [1, 1, 1, 20, 18, 20, 18, 1],
                type: 'poly'
              };
              for (var i = 0; i < beaches.length; i++) {
                var beach = beaches[i];
                var marker = new google.maps.Marker({
                  position: {lat: beach[1], lng: beach[2]},
                  map: map,
                  icon: image,
                  draggable:true,
                  shape: shape,
                  title: beach[3],
                  panoid: beach[3],
                  localid: beach[4]
                });

                marker.addListener('click', function(){

                    panorama.setPano(this.panoid);
                });

              } // for ends

            } // setMarkers ends
</script>
</code>```

panorama.setPano(this.panoid);  fires only once for a marker

答:
Don't know why the panorama doesn't work a second time.  A workaround which works for me, would be to create the panorama each time in the click event listener:

```<code>marker.addListener('click', function() {
  var panorama = new google.maps.StreetViewPanorama(
    document.getElementById('panomap'), {
      pov: {
        heading: 165,
        pitch: 0
      },
      motionTracking: false,
      motionTrackingControl: false
    });
  panorama.setPano(this.panoid);
});
</code>```

proof of concept fiddle

code snippet:

function initMap() {
  var map = new google.maps.Map(document.getElementById('tourmap'), {
    zoom: 22,
    center: {
      lat: 30.878170532669305,
      lng: 75.8590769883433
    }
  });
  setMarkers(map);
}

var beaches = [
  ['pano1.jpg', 30.878170532669305, 75.8590769883433, 'CAoSLEFGMVFpcFBta1ZwakNRc2V2NkhrWjdGTmIxeXRJeWRYd2E3TF9paVRKN1FP', 31],
  ['pano2.jpg', 30.87816823063522, 75.85907497668654, 'CAoSLEFGMVFpcE5Ca2Zld3pVVEkyS0pjWGxjNHZOZ0c1bTE4MzhfdkdIN3VSNkRw', 32],
  ['pano3.jpg', 30.87816823063522, 75.85907967055232, 'CAoSLEFGMVFpcE10UlhvcHU5QWxOckRxX0ZaZm5aYVJKSmFKWlExcEpNMWJ4aE55', 33],
  ['pano4.jpg', 30.87816650410961, 75.8590769883433, 'CAoSLEFGMVFpcFB5V045allBU1Qzal9hSFVIVXlHa05TaXl0MkRyNUpOZjFxUjVF', 34],

];

function setMarkers(map) {
  for (var i = 0; i < beaches.length; i++) {
    var beach = beaches[i];
    var marker = new google.maps.Marker({
      position: {
        lat: beach[1],
        lng: beach[2]
      },
      map: map,
      draggable: true,
      title: beach[3],
      panoid: beach[3],
      localid: beach[4]
    });
    marker.addListener('click', function() {
      var panorama = new google.maps.StreetViewPanorama(
        document.getElementById('panomap'), {
          pov: {
            heading: 165,
            pitch: 0
          },
          motionTracking: false,
          motionTrackingControl: false
        });
      panorama.setPano(this.panoid);
    });
  } // for ends
} // setMarkers ends
google.maps.event.addDomListener(window, "load", initMap);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}

.col-md-12 {
  width: 100%;
  height: 100%;
}

#tourmap {
  width: 50%;
  height: 100%;
  float: left;
}

#panomap {
  width: 50%;
  height: 100%;
  float: right;
}</code>```

```

ContentLicense: CC BY-SA 3.0

Body:
I have a google map and a streetview panorama viewer on a page. There are few markers draw on my google map carrying some info of panorama eg panoId, Panoname etc. And in the streetview panorama viewer i am showing one of very first panorama of all those panorama whose markers are on map. Now i want to create a click event on marker to initialize/load new panorama image on streetviewpanorama viewer. The click event i have created works only for first time when i click next time it returns error on console (Uncaught TypeError: a.ha is not a function) which is showing in the image below:

Here is my code:

panorama.setPano(this.panoid);  fires only once for a marker

Body:
Don't know why the panorama doesn't work a second time.  A workaround which works for me, would be to create the panorama each time in the click event listener:

marker.addListener('click', function() {
  var panorama = new google.maps.StreetViewPanorama(
    document.getElementById('panomap'), {
      pov: {
        heading: 165,
        pitch: 0
      },
      motionTracking: false,
      motionTrackingControl: false
    });
  panorama.setPano(this.panoid);
});

proof of concept fiddle

code snippet:

function initMap() {
  var map = new google.maps.Map(document.getElementById('tourmap'), {
    zoom: 22,
    center: {
      lat: 30.878170532669305,
      lng: 75.8590769883433
    }
  });
  setMarkers(map);
}

var beaches = [
  ['pano1.jpg', 30.878170532669305, 75.8590769883433, 'CAoSLEFGMVFpcFBta1ZwakNRc2V2NkhrWjdGTmIxeXRJeWRYd2E3TF9paVRKN1FP', 31],
  ['pano2.jpg', 30.87816823063522, 75.85907497668654, 'CAoSLEFGMVFpcE5Ca2Zld3pVVEkyS0pjWGxjNHZOZ0c1bTE4MzhfdkdIN3VSNkRw', 32],
  ['pano3.jpg', 30.87816823063522, 75.85907967055232, 'CAoSLEFGMVFpcE10UlhvcHU5QWxOckRxX0ZaZm5aYVJKSmFKWlExcEpNMWJ4aE55', 33],
  ['pano4.jpg', 30.87816650410961, 75.8590769883433, 'CAoSLEFGMVFpcFB5V045allBU1Qzal9hSFVIVXlHa05TaXl0MkRyNUpOZjFxUjVF', 34],

];

function setMarkers(map) {
  for (var i = 0; i < beaches.length; i++) {
    var beach = beaches[i];
    var marker = new google.maps.Marker({
      position: {
        lat: beach[1],
        lng: beach[2]
      },
      map: map,
      draggable: true,
      title: beach[3],
      panoid: beach[3],
      localid: beach[4]
    });
    marker.addListener('click', function() {
      var panorama = new google.maps.StreetViewPanorama(
        document.getElementById('panomap'), {
          pov: {
            heading: 165,
            pitch: 0
          },
          motionTracking: false,
          motionTrackingControl: false
        });
      panorama.setPano(this.panoid);
    });
  } // for ends
} // setMarkers ends
google.maps.event.addDomListener(window, "load", initMap);

html,
body {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}

.col-md-12 {
  width: 100%;
  height: 100%;
}

#tourmap {
  width: 50%;
  height: 100%;
  float: left;
}

#panomap {
  width: 50%;
  height: 100%;
  float: right;
}

<script src="https://maps.googleapis.com/maps/api/js"></script>
<div class="col-md-12" style="padding-bottom:20px;">
  <div id="tourmap"></div>
  <div id="panomap"></div>
</div>


问:
Run specific code when overloading C++ operators
I have a class, let's call it Foo, which contains the 3 following methods (overloading the left-associative < binary operator):

```<code>... operator<(A a) { return *this; }
... operator<(B b) { return *this; }
... operator<(C c) { return *this; }
</code>```

A, B, C classes are not related in any way(if that, is of any matter).

Now In my program I only have the 2 following cases:

```<code>A a = new A();
B b = new B();
C c = new C();

(First Case): new Foo() < a < b;
</code>```

or

```<code>(Second Case): new Foo() < a < b < c;
</code>```

Whenever I have the first case (which ends with b), I want to execute a function run() when I have read(I know) the b instance. So the idea is that I would have the following code in the Foo class:

```<code>... operator<(B b)
{
    run();
}
</code>```

Now when I have the code of the first case, run() is being executed.

The problem is that when I have code like in the second case(which ends in c).
I want to execute the run() function again but NOT until I know what c is.
So If I have the previous piece of code run() will be called when doing < b
which is not what I want as I don't know c yet.
If I add run() in operator<(C c) I will call run() twice.

In a few words what I want to accomplish is when having the first case call run() at operator<(B b) and when I have the second case ONLY call run at operator<(C c).

Any ideas on how this can be solved(if it can)?

答: You could create separate proxy object return types, so when you define an operator for that proxy object, you know which types have gone before it.</p>

ContentLicense: CC BY-SA 2.5

Body:
I have a class, let's call it Foo, which contains the 3 following methods (overloading the left-associative < binary operator):

... operator<(A a) { return *this; }
... operator<(B b) { return *this; }
... operator<(C c) { return *this; }

A, B, C classes are not related in any way(if that, is of any matter).

Now In my program I only have the 2 following cases:

A a = new A();
B b = new B();
C c = new C();

(First Case): new Foo() < a < b;

or

(Second Case): new Foo() < a < b < c;

Whenever I have the first case (which ends with b), I want to execute a function run() when I have read(I know) the b instance. So the idea is that I would have the following code in the Foo class:

... operator<(B b)
{
    run();
}

Now when I have the code of the first case, run() is being executed.

The problem is that when I have code like in the second case(which ends in c).
I want to execute the run() function again but NOT until I know what c is.
So If I have the previous piece of code run() will be called when doing < b
which is not what I want as I don't know c yet.
If I add run() in operator<(C c) I will call run() twice.

In a few words what I want to accomplish is when having the first case call run() at operator<(B b) and when I have the second case ONLY call run at operator<(C c).

Any ideas on how this can be solved(if it can)?


问:
SQL: No Sub-Query but only Joins
I am trying to find an alternative to this query where no sub-select is present but only joins (left, right, inner etc).

```<code>select count(SC.NUMBER_C)
from FNQP2PORTAL.SA.SEC_CAS SC
where SC.NUMBER_C not in (
select E.Reference from
FNQP2HQ.dbo.Entities E
join FNQP2HQ.dbo.Classes C on C.ID = E.ClassID
where C.Reference =  'Assembly case')
</code>```

So, it should be something like...

```<code>select count(SC.NUMBER_C)
from FNQP2PORTAL.SA.SEC_CAS SC
left join  FNQP2HQ.dbo.Entities E on E.Reference = SC.NUMBER_C and E.Reference IS NULL
inner join FNQP2HQ.dbo.Classes C on C.ID = E.ClassID and C.Reference =  'Assembly case'
</code>```

Can somebody help me here?

答:
One reason people use the WHERE IN logic is because of duplicates being returned via join.  So in this case moving the logic to inner joins could result in the count inflating.  Here's how you would work around that:</p>

```<code>select count(SC.NUMBER_C)
from FNQP2PORTAL.SA.SEC_CAS SC
inner join
    (
        select distinct E.Reference
        from FNQP2HQ.dbo.Entities E
        join FNQP2HQ.dbo.Classes C on C.ID = E.ClassID
        where C.Reference =  'Assembly case'
        ) as b
    on b.reference = sc.NUMBER_C
</code>```

Title: SQL: No Sub-Query but only Joins

Body:
I am trying to find an alternative to this query where no sub-select is present but only joins (left, right, inner etc).

select count(SC.NUMBER_C)
from FNQP2PORTAL.SA.SEC_CAS SC
where SC.NUMBER_C not in (
select E.Reference from
FNQP2HQ.dbo.Entities E
join FNQP2HQ.dbo.Classes C on C.ID = E.ClassID
where C.Reference =  'Assembly case')

So, it should be something like...

select count(SC.NUMBER_C)
from FNQP2PORTAL.SA.SEC_CAS SC
left join  FNQP2HQ.dbo.Entities E on E.Reference = SC.NUMBER_C and E.Reference IS NULL
inner join FNQP2HQ.dbo.Classes C on C.ID = E.ClassID and C.Reference =  'Assembly case'

Can somebody help me here?

Body:
One reason people use the WHERE IN logic is because of duplicates being returned via join.  So in this case moving the logic to inner joins could result in the count inflating.  Here's how you would work around that:

select count(SC.NUMBER_C)
from FNQP2PORTAL.SA.SEC_CAS SC
inner join
    (
        select distinct E.Reference
        from FNQP2HQ.dbo.Entities E
        join FNQP2HQ.dbo.Classes C on C.ID = E.ClassID
        where C.Reference =  'Assembly case'
        ) as b
    on b.reference = sc.NUMBER_C


问:
How do I add a new value to a dictionary's key on top of the old one, to create a sum?
I'm trying to continously add a value to a dictionary's key's value, to form a sum of an old and new value.

My code checks if one string [str_1] from now is the same as a string from 1 second ago, [str_2] if it isn't, it should create a key with the key from 1 second ago, store for how long it's been on that string and move on to the next [str_?], repeating the process for a new string (creating a new key), then, if it meets any of the strings stored [str_?], it should take that key's value and add the new value on top of it, to create a sum.

```<code>seconds = 0
my_dict = {}
stop = 0

while stop != 1:

    then_string = getStringValue() #Copies a string from somewhere.
    sleep(1)
    now_string = getStringValue() #Copies a string from somewhere, note, we waited 1 sec.

    if then_string == now_string:
        seconds += 1
    elif then_string != now_string:
        my_dict[then_string] = seconds
        """This is where I'm stuck."""
        seconds = 0 #Resets the seconds.
    else:
        pass
</code>```

My problem is that once I get to the elif (strings changed, alarm for adding new value), it breaks.

It only adds the value of seconds, even if I were to do something like

```<code>my_dict[then_string] = my_dict.get(then_string) + seconds
</code>```

The value is a seemingly doubled number of seconds and it yields improper results.

My goal is to properly get the seconds spent on a string.

答:
You could use a while loop, which I think is a bit more logical.</p>

```<code>then_string = getStringValue()
now_string = then_string

while stop != 1:
    seconds = 0

    while then_string==now_string:
        time.sleep(1)
        seconds += 1
        now_string = getStringValue()

    if then_string in my_dict:
        my_dict[then_string] += seconds
    else:
        my_dict[then_string] = seconds

    then_string = now_string
</code>```

Body:
I'm trying to continously add a value to a dictionary's key's value, to form a sum of an old and new value.

My code checks if one string [str_1] from now is the same as a string from 1 second ago, [str_2] if it isn't, it should create a key with the key from 1 second ago, store for how long it's been on that string and move on to the next [str_?], repeating the process for a new string (creating a new key), then, if it meets any of the strings stored [str_?], it should take that key's value and add the new value on top of it, to create a sum.

seconds = 0
my_dict = {}
stop = 0

while stop != 1:

    then_string = getStringValue() #Copies a string from somewhere.
    sleep(1)
    now_string = getStringValue() #Copies a string from somewhere, note, we waited 1 sec.

    if then_string == now_string:
        seconds += 1
    elif then_string != now_string:
        my_dict[then_string] = seconds
        """This is where I'm stuck."""
        seconds = 0 #Resets the seconds.
    else:
        pass

My problem is that once I get to the elif (strings changed, alarm for adding new value), it breaks.

It only adds the value of seconds, even if I were to do something like

my_dict[then_string] = my_dict.get(then_string) + seconds

The value is a seemingly doubled number of seconds and it yields improper results.

My goal is to properly get the seconds spent on a string.

Body:
You could use a while loop, which I think is a bit more logical.

then_string = getStringValue()
now_string = then_string

while stop != 1:
    seconds = 0

    while then_string==now_string:
        time.sleep(1)
        seconds += 1
        now_string = getStringValue()

    if then_string in my_dict:
        my_dict[then_string] += seconds
    else:
        my_dict[then_string] = seconds

    then_string = now_string


问:
JavaFX TableView bold whole row iff `message.isUnread()==true`
I am trying to replicate Gmail behavior in Javafx TableView. Row of new Unread message should be shown in bold. Here is what I was able to do so far:

I can change background of the whole row, and bold a cell, but can't bold the whole row.
How to explain Javafx to do this?

```<code>for each Cell cell in tableview:
    get Message m corresponding to row.
    String style = m.isUnread() ? "
    cell.setStyle("-fx-font-weight: 800" : "-fx-font-weight: 100")

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

public class Message {
    final static public ObservableList<Message> data = FXCollections.observableArrayList(
            new Message("Bob", "Where are you?", true, true),
            new Message("Elise", "Payment", false, false),
            new Message("Charlie", "Read this book: 'Clean code'", true, true),
            new Message("Oscar", "Golf class tonight", true, false),
            new Message("Sam", "How is your TableView progress?", false, true),
            new Message("Alice", "Latte", true, true)
    );

    final private String  name;
    final private String  title;
    private boolean isUnread;
    private boolean isArchived;

    public Message(String name, String title, boolean isUnread, boolean isArchived) {
        this.name = name; this.title = title; this.isUnread = isUnread;this.isArchived = isArchived;
    }
    public String  getName()    { return name;    }
    public String  getTitle()  { return title;  }
    public boolean getIsUnread() { return isUnread; }
    public boolean getisArchived() { return isArchived; }

    public void setIsUnread(boolean isUnread) { this.isUnread = isUnread;     }
 }
</code>```

MyTable.java

```<code>import javafx.application.Application;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import javafx.util.Callback;

public class MyTable extends Application {
    public static void main(String[] args) throws Exception { launch(args); }
    public void start(final Stage stage) throws Exception {
        stage.setTitle("Inbox");

        // create a table.
        TableView<Message> table = new TableView(Message.data);
        table.getColumns().addAll(makeStringColumn("Name", "name", 150), makeStringColumn("Title", "title", 300), makeBooleanColumn("New", "isUnread", 150));
        table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
        table.setPrefHeight(250);

        stage.setScene(new Scene(table));
        stage.getScene().getStylesheets().add(getClass().getResource("message.css").toExternalForm());
        stage.show();

        // highlight the table rows depending upon whether we expect to get paid.
        int i = 0;
        for (Node n: table.lookupAll("TableRow")) {
            if (n instanceof TableRow) {
                TableRow row = (TableRow) n;
                if (table.getItems().get(i).getIsUnread()) {
                    row.getStyleClass().add("isReadRow");
                } else {
                    row.getStyleClass().add("isUnreadRow");
                }
                i++;
                if (i == table.getItems().size())
                    break;
            }
        }
    }

    private TableColumn<Message, String> makeStringColumn(String columnName, String propertyName, int prefWidth) {
        TableColumn<Message, String> column = new TableColumn<>(columnName);
        column.setCellValueFactory(new PropertyValueFactory<Message, String>(propertyName));
        column.setCellFactory(new Callback<TableColumn<Message, String>, TableCell<Message, String>>() {
            @Override public TableCell<Message, String> call(TableColumn<Message, String> soCalledFriendStringTableColumn) {
                return new TableCell<Message, String>() {
                    @Override public void updateItem(String item, boolean empty) {
                        super.updateItem(item, empty);
                        if (item != null) {
                            setText(item);
                        }
                    }
                };
            }
        });
        column.setPrefWidth(prefWidth);
        column.setSortable(false);
        return column;
    }

    private TableColumn<Message, Boolean> makeBooleanColumn(String columnName, String propertyName, int prefWidth) {
        TableColumn<Message, Boolean> column = new TableColumn<>(columnName);
        column.setCellValueFactory(new PropertyValueFactory<Message, Boolean>(propertyName));
        column.setCellFactory(new Callback<TableColumn<Message, Boolean>, TableCell<Message, Boolean>>() {
            @Override public TableCell<Message, Boolean> call(TableColumn<Message, Boolean> soCalledFriendBooleanTableColumn) {
                return new TableCell<Message, Boolean>() {
                    @Override public void updateItem(final Boolean item, final boolean empty) {
                        super.updateItem(item, empty);
                        if (item != null) {
                            setText(item.toString());
                            this.getStyleClass().add(item ? "isUnreadCell" : "isReadCell");
                        }
                    }
                };
            }
        });
        column.setPrefWidth(prefWidth);
        column.setSortable(false);
        return column;
    }
}
</code>```

(Message.css)

```<code>   .column-header-background         { -fx-background-color: azure;       }
   .isReadRow                       { -fx-background-color: palegreen;   }
   .isUnreadRow                       { -fx-background-color: yellow;       }
   .isReadCell                      { -fx-font-weight: 100 ; -fx-text-fill: darkgreen;}
   .isUnreadCell                     { -fx-font-weight: 800 ; -fx-text-fill: red;}
</code>```

答:
To bold a row associate a RowFactory as shown below.

```<code>table.setPrefHeight(250);
        table.setRowFactory(new Callback<TableView<Message>, TableRow<Message>>() {
            @Override
            public TableRow<Message> call(TableView<Message> param) {
                final TableRow<Message> row = new TableRow<Message>() {
                    @Override
                    protected void updateItem(Message row, boolean empty) {
                        super.updateItem(row, empty);
                        if (!empty)
                            styleProperty().bind(Bindings.when(row.selectedProperty())
                                    .then("-fx-font-weight: bold; -fx-font-size: 16;")
                                    .otherwise(""));
                    }
                };
                return row;
            }
        });

        stage.setScene(new Scene(table));
</code>```

In the above sample, selectedProperty() function has been called by the Message row. The selectedProperty() function returns the value of boolean variable isUnread. If the isUnread value is true then the whole row will be bolded else it won't be.

```<code> final private String  title;
    private boolean isUnread;
    private boolean isArchived;
    private BooleanProperty selected;

    public boolean getSelected() {return selected.get();}
    public BooleanProperty selectedProperty(){return selected;}

    public Message(String name, String title, boolean isUnread, boolean isArchived) {
        this.name = name; this.title = title; this.isUnread = isUnread;this.isArchived = isArchived;
        this.selected = new SimpleBooleanProperty(isUnread);
    }
</code>```

Setting the font style as bold and size to 16 gives following output:

Body:
I am trying to replicate Gmail behavior in Javafx TableView. Row of new Unread message should be shown in bold. Here is what I was able to do so far:

I can change background of the whole row, and bold a cell, but can't bold the whole row.
How to explain Javafx to do this?

for each Cell cell in tableview:
    get Message m corresponding to row.
    String style = m.isUnread() ? "
    cell.setStyle("-fx-font-weight: 800" : "-fx-font-weight: 100")

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

public class Message {
    final static public ObservableList<Message> data = FXCollections.observableArrayList(
            new Message("Bob", "Where are you?", true, true),
            new Message("Elise", "Payment", false, false),
            new Message("Charlie", "Read this book: 'Clean code'", true, true),
            new Message("Oscar", "Golf class tonight", true, false),
            new Message("Sam", "How is your TableView progress?", false, true),
            new Message("Alice", "Latte", true, true)
    );

    final private String  name;
    final private String  title;
    private boolean isUnread;
    private boolean isArchived;

    public Message(String name, String title, boolean isUnread, boolean isArchived) {
        this.name = name; this.title = title; this.isUnread = isUnread;this.isArchived = isArchived;
    }
    public String  getName()    { return name;    }
    public String  getTitle()  { return title;  }
    public boolean getIsUnread() { return isUnread; }
    public boolean getisArchived() { return isArchived; }

    public void setIsUnread(boolean isUnread) { this.isUnread = isUnread;     }
 }

MyTable.java

import javafx.application.Application;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import javafx.util.Callback;

public class MyTable extends Application {
    public static void main(String[] args) throws Exception { launch(args); }
    public void start(final Stage stage) throws Exception {
        stage.setTitle("Inbox");

        // create a table.
        TableView<Message> table = new TableView(Message.data);
        table.getColumns().addAll(makeStringColumn("Name", "name", 150), makeStringColumn("Title", "title", 300), makeBooleanColumn("New", "isUnread", 150));
        table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
        table.setPrefHeight(250);

        stage.setScene(new Scene(table));
        stage.getScene().getStylesheets().add(getClass().getResource("message.css").toExternalForm());
        stage.show();

        // highlight the table rows depending upon whether we expect to get paid.
        int i = 0;
        for (Node n: table.lookupAll("TableRow")) {
            if (n instanceof TableRow) {
                TableRow row = (TableRow) n;
                if (table.getItems().get(i).getIsUnread()) {
                    row.getStyleClass().add("isReadRow");
                } else {
                    row.getStyleClass().add("isUnreadRow");
                }
                i++;
                if (i == table.getItems().size())
                    break;
            }
        }
    }

    private TableColumn<Message, String> makeStringColumn(String columnName, String propertyName, int prefWidth) {
        TableColumn<Message, String> column = new TableColumn<>(columnName);
        column.setCellValueFactory(new PropertyValueFactory<Message, String>(propertyName));
        column.setCellFactory(new Callback<TableColumn<Message, String>, TableCell<Message, String>>() {
            @Override public TableCell<Message, String> call(TableColumn<Message, String> soCalledFriendStringTableColumn) {
                return new TableCell<Message, String>() {
                    @Override public void updateItem(String item, boolean empty) {
                        super.updateItem(item, empty);
                        if (item != null) {
                            setText(item);
                        }
                    }
                };
            }
        });
        column.setPrefWidth(prefWidth);
        column.setSortable(false);
        return column;
    }

    private TableColumn<Message, Boolean> makeBooleanColumn(String columnName, String propertyName, int prefWidth) {
        TableColumn<Message, Boolean> column = new TableColumn<>(columnName);
        column.setCellValueFactory(new PropertyValueFactory<Message, Boolean>(propertyName));
        column.setCellFactory(new Callback<TableColumn<Message, Boolean>, TableCell<Message, Boolean>>() {
            @Override public TableCell<Message, Boolean> call(TableColumn<Message, Boolean> soCalledFriendBooleanTableColumn) {
                return new TableCell<Message, Boolean>() {
                    @Override public void updateItem(final Boolean item, final boolean empty) {
                        super.updateItem(item, empty);
                        if (item != null) {
                            setText(item.toString());
                            this.getStyleClass().add(item ? "isUnreadCell" : "isReadCell");
                        }
                    }
                };
            }
        });
        column.setPrefWidth(prefWidth);
        column.setSortable(false);
        return column;
    }
}

(Message.css)

   .column-header-background         { -fx-background-color: azure;       }
   .isReadRow                       { -fx-background-color: palegreen;   }
   .isUnreadRow                       { -fx-background-color: yellow;       }
   .isReadCell                      { -fx-font-weight: 100 ; -fx-text-fill: darkgreen;}
   .isUnreadCell                     { -fx-font-weight: 800 ; -fx-text-fill: red;}

Body:
To bold a row associate a RowFactory as shown below.

table.setPrefHeight(250);
        table.setRowFactory(new Callback<TableView<Message>, TableRow<Message>>() {
            @Override
            public TableRow<Message> call(TableView<Message> param) {
                final TableRow<Message> row = new TableRow<Message>() {
                    @Override
                    protected void updateItem(Message row, boolean empty) {
                        super.updateItem(row, empty);
                        if (!empty)
                            styleProperty().bind(Bindings.when(row.selectedProperty())
                                    .then("-fx-font-weight: bold; -fx-font-size: 16;")
                                    .otherwise(""));
                    }
                };
                return row;
            }
        });

        stage.setScene(new Scene(table));

In the above sample, selectedProperty() function has been called by the Message row. The selectedProperty() function returns the value of boolean variable isUnread. If the isUnread value is true then the whole row will be bolded else it won't be.

 final private String  title;
    private boolean isUnread;
    private boolean isArchived;
    private BooleanProperty selected;

    public boolean getSelected() {return selected.get();}
    public BooleanProperty selectedProperty(){return selected;}

    public Message(String name, String title, boolean isUnread, boolean isArchived) {
        this.name = name; this.title = title; this.isUnread = isUnread;this.isArchived = isArchived;
        this.selected = new SimpleBooleanProperty(isUnread);
    }

Setting the font style as bold and size to 16 gives following output:


问:
Training locally with ML Engine & GCloud
I would like to train my model locally using this command:

```<code>gcloud ml-engine local train
  --module-name cloud_runner
  --job-dir ./tmp/output
</code>```

The issue is that it complains that --job-dir: Must be of form gs://bucket/object.

This is a local train so I'm wondering why it wants the output to be a gs storage bucket rather than a local directory.

答:
As explained by other gcloud --job-dir expects the location to be in GCS. To go around that you can pass it as a folder directly to your module.</p>

```<code>gcloud ml-engine local train \
    --package-path trainer \
    --module-name trainer.task \
    -- \
    --train-files $TRAIN_FILE \
    --eval-files $EVAL_FILE \
    --job-dir $JOB_DIR \
    --train-steps $TRAIN_STEPS
</code>```

Body:
I would like to train my model locally using this command:

gcloud ml-engine local train
  --module-name cloud_runner
  --job-dir ./tmp/output

The issue is that it complains that --job-dir: Must be of form gs://bucket/object.

This is a local train so I'm wondering why it wants the output to be a gs storage bucket rather than a local directory.

Body:
As explained by other gcloud --job-dir expects the location to be in GCS. To go around that you can pass it as a folder directly to your module.

gcloud ml-engine local train \
    --package-path trainer \
    --module-name trainer.task \
    -- \
    --train-files $TRAIN_FILE \
    --eval-files $EVAL_FILE \
    --job-dir $JOB_DIR \
    --train-steps $TRAIN_STEPS


问:
Change component's template Angular 2
I'm using mdl-select component. It's a drop-down list. When you press it there are focusin event fired. But it doesn't when you press an arrow-dropdown icon, so I needed to change a template a bit to have a desired behavior. But it's a library component. Is there a way to override it's template?

The thing I need to change just to add tabindex=\"-1\" to element. I can do it with js, but I use component a lot in app, and I don't want to use document.getElement... every time I use MdlSelectComponent in the views of my own components.

I tried to use @Component decorator function on MdlSelectComponent type, however it requires to declare this class once again and anyway have done nothing.

Update

main.browser.ts

```<code>/*
 * Angular bootstraping
 */
import { Component } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { decorateModuleRef } from './app/environment';
import { bootloader } from '@angularclass/hmr';

import {MdlSelectComponent} from '@angular2-mdl-ext/select';
/*
 * App Module
 * our top level module that holds all of our components
 */
import { AppModule } from './app';

/*
 * Bootstrap our Angular app with a top level NgModule
 */
export function main(): Promise<any> {
  console.log(MdlSelectComponent)
  MdlSelectComponent.decorator.template = "<div class=\"mdl-textfield is-upgraded\" [class.is-focused]=\"this.popoverComponent.isVisible || this.focused\" [class.is-disabled]=\"this.disabled\" [class.is-dirty]=\"isDirty()\"> <span [attr.tabindex]=\"!this.disabled ? 0 : null\" (focus)=\"open($event);addFocus();\" (blur)=\"removeFocus()\"> <!-- don't want click to also trigger focus --> </span> <input #selectInput tabindex=\"-1\" [readonly]=\"!autocomplete\" class=\"mdl-textfield__input\" (click)=\"toggle($event)\" (keyup)=\"onInputChange($event)\" (blur)=\"onInputBlur()\" [placeholder]=\"placeholder ? placeholder : ''\" [attr.id]=\"textfieldId\" [value]=\"text\"> <span class=\"mdl-select__toggle material-icons\" (click)=\"toggle($event)\"> keyboard_arrow_down </span> <label class=\"mdl-textfield__label\" [attr.for]=\"textfieldId\">{{ label }}</label> <span class=\"mdl-textfield__error\"></span> <mdl-popover [class.mdl-popover--above]=\"autocomplete\" hide-on-click=\"!multiple\" [style.width.%]=\"100\"> <div class=\"mdl-list mdl-shadow--6dp\"> <ng-content></ng-content> </div> </mdl-popover> </div> ";

  return platformBrowserDynamic()
    .bootstrapModule(AppModule)
    .then(decorateModuleRef)
    .catch((err) => console.error(err));
}

// needed for hmr
// in prod this is replace for document ready
bootloader(main);
</code>```

APP.COMPONENT.TS

```<code>import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { Router } from '@angular/router';
require('../../../styles/styles.scss');
import {MdlSelectComponent} from '@angular2-mdl-ext/select';
//
declare let Reflect: any;
Reflect.getOwnMetadata('annotations', MdlSelectComponent)[0].template = 'Hooray';
@Component({
    selector: 'app',
    encapsulation: ViewEncapsulation.None,
    styleUrls: [],
    template: `
        <div>
            <mdl-select [(ngModel)]="personId">
                <mdl-option *ngFor="let p of people" [value]="p.id">{{p.name}}</mdl-option>
            </mdl-select>
            <router-outlet></router-outlet>
        </div>`
})
export class AppComponent implements OnInit {
    constructor(
        router: Router,
    ) {
        router.events.subscribe(data => {
            scrollTo(0, 0);
        });
    }

    public ngOnInit() {
    }
}
</code>```

答:
As @angular2-mdl-ext/select uses Reflect to define decorators then you do the following

```<code>declare let Reflect: any;
Reflect.getOwnMetadata('annotations', MdlSelectComponent)[0].template = 'Hooray';
</code>```

Plunker Example

ContentLicense: CC BY-SA 4.0

Title: Change component's template Angular 2

Body:
I'm using mdl-select component. It's a drop-down list. When you press it there are focusin event fired. But it doesn't when you press an arrow-dropdown icon, so I needed to change a template a bit to have a desired behavior. But it's a library component. Is there a way to override it's template?

The thing I need to change just to add tabindex=\"-1\" to element. I can do it with js, but I use component a lot in app, and I don't want to use document.getElement... every time I use MdlSelectComponent in the views of my own components.

I tried to use @Component decorator function on MdlSelectComponent type, however it requires to declare this class once again and anyway have done nothing.

Update

main.browser.ts

/*
 * Angular bootstraping
 */
import { Component } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { decorateModuleRef } from './app/environment';
import { bootloader } from '@angularclass/hmr';

import {MdlSelectComponent} from '@angular2-mdl-ext/select';
/*
 * App Module
 * our top level module that holds all of our components
 */
import { AppModule } from './app';

/*
 * Bootstrap our Angular app with a top level NgModule
 */
export function main(): Promise<any> {
  console.log(MdlSelectComponent)
  MdlSelectComponent.decorator.template = "
    <input #selectInput tabindex=\"-1\" [readonly]=\"!autocomplete\" class=\"mdl-textfield__input\" (click)=\"toggle($event)\" (keyup)=\"onInputChange($event)\" (blur)=\"onInputBlur()\" [placeholder]=\"placeholder ? placeholder : ''\" [attr.id]=\"textfieldId\" [value]=\"text\">  keyboard_arrow_down  {{ label }}  <mdl-popover [class.mdl-popover--above]=\"autocomplete\" hide-on-click=\"!multiple\" [style.width.%]=\"100\">
 <ng-content></ng-content>
 </mdl-popover>
 ";

  return platformBrowserDynamic()
    .bootstrapModule(AppModule)
    .then(decorateModuleRef)
    .catch((err) => console.error(err));
}

// needed for hmr
// in prod this is replace for document ready
bootloader(main);

APP.COMPONENT.TS

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { Router } from '@angular/router';
require('../../../styles/styles.scss');
import {MdlSelectComponent} from '@angular2-mdl-ext/select';
//
declare let Reflect: any;
Reflect.getOwnMetadata('annotations', MdlSelectComponent)[0].template = 'Hooray';
@Component({
    selector: 'app',
    encapsulation: ViewEncapsulation.None,
    styleUrls: [],
    template: `

            <mdl-select [(ngModel)]="personId">
                <mdl-option *ngFor="let p of people" [value]="p.id">{{p.name}}</mdl-option>
            </mdl-select>
            <router-outlet></router-outlet>

`
})
export class AppComponent implements OnInit {
    constructor(
        router: Router,
    ) {
        router.events.subscribe(data => {
            scrollTo(0, 0);
        });
    }

    public ngOnInit() {
    }
}

Body:
As @angular2-mdl-ext/select uses Reflect to define decorators then you do the following

declare let Reflect: any;
Reflect.getOwnMetadata('annotations', MdlSelectComponent)[0].template = 'Hooray';

Plunker Example


问:
How to quickly build a two dimensional array from two arrays using FP or 3rd party library
I have two double arrays x[], y[] with equal dimension, how to quickly build a double array without loops

Double xy[][] from x, y with the second dimension be 2.

I am OK with using any third part libraries

code using loops

```<code> double xy[][] = new double[x.length][2];
 for (int i = 0; i< x.length; i++) {
            xy[i][0] = x[i];
            xy[i][1] = y[i];
 }
</code>```

To be frank, I do not like the above code. I wish there is some FP way to solve this problem.

答:
All you have to do is write the following line
double[][] xy = {x, y};

Body:
I have two double arrays x[], y[] with equal dimension, how to quickly build a double array without loops

Double xy[][] from x, y with the second dimension be 2.

I am OK with using any third part libraries

code using loops

 double xy[][] = new double[x.length][2];
 for (int i = 0; i< x.length; i++) {
            xy[i][0] = x[i];
            xy[i][1] = y[i];
 }

To be frank, I do not like the above code. I wish there is some FP way to solve this problem.


问:
How can I destroy multi-session LTTng
I created an LTTng session:

```<code># lttng create A
</code>```

then unintentionally created another session:

```<code># lttng create B
</code>```

so i destroyed the session:

```<code># lttng destroy
</code>```

however, it only destroy B. Another 'lttng destroy' only gave error.
What should I do to destroy A?

答:
You can use this command to destroy all sessions:

lttng destroy --all

Or as you found out, use the session name like this:

lttng destroy $SESSION_NAME

For more details, look up the LTTNG-DESTROY(1) man page.

Title: How can I destroy multi-session LTTng

Body:
I created an LTTng session:

# lttng create A

then unintentionally created another session:

# lttng create B

so i destroyed the session:

# lttng destroy

however, it only destroy B. Another 'lttng destroy' only gave error.
What should I do to destroy A?


问:
neo4j LOAD CSV returns Couldn't Load external resource
Trying CSV import to Neo4j - doesn't seem to be working.

I'm loading a local file using the syntax:

```<code>LOAD CSV WITH HEADERS FROM "file:///location/local/my.csv" AS csvDoc
</code>```

Am wondering if there's something wrong with my CSV file, or if there's some syntax problem here.

If you didn't read the title, the error is:

```<code>Couldn't load the external resource at: file:/location/local/my.csv
[Neo.TransientError.Statement.ExternalResourceFailure]
</code>```

答:
Easy solution:
Once you choose your database location (in my case ReactomeGraphDB60)...
here I placed my ddbb
...go to that folder, and create inside a folder called "import".

Later in the cypher query write (as an example):
LOAD CSV WITH HEADERS FROM "file:///ILClasiffStruct.csv" AS row
CREATE (n:Interleukines)
SET n = row

Body:
Trying CSV import to Neo4j - doesn't seem to be working.

I'm loading a local file using the syntax:

LOAD CSV WITH HEADERS FROM "file:///location/local/my.csv" AS csvDoc

Am wondering if there's something wrong with my CSV file, or if there's some syntax problem here.

If you didn't read the title, the error is:

Couldn't load the external resource at: file:/location/local/my.csv
[Neo.TransientError.Statement.ExternalResourceFailure]


问:
Random string in PHP not enough characters
I'm trying to make some random string in PHP with 5 letters/numbers.
It's working fine but sometimes I get a shorter string.

```<code>$characterset='ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$count=0;
$lenght=strlen($characterset);
$i=5; #number of characters
while($count < $i){
  $num=rand(1,$lenght);
  $letter=substr($characterset, $num, 1);
  $string.=$letter;
  $count++;
}
</code>```

And strlen($string) is sometimes 4  (checked 100 records, 85 was 4 characters)

答:
Thank you all for help, following code working great:

```<code>$characters='ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$string = '';
$random_string_length = 5;
$max = strlen($characters) - 1;
for ($i = 0; $i < $random_string_length; $i++) {
     $string .= $characters[mt_rand(0, $max)];
}
</code>```

Is it possible to avoid the same strings? I generated 50 000 records and had 48 the same.

Body:
I'm trying to make some random string in PHP with 5 letters/numbers.
It's working fine but sometimes I get a shorter string.

$characterset='ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$count=0;
$lenght=strlen($characterset);
$i=5; #number of characters
while($count < $i){
  $num=rand(1,$lenght);
  $letter=substr($characterset, $num, 1);
  $string.=$letter;
  $count++;
}

And strlen($string) is sometimes 4  (checked 100 records, 85 was 4 characters)

Body:
Thank you all for help, following code working great:

$characters='ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$string = '';
$random_string_length = 5;
$max = strlen($characters) - 1;
for ($i = 0; $i < $random_string_length; $i++) {
     $string .= $characters[mt_rand(0, $max)];
}

Is it possible to avoid the same strings? I generated 50 000 records and had 48 the same.


问:
iOS App crash when it comes back to previous UIViewController
I have the same issue described in this question (link) but in my case I'm using AVPlayerViewController instead MPMoviePlayerController, so I tried to apply the same logic of the answer but AVPlayer has only unknow, readyToPlay and failed status and I can't know when the Controller is closed.How can I know when the AVPlayerViewController is closed or how can I solved the same crash caused by orientation?

my ViewController orientation methods:

```<code>override var shouldAutorotate : Bool {
    return false
}

override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
    return UIInterfaceOrientationMask.portrait
}
</code>```

this is the method that opens the AVPlayerViewController:

```<code>func playVideo(at videoUrl: URL) {
    let controller = AVPlayerViewController()
    controller.player = AVPlayer(playerItem: AVPlayerItem(url: videoUrl))
    self.present(controller, animated: true, completion: {
        controller.player?.play()
    })
}
</code>```

UPDATE:

Crash log:

```<code>Fatal Exception: UIApplicationInvalidInterfaceOrientation
0  CoreFoundation                 0x183dc2fe0 __exceptionPreprocess
1  libobjc.A.dylib                0x182824538 objc_exception_throw
2  CoreFoundation                 0x183dc2f28 -[NSException initWithCoder:]
3  UIKit                          0x189fe7f78 -[UIViewController _preferredInterfaceOrientationForPresentationInWindow:fromInterfaceOrientation:]
4  UIKit                          0x18a8c5b68 -[_UIFullscreenPresentationController _adjustOrientationIfNecessaryInWindow:forViewController:preservingViewController:]
5  UIKit                          0x18a2421a4 -[UIPresentationController _dismissWithAnimationController:interactionController:target:didEndSelector:]
6  UIKit                          0x18a2689a4 -[UIViewController _dismissViewControllerWithAnimationController:interactionController:completion:]
7  UIKit                          0x18a01dc04 -[UIViewController _dismissViewControllerWithTransition:from:completion:]
8  UIKit                          0x189fc5a98 -[UIViewController dismissViewControllerWithTransition:completion:]
9  UIKit                          0x18a267c4c -[UIViewController _performCoordinatedPresentOrDismiss:animated:]
10 UIKit                          0x189fc55ec -[UIViewController dismissViewControllerAnimated:completion:]
11 AVKit                          0x191667f28 -[AVPlayerViewController(AVPlaybackControlsViewControllerActions) doneButtonTapped:]
12 AVKit                          0x19168d614 -[AVPlaybackControlsViewController doneButtonTapped:]
13 UIKit                          0x189f29010 -[UIApplication sendAction:to:from:forEvent:]
14 UIKit                          0x189f28f90 -[UIControl sendAction:to:forEvent:]
15 UIKit                          0x189f13504 -[UIControl _sendActionsForEvents:withEvent:]
16 UIKit                          0x189f28874 -[UIControl touchesEnded:withEvent:]
17 UIKit                          0x189f28390 -[UIWindow _sendTouchesForEvent:]
18 UIKit                          0x189f23728 -[UIWindow sendEvent:]
19 UIKit                          0x189ef433c -[UIApplication sendEvent:]
20 UIKit                          0x18a6ee014 __dispatchPreprocessedEventFromEventQueue
21 UIKit                          0x18a6e8770 __handleEventQueue
22 UIKit                          0x18a6e8b9c __handleHIDEventFetcherDrain
23 CoreFoundation                 0x183d7142c __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__
24 CoreFoundation                 0x183d70d9c __CFRunLoopDoSources0
25 CoreFoundation                 0x183d6e9a8 __CFRunLoopRun
26 CoreFoundation                 0x183c9eda4 CFRunLoopRunSpecific
27 GraphicsServices               0x185708074 GSEventRunModal
28 UIKit                          0x189f59058 UIApplicationMain
29 selftv                         0x10006c124 main (AppDelegate.swift:15)
30 libdyld.dylib                  0x182cad59c start
</code>```

答:
Best solution is create new UIWindow and set AVPlayerViewController as rootViewController and configure orientations for new window.

I used this solution for images gallery with landscape and portrait orientations when app is used only portrait.

Example:

```<code>UIWindow *modalWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
modalWindow.tag = kWindowTag;
modalWindow.rootViewController = <your player vc>;
[modalWindow makeKeyAndVisible];
</code>```

But you need after closing AVPlayerViewController set modalWindow.hidden = yes and call makeKeyAndVisible for previous window.

I used #import <objc/runtime.h> for overriding presentViewController:animated:completion: and dismissViewControllerAnimated:completion: and in my methods i implemented logic for showing/dismissing new window.

If you will need more examples or explanations, please let me know.
Thanks

Body:
I have the same issue described in this question (link) but in my case I'm using AVPlayerViewController instead MPMoviePlayerController, so I tried to apply the same logic of the answer but AVPlayer has only unknow, readyToPlay and failed status and I can't know when the Controller is closed.How can I know when the AVPlayerViewController is closed or how can I solved the same crash caused by orientation?

my ViewController orientation methods:

override var shouldAutorotate : Bool {
    return false
}

override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
    return UIInterfaceOrientationMask.portrait
}

this is the method that opens the AVPlayerViewController:

func playVideo(at videoUrl: URL) {
    let controller = AVPlayerViewController()
    controller.player = AVPlayer(playerItem: AVPlayerItem(url: videoUrl))
    self.present(controller, animated: true, completion: {
        controller.player?.play()
    })
}

UPDATE:

Crash log:

Fatal Exception: UIApplicationInvalidInterfaceOrientation
0  CoreFoundation                 0x183dc2fe0 __exceptionPreprocess
1  libobjc.A.dylib                0x182824538 objc_exception_throw
2  CoreFoundation                 0x183dc2f28 -[NSException initWithCoder:]
3  UIKit                          0x189fe7f78 -[UIViewController _preferredInterfaceOrientationForPresentationInWindow:fromInterfaceOrientation:]
4  UIKit                          0x18a8c5b68 -[_UIFullscreenPresentationController _adjustOrientationIfNecessaryInWindow:forViewController:preservingViewController:]
5  UIKit                          0x18a2421a4 -[UIPresentationController _dismissWithAnimationController:interactionController:target:didEndSelector:]
6  UIKit                          0x18a2689a4 -[UIViewController _dismissViewControllerWithAnimationController:interactionController:completion:]
7  UIKit                          0x18a01dc04 -[UIViewController _dismissViewControllerWithTransition:from:completion:]
8  UIKit                          0x189fc5a98 -[UIViewController dismissViewControllerWithTransition:completion:]
9  UIKit                          0x18a267c4c -[UIViewController _performCoordinatedPresentOrDismiss:animated:]
10 UIKit                          0x189fc55ec -[UIViewController dismissViewControllerAnimated:completion:]
11 AVKit                          0x191667f28 -[AVPlayerViewController(AVPlaybackControlsViewControllerActions) doneButtonTapped:]
12 AVKit                          0x19168d614 -[AVPlaybackControlsViewController doneButtonTapped:]
13 UIKit                          0x189f29010 -[UIApplication sendAction:to:from:forEvent:]
14 UIKit                          0x189f28f90 -[UIControl sendAction:to:forEvent:]
15 UIKit                          0x189f13504 -[UIControl _sendActionsForEvents:withEvent:]
16 UIKit                          0x189f28874 -[UIControl touchesEnded:withEvent:]
17 UIKit                          0x189f28390 -[UIWindow _sendTouchesForEvent:]
18 UIKit                          0x189f23728 -[UIWindow sendEvent:]
19 UIKit                          0x189ef433c -[UIApplication sendEvent:]
20 UIKit                          0x18a6ee014 __dispatchPreprocessedEventFromEventQueue
21 UIKit                          0x18a6e8770 __handleEventQueue
22 UIKit                          0x18a6e8b9c __handleHIDEventFetcherDrain
23 CoreFoundation                 0x183d7142c __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__
24 CoreFoundation                 0x183d70d9c __CFRunLoopDoSources0
25 CoreFoundation                 0x183d6e9a8 __CFRunLoopRun
26 CoreFoundation                 0x183c9eda4 CFRunLoopRunSpecific
27 GraphicsServices               0x185708074 GSEventRunModal
28 UIKit                          0x189f59058 UIApplicationMain
29 selftv                         0x10006c124 main (AppDelegate.swift:15)
30 libdyld.dylib                  0x182cad59c start

Body:
Best solution is create new UIWindow and set AVPlayerViewController as rootViewController and configure orientations for new window.

I used this solution for images gallery with landscape and portrait orientations when app is used only portrait.

Example:

UIWindow *modalWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
modalWindow.tag = kWindowTag;
modalWindow.rootViewController = <your player vc>;
[modalWindow makeKeyAndVisible];

But you need after closing AVPlayerViewController set modalWindow.hidden = yes and call makeKeyAndVisible for previous window.

I used #import <objc/runtime.h> for overriding presentViewController:animated:completion: and dismissViewControllerAnimated:completion: and in my methods i implemented logic for showing/dismissing new window.

If you will need more examples or explanations, please let me know.
Thanks


问:
Signature Reference can not be resolved (Apache Santuario)
I want to create an xml signature by use of apache santuario lib and include a custom element into the signature calculation by referencing that element. Here is what I got so far, and is working fine:

```<code>public void signXmlNode(Node n) {
    try {
        Reference qSigRef = sigFactory.newReference(
                "#SignatureProperties", sigFactory.newDigestMethod(
                        this.refAlgo, null), Collections
                        .singletonList(sigFactory.newTransform(
                                CanonicalizationMethod.EXCLUSIVE,
                                (TransformParameterSpec) null)),
                "http://uri.etsi.org/01903#SignedProperties",
                "Reference-SignedProperties-1497606229690");

        SignedInfo signedInfo = sigFactory.newSignedInfo(sigFactory
                .newCanonicalizationMethod(
                        CanonicalizationMethod.EXCLUSIVE,
                        (C14NMethodParameterSpec) null), sigFactory
                .newSignatureMethod(this.sigAlgo, null), Arrays.asList(
                qSigRef));
        Element qSig = createXades(n.getOwnerDocument());
        XMLObject xmlObject = sigFactory.newXMLObject(
                Collections.singletonList(new DOMStructure(qSig)),
                "SignatureProperties", null, null);

        KeyInfoFactory keyInfoFactory = sigFactory.getKeyInfoFactory();
        List<Object> x509Content = new ArrayList<>();
        x509Content.add(signerCert);
        X509Data xd = keyInfoFactory.newX509Data(x509Content);
        KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections
                .singletonList(xd));

        XMLSignature xmlSignature = sigFactory.newXMLSignature(signedInfo,
                keyInfo, Collections.singletonList(xmlObject), "Signature-"
                        + SIGNATURE_ID, null);
        DOMSignContext signContext = new DOMSignContext(signerKey, n);
        signContext.setDefaultNamespacePrefix("ds");
        xmlSignature.sign(signContext);
        final Transformer t = TransformerFactory.newInstance()
                .newTransformer();
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        t.setOutputProperty(OutputKeys.INDENT, "yes");
        final StringWriter w = new StringWriter();
        t.transform(new DOMSource(n), new StreamResult(w));
        System.out.println(w.toString());
    } catch (MarshalException ex) {
        log.log(Level.WARNING, "MarshalException in handler!", ex);
    } catch (XMLSignatureException ex) {
        log.log(Level.WARNING, "XMLSignatureException in handler!", ex);
    } catch (InvalidAlgorithmParameterException ex) {
        log.log(Level.SEVERE, "InvalidAlgorithmParameterException "
                + "while signing message!", ex);
        logSecurityProviders();
    } catch (NoSuchAlgorithmException ex) {
        log.log(Level.SEVERE, "NoSuchAlgorithmException "
                + "while signing message!", ex);
        logSecurityProviders();
    } catch (TransformerConfigurationException e) {
        e.printStackTrace();
    } catch (TransformerFactoryConfigurationError e) {
        e.printStackTrace();
    } catch (TransformerException e) {
        e.printStackTrace();
    }
}

private Element createXades(Document doc) {
    Element qualifyingProperties = doc.createElementNS(
            "http://uri.etsi.org/01903/v1.3.2#",
            "xades:QualifyingProperties");
    qualifyingProperties.setAttribute("Target", "#Signature-"
            + SIGNATURE_ID);
    Element signedProperties = qualifyingProperties.getOwnerDocument()
            .createElementNS("http://uri.etsi.org/01903/v1.3.2#",
                    "xades:SignedProperties");
    signedProperties.setAttribute("Id", "SignedProperties-" + SIGNATURE_ID);
    Element signedSignatureProperties = signedProperties.getOwnerDocument()
            .createElementNS("http://uri.etsi.org/01903/v1.3.2#",
                    "xades:SignedSignatureProperties");

    signedProperties.appendChild(signedSignatureProperties);
    qualifyingProperties.appendChild(signedProperties);
    return qualifyingProperties;
}
</code>```

Now, I want the reference qSigRef referring to the xml element <xades:SignedProperties Id="SignedProperties-0123456789"> rather than <Object ID="SignatureProperties">. Upon changing the URI from "#SignatureProperties" to "SignedProperties-0123456789" (as shown below):

```<code>Reference qSigRef = sigFactory.newReference(
                "#SignatureProperties", sigFactory.newDigestMethod(
                        this.refAlgo, null), Collections
                        .singletonList(sigFactory.newTransform(
                                CanonicalizationMethod.EXCLUSIVE,
                                (TransformParameterSpec) null)),
                "http://uri.etsi.org/01903#SignedProperties",
                "Reference-SignedProperties-1497606229690");
</code>```

to

```<code>Reference qSigRef = sigFactory.newReference(
                "#SignedProperties-0123456789", sigFactory.newDigestMethod(
                        this.refAlgo, null), Collections
                        .singletonList(sigFactory.newTransform(
                                CanonicalizationMethod.EXCLUSIVE,
                                (TransformParameterSpec) null)),
                "http://uri.etsi.org/01903#SignedProperties",
                "Reference-SignedProperties-1497606229690");
</code>```

an XMLSignatureException is thrown stateing:

```<code>javax.xml.crypto.dsig.XMLSignatureException: javax.xml.crypto.URIReferenceException: org.apache.xml.security.utils.resolver.ResourceResolverException:  Cannot resolve element with ID SignedProperties-0123456789
</code>```

Since, I can not find any solution nor reason why the exception is thrown I decided to ask this question over here.

答:
I solved the issue.

I had to register the id attribute of the SignedProperties element.

This is archived implcitly by calling setIdAttributeNS() of the related Element:

```<code>Element signedProperties = qualifyingProperties.getOwnerDocument()
                .createElementNS("http://uri.etsi.org/01903/v1.3.2#",
                        "xades:SignedProperties");
        signedProperties.setAttributeNS("", "Id", "SignedProperties-"
                + SIGNATURE_ID);//Set ID attribute

        signedProperties.setIdAttributeNS("", "Id", true);//register attribute as id
</code>```

Body:
I want to create an xml signature by use of apache santuario lib and include a custom element into the signature calculation by referencing that element. Here is what I got so far, and is working fine:

public void signXmlNode(Node n) {
    try {
        Reference qSigRef = sigFactory.newReference(
                "#SignatureProperties", sigFactory.newDigestMethod(
                        this.refAlgo, null), Collections
                        .singletonList(sigFactory.newTransform(
                                CanonicalizationMethod.EXCLUSIVE,
                                (TransformParameterSpec) null)),
                "http://uri.etsi.org/01903#SignedProperties",
                "Reference-SignedProperties-1497606229690");

        SignedInfo signedInfo = sigFactory.newSignedInfo(sigFactory
                .newCanonicalizationMethod(
                        CanonicalizationMethod.EXCLUSIVE,
                        (C14NMethodParameterSpec) null), sigFactory
                .newSignatureMethod(this.sigAlgo, null), Arrays.asList(
                qSigRef));
        Element qSig = createXades(n.getOwnerDocument());
        XMLObject xmlObject = sigFactory.newXMLObject(
                Collections.singletonList(new DOMStructure(qSig)),
                "SignatureProperties", null, null);

        KeyInfoFactory keyInfoFactory = sigFactory.getKeyInfoFactory();
        List<Object> x509Content = new ArrayList<>();
        x509Content.add(signerCert);
        X509Data xd = keyInfoFactory.newX509Data(x509Content);
        KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections
                .singletonList(xd));

        XMLSignature xmlSignature = sigFactory.newXMLSignature(signedInfo,
                keyInfo, Collections.singletonList(xmlObject), "Signature-"
                        + SIGNATURE_ID, null);
        DOMSignContext signContext = new DOMSignContext(signerKey, n);
        signContext.setDefaultNamespacePrefix("ds");
        xmlSignature.sign(signContext);
        final Transformer t = TransformerFactory.newInstance()
                .newTransformer();
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        t.setOutputProperty(OutputKeys.INDENT, "yes");
        final StringWriter w = new StringWriter();
        t.transform(new DOMSource(n), new StreamResult(w));
        System.out.println(w.toString());
    } catch (MarshalException ex) {
        log.log(Level.WARNING, "MarshalException in handler!", ex);
    } catch (XMLSignatureException ex) {
        log.log(Level.WARNING, "XMLSignatureException in handler!", ex);
    } catch (InvalidAlgorithmParameterException ex) {
        log.log(Level.SEVERE, "InvalidAlgorithmParameterException "
                + "while signing message!", ex);
        logSecurityProviders();
    } catch (NoSuchAlgorithmException ex) {
        log.log(Level.SEVERE, "NoSuchAlgorithmException "
                + "while signing message!", ex);
        logSecurityProviders();
    } catch (TransformerConfigurationException e) {
        e.printStackTrace();
    } catch (TransformerFactoryConfigurationError e) {
        e.printStackTrace();
    } catch (TransformerException e) {
        e.printStackTrace();
    }
}

private Element createXades(Document doc) {
    Element qualifyingProperties = doc.createElementNS(
            "http://uri.etsi.org/01903/v1.3.2#",
            "xades:QualifyingProperties");
    qualifyingProperties.setAttribute("Target", "#Signature-"
            + SIGNATURE_ID);
    Element signedProperties = qualifyingProperties.getOwnerDocument()
            .createElementNS("http://uri.etsi.org/01903/v1.3.2#",
                    "xades:SignedProperties");
    signedProperties.setAttribute("Id", "SignedProperties-" + SIGNATURE_ID);
    Element signedSignatureProperties = signedProperties.getOwnerDocument()
            .createElementNS("http://uri.etsi.org/01903/v1.3.2#",
                    "xades:SignedSignatureProperties");

    signedProperties.appendChild(signedSignatureProperties);
    qualifyingProperties.appendChild(signedProperties);
    return qualifyingProperties;
}

Now, I want the reference qSigRef referring to the xml element <xades:SignedProperties Id="SignedProperties-0123456789"> rather than <Object ID="SignatureProperties">. Upon changing the URI from "#SignatureProperties" to "SignedProperties-0123456789" (as shown below):

Reference qSigRef = sigFactory.newReference(
                "#SignatureProperties", sigFactory.newDigestMethod(
                        this.refAlgo, null), Collections
                        .singletonList(sigFactory.newTransform(
                                CanonicalizationMethod.EXCLUSIVE,
                                (TransformParameterSpec) null)),
                "http://uri.etsi.org/01903#SignedProperties",
                "Reference-SignedProperties-1497606229690");

to

Reference qSigRef = sigFactory.newReference(
                "#SignedProperties-0123456789", sigFactory.newDigestMethod(
                        this.refAlgo, null), Collections
                        .singletonList(sigFactory.newTransform(
                                CanonicalizationMethod.EXCLUSIVE,
                                (TransformParameterSpec) null)),
                "http://uri.etsi.org/01903#SignedProperties",
                "Reference-SignedProperties-1497606229690");

an XMLSignatureException is thrown stateing:

javax.xml.crypto.dsig.XMLSignatureException: javax.xml.crypto.URIReferenceException: org.apache.xml.security.utils.resolver.ResourceResolverException:  Cannot resolve element with ID SignedProperties-0123456789

Since, I can not find any solution nor reason why the exception is thrown I decided to ask this question over here.

Body:
I solved the issue.

I had to register the id attribute of the SignedProperties element.

This is archived implcitly by calling setIdAttributeNS() of the related Element:

Element signedProperties = qualifyingProperties.getOwnerDocument()
                .createElementNS("http://uri.etsi.org/01903/v1.3.2#",
                        "xades:SignedProperties");
        signedProperties.setAttributeNS("", "Id", "SignedProperties-"
                + SIGNATURE_ID);//Set ID attribute

        signedProperties.setIdAttributeNS("", "Id", true);//register attribute as id


问:
Parallax Sliding long movieclip Animate CC and TweenJs
I'm creating a sliding movieclip in Animate CC. I have a movie clip that is 19200 pixels wide. How can I TweenJS the movieclip 1920 to the left when the right arrow is clicked and TweenJS the same movieclip 1920 to the right when the left arrow is clicked?

Here is what I have so far in Animate CC HTML5 Canvas:

```<code>/* Mouse Click Event
Clicking on the specified symbol instance executes a function in which you can add your own custom code.
*/

this.next.addEventListener("click", fl_MouseClickHandler.bind(this));

function fl_MouseClickHandler()
{
    createjs.Tween.get(this.movieClip_1).to({x:-1920}, 500, Ease.getPowIn(2.2))
}

this.prev.addEventListener("click", fl_MouseClickHandler.bind(this));

function fl_MouseClickHandler()
{
    createjs.Tween.get(this.movieClip_1).to({x:1920}, 500, Ease.getPowIn(2.2))
}
</code>```

答:
1) In your code, you have two functions named equally, but with different code inside. The same name is specified on the listener-adding code. Because of that, both listeners will be linked to just one of the functions (specifically, the second one, for being the last one declared).

```<code>this.next.addEventListener("click", fl_MouseClickHandler.bind(this));

function fl_MouseClickHandler()
{
    /* Code */
}

this.prev.addEventListener("click", fl_MouseClickHandler.bind(this));

function fl_MouseClickHandler()
{
    /* Code */
}
</code>```

To solve that, changing the names of both functions will be enough. Of course, you'll have to change the names in the listener-adding code.

nextMouseClickHandler()

```<code>this.next.addEventListener("click", nextMouseClickHandler.bind(this));

function nextMouseClickHandler() {
    /* Code */
}
</code>```

prevMouseClickHandler()

```<code>this.prev.addEventListener("click", prevMouseClickHandler.bind(this));

function prevMouseClickHandler() {
    /* Code */
}
</code>```

2) On the to method of the Tweens in both functions, in the ease parameter, before specifying the ease, you need to add createjs:

Tween in nextMouseClickHandler()

```<code>createjs.Tween.get(this.movieClip_1).to({x:-1920}, 500, createjs.Ease.getPowIn(2.2));
</code>```

Tween in prevMouseClickHandler()

```<code>createjs.Tween.get(this.movieClip_1).to({x:1920}, 500, createjs.Ease.getPowIn(2.2));
</code>```

Solving both issues will result in the following code:

```<code>this.next.addEventListener("click", nextMouseClickHandler.bind(this));

function nextMouseClickHandler() {
    createjs.Tween.get(this.movieClip_1).to({x:-1920}, 500, createjs.Ease.getPowIn(2.2));
}

this.prev.addEventListener("click", prevMouseClickHandler.bind(this));

function prevMouseClickHandler() {
    createjs.Tween.get(this.movieClip_1).to({x:1920}, 500, createjs.Ease.getPowIn(2.2));
}
</code>```

This code works in Animate CC, replicating the MovieClip names you specified.

Body:
I'm creating a sliding movieclip in Animate CC. I have a movie clip that is 19200 pixels wide. How can I TweenJS the movieclip 1920 to the left when the right arrow is clicked and TweenJS the same movieclip 1920 to the right when the left arrow is clicked?

Here is what I have so far in Animate CC HTML5 Canvas:

/* Mouse Click Event
Clicking on the specified symbol instance executes a function in which you can add your own custom code.
*/

this.next.addEventListener("click", fl_MouseClickHandler.bind(this));

function fl_MouseClickHandler()
{
    createjs.Tween.get(this.movieClip_1).to({x:-1920}, 500, Ease.getPowIn(2.2))
}

this.prev.addEventListener("click", fl_MouseClickHandler.bind(this));

function fl_MouseClickHandler()
{
    createjs.Tween.get(this.movieClip_1).to({x:1920}, 500, Ease.getPowIn(2.2))
}

Body:
1) In your code, you have two functions named equally, but with different code inside. The same name is specified on the listener-adding code. Because of that, both listeners will be linked to just one of the functions (specifically, the second one, for being the last one declared).

this.next.addEventListener("click", fl_MouseClickHandler.bind(this));

function fl_MouseClickHandler()
{
    /* Code */
}

this.prev.addEventListener("click", fl_MouseClickHandler.bind(this));

function fl_MouseClickHandler()
{
    /* Code */
}

To solve that, changing the names of both functions will be enough. Of course, you'll have to change the names in the listener-adding code.

nextMouseClickHandler()

this.next.addEventListener("click", nextMouseClickHandler.bind(this));

function nextMouseClickHandler() {
    /* Code */
}

prevMouseClickHandler()

this.prev.addEventListener("click", prevMouseClickHandler.bind(this));

function prevMouseClickHandler() {
    /* Code */
}

2) On the to method of the Tweens in both functions, in the ease parameter, before specifying the ease, you need to add createjs:

Tween in nextMouseClickHandler()

createjs.Tween.get(this.movieClip_1).to({x:-1920}, 500, createjs.Ease.getPowIn(2.2));

Tween in prevMouseClickHandler()

createjs.Tween.get(this.movieClip_1).to({x:1920}, 500, createjs.Ease.getPowIn(2.2));

Solving both issues will result in the following code:

this.next.addEventListener("click", nextMouseClickHandler.bind(this));

function nextMouseClickHandler() {
    createjs.Tween.get(this.movieClip_1).to({x:-1920}, 500, createjs.Ease.getPowIn(2.2));
}

this.prev.addEventListener("click", prevMouseClickHandler.bind(this));

function prevMouseClickHandler() {
    createjs.Tween.get(this.movieClip_1).to({x:1920}, 500, createjs.Ease.getPowIn(2.2));
}

This code works in Animate CC, replicating the MovieClip names you specified.


问:
ML-Engine with GPUs workers errors
Hi I am using ML Engine with a custom tier made up of a complex_m master, four workers each with a GPU and one complex_m as parameter server.

The model is training a CNN. However, there seem to be trouble with the workers.
This is an image of the logs https://i.stack.imgur.com/VJqE0.png.

The master still seems to be working because there are session checkpoints being saved, however, this is nowwhere near the speed it should be.

With complex_m workers, the model works. It just gives a waiting for the model to be ready in the beginning (i assume it is until the master intializes global variables, correct me if i am wrong) and then works normally. With GPUs however there seem to be a problem with the task.

I didnt' use the tf.Device() function anywhere, in the cloud i thought the device is set automatically if a GPU is available.

I followed the Census example and loaded the TF_CONFIG environment variable.

```<code>tf.logging.info('Setting up the server')
tf_config = os.environ.get('TF_CONFIG')

# If TF_CONFIG is not available run local
if not tf_config:
    return run('', True, *args, **kwargs)

tf_config_json = json.loads(tf_config)

cluster = tf_config_json.get('cluster')
job_name = tf_config_json.get('task', {}).get('type')
task_index = tf_config_json.get('task', {}).get('index')

# If cluster information is empty run local
if job_name is None or task_index is None:
    return run('', True, *args, **kwargs)

cluster_spec = tf.train.ClusterSpec(cluster)
server = tf.train.Server(cluster_spec,
                         job_name=job_name,
                         task_index=task_index)

# Wait for incoming connections forever
# Worker ships the graph to the ps server
# The ps server manages the parameters of the model.
if job_name == 'ps':
    server.join()
    return
elif job_name in ['master', 'worker']:
    return run(server.target, job_name == 'master', *args, **kwargs)
</code>```

Then used the tf.replica_device_setter before defining the main graph.

As a session i am using tf.train.MonitoredTrainingSession, this should handle the initialization of variables and checkpoint saving. I do not know why the workers are saying that the variables are not initialized.

Variables to be initialized are all variables: https://i.stack.imgur.com/hAHPL.png

Optimizer: AdaDelta

I appreciate the help!

答:
In the comments, you seem to have answered your own question (using cluster_spec in replica_setter). Allow me to address the issue of throughput of a cluster of CPUs vs. a cluster of GPUs.

GPUs are fairly powerful. You'll typically get higher throughput by getting a single machine with many GPUs rather than having many machines each with a single GPU. That's because the communication overhead becomes a bottleneck (the bandwidth and latency to main memory on the same machine is much better than communicating with a parameter server on a remote machine).

The reason for the GPUs being slower than CPUs may be due to the extra overhead of GPUs needing to copy data from main memory to the GPU and back. If you're doing a lot of parallelizable computation, then this copy is negligible. Your model may be doing too little on the GPU and the overhead may swamp the actual computation.

For more information about building high performance models, see this guide.

In the meantime, I recommend using a single machine with more GPUs to see if that helps:

```<code>{
  "scaleTier": "CUSTOM",
  "masterType": "complex_model_l_gpu",
  ...
}
</code>```

Just beware, that you'll have to modify your code to assign ops to the right GPUs, probably using towers.

Title: ML-Engine with GPUs workers errors

Body:
Hi I am using ML Engine with a custom tier made up of a complex_m master, four workers each with a GPU and one complex_m as parameter server.

The model is training a CNN. However, there seem to be trouble with the workers.
This is an image of the logs https://i.stack.imgur.com/VJqE0.png.

The master still seems to be working because there are session checkpoints being saved, however, this is nowwhere near the speed it should be.

With complex_m workers, the model works. It just gives a waiting for the model to be ready in the beginning (i assume it is until the master intializes global variables, correct me if i am wrong) and then works normally. With GPUs however there seem to be a problem with the task.

I didnt' use the tf.Device() function anywhere, in the cloud i thought the device is set automatically if a GPU is available.

I followed the Census example and loaded the TF_CONFIG environment variable.

tf.logging.info('Setting up the server')
tf_config = os.environ.get('TF_CONFIG')

# If TF_CONFIG is not available run local
if not tf_config:
    return run('', True, *args, **kwargs)

tf_config_json = json.loads(tf_config)

cluster = tf_config_json.get('cluster')
job_name = tf_config_json.get('task', {}).get('type')
task_index = tf_config_json.get('task', {}).get('index')

# If cluster information is empty run local
if job_name is None or task_index is None:
    return run('', True, *args, **kwargs)

cluster_spec = tf.train.ClusterSpec(cluster)
server = tf.train.Server(cluster_spec,
                         job_name=job_name,
                         task_index=task_index)

# Wait for incoming connections forever
# Worker ships the graph to the ps server
# The ps server manages the parameters of the model.
if job_name == 'ps':
    server.join()
    return
elif job_name in ['master', 'worker']:
    return run(server.target, job_name == 'master', *args, **kwargs)

Then used the tf.replica_device_setter before defining the main graph.

As a session i am using tf.train.MonitoredTrainingSession, this should handle the initialization of variables and checkpoint saving. I do not know why the workers are saying that the variables are not initialized.

Variables to be initialized are all variables: https://i.stack.imgur.com/hAHPL.png

Optimizer: AdaDelta

I appreciate the help!

Body:
In the comments, you seem to have answered your own question (using cluster_spec in replica_setter). Allow me to address the issue of throughput of a cluster of CPUs vs. a cluster of GPUs.

GPUs are fairly powerful. You'll typically get higher throughput by getting a single machine with many GPUs rather than having many machines each with a single GPU. That's because the communication overhead becomes a bottleneck (the bandwidth and latency to main memory on the same machine is much better than communicating with a parameter server on a remote machine).

The reason for the GPUs being slower than CPUs may be due to the extra overhead of GPUs needing to copy data from main memory to the GPU and back. If you're doing a lot of parallelizable computation, then this copy is negligible. Your model may be doing too little on the GPU and the overhead may swamp the actual computation.

For more information about building high performance models, see this guide.

In the meantime, I recommend using a single machine with more GPUs to see if that helps:

{
  "scaleTier": "CUSTOM",
  "masterType": "complex_model_l_gpu",
  ...
}

Just beware, that you'll have to modify your code to assign ops to the right GPUs, probably using towers.


问:
use addEventListener to replace each onClick
I have unordered lists below for fruits, animals, trees....about 100 buttons with same class:

```<code><ul>
   <li><button class="bb" value="apple" onClick="aJax(value)">Apple</button></li>
   <li>Banana
      <ul>
         <li><button class="bb" value="green_banana" onClick="aJax(value)">Green_banana</button></li>
         <li><button class="bb" value="yellow_banana" onClick="aJax(value)">Yellow Banana</button></li>
      </ul>
   </li>
   <li><button class="bb" value="cherry" onClick="aJax(value)">Cherry</button></li>
   <li><button class="bb" value="cow..................and more....
</ul>
</code>```

If clicked, I want to pass value to Ajax to return data from mySql:

```<code>  <script>
  function aJax(value)
      xmlhttp = new XMLHttpRequest();
      xmlhttp.open("GET","some_page.php?q="+value,true);
      xmlhttp.send();
      xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
       document.getElementById("some_id").innerHTML = xmlhttp.responseText;}
                                                }
                 }
  </script>
</code>```

Is it possible to use addEventListener in my case above to replace each onClick? How to do it if I want to put the JS code on the header? Pls help, I need it in native JS. Thanks.

答:
the simplest way (no loops needed)

var container = document.querySelector("ul");
container.addEventListener("click", doSomething, false);

function doSomething(e) {
    if (e.target !== e.currentTarget) {
        var clickedItem = e.target.value;
        console.log(clickedItem);
    }
    e.stopPropagation();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
   <li><button class="bb" value="apple" >Apple</button></li>
   <li><button class="bb" value="banana">Banana</button></li>
   <li><button class="bb" value="cherry">Cherry</button></li>
</ul></code>```

check this awesome article, I'm pretty sure it's what you're looking for Handling Events for Many Elements

Body:
I have unordered lists below for fruits, animals, trees....about 100 buttons with same class:

<button class="bb" value="apple" onClick="aJax(value)">Apple</button>

Banana

<button class="bb" value="green_banana" onClick="aJax(value)">Green_banana</button>

<button class="bb" value="yellow_banana" onClick="aJax(value)">Yellow Banana</button>

<button class="bb" value="cherry" onClick="aJax(value)">Cherry</button>

<button class="bb" value="cow..................and more....

If clicked, I want to pass value to Ajax to return data from mySql:

Is it possible to use addEventListener in my case above to replace each onClick? How to do it if I want to put the JS code on the header? Pls help, I need it in native JS. Thanks.

Body:
the simplest way (no loops needed)

var container = document.querySelector("ul");
container.addEventListener("click", doSomething, false);

function doSomething(e) {
    if (e.target !== e.currentTarget) {
        var clickedItem = e.target.value;
        console.log(clickedItem);
    }
    e.stopPropagation();
}

<ul>
   <li><button class="bb" value="apple" >Apple</button></li>
   <li><button class="bb" value="banana">Banana</button></li>
   <li><button class="bb" value="cherry">Cherry</button></li>
</ul>

check this awesome article, I'm pretty sure it's what you're looking for Handling Events for Many Elements