问:
How i can send data between controllers AngularJS
How i can send data between controllers AngularJS in my occasion?
I wanna send result of scanned qr code into things[] and,of course, show it.
I'm beginner in AngularJS and JavaScript and making this program just for me

App.js:

var MKscanner = angular.module('starter', ['ionic', 'ngCordova', 'ngStorage'])

MKscanner.controller('scanBarCtrl', function($scope, $cordovaBarcodeScanner) {

$scope.input ={
  MyText : ''
};

  $scope.scanBarcode = function() {
    $cordovaBarcodeScanner.scan(
      {
        preferFrontCamera : false,
        orientation : 'portrait'
      }).then(function (result) {
        alert(result.text);
              },
      function (error) {
        alert('Scanning failed: ' + error);
      });
  };

});

MKscanner.factory ('StorageService', function ($localStorage) {

  $localStorage = $localStorage.$default({
    things: []
  });

  var _getAll = function () {
    return $localStorage.things;
  };

  var _add = function (thing) {
    $localStorage.things.push(thing);
  }

  var _remove = function (thing) {
    $localStorage.things.splice($localStorage.things.indexOf(thing), 1);
  }

  return {
    getAll: _getAll,
    add: _add,
    remove: _remove
  };
});

MKscanner.controller( 'MainCtrl', function ($scope, StorageService) {
  $scope.things = StorageService.getAll();

  $scope.add = function (newThing) {
    StorageService.add(newThing);
      };

  $scope.remove = function (thing) {
    StorageService.remove(thing);
  };
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div ng-controller="MainCtrl">
            <div class="list">
                <div class="item item-input-inset">
                    <label class="item-input-wrapper">
                        <input type="text" placeholder="Save your own text" ng-model="newThing">
                    </label>
                    <button class="button button-clear button-positive icon" ng-click="add(newThing)">
                        <i class="ion-ios-plus-outline"></i> Add
                    </button>
                </div>
            </div>

            <ion-list show-delete="false" can-swipe="true">
                <ion-item ng-repeat="thing in things">
                    {{thing}}
                    <ion-option-button class="button-assertive ion-trash-b" ng-click="remove(thing)"></ion-option-button>
                </ion-item>
            </ion-list>
            </div></code>```

答:
You can share data between controllers using $emit and $broadcast :
These events can be used to send data as well, The classic example is given below. You can share data any controller in the app.</p>

```<code>                <div ng-app="myApp" ng-controller="myCtrl">
                <button ng-click="sendData();"></button>
            </div>

            <script>
                var app = angular.module('myApp', []);
                app.controller('myCtrl', function($scope, $http) {
                    function sendData($scope) {
                        var arrayData = [1,2,3];
                        $scope.$emit('someEvent', arrayData);
                    }

                });
                app.controller('yourCtrl', function($scope, $http) {
                    $scope.$on('someEvent', function(event, data) {
                        console.log(data);
                    });
                });
            </script>
</code>```

Body:
How i can send data between controllers AngularJS in my occasion?
I wanna send result of scanned qr code into things[] and,of course, show it.
I'm beginner in AngularJS and JavaScript and making this program just for me

App.js:

var MKscanner = angular.module('starter', ['ionic', 'ngCordova', 'ngStorage'])

MKscanner.controller('scanBarCtrl', function($scope, $cordovaBarcodeScanner) {

$scope.input ={
  MyText : ''
};

  $scope.scanBarcode = function() {
    $cordovaBarcodeScanner.scan(
      {
        preferFrontCamera : false,
        orientation : 'portrait'
      }).then(function (result) {
        alert(result.text);
              },
      function (error) {
        alert('Scanning failed: ' + error);
      });
  };

});

MKscanner.factory ('StorageService', function ($localStorage) {

  $localStorage = $localStorage.$default({
    things: []
  });

  var _getAll = function () {
    return $localStorage.things;
  };

  var _add = function (thing) {
    $localStorage.things.push(thing);
  }

  var _remove = function (thing) {
    $localStorage.things.splice($localStorage.things.indexOf(thing), 1);
  }

  return {
    getAll: _getAll,
    add: _add,
    remove: _remove
  };
});

MKscanner.controller( 'MainCtrl', function ($scope, StorageService) {
  $scope.things = StorageService.getAll();

  $scope.add = function (newThing) {
    StorageService.add(newThing);
      };

  $scope.remove = function (thing) {
    StorageService.remove(thing);
  };
});

                        <input type="text" placeholder="Save your own text" ng-model="newThing">

                    <button class="button button-clear button-positive icon" ng-click="add(newThing)">
                         Add
                    </button>

            <ion-list show-delete="false" can-swipe="true">
                <ion-item ng-repeat="thing in things">
                    {{thing}}
                    <ion-option-button class="button-assertive ion-trash-b" ng-click="remove(thing)"></ion-option-button>
                </ion-item>
            </ion-list>

Body:
You can share data between controllers using $emit and $broadcast :
These events can be used to send data as well, The classic example is given below. You can share data any controller in the app.

                <div ng-app="myApp" ng-controller="myCtrl">
                <button ng-click="sendData();"></button>
            </div>

            <script>
                var app = angular.module('myApp', []);
                app.controller('myCtrl', function($scope, $http) {
                    function sendData($scope) {
                        var arrayData = [1,2,3];
                        $scope.$emit('someEvent', arrayData);
                    }

                });
                app.controller('yourCtrl', function($scope, $http) {
                    $scope.$on('someEvent', function(event, data) {
                        console.log(data);
                    });
                });
            </script>


来源: stackexchange

问:
MYSQL SELECT WITH LEFT JOIN LIMIT 1
I have a problem:
I want to select all babble-rooms where user1 or user2 are a specific user id. (SELECT * FROM babble WHERE user1 = '$user' OR user2 = '$user')

But I also want to get the last entry of babble_messages where the babble ID is equal to babble_id.

My database structure:

Table babble:

     ID | user1 | user2 | created

Table babble_messages:

     ID | sender | babble_id | created | seen | message

My attempt is:

```<code>SELECT
    *
FROM
    babble
LEFT JOIN (
    SELECT
        babble_messages.ID AS last_id,
        babble_messages.sender AS last_sender,
        babble_messages.babble_id,
        babble_messages.created AS last_created,
        babble_messages.seen AS last_seen,
        babble_messages.message AS last_message
    FROM
        babble_messages
    ORDER BY
        created DESC LIMIT 1
    ) babble_messages ON
    babble.ID = babble_messages.babble_id
WHERE
    user1 = '$user' OR user2 = '$user'
ORDER BY
    last_created DESC
</code>```

This outputs empty entries for the LEFT JOIN table. I think this happens because I select in the subquery just the last entry of babble_messages...
I tried to add a WHERE tag into the subquery but that throws an error:

```<code>SELECT
    *
FROM
    babble
LEFT JOIN (
    SELECT
        babble_messages.ID AS last_id,
        babble_messages.sender AS last_sender,
        babble_messages.babble_id,
        babble_messages.created AS last_created,
        babble_messages.seen AS last_seen,
        babble_messages.message AS last_message
    FROM
        babble_messages
    WHERE
        babble.ID = babble_messages.babble_id*
    ORDER BY
        created DESC
    LIMIT
        1
    ) babble_messages ON
    babble.ID = babble_messages.babble_id
WHERE
    user1 = '$user' OR user2 = '$user'
ORDER BY
    last_created DESC
</code>```

In the subquery mysql does not know the "babble.ID".
How can I select just the last entry of babble_messages?

Of course I can use multiple request but I want to make just one request, because it is faster.

I hope this is enough information. :D
Thanks for reading and hopefully answering :)

Have a nice day hadome

答:
This may be somewhat slow if the number of users is massive, especially with the OR in there. </p>

```<code>SELECT
    ID
    ,user1
    ,user2
    ,created
    ,last_id
    ,last_sender
    ,babble_id
    ,last_created
    ,last_seen
    ,last_message
FROM
(
    SELECT
        ID
        ,user1
        ,user2
        ,created
        ,(SELECT ID FROM babble_messages WHERE babble_ID = user1 ORDER BY created DESC LIMIT 1) AS babble_message_id
    FROM babble
    WHERE user1 = 1
) a
LEFT JOIN (
    SELECT
        ID last_id
        ,sender last_sender
        ,babble_id
        ,created last_created
        ,seen last_seen
        ,message last_message
    FROM babble_messages
) b ON a.babble_message_id = b.last_id
ORDER BY last_created DESC
</code>```

ContentLicense: CC BY-SA 3.0

Title: MYSQL SELECT WITH LEFT JOIN LIMIT 1

Body:
I have a problem:
I want to select all babble-rooms where user1 or user2 are a specific user id. (SELECT * FROM babble WHERE user1 = '$user' OR user2 = '$user')

But I also want to get the last entry of babble_messages where the babble ID is equal to babble_id.

My database structure:

Table babble:

     ID | user1 | user2 | created

Table babble_messages:

     ID | sender | babble_id | created | seen | message

My attempt is:

SELECT
    *
FROM
    babble
LEFT JOIN (
    SELECT
        babble_messages.ID AS last_id,
        babble_messages.sender AS last_sender,
        babble_messages.babble_id,
        babble_messages.created AS last_created,
        babble_messages.seen AS last_seen,
        babble_messages.message AS last_message
    FROM
        babble_messages
    ORDER BY
        created DESC LIMIT 1
    ) babble_messages ON
    babble.ID = babble_messages.babble_id
WHERE
    user1 = '$user' OR user2 = '$user'
ORDER BY
    last_created DESC

This outputs empty entries for the LEFT JOIN table. I think this happens because I select in the subquery just the last entry of babble_messages...
I tried to add a WHERE tag into the subquery but that throws an error:

SELECT
    *
FROM
    babble
LEFT JOIN (
    SELECT
        babble_messages.ID AS last_id,
        babble_messages.sender AS last_sender,
        babble_messages.babble_id,
        babble_messages.created AS last_created,
        babble_messages.seen AS last_seen,
        babble_messages.message AS last_message
    FROM
        babble_messages
    WHERE
        babble.ID = babble_messages.babble_id*
    ORDER BY
        created DESC
    LIMIT
        1
    ) babble_messages ON
    babble.ID = babble_messages.babble_id
WHERE
    user1 = '$user' OR user2 = '$user'
ORDER BY
    last_created DESC

In the subquery mysql does not know the "babble.ID".
How can I select just the last entry of babble_messages?

Of course I can use multiple request but I want to make just one request, because it is faster.

I hope this is enough information. :D
Thanks for reading and hopefully answering :)

Have a nice day hadome

Body:
This may be somewhat slow if the number of users is massive, especially with the OR in there.

SELECT
    ID
    ,user1
    ,user2
    ,created
    ,last_id
    ,last_sender
    ,babble_id
    ,last_created
    ,last_seen
    ,last_message
FROM
(
    SELECT
        ID
        ,user1
        ,user2
        ,created
        ,(SELECT ID FROM babble_messages WHERE babble_ID = user1 ORDER BY created DESC LIMIT 1) AS babble_message_id
    FROM babble
    WHERE user1 = 1
) a
LEFT JOIN (
    SELECT
        ID last_id
        ,sender last_sender
        ,babble_id
        ,created last_created
        ,seen last_seen
        ,message last_message
    FROM babble_messages
) b ON a.babble_message_id = b.last_id
ORDER BY last_created DESC


问:
Docker container will automatically stop after "docker run -d"
According to tutorial I read so far, use "docker run -d" will start a container from image, and the container will run in background. This is how it looks like, we can see we already have container id.

```<code>root@docker:/home/root# docker run -d centos
605e3928cdddb844526bab691af51d0c9262e0a1fc3d41de3f59be1a58e1bd1d
</code>```

But if I ran "docker ps", nothing was returned.

So I tried "docker ps -a", I can see container already exited:

```<code>root@docker:/home/root# docker ps -a
CONTAINER ID        IMAGE                 COMMAND             CREATED             STATUS                         PORTS               NAMES
605e3928cddd        centos:latest         "/bin/bash"         31 minutes ago      Exited (0) 31 minutes ago                          kickass_swartz
</code>```

Anything I did wrong? How can I troubleshoot this issue?

答:
execute command as follows :

```<code>docker run -t -d <image-name>
</code>```

if you want to specify port then command as below:

```<code>docker run -t -d -p <port-no> <image-name>
</code>```

verify the running container using following command:

```<code>docker ps
</code>```

Body:
According to tutorial I read so far, use "docker run -d" will start a container from image, and the container will run in background. This is how it looks like, we can see we already have container id.

root@docker:/home/root# docker run -d centos
605e3928cdddb844526bab691af51d0c9262e0a1fc3d41de3f59be1a58e1bd1d

But if I ran "docker ps", nothing was returned.

So I tried "docker ps -a", I can see container already exited:

root@docker:/home/root# docker ps -a
CONTAINER ID        IMAGE                 COMMAND             CREATED             STATUS                         PORTS               NAMES
605e3928cddd        centos:latest         "/bin/bash"         31 minutes ago      Exited (0) 31 minutes ago                          kickass_swartz

Anything I did wrong? How can I troubleshoot this issue?

Body:
execute command as follows :

docker run -t -d <image-name>

if you want to specify port then command as below:

docker run -t -d -p <port-no> <image-name>

verify the running container using following command:

docker ps


问:
Converting a VARCHAR ',96' into integer 0.96 in SQL Server
I have to do the conversion as mentioned in the title, I tried a lot of things and couldn't find the solution yet.

Any help please?

Thanks!

答:
You could use CONCAT.

```<code>mysql> SELECT CONCAT('My', 'S', 'QL');
        -> 'MySQL'
mysql> SELECT CONCAT('My', NULL, 'QL');
        -> NULL
mysql> SELECT CONCAT(14.3);
        -> '14.3'
</code>```

Body:
You could use CONCAT.

mysql> SELECT CONCAT('My', 'S', 'QL');
        -> 'MySQL'
mysql> SELECT CONCAT('My', NULL, 'QL');
        -> NULL
mysql> SELECT CONCAT(14.3);
        -> '14.3'


问:
Javascript - Assign value of reference returned by function
I have a function of the prototype of an object called getComponent which returns this.components[name]

```<code>function Foo()
{
    this.components = {"Scripts": [...], "Sprites": [...], "States": {...}, etc };
}

Foo.prototype.getComponent = function(name)
{
    return this.components[name];
}
</code>```

Then I have some code that gets a component and sets it to something else...

```<code>var foo = new Foo();
foo.getComponent("Sprites") = [];
</code>```

This obviously raises the Uncaught ReferenceError: Invalid left-hand side in assignment.

Is there anyway to set the value of the returned value?

I don't want to access the objects variables directly: foo.components.Sprites = [].

Thanks in advance,

David

答:
No.

You can assign values to variables, constants and to the properties of objects.

A function returns a value. It never returns a variable, constant or property (not even if it reads one of those to get the value).

Either:

create a setComponent method which takes two arguments and assigns the value of the second one to the property.

rename your method to component and have it take an optional second argument and then act as either setComponent or getComponent depending on how many arguments were passed.

ContentLicense: CC BY-SA 4.0

Body:
I have a function of the prototype of an object called getComponent which returns this.components[name]

function Foo()
{
    this.components = {"Scripts": [...], "Sprites": [...], "States": {...}, etc };
}

Foo.prototype.getComponent = function(name)
{
    return this.components[name];
}

Then I have some code that gets a component and sets it to something else...

var foo = new Foo();
foo.getComponent("Sprites") = [];

This obviously raises the Uncaught ReferenceError: Invalid left-hand side in assignment.

Is there anyway to set the value of the returned value?

I don't want to access the objects variables directly: foo.components.Sprites = [].

Thanks in advance,

David


答:
First you should do everything Database side. So no php. That would be my advice.

Then not having sequence in MySQL that what I would Suggest you :

```<code>SELECT COUNT(id)
FROM GOODS
WHERE GKEY LIKE('BOOK-%')
</code>```

Then you insert

```<code>INSERT INTO goods (id, "BOOK-" || SELECT MAX(SUBSTR(LENGTH(GKEY -1), LENGTH(GKEY))FROM GOODS WHERE GKEY LIKE('BOOK-%') + 1, ...)
</code>```

This way you will always have the next number available.

ContentLicense: CC BY-SA 2.5

Title: MYSQL - how to a second unique string key?

Body:
Here is my goods table.

+----------------------+---------------+------+-----+---------+-------+
| Field                | Type          | Null | Key | Default | Extra |
+----------------------+---------------+------+-----+---------+-------+
| ID                   | decimal(18,0) | NO   | PRI |         |       |
| gkey                 | varchar(255)  | YES  | MUL | NULL    |       |
| GOODS                | decimal(18,0) | YES  | MUL | NULL    |       |

Column ID is auto-increment.
GOODS is the id of a goods category.
Here is the goods category table.

+-------+---------------------+
| ID    | NAME                |
+-------+---------------------+
| 1     | book                |
| 2     | phone               |
+-------+---------------------+

My question is in goods table I need the gkey is also an unique key with prefix-id(here id is started from 1.) Like BOOK-1,BOOK-2....PHONE-1,PHONE-2... when insert a new goods record into goods table.
Like that:

+--------------------+---------------+------+-----+---------+-------+
| ID                 | GKEY          |GOODS | PRI | COUNTRY | Extra |
+--------------------+---------------+------+-----+---------+-------+
| 1                  | BOOK-1        | 1    | 10  |         |       |
| 2                  | PHONE-1       | 2    | 12  |         |       |
| 3                  | BOOK-2        | 1    | 13  |         |       |
| 4                  | BOOK-3        | 1    | 10  |         |       |
| 5                  | PHONE-2       | 2    | 10  |         |       |
| 6                  | PHONE-3       | 2    | 20  |         |       |
+--------------------+---------------+------+-----+---------+-------+

How to get that GKEY in PHP+MYSQL?

thanks.

Body:
First you should do everything Database side. So no php. That would be my advice.

Then not having sequence in MySQL that what I would Suggest you :

SELECT COUNT(id)
FROM GOODS
WHERE GKEY LIKE('BOOK-%')

Then you insert

INSERT INTO goods (id, "BOOK-" || SELECT MAX(SUBSTR(LENGTH(GKEY -1), LENGTH(GKEY))FROM GOODS WHERE GKEY LIKE('BOOK-%') + 1, ...)

This way you will always have the next number available.


问:
Two common elements between lists
I have a problem with this function two-similar-p.

```<code>(defun two-similar-p (list1 list2)
  (mapcar
   (lambda (e)
     (mapcar
      (lambda (e1)
        (if (equal e e1) t))
      list2))
   list1))
</code>```

But is not correct use mapcar because this function returns a new list with T or NIL, but I need only to return a true or false.

ex.

```<code>(two-similar-p '(2 1 3) '(1 2 3))
==> ((NIL T NIL) (T NIL NIL) (NIL NIL T))
</code>```

I was thinking to use recursion to compare the various elements, but I have no idea how to do that.
My function needs to work like:

```<code>(two-similar-p '(1 2 3) '(1 4 5)) ; ==> nil

(two-similar-p '(1 2 5) '(1 4 5)) ; ==> t

(two-similar-p '(1 2 6) '(6 4 2)) ; ==> t
</code>```

Any advice?

答:
The easiest "off-the-shelf" solution is to check that the intersection contains at least two elements:

```<code>(defun two-similar-p (l1 l2)
  (consp (cdr (intersection l1 l2 :test #'equal))))
</code>```

A slightly less OTS solution is to use hash tables:

```<code>(defun two-similar-p (l1 l2)
  (let ((h1 (make-hash-table :test 'equal))
        (common 0))
    (dolist (x l1)
      (setf (gethash x h1) t))
    (dolist (x l2)
      (when (gethash x h1)
        (incf common))
      (when (>= common 2)
        (return t)))))
</code>```

The advantage of the second approach is that its complexity is O(len(l1) + len(l2)),
while the mapcar approach will be O(len(l1) * len(l2)).

The standard does not specify the complexity of intersection and friends, but most implementations take good care of their users here (IOW, the complexity will be linear, not quadratic).

Title: Two common elements between lists

Body:
I have a problem with this function two-similar-p.

(defun two-similar-p (list1 list2)
  (mapcar
   (lambda (e)
     (mapcar
      (lambda (e1)
        (if (equal e e1) t))
      list2))
   list1))

But is not correct use mapcar because this function returns a new list with T or NIL, but I need only to return a true or false.

ex.

(two-similar-p '(2 1 3) '(1 2 3))
==> ((NIL T NIL) (T NIL NIL) (NIL NIL T))

I was thinking to use recursion to compare the various elements, but I have no idea how to do that.
My function needs to work like:

(two-similar-p '(1 2 3) '(1 4 5)) ; ==> nil

(two-similar-p '(1 2 5) '(1 4 5)) ; ==> t

(two-similar-p '(1 2 6) '(6 4 2)) ; ==> t

Any advice?

Body:
The easiest "off-the-shelf" solution is to check that the intersection contains at least two elements:

(defun two-similar-p (l1 l2)
  (consp (cdr (intersection l1 l2 :test #'equal))))

A slightly less OTS solution is to use hash tables:

(defun two-similar-p (l1 l2)
  (let ((h1 (make-hash-table :test 'equal))
        (common 0))
    (dolist (x l1)
      (setf (gethash x h1) t))
    (dolist (x l2)
      (when (gethash x h1)
        (incf common))
      (when (>= common 2)
        (return t)))))

The advantage of the second approach is that its complexity is O(len(l1) + len(l2)),
while the mapcar approach will be O(len(l1) * len(l2)).

The standard does not specify the complexity of intersection and friends, but most implementations take good care of their users here (IOW, the complexity will be linear, not quadratic).


问:
Tracking down "missing parameter type for expanded function"
Im stuck with with code, whenever I try to run it I get the error:

```<code>Error:(37, 66) missing parameter type for expanded function
The argument types of an anonymous function must be fully known. (SLS 8.5)
Expected type was: com.bfg.domain.model.RunnerSnap
  def syncPrices(pair: (RunnerSnap, RunnerChange)): RunnerSnap = {
</code>```

However the error message is not enogh for me to know what I need to change to get this working.

```<code>  def syncPrices(pair: (RunnerSnap, RunnerChange)): RunnerSnap = {
    case (cache: RunnerSnap, delta: RunnerChange) =>
      val newHc = if (delta.hc.isEmpty) cache.runnerId.handicap else delta.hc
      val id = RunnerId(delta.id, newHc)
      val prices = MarketRunnerPrices(
        atl = syncPriceVolume(cache.prices.atl, delta.atl),
        atb = syncPriceVolume(cache.prices.atb, delta.atb),
        trd = syncPriceVolume(cache.prices.trd, delta.trd),
        spb = syncPriceVolume(cache.prices.spb, delta.spb),
        spl = syncPriceVolume(cache.prices.spl, delta.spl),

        batb = syncLevelPriceVolume(cache.prices.batb, delta.batb),
        batl = syncLevelPriceVolume(cache.prices.batl, delta.batl),
        bdatb = syncLevelPriceVolume(cache.prices.bdatb, delta.bdatb),
        bdatl = syncLevelPriceVolume(cache.prices.bdatl, delta.bdatl),

        spn = if (delta.spn.isEmpty) cache.prices.spn else delta.spn,
        spf = if (delta.hc.isEmpty) cache.prices.spf else delta.spf,
        ltp = if (delta.hc.isEmpty) cache.prices.ltp else delta.ltp,
        tv = if (delta.hc.isEmpty) cache.prices.tv else delta.tv
      )
      RunnerSnap(id, prices)
  }
</code>```

My question is: Why am I getting this error and what do I need to
  change in my code to get it working as expected?

答:
You are missing pair match:

```<code>def syncPrices(pair: (RunnerSnap, RunnerChange)): RunnerSnap = pair match {
  case (cache: RunnerSnap, delta: RunnerChange) =>
    ...
}
</code>```

Body:
Im stuck with with code, whenever I try to run it I get the error:

Error:(37, 66) missing parameter type for expanded function
The argument types of an anonymous function must be fully known. (SLS 8.5)
Expected type was: com.bfg.domain.model.RunnerSnap
  def syncPrices(pair: (RunnerSnap, RunnerChange)): RunnerSnap = {

However the error message is not enogh for me to know what I need to change to get this working.

  def syncPrices(pair: (RunnerSnap, RunnerChange)): RunnerSnap = {
    case (cache: RunnerSnap, delta: RunnerChange) =>
      val newHc = if (delta.hc.isEmpty) cache.runnerId.handicap else delta.hc
      val id = RunnerId(delta.id, newHc)
      val prices = MarketRunnerPrices(
        atl = syncPriceVolume(cache.prices.atl, delta.atl),
        atb = syncPriceVolume(cache.prices.atb, delta.atb),
        trd = syncPriceVolume(cache.prices.trd, delta.trd),
        spb = syncPriceVolume(cache.prices.spb, delta.spb),
        spl = syncPriceVolume(cache.prices.spl, delta.spl),

        batb = syncLevelPriceVolume(cache.prices.batb, delta.batb),
        batl = syncLevelPriceVolume(cache.prices.batl, delta.batl),
        bdatb = syncLevelPriceVolume(cache.prices.bdatb, delta.bdatb),
        bdatl = syncLevelPriceVolume(cache.prices.bdatl, delta.bdatl),

        spn = if (delta.spn.isEmpty) cache.prices.spn else delta.spn,
        spf = if (delta.hc.isEmpty) cache.prices.spf else delta.spf,
        ltp = if (delta.hc.isEmpty) cache.prices.ltp else delta.ltp,
        tv = if (delta.hc.isEmpty) cache.prices.tv else delta.tv
      )
      RunnerSnap(id, prices)
  }

My question is: Why am I getting this error and what do I need to
  change in my code to get it working as expected?

Body:
You are missing pair match:

def syncPrices(pair: (RunnerSnap, RunnerChange)): RunnerSnap = pair match {
  case (cache: RunnerSnap, delta: RunnerChange) =>
    ...
}


问:
Pressing back button shows same activity
I have two Activities.

LoginActivity

HomeScreen

I also have a splash screen with this setting:

```<code><activity android:name=".SplashScreen"
            android:theme="@style/AppTheme.NoActionBar"
            android:noHistory="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
</activity>
</code>```

The Splash Screen then transfers the user to the HomeScreen by using this code:

```<code>Intent intent = new Intent(SplashScreen.this, HomeScreen.class);
</code>```

Inside the HomeScreen Activity, I check if the user is already signed in or not. If he's not signed in, I transfer him to the LoginActivity:

```<code> mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(FirebaseAuth firebaseAuth) {
                if(firebaseAuth.getCurrentUser() == null)
                {
                    Intent intent = new Intent(HomeScreen.this,LoginActivity.class);
                    Toast.makeText(HomeScreen.this,"H>L on no login",Toast.LENGTH_LONG).show(); //toast to show me why my app is in infinite loop
                    startActivity(intent);
                }
            }
        };
</code>```

On the LoginActivity, I have a simple Login button which uses FireBase Google Authentication. Also, I check if the user is already signed in or not, and if he is, he's transferred to HomeScreen Activity:

```<code>mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                if(firebaseAuth.getCurrentUser() != null)
                {
                    Intent intent = new Intent(LoginActivity.this,HomeScreen.class);
                    Toast.makeText(LoginActivity.this,"L>H already signed in",Toast.LENGTH_LONG).show();
                    startActivity(intent);
                }
            }
        };
</code>```

And, also:

```<code>private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());

        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            Intent intent = new Intent(LoginActivity.this,HomeScreen.class);
                            Toast.makeText(LoginActivity.this,"L>H on login",Toast.LENGTH_LONG).show();
                            startActivity(intent);
                        } else {
                            // If sign in fails, display a message to the user.
                            Log.w(TAG, "signInWithCredential:failure", task.getException());
                            Toast.makeText(LoginActivity.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }
</code>```

Now, the problem is: When I open the app, I get a splash screen and I'm transferred to the Login page. Then when I press back, I get the Login page AGAIN instead of exiting the app. Also, once I'm singed in: I get the splash screen and I'm taken to the HomeScreen. Then if I press back, I am taken to the HomeScreen AGAIN instead of exiting the app.

Please help me out. I searched StackOverflow, but didn't quite reach anywhere. Any help is appreciated. Ask me for updates if you need more info! :)

答:
You need to implement onBackPressed() and by default your app should exit. However, to exit your app you can use

getActivity.finish();

or

finishAndRemoveTask(); - it finishes all activities and removes it from recent tasks list

Body:
I have two Activities.

LoginActivity

HomeScreen

I also have a splash screen with this setting:

<activity android:name=".SplashScreen"
            android:theme="@style/AppTheme.NoActionBar"
            android:noHistory="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
</activity>

The Splash Screen then transfers the user to the HomeScreen by using this code:

Intent intent = new Intent(SplashScreen.this, HomeScreen.class);

Inside the HomeScreen Activity, I check if the user is already signed in or not. If he's not signed in, I transfer him to the LoginActivity:

 mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(FirebaseAuth firebaseAuth) {
                if(firebaseAuth.getCurrentUser() == null)
                {
                    Intent intent = new Intent(HomeScreen.this,LoginActivity.class);
                    Toast.makeText(HomeScreen.this,"H>L on no login",Toast.LENGTH_LONG).show(); //toast to show me why my app is in infinite loop
                    startActivity(intent);
                }
            }
        };

On the LoginActivity, I have a simple Login button which uses FireBase Google Authentication. Also, I check if the user is already signed in or not, and if he is, he's transferred to HomeScreen Activity:

mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                if(firebaseAuth.getCurrentUser() != null)
                {
                    Intent intent = new Intent(LoginActivity.this,HomeScreen.class);
                    Toast.makeText(LoginActivity.this,"L>H already signed in",Toast.LENGTH_LONG).show();
                    startActivity(intent);
                }
            }
        };

And, also:

private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());

        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            Intent intent = new Intent(LoginActivity.this,HomeScreen.class);
                            Toast.makeText(LoginActivity.this,"L>H on login",Toast.LENGTH_LONG).show();
                            startActivity(intent);
                        } else {
                            // If sign in fails, display a message to the user.
                            Log.w(TAG, "signInWithCredential:failure", task.getException());
                            Toast.makeText(LoginActivity.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

Now, the problem is: When I open the app, I get a splash screen and I'm transferred to the Login page. Then when I press back, I get the Login page AGAIN instead of exiting the app. Also, once I'm singed in: I get the splash screen and I'm taken to the HomeScreen. Then if I press back, I am taken to the HomeScreen AGAIN instead of exiting the app.

Please help me out. I searched StackOverflow, but didn't quite reach anywhere. Any help is appreciated. Ask me for updates if you need more info! :)


问:
What is <cycle> in data?
(I use OCaml version 4.02.3)

I defined a type self

```<code># type self = Self of self;;
type self = Self of self
</code>```

and its instance s

```<code># let rec s = Self s;;
val s : self = Self <cycle>
</code>```

Since OCaml is a strict language, I expected defining s will fall into infinite recursion. But the interpreter said s has a value and it is Self <cycle>.

I also applied a function to s.

```<code># let f (s: self) = 1;;
val f : self -> int = <fun>
# f s;;
- : int = 1
</code>```

It seems s is not evaluated before the function application (like in non-strict language).

How OCaml deal with cyclic data like s? Self <cycle> is a normal form?

答:
OCaml is indeed an eager language, however s is a perfectly valid and fully evaluated term that happens to contain a cycle. For instance, this code yields the expected result:

```<code>let f (Self Self x) = x
f s == s;;
</code>```

More precisely, the memory representation of constructors with at n arguments are boxed and read like this:

```<code>⋅—————————————————————————————————————————————⋅
| header | field[0] | field[1] | ⋯ | fiekd[n] |
⋅—————————————————————————————————————————————⋅
</code>```

The header contains metadata whereas field[k] is an OCaml value, i.e. either an integer or a pointer. In the case of s, Self has only one argument, and thus only one field field[0]. The value of field[0] is then simply a pointer towards the start of the block. The term s is thus perfectly representable in OCaml.

Moreover, the toplevel printer is able to detect this kind of cycles and print an <cycle> to avoid falling into an infinite recursion when printing the value of s. Here, <cycle>, like <abstr> or <fun>, represents just a kind of value that the toplevel printer cannot print.

Note, however, that cyclical value will trigger infinite recursion in many situations, for instance f s = s where (=) is the structural equality
and not the physical one (i.e. (==)) triggers such recursion, another example would be

```<code>let rec ones = 1 :: ones;; (* prints [1;<cycle>] *)
let twos = List.map ((+) 1) ones;; (* falls in an infinite recursion *)
</code>```

Title: What is <cycle> in data?

Body:
(I use OCaml version 4.02.3)

I defined a type self

# type self = Self of self;;
type self = Self of self

and its instance s

# let rec s = Self s;;
val s : self = Self <cycle>

Since OCaml is a strict language, I expected defining s will fall into infinite recursion. But the interpreter said s has a value and it is Self <cycle>.

I also applied a function to s.

# let f (s: self) = 1;;
val f : self -> int = <fun>
# f s;;
- : int = 1

It seems s is not evaluated before the function application (like in non-strict language).

How OCaml deal with cyclic data like s? Self <cycle> is a normal form?

Body:
OCaml is indeed an eager language, however s is a perfectly valid and fully evaluated term that happens to contain a cycle. For instance, this code yields the expected result:

let f (Self Self x) = x
f s == s;;

More precisely, the memory representation of constructors with at n arguments are boxed and read like this:

⋅—————————————————————————————————————————————⋅
| header | field[0] | field[1] | ⋯ | fiekd[n] |
⋅—————————————————————————————————————————————⋅

The header contains metadata whereas field[k] is an OCaml value, i.e. either an integer or a pointer. In the case of s, Self has only one argument, and thus only one field field[0]. The value of field[0] is then simply a pointer towards the start of the block. The term s is thus perfectly representable in OCaml.

Moreover, the toplevel printer is able to detect this kind of cycles and print an <cycle> to avoid falling into an infinite recursion when printing the value of s. Here, <cycle>, like <abstr> or <fun>, represents just a kind of value that the toplevel printer cannot print.

Note, however, that cyclical value will trigger infinite recursion in many situations, for instance f s = s where (=) is the structural equality
and not the physical one (i.e. (==)) triggers such recursion, another example would be

let rec ones = 1 :: ones;; (* prints [1;<cycle>] *)
let twos = List.map ((+) 1) ones;; (* falls in an infinite recursion *)


问:
How to add the current client directory to the log file name?
I've been struggling with this problem in subject.

I tried something like this:

```<code>String sCurrDir = System.getProperty("user.dir");
int nLastBSlash = sCurrDir.lastIndexOf('/');
System.setProperty("current.folder", sCurrDir.substring(nLastBSlash + 1));
</code>```

and added the following to the log4j.properties:

```<code><appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
  <param name="Threshold" value="DEBUG" />
  <param name="append" value="true" />
  <param name="maxFileSize" value="10MB" />
  <param name="maxBackupIndex" value="50" />

  <param name="File" value="./log/${current.folder}-wcss-simulator-${current.date}.log"/>

  <layout class="org.apache.log4j.PatternLayout">
     <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss,SSS}\t %-5p\t [%X{ThreadId}]\t %X{MethodName}\t - %m%n" />
  </layout>
</appender>
</code>```

But the file name only starts with an hyphen.

答:
Your implementation doesn't work because logging has already started before you set the current.folder property. Do you have access to the program's main method or is this a container based application?

If you have access to the main method you have to make sure the first thing you do is set that property, before creating the first Logger instance.

Body:
I've been struggling with this problem in subject.

I tried something like this:

String sCurrDir = System.getProperty("user.dir");
int nLastBSlash = sCurrDir.lastIndexOf('/');
System.setProperty("current.folder", sCurrDir.substring(nLastBSlash + 1));

and added the following to the log4j.properties:

<appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
  <param name="Threshold" value="DEBUG" />
  <param name="append" value="true" />
  <param name="maxFileSize" value="10MB" />
  <param name="maxBackupIndex" value="50" />

  <param name="File" value="./log/${current.folder}-wcss-simulator-${current.date}.log"/>

  <layout class="org.apache.log4j.PatternLayout">
     <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss,SSS}\t %-5p\t [%X{ThreadId}]\t %X{MethodName}\t - %m%n" />
  </layout>
</appender>

But the file name only starts with an hyphen.


问:
Adding custom header in HTTP request of prometheus
Prometheus send HTTP request to get monitor values. My custom export supports variety of clients (to monitors system status). There is a general REST API to get list of monitors:

```<code>/api/v1/monitor/find
</code>```

the output result depend on Accept attribute in header. The default accept value is application/json.

I add new mime type to support prometheus (e.g. application/prometheus) into the API.

But, how to config Prometheus to add a custom header (Accept: application/prometheus)?

答:
Actually it is not support in current version (V2.0 alpha).

If you take a look at the scrapes.go in the master branch, then you can see some constant header attached into request:

req.Header.Add("Accept", acceptHeader)
req.Header.Set("User-Agent", userAgentHeader)
req.Header.Set("X-Prometheus-Scrape-Timeout-Seconds", fmt.Sprintf("%f", s.timeout.Seconds()))
```
<p>So, there are some basic mime-types which you can support:</p>
```application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited;q=0.7,text/plain;version=0.0.4;q=0.3,*/*;q=0.1
```

None of artifacts on premetheus.io added this header, so you have to build from source (master branch).

I run a PHP exporter (my own exporter), here is screen shot of request header

Body:
Prometheus send HTTP request to get monitor values. My custom export supports variety of clients (to monitors system status). There is a general REST API to get list of monitors:

/api/v1/monitor/find

the output result depend on Accept attribute in header. The default accept value is application/json.

I add new mime type to support prometheus (e.g. application/prometheus) into the API.

But, how to config Prometheus to add a custom header (Accept: application/prometheus)?

Body:
Actually it is not support in current version (V2.0 alpha).

If you take a look at the scrapes.go in the master branch, then you can see some constant header attached into request:

req.Header.Add("Accept", acceptHeader)
req.Header.Set("User-Agent", userAgentHeader)
req.Header.Set("X-Prometheus-Scrape-Timeout-Seconds", fmt.Sprintf("%f", s.timeout.Seconds()))

So, there are some basic mime-types which you can support:

application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited;q=0.7,text/plain;version=0.0.4;q=0.3,*/*;q=0.1

None of artifacts on premetheus.io added this header, so you have to build from source (master branch).

I run a PHP exporter (my own exporter), here is screen shot of request header


问:
Functional switch statement in Javascript
Say I have a switch statement that takes a variable myData between 1 and some larger value, i.e. 300.

Depending on the "status code" variable, the result is the text value of another variable. For example, if myData == 1, I want to return the a variable called code1. If myData == 300, I want to return the a variable called code300. Code1 and code300 variables store unrelated strings, i.e. "This is a summary", or "This is a note". Some psuedo-code below:

```<code>var myData = statusCode;

var code1 = "This is a summary";
var code300 = "This is a note";

switch(myData) {
    case statusCode:
        scriptletResult = returnCode("code", statusCode); // code1 if myData == 1
        break;
    default:
        scriptletResult = code1;
}

function returnCode(code, statusCode) {
    return code + statusCode; // Returns a variable "code1" if statusCode == 1
}
</code>```

How can I get this to work?

答:
```<code>var yourStatusCode = 300; //function get300();
var data = "MyData"; //function data();

function runner(){
    switch(data){
        case "MyData":
        myFunc();
        return "hola data we are looking for!";
        break;
        case "DataNumberTwo":
        return "this is data number 2";
        break;
        default:
        return "WOAH what data is this??";
        break;
    }

}

console.log(runner());
</code>```

Body:
Say I have a switch statement that takes a variable myData between 1 and some larger value, i.e. 300.

Depending on the "status code" variable, the result is the text value of another variable. For example, if myData == 1, I want to return the a variable called code1. If myData == 300, I want to return the a variable called code300. Code1 and code300 variables store unrelated strings, i.e. "This is a summary", or "This is a note". Some psuedo-code below:

var myData = statusCode;

var code1 = "This is a summary";
var code300 = "This is a note";

switch(myData) {
    case statusCode:
        scriptletResult = returnCode("code", statusCode); // code1 if myData == 1
        break;
    default:
        scriptletResult = code1;
}

function returnCode(code, statusCode) {
    return code + statusCode; // Returns a variable "code1" if statusCode == 1
}

How can I get this to work?


问:
Introducing Array[] field using JS innerHTML and
Trying to build a dynamic web form using JS, please refer the sample code enclosed with this request. The registrant can choose the number of seat and different Seat price for each registration. I am looking at bringing the total value into 'pay_total' the Final Sum field - But, all entries of registration seat price 'pay_fee' are inserted into the form using JS in Array format (pay_fee[]) - so I am not sure on how to calculate the sum of all (pay_fee[]) - any help would be grateful.

function process_participant(){

function clear() {
          document.getElementById("participant_list").innerHTML = "";
 }

var fieldSet = '

<input id="fname" name="name[]" type="" class="form-control" required placeholder="Name">

<input id="email" name="email[]"  required type="email" class="sm form-control"   placeholder="Enter email">

Seat Price
<select id="pay_fee" name="pay_fee[]"  onchange="total_processing()"  required class="form-control"><option ></option><option value="5000">Bay 1 - $ 5000</option><option value="3000">Bay 2 - $ 3000</option></select>

';

var NumberOfSeats = document.getElementById('seatNumbers').value;
   // alert(NumberOfSeats);

    if ( NumberOfSeats == 1 ) {

    document.getElementById('participant_list').innerHTML = fieldSet + '
';

    }

    if ( NumberOfSeats == 2 ) {

    document.getElementById('participant_list').innerHTML = fieldSet + fieldSet +'
';
    }

  if ( NumberOfSeats == 3 ) {

    document.getElementById('participant_list').innerHTML = fieldSet + fieldSet + fieldSet +'
';

    }

  if ( NumberOfSeats == 4 ) {

     document.getElementById('participant_list').innerHTML = fieldSet + fieldSet + fieldSet + fieldSet +'
';

    }

  if ( NumberOfSeats == 5 ) {

      document.getElementById('participant_list').innerHTML = fieldSet + fieldSet + fieldSet + fieldSet + fieldSet +'
';

    }

  }

 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
 <head>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>infinitheism Registrations </title>

        <!-- CSS -->
        <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:400,100,300,500">
        <link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">
        <link rel="stylesheet" href="assets/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="assets/css/form-elements.css">
        <link rel="stylesheet" href="assets/css/style.css">

  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/holder/2.9.4/holder.js"></script>
  </head>
  <body>

<div class="col-md-12">

<form class="form-inline" id="form1" name="Online" method='post' action="" class="form-horizontal" role="form"  >

<div class="bg-primary form-group-sm col-md-12 text-left contianer">

<h5 class="">Register Here </h5>
<div class="form-group form-group-sm">
<label for="no_of_participants">No. of Seat</label>
<select id="seatNumbers" name="seatNumbers" onchange="process_participant()" class="form-control">
<option></option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</div>

<!-- Particpant list -->

<div id="participant_list" class="text-center contianer">

</div>

  <div class="text-center col-md-12 form-group">
<div class="input-group col-md-2 ">

<div class="input-group-addon">Total.</div>
<input type="text" class="form-control" name="pay_total" id="pay_total" placeholder=" ">
<div class="input-group-addon">.00</div>
</div>
<p><hr/></p>
<input id="js_count" name="count" value="1" style="display:none"/>
<button type="submit" style="color:black;"  name="Online" class="btn btn">Complete Registration</button>

</div>

  </form></code>```

答:
Do with while loop instead multiple if condition parseInt the selected seat value and apply the while loop.And create  the total_processing function like this

```<code>function total_processing(that) {
    document.getElementById("pay_total").value = parseFloat(document.getElementById("pay_total").value|0)+parseFloat(that.value)
    }
</code>```

Then add the total value using existing  pay_total value with newly selected value on dropdown change .parseFloat is important They are convert the string to number

Updated

total amount refresh on change event

function process_participant() {
 document.getElementById("participant_list").innerHTML = "";
 document.getElementById("pay_total").value =""
  var fieldSet = '

<input id="fname" name="name[]" type="" class="form-control" required placeholder="Name">

<input id="email" name="email[]"  required type="email" class="sm form-control"   placeholder="Enter email">

Seat Price
<select id="pay_fee" name="pay_fee[]"  onchange="total_processing()"  required class="form-control amount"><option ></option><option value="5000">Bay 1 - $ 5000</option><option value="3000">Bay 2 - $ 3000</option></select>

';

  var NumberOfSeats = document.getElementById('seatNumbers').value;
  // alert(NumberOfSeats);
  var i = 0;
  while (i < parseInt(NumberOfSeats)) {
    document.getElementById('participant_list').innerHTML += fieldSet
    '
';
    i++;
  }
}

function clear() {
  document.getElementById("participant_list").innerHTML = "";
}
function total_processing() {
var total=0;
document.querySelectorAll('.amount').forEach(function(a,b){
     total += parseFloat(a.value|0)
})
document.getElementById("pay_total").value =total
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<head>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>infinitheism Registrations </title>

  <!-- CSS -->
  <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:400,100,300,500">
  <link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">
  <link rel="stylesheet" href="assets/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="assets/css/form-elements.css">
  <link rel="stylesheet" href="assets/css/style.css">

  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/holder/2.9.4/holder.js"></script>
</head>

<body>

  <div class="col-md-12">

    <form class="form-inline" id="form1" name="Online" method='post' action="" class="form-horizontal" role="form" >

      <div class="bg-primary form-group-sm col-md-12 text-left contianer">

        <h5 class="">Register Here </h5>
        <div class="form-group form-group-sm">
          <label for="no_of_participants">No. of Seat</label>
          <select id="seatNumbers" name="seatNumbers" onchange="process_participant()" class="form-control">
<option></option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
        </div>

        <!-- Particpant list -->

        <div id="participant_list" class="text-center contianer">

        </div>

        <div class="text-center col-md-12 form-group">
          <div class="input-group col-md-2 ">

            <div class="input-group-addon">Total.</div>
            <input type="text" class="form-control" name="pay_total" id="pay_total" placeholder=" ">
            <div class="input-group-addon">.00</div>
          </div>
          <p>
            <hr/>
          </p>
          <input id="js_count" name="count" value="1" style="display:none" />
          <button type="submit" style="color:black;" name="Online" class="btn btn">Complete Registration</button>

        </div>

    </form></code>```

Body:
Trying to build a dynamic web form using JS, please refer the sample code enclosed with this request. The registrant can choose the number of seat and different Seat price for each registration. I am looking at bringing the total value into 'pay_total' the Final Sum field - But, all entries of registration seat price 'pay_fee' are inserted into the form using JS in Array format (pay_fee[]) - so I am not sure on how to calculate the sum of all (pay_fee[]) - any help would be grateful.

function process_participant(){

function clear() {
          document.getElementById("participant_list").innerHTML = "";
 }

var fieldSet = '

<input id="fname" name="name[]" type="" class="form-control" required placeholder="Name">

<input id="email" name="email[]"  required type="email" class="sm form-control"   placeholder="Enter email">

Seat Price
<select id="pay_fee" name="pay_fee[]"  onchange="total_processing()"  required class="form-control"><option ></option><option value="5000">Bay 1 - $ 5000</option><option value="3000">Bay 2 - $ 3000</option></select>

';

var NumberOfSeats = document.getElementById('seatNumbers').value;
   // alert(NumberOfSeats);

    if ( NumberOfSeats == 1 ) {

    document.getElementById('participant_list').innerHTML = fieldSet + '
';

    }

    if ( NumberOfSeats == 2 ) {

    document.getElementById('participant_list').innerHTML = fieldSet + fieldSet +'
';
    }

  if ( NumberOfSeats == 3 ) {

    document.getElementById('participant_list').innerHTML = fieldSet + fieldSet + fieldSet +'
';

    }

  if ( NumberOfSeats == 4 ) {

     document.getElementById('participant_list').innerHTML = fieldSet + fieldSet + fieldSet + fieldSet +'
';

    }

  if ( NumberOfSeats == 5 ) {

      document.getElementById('participant_list').innerHTML = fieldSet + fieldSet + fieldSet + fieldSet + fieldSet +'
';

    }

  }

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>infinitheism Registrations </title>

        <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:400,100,300,500">
        <link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">
        <link rel="stylesheet" href="assets/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="assets/css/form-elements.css">
        <link rel="stylesheet" href="assets/css/style.css">

  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

  <link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">

<form class="form-inline" id="form1" name="Online" method='post' action="" class="form-horizontal" role="form"  >

Register Here

No. of Seat
<select id="seatNumbers" name="seatNumbers" onchange="process_participant()" class="form-control">
<option></option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>

Total.

<input type="text" class="form-control" name="pay_total" id="pay_total" placeholder=" ">

.00

<input id="js_count" name="count" value="1" style="display:none"/>
<button type="submit" style="color:black;"  name="Online" class="btn btn">Complete Registration</button>

  </form>

Body:
Do with while loop instead multiple if condition parseInt the selected seat value and apply the while loop.And create  the total_processing function like this

function total_processing(that) {
    document.getElementById("pay_total").value = parseFloat(document.getElementById("pay_total").value|0)+parseFloat(that.value)
    }

Then add the total value using existing  pay_total value with newly selected value on dropdown change .parseFloat is important They are convert the string to number

Updated

total amount refresh on change event

function process_participant() {
 document.getElementById("participant_list").innerHTML = "";
 document.getElementById("pay_total").value =""
  var fieldSet = '<h5 class="text-left" > </h5><div class="form-group "><input id="fname" name="name[]" type="" class="form-control" required placeholder="Name"></div>  <div class="form-group "><input id="email" name="email[]"  required type="email" class="sm form-control"   placeholder="Enter email"></div> </div><div class="form-group"><div class="input-group"><div class="input-group-addon">Seat Price</div><select id="pay_fee" name="pay_fee[]"  onchange="total_processing()"  required class="form-control amount"><option ></option><option value="5000">Bay 1 - $ 5000</option><option value="3000">Bay 2 - $ 3000</option></select></div></div>';

  var NumberOfSeats = document.getElementById('seatNumbers').value;
  // alert(NumberOfSeats);
  var i = 0;
  while (i < parseInt(NumberOfSeats)) {
    document.getElementById('participant_list').innerHTML += fieldSet
    '<hr/>';
    i++;
  }
}

function clear() {
  document.getElementById("participant_list").innerHTML = "";
}
function total_processing() {
var total=0;
document.querySelectorAll('.amount').forEach(function(a,b){
     total += parseFloat(a.value|0)
})
document.getElementById("pay_total").value =total
}

<html>

<head>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>infinitheism Registrations </title>

  <!-- CSS -->
  <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:400,100,300,500">
  <link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">
  <link rel="stylesheet" href="assets/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="assets/css/form-elements.css">
  <link rel="stylesheet" href="assets/css/style.css">

  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/holder/2.9.4/holder.js"></script>
</head>

<body>

  <div class="col-md-12">

    <form class="form-inline" id="form1" name="Online" method='post' action="" class="form-horizontal" role="form" >

      <div class="bg-primary form-group-sm col-md-12 text-left contianer">

        <h5 class="">Register Here </h5>
        <div class="form-group form-group-sm">
          <label for="no_of_participants">No. of Seat</label>
          <select id="seatNumbers" name="seatNumbers" onchange="process_participant()" class="form-control">
<option></option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
        </div>

        <!-- Particpant list -->

        <div id="participant_list" class="text-center contianer">

        </div>

        <div class="text-center col-md-12 form-group">
          <div class="input-group col-md-2 ">

            <div class="input-group-addon">Total.</div>
            <input type="text" class="form-control" name="pay_total" id="pay_total" placeholder=" ">
            <div class="input-group-addon">.00</div>
          </div>
          <p>
            <hr/>
          </p>
          <input id="js_count" name="count" value="1" style="display:none" />
          <button type="submit" style="color:black;" name="Online" class="btn btn">Complete Registration</button>

        </div>

    </form>


问:
Get only filename from full path of a file
I want to split the path and just save the file name test.xls in a new variable

```<code>$namearray = "C:\Users\z003m\Desktop\Service_Tickets\automationscript\vbs\Newfolder\test.xls"
</code>```

答:
You can also use the .Net implementation

[System.IO.Path] is 10 times faster than the split-path cmdlet

```<code>[System.IO.Path]::GetFileName('c:\myFile.txt')
# result myFile.txt

[System.IO.Path]::GetFileNameWithoutExtension('c:\myFile.txt')
# result myFile
</code>```

Performance comparision: 50.000 items

```<code>[System.IO.Path]::GetFileName(...)    Average: 12,84143

Split-Path                            Average: 113,537884
</code>```

Body:
I want to split the path and just save the file name test.xls in a new variable

$namearray = "C:\Users\z003m\Desktop\Service_Tickets\automationscript\vbs\Newfolder\test.xls"

Body:
You can also use the .Net implementation

[System.IO.Path] is 10 times faster than the split-path cmdlet

[System.IO.Path]::GetFileName('c:\myFile.txt')
# result myFile.txt

[System.IO.Path]::GetFileNameWithoutExtension('c:\myFile.txt')
# result myFile

Performance comparision: 50.000 items

[System.IO.Path]::GetFileName(...)    Average: 12,84143

Split-Path                            Average: 113,537884


问:
Tool to find global/static variables in C codebase
I have created a C++-wrapper (a class) for a larger C codebase which was originally written for a microprocessor. Now we want to simulate multiple instances of "agents" running this C code. As we want to see how they interact, we need to run them simultaneously. If possible, we'd like to run them in one process.

This failed at first because the C code used static variables and thus wasn't thread safe. We thought we had removed all static and global variables but still don't get the expected results. (Everything runs fine if we have only one instance.)

So my question is: instead of searching the whole code base for such variables, is there any tool that might assist to find the problem? The C code was written in Keil μVision and is now compiled in Visual Studio 2008 Team Suite.

Thanks for suggestions!

答:
If you can build it in a more unix-ish environment, you should have a size command you can run on .o files that will tell you the data and bss segment sizes for each .o file. This is a very quick way to find variables of static storage duration (just look for nonzero sizes in either of these fields).

Perhaps you could try building with mingw or cygwin, or looking for a similar tool in the MSVC toolset.


问:
GlobalWindows assign elements with same key in the same GlobalWindows in Flink?
Based on document below "A global windows assigner assigns all elements with the same key to the same single global window"

https://ci.apache.org/projects/flink/flink-docs-release-1.2/dev/windows.html

Then I checked the source code and found assignWindows method of GlobalWindows just return the global Window and didn't do anything for the parameter element,so how all elements with the same key to the same single global window?

https://github.com/apache/flink/blob/12b4185c6c09101b64e12a84c33dc4d28f95cff9/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/windowing/assigners/GlobalWindows.java

```<code>@Override
public Collection<GlobalWindow> assignWindows(Object element, long timestamp, WindowAssignerContext context) {
    return Collections.singletonList(GlobalWindow.get());
}
</code>```

答:
In Flink, windows and keys are largely independent of each other. Stream elements can be grouped by key, and by window, and these are orthogonal dimensions. (When we want to talk about the combination of a window with a key this is called a pane.)

Window instances don't have keys, and neither do window assigners. Instead, keys and key-partitioned state are part of the runtime context in which windows are evaluated.

When I was trying to understand the relationship of keys to window assigners I found it helpful to read through the WindowOperator's implementation of processElement. This code is called as each stream element arrives at a window operator. Paying attention to the role of the key, while leaving out a lot of other details, we see this:

```<code>public void processElement(StreamRecord<IN> element) throws Exception {
    final Collection<W> elementWindows = windowAssigner.assignWindows(
        element.getValue(), element.getTimestamp(), windowAssignerContext);

    ...

    final K key = this.<K>getKeyedStateBackend().getCurrentKey();

    ...

    for (W window: elementWindows) {

        ...

        windowState.add(element.getValue());

        triggerContext.key = key;
        triggerContext.window = window;

        TriggerResult triggerResult = triggerContext.onElement(element);
        if (triggerResult.isFire()) {
            ...
            emitWindowContents(window, contents);
        }

        ...
    }
}
</code>```

Here you can see that the key is available to the window operator via getKeyedStateBackend(), but isn't even retrieved until after getting the windows for this element from the window assigner. The window assigner does its job without any concern for keys.

The key is later being fetched, though, so that it can be made available to the trigger via the trigger context.

Body:
Based on document below "A global windows assigner assigns all elements with the same key to the same single global window"

https://ci.apache.org/projects/flink/flink-docs-release-1.2/dev/windows.html

Then I checked the source code and found assignWindows method of GlobalWindows just return the global Window and didn't do anything for the parameter element,so how all elements with the same key to the same single global window?

https://github.com/apache/flink/blob/12b4185c6c09101b64e12a84c33dc4d28f95cff9/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/windowing/assigners/GlobalWindows.java

@Override
public Collection<GlobalWindow> assignWindows(Object element, long timestamp, WindowAssignerContext context) {
    return Collections.singletonList(GlobalWindow.get());
}

Body:
In Flink, windows and keys are largely independent of each other. Stream elements can be grouped by key, and by window, and these are orthogonal dimensions. (When we want to talk about the combination of a window with a key this is called a pane.)

Window instances don't have keys, and neither do window assigners. Instead, keys and key-partitioned state are part of the runtime context in which windows are evaluated.

When I was trying to understand the relationship of keys to window assigners I found it helpful to read through the WindowOperator's implementation of processElement. This code is called as each stream element arrives at a window operator. Paying attention to the role of the key, while leaving out a lot of other details, we see this:

public void processElement(StreamRecord<IN> element) throws Exception {
    final Collection<W> elementWindows = windowAssigner.assignWindows(
        element.getValue(), element.getTimestamp(), windowAssignerContext);

    ...

    final K key = this.<K>getKeyedStateBackend().getCurrentKey();

    ...

    for (W window: elementWindows) {

        ...

        windowState.add(element.getValue());

        triggerContext.key = key;
        triggerContext.window = window;

        TriggerResult triggerResult = triggerContext.onElement(element);
        if (triggerResult.isFire()) {
            ...
            emitWindowContents(window, contents);
        }

        ...
    }
}

Here you can see that the key is available to the window operator via getKeyedStateBackend(), but isn't even retrieved until after getting the windows for this element from the window assigner. The window assigner does its job without any concern for keys.

The key is later being fetched, though, so that it can be made available to the trigger via the trigger context.


问:
why dividing by a constant an xts object in R results in a matrix object (losing the Date column)?
thanks for any help regarding:

why dividing by a constant an xts object in R results in a matrix object (the Date/index column is lost)?
I would expect that the resulting object would be an xts object, like the input xts, with just the column values divided by the constant. Why this happens and how to avoid it?

Example of the problem that I observe.

Code extract:

```<code>TradeProfit <- as.xts(ifelse(is.na(lag(GLD$Signal, 1)) == 0 & GLD$Signal != lag(GLD$Signal, 1), GLD$TotTradCapital, NA ))
TradeProfit <- na.omit(TradeProfit)

TradeProfitPerc <- ifelse(is.na(lag(TradeProfit,1)) == 0, TradeProfit / 100, NA)
TradeProfitPerc <- na.omit(TradeProfitPerc)

> class(TradeProfit)
[1] "xts" "zoo"

> head(TradeProfit)
              Signal
2012-08-15  0.000000
2012-11-02  6.970001
2012-11-06  6.970001
2013-08-09 46.410003
2013-08-14 46.410003
2013-09-27 46.380004

head(TradeProfitPerc)
        Signal
[1,] 0.06970001
[2,] 0.06970001
[3,] 0.46410003
[4,] 0.46410003
[5,] 0.46380004
[6,] 0.46380004

> class(TradeProfitPerc)
[1] "matrix"
>
</code>```

The problem is that TradeProfitPerc looses the Date column/index which I want to retain. Also as TradeProfit is an xts object why the division causes such a strange behavior transforming an xts into a matrix object? How can I keep the xts properties?
Thanks!

答:
If I were you I would simply add a column to your existing object, which will keep the xts class.

```<code>GLD <- xts(matrix(1:10,ncol=2),Sys.Date()+0:4)
colnames(GLD) <- c("Signal","TotTradCapital")
TradeProfit <- as.xts(ifelse(is.na(lag(GLD$Signal, 1)) == 0 & GLD$Signal != lag(GLD$Signal, 1), GLD$TotTradCapital, NA ))
TradeProfit <- na.omit(TradeProfit)

TradeProfit$TradeProfitPerc <- ifelse(!is.na(lag(TradeProfit,1)), TradeProfit / 100, NA)

           Signal TradeProfitPerc
2017-06-06      7              NA
2017-06-07      8            0.08
2017-06-08      9            0.09
2017-06-09     10            0.10
</code>```

Body:
thanks for any help regarding:

why dividing by a constant an xts object in R results in a matrix object (the Date/index column is lost)?
I would expect that the resulting object would be an xts object, like the input xts, with just the column values divided by the constant. Why this happens and how to avoid it?

Example of the problem that I observe.

Code extract:

TradeProfit <- as.xts(ifelse(is.na(lag(GLD$Signal, 1)) == 0 & GLD$Signal != lag(GLD$Signal, 1), GLD$TotTradCapital, NA ))
TradeProfit <- na.omit(TradeProfit)

TradeProfitPerc <- ifelse(is.na(lag(TradeProfit,1)) == 0, TradeProfit / 100, NA)
TradeProfitPerc <- na.omit(TradeProfitPerc)

> class(TradeProfit)
[1] "xts" "zoo"

> head(TradeProfit)
              Signal
2012-08-15  0.000000
2012-11-02  6.970001
2012-11-06  6.970001
2013-08-09 46.410003
2013-08-14 46.410003
2013-09-27 46.380004

head(TradeProfitPerc)
        Signal
[1,] 0.06970001
[2,] 0.06970001
[3,] 0.46410003
[4,] 0.46410003
[5,] 0.46380004
[6,] 0.46380004

> class(TradeProfitPerc)
[1] "matrix"
>

The problem is that TradeProfitPerc looses the Date column/index which I want to retain. Also as TradeProfit is an xts object why the division causes such a strange behavior transforming an xts into a matrix object? How can I keep the xts properties?
Thanks!

Body:
If I were you I would simply add a column to your existing object, which will keep the xts class.

GLD <- xts(matrix(1:10,ncol=2),Sys.Date()+0:4)
colnames(GLD) <- c("Signal","TotTradCapital")
TradeProfit <- as.xts(ifelse(is.na(lag(GLD$Signal, 1)) == 0 & GLD$Signal != lag(GLD$Signal, 1), GLD$TotTradCapital, NA ))
TradeProfit <- na.omit(TradeProfit)

TradeProfit$TradeProfitPerc <- ifelse(!is.na(lag(TradeProfit,1)), TradeProfit / 100, NA)

           Signal TradeProfitPerc
2017-06-06      7              NA
2017-06-07      8            0.08
2017-06-08      9            0.09
2017-06-09     10            0.10


问:
How to change source of  tag on hover?
I need to change  source URL on hover.

I have tried this but won't work :

HTML

```<code><img id="my-img" src="http://dummyimage.com/100x100/000/fff"/>
</code>```

CSS

```<code>#my-img:hover {
    content: url('http://dummyimage.com/100x100/eb00eb/fff');
}
</code>```

jsFiddle

Any help would be appreciated.

Update:

This only works for Webkit / Google Chrome.

答:
Try This Code.

   .card {

            width: 200px;

            height: 195px;

            position: relative;

            display: inline-block;

        }

        .card .img-top {

            display: none;

            position: absolute;

            top: 0;

            left: 0;

            z-index: 99;
width:200px;
        }

        .card:hover .img-top {

            display: inline;

        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <!DOCTYPE html>

    <html lang="en">

    <head>

    <title>Image Change on Hover with CSS</title>

    </head>

    <body>

        <div class="card">

            <img src="http://www.dhresource.com/200x200s/f2-albu-g5-M00-EC-97-rBVaJFkAobCAHD9XAADvz9DDocA266.jpg/diy-wall-stickers-home-decor-nature-colorful.jpg" alt="Card Back" style="width:200px">

            <img src="https://s-media-cache-ak0.pinimg.com/236x/31/17/98/3117987a0be0a7d8976869aabf54d2d7.jpg" class="img-top" alt="Card Front">

        </div>

    </body>

    </html></code>```

Title: How to change source of <img> tag on hover?

Body:
I need to change  source URL on hover.

I have tried this but won't work :

HTML

CSS

#my-img:hover {
    content: url('http://dummyimage.com/100x100/eb00eb/fff');
}

jsFiddle

Any help would be appreciated.

Update:

This only works for Webkit / Google Chrome.

Body:
Try This Code.

   .card {

            width: 200px;

            height: 195px;

            position: relative;

            display: inline-block;

        }

        .card .img-top {

            display: none;

            position: absolute;

            top: 0;

            left: 0;

            z-index: 99;
width:200px;
        }

        .card:hover .img-top {

            display: inline;

        }

 <!DOCTYPE html>

    <html lang="en">

    <head>

    <title>Image Change on Hover with CSS</title>

    </head>

    <body>

        <div class="card">

            <img src="http://www.dhresource.com/200x200s/f2-albu-g5-M00-EC-97-rBVaJFkAobCAHD9XAADvz9DDocA266.jpg/diy-wall-stickers-home-decor-nature-colorful.jpg" alt="Card Back" style="width:200px">

            <img src="https://s-media-cache-ak0.pinimg.com/236x/31/17/98/3117987a0be0a7d8976869aabf54d2d7.jpg" class="img-top" alt="Card Front">

        </div>

    </body>

    </html>


问:
Passing parameters between tab fragments by using FragmentTabHost
I need to pass data between tab fragments after calling switch method of tabhost mTabHost.setCurrentTab(index);

```<code>public class FragmentTabs extends FragmentActivity {
    private FragmentTabHost mTabHost;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.fragment_tabs);
        mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.content);

        mTabHost.addTab(mTabHost.newTabSpec("class1").setIndicator("Class 1"),
            Class1.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("class2").setIndicator("Class 2"),
            Class2.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("class3").setIndicator("Class C"),
            Class3.class, null);
    }
}
</code>```

Is there any way to do that ?

答:
Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.

Check this: https://developer.android.com/training/basics/fragments/communicating.html

Body:
I need to pass data between tab fragments after calling switch method of tabhost mTabHost.setCurrentTab(index);

public class FragmentTabs extends FragmentActivity {
    private FragmentTabHost mTabHost;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.fragment_tabs);
        mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.content);

        mTabHost.addTab(mTabHost.newTabSpec("class1").setIndicator("Class 1"),
            Class1.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("class2").setIndicator("Class 2"),
            Class2.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("class3").setIndicator("Class C"),
            Class3.class, null);
    }
}

Is there any way to do that ?


问:
select option selected by 2 times jquery not working properly
```<code>$(".treatment-btn").click(function()
{
    $("#treatmentModal").modal('show');
    $('.treatment-form')[0].reset();
    $('#treatmentModal #treatment_time option').removeAttr("selected");
    $('#treatmentModal #treatment_time option[value=""]').attr("selected", "selected");
}); //when i click on this button it resets form successfully but select option is not reset.

function makeEditHtml(response) {
var price = response[0].treatment_price.split(".")[0];
var cent = response[0].treatment_price.split(".")[1];
$("#treatmentModal #treatment").val(response[0].treatment_name);
$("#treatmentModal #price").val(price);
$('#treatmentModal #cent option[value='+cent+']').attr("selected", "selected");
$('#treatmentModal #treatment_time option').removeAttr("selected");
$('#treatmentModal #treatment_time option[value='+response[0].treatment_duration+']').attr("selected", "selected"); //i select it again at here after ajax call
$.each(response, function(i)
{
    $("#treatmentModal input[type=checkbox][value="+response[i].worker_id+"]").prop("checked",true);
});
$("#treatmentModal").modal('show');
}
</code>```

<p>// and this is called when ajax request fires i append data in same form but select box value not selected. it is showing correct in firebug but not display on screen. first time it is working fine</p>

答:
Change your click function code to below. To reset select you can simply set its value to blank.

```<code>$(".treatment-btn").click(function()
{
   $("#treatmentModal").modal('show');
   $('.treatment-form')[0].reset();
   $('#treatmentModal #treatment_time').val("");
 });
</code>```

Change the other code accordingly. Hope it helps!

Body:
$(".treatment-btn").click(function()
{
    $("#treatmentModal").modal('show');
    $('.treatment-form')[0].reset();
    $('#treatmentModal #treatment_time option').removeAttr("selected");
    $('#treatmentModal #treatment_time option[value=""]').attr("selected", "selected");
}); //when i click on this button it resets form successfully but select option is not reset.

function makeEditHtml(response) {
var price = response[0].treatment_price.split(".")[0];
var cent = response[0].treatment_price.split(".")[1];
$("#treatmentModal #treatment").val(response[0].treatment_name);
$("#treatmentModal #price").val(price);
$('#treatmentModal #cent option[value='+cent+']').attr("selected", "selected");
$('#treatmentModal #treatment_time option').removeAttr("selected");
$('#treatmentModal #treatment_time option[value='+response[0].treatment_duration+']').attr("selected", "selected"); //i select it again at here after ajax call
$.each(response, function(i)
{
    $("#treatmentModal input[type=checkbox][value="+response[i].worker_id+"]").prop("checked",true);
});
$("#treatmentModal").modal('show');
}

// and this is called when ajax request fires i append data in same form but select box value not selected. it is showing correct in firebug but not display on screen. first time it is working fine

Body:
Change your click function code to below. To reset select you can simply set its value to blank.

$(".treatment-btn").click(function()
{
   $("#treatmentModal").modal('show');
   $('.treatment-form')[0].reset();
   $('#treatmentModal #treatment_time').val("");
 });

Change the other code accordingly. Hope it helps!


问:
Optimizing multiple output variables of a function in Python
I'm currently working on an algorithm that determines the cost of a wind turbine support structure. The algorithm I'm writing needs to optimize the weight of an initial input support structure so that the stress levels will not exceed but be near to the failure criteria of the properties of the materials used. Another requirement is that the natural frequency of the structure needs to be bounded between 2 values. To optimize the structure 4 variables can be altered.

Can I use a function from the Scipy.Optimize library that optimizes the weight of this structure using several design parameters, but keeps into account the natural frequency and the maximum stress value in the support structure?

The function I'm optimizing looks like this:

```<code>def func(self, x):
    self.properties.D_mp = x[0]                    # Set a new diameter for the monopile
    self.properties.Dtrat_tower = x[1]             # Set a new thickness ratio for the tower
    self.properties.Dtrat_tp = x[2]                # Set a new thickness ratio for the transition piece
    self.properties.Dtrat_mud = x[3]               # Set a new thickness ratio for the mudline region of the monopile

    self.UpdateAll()                               # Update the support structure based on the changes in variables above

    eig = self.GetEigenFrequency()                 # Get the natural frequency
    maxUtil = self.GetMaximumUtilisationFactor()   # Get the maximum utilisation ratio on the structure (more than 1 means stress is higher than maximum allowed)

    # Natural frequency of 0.25 and utilisation ratio of 1 are ideal
    # Create some penalty...
    penalty = (100000 * abs((eig - 0.25)))
    penalty +=  (100000 * abs(maxUtil - 1))

    return self.GetTotalMass() + penalty
</code>```

Thanks in advance!

答:
It is probably easiest to make this a single-value optimization problem by folding in the frequency and stress constraints as penalties to the overall fitness, something like

```<code>LOW_COST = 10.
MID_COST = 150.
HIGH_COST = 400.

def weight(a, b, c, d):
    return "calculated weight of structure"

def frequency(a, b, c, d):
    return "calculated resonant frequency"

def freq_penalty(freq):
    # Example linear piecewise penalty function -
    #   increasing cost for frequencies below 205 or above 395
    if freq < 205:
        return MID_COST * (205 - freq)
    elif freq < 395:
        return 0.
    else:
        return MID_COST * (freq - 395)

def stress_fraction(a, b, c, d):
    return "calculated stress / failure criteria"

def stress_penalty(stress_frac):
    # Example linear piecewise penalty function -
    #   low extra cost for stress fraction below 0.85,
    #   high extra cost for stress fraction over 0.98
    if stress_frac < 0.85:
        return LOW_COST * (0.85 - stress_frac)
    elif stress_frac < 0.98:
        return 0.
    else:
        return HIGH_COST * (stress_frac - 0.98)

def overall_fitness(parameter_vector):
    a, b, c, d = parameter_vector
    return (
        # D'oh! it took me a while to get this right -
        # we want _minimum_ weight and _minimum_ penalty
        # to get _maximum_ fitness.
       -weight(a, b, c, d)
      - freq_penalty(frequency(a, b, c, d))
      - stress_penalty(stress_fraction(a, b, c, d)
    )
</code>```

... you will of course want to find more suitable penalty functions and play with the relative weighting, but this should give you the general idea. Then you can maximize it like

```<code>from scipy.optimize import fmin

initial_guess = [29., 45., 8., 0.06]
result = fmin(lambda x: -overall_fitness(x), initial_guess, maxfun=100000, full_output=True)
</code>```

(using the lambda lets fmin (a minimizer) find a maximum value for overall_fitness).

Alternatively, fmin allows a callback function which is applied after each iteration; you could use this to put hard limits on frequency IF you know how to tweak a,b,c,d appropriately - something like

```<code>def callback(x):
    a, b, c, d = x     # unpack parameter vector
    freq = frequency(a, b, c, d)
    if freq < 205:
        # apply appropriate correction to put frequency back in bounds
        return [a, b, c + 0.2, d]
    elif freq < 395:
        return x
    else:
        return [a, b, c - 0.2, d]
</code>```

Body:
I'm currently working on an algorithm that determines the cost of a wind turbine support structure. The algorithm I'm writing needs to optimize the weight of an initial input support structure so that the stress levels will not exceed but be near to the failure criteria of the properties of the materials used. Another requirement is that the natural frequency of the structure needs to be bounded between 2 values. To optimize the structure 4 variables can be altered.

Can I use a function from the Scipy.Optimize library that optimizes the weight of this structure using several design parameters, but keeps into account the natural frequency and the maximum stress value in the support structure?

The function I'm optimizing looks like this:

def func(self, x):
    self.properties.D_mp = x[0]                    # Set a new diameter for the monopile
    self.properties.Dtrat_tower = x[1]             # Set a new thickness ratio for the tower
    self.properties.Dtrat_tp = x[2]                # Set a new thickness ratio for the transition piece
    self.properties.Dtrat_mud = x[3]               # Set a new thickness ratio for the mudline region of the monopile

    self.UpdateAll()                               # Update the support structure based on the changes in variables above

    eig = self.GetEigenFrequency()                 # Get the natural frequency
    maxUtil = self.GetMaximumUtilisationFactor()   # Get the maximum utilisation ratio on the structure (more than 1 means stress is higher than maximum allowed)

    # Natural frequency of 0.25 and utilisation ratio of 1 are ideal
    # Create some penalty...
    penalty = (100000 * abs((eig - 0.25)))
    penalty +=  (100000 * abs(maxUtil - 1))

    return self.GetTotalMass() + penalty

Thanks in advance!

Body:
It is probably easiest to make this a single-value optimization problem by folding in the frequency and stress constraints as penalties to the overall fitness, something like

LOW_COST = 10.
MID_COST = 150.
HIGH_COST = 400.

def weight(a, b, c, d):
    return "calculated weight of structure"

def frequency(a, b, c, d):
    return "calculated resonant frequency"

def freq_penalty(freq):
    # Example linear piecewise penalty function -
    #   increasing cost for frequencies below 205 or above 395
    if freq < 205:
        return MID_COST * (205 - freq)
    elif freq < 395:
        return 0.
    else:
        return MID_COST * (freq - 395)

def stress_fraction(a, b, c, d):
    return "calculated stress / failure criteria"

def stress_penalty(stress_frac):
    # Example linear piecewise penalty function -
    #   low extra cost for stress fraction below 0.85,
    #   high extra cost for stress fraction over 0.98
    if stress_frac < 0.85:
        return LOW_COST * (0.85 - stress_frac)
    elif stress_frac < 0.98:
        return 0.
    else:
        return HIGH_COST * (stress_frac - 0.98)

def overall_fitness(parameter_vector):
    a, b, c, d = parameter_vector
    return (
        # D'oh! it took me a while to get this right -
        # we want _minimum_ weight and _minimum_ penalty
        # to get _maximum_ fitness.
       -weight(a, b, c, d)
      - freq_penalty(frequency(a, b, c, d))
      - stress_penalty(stress_fraction(a, b, c, d)
    )

... you will of course want to find more suitable penalty functions and play with the relative weighting, but this should give you the general idea. Then you can maximize it like

from scipy.optimize import fmin

initial_guess = [29., 45., 8., 0.06]
result = fmin(lambda x: -overall_fitness(x), initial_guess, maxfun=100000, full_output=True)

(using the lambda lets fmin (a minimizer) find a maximum value for overall_fitness).

Alternatively, fmin allows a callback function which is applied after each iteration; you could use this to put hard limits on frequency IF you know how to tweak a,b,c,d appropriately - something like

def callback(x):
    a, b, c, d = x     # unpack parameter vector
    freq = frequency(a, b, c, d)
    if freq < 205:
        # apply appropriate correction to put frequency back in bounds
        return [a, b, c + 0.2, d]
    elif freq < 395:
        return x
    else:
        return [a, b, c - 0.2, d]


问:
Is it possible to create Ionic 2 project in Ionic 3 CLI
When I do this, I get the message below:

Command :

```<code>ionic start blank myapp --v2
</code>```

Error :

[ERROR] Sorry! The --v1 and --v2 flags have been removed.
          Use the --type option. (ionic start --help)
          For Ionic Angular projects, try ionic start blank myapp --type=ionic-angular

My Ionic CLI version is :

```<code>ionic -v
3.3.0
</code>```

答: You don't have to specify --v2 for an Ionic 2 project because an Ionic 3 project is just an Ionic 2 project with some new features such as lazy loading and adoption of Angular 4 instead of Angular 2 .Just like Angular 2 and 4 are the same framework ,Ionic 2 and 3 are the same also </p>

Body:
When I do this, I get the message below:

Command :

ionic start blank myapp --v2

Error :

[ERROR] Sorry! The --v1 and --v2 flags have been removed.
          Use the --type option. (ionic start --help)
          For Ionic Angular projects, try ionic start blank myapp --type=ionic-angular

My Ionic CLI version is :

ionic -v
3.3.0


问:
How to display specific img on li hover without get request in react?
I have 4 boxes(
 elements) and 4 images. Task is to show specific image when user hovers specific box. If user hovers over box 0 show image 0 if 1 show image 1.

On hover I update the state currantBox(for example currantBox: 1) and pass it to the img src attribute like so:

```<code><img src={this.props.content[this.props.currantBox]}/>
</code>```

content is a JSON array with img paths. Problem is that react on each hover ie render ie state update React makes get request to download the image, which is not efficient at all.

What is the best way to implement my idea or fix currant implementation?

答: If the images are not going to be changed I would suggest an entirely CSS solution. You could generate sprite with the 4 images and change the background-position property on hover.

Body:
I have 4 boxes(
 elements) and 4 images. Task is to show specific image when user hovers specific box. If user hovers over box 0 show image 0 if 1 show image 1.

On hover I update the state currantBox(for example currantBox: 1) and pass it to the img src attribute like so:

content is a JSON array with img paths. Problem is that react on each hover ie render ie state update React makes get request to download the image, which is not efficient at all.

What is the best way to implement my idea or fix currant implementation?


答:
You'll want to use a lookup map for that, instead of multiple variables:

```<code>var codes = {
    1: "This is a summary",
    300: "This is a note"
};
</code>```

With that you can do

```<code>if (statusCode in codes) {
    scriptletResult = codes[statusCode];
} else {
    scriptletResult = codes[1];
}
</code>```

Title: Functional switch statement in Javascript

Body:
Say I have a switch statement that takes a variable myData between 1 and some larger value, i.e. 300.

Depending on the "status code" variable, the result is the text value of another variable. For example, if myData == 1, I want to return the a variable called code1. If myData == 300, I want to return the a variable called code300. Code1 and code300 variables store unrelated strings, i.e. "This is a summary", or "This is a note". Some psuedo-code below:

var myData = statusCode;

var code1 = "This is a summary";
var code300 = "This is a note";

switch(myData) {
    case statusCode:
        scriptletResult = returnCode("code", statusCode); // code1 if myData == 1
        break;
    default:
        scriptletResult = code1;
}

function returnCode(code, statusCode) {
    return code + statusCode; // Returns a variable "code1" if statusCode == 1
}

How can I get this to work?

Body:
You'll want to use a lookup map for that, instead of multiple variables:

var codes = {
    1: "This is a summary",
    300: "This is a note"
};

With that you can do

if (statusCode in codes) {
    scriptletResult = codes[statusCode];
} else {
    scriptletResult = codes[1];
}


问:
How to restart one live node from a multi node cassandra cluster?
I have a production cassandra cluster of 6 nodes. I have made some changes to the cassandra.yaml file on one node and hence need to restart it.
How can I do it without losing any data or causing any cluster related issues?
Can I just kill the cassandra process on that particular node and start it again.
Cluster Info:
6 nodes. All active.
I am using AWS Ec2Snitch.

Thanks.

答:
In case you are using replication factor greater than 1, and not using ALL consistency setting on your writes/reads, you can perform steps listed below, without any downtime/data loss. In case you have one of the limitations listed above, you'll need to increase your replication factor/change requests consistency before you continue.

Perform nodetool drain on that node (http://docs.datastax.com/en/cassandra/2.1/cassandra/tools/toolsDrain.html).

Stop the service.

Start the service.

In Cassandra, if durable writes are enabled, you should not lose data anyway - there's a mechanism of commitlog log replay in case of accidental restart, so you should not lose any data if doing just restart, but replaying commitlog can take some time.

The steps written above are a part of official upgrade procedure, and should be the "safest" option. You can do nodetool flush + restart, this will ensure that commitlog replay will be minimal and can be faster than drain approach.


问:
PHP sessions not initiated in Kohana https site
In our PHP Kohana Website, PHP sessions are not being initialized in https site (Kohana sessions works fine). The same works fine in http as well as in the local machine. We feel it is something related to configurations. If this issue is related to configurations, what are the config file I have to dig into else what might be the problem ?

I tried changing sessions.auto_start to 1 from 0, but it didn't work.

Below is the logic where Sessions are not being initialized.

`

```<code>session_start();
$digit = '';
$keys = array_merge(range(0, 9), range('a', 'z'), range('A', 'Z'));
for($x = 10; $x <= 130; $x += 30) {
    $digit .= ($num = $keys[array_rand($keys)]);
}
$_SESSION['captchaCodeValue'] = $digit;
</code>```

答: Fixed this issue by moving the php session in to Kohana sesion, since I was not able to find what is wrong with the php session and the relevent configuration file to be changed.</p>

Body:
In our PHP Kohana Website, PHP sessions are not being initialized in https site (Kohana sessions works fine). The same works fine in http as well as in the local machine. We feel it is something related to configurations. If this issue is related to configurations, what are the config file I have to dig into else what might be the problem ?

I tried changing sessions.auto_start to 1 from 0, but it didn't work.

Below is the logic where Sessions are not being initialized.

`

session_start();
$digit = '';
$keys = array_merge(range(0, 9), range('a', 'z'), range('A', 'Z'));
for($x = 10; $x <= 130; $x += 30) {
    $digit .= ($num = $keys[array_rand($keys)]);
}
$_SESSION['captchaCodeValue'] = $digit;


问:
run iperf broadcast traffic on linux
I am in the domain 192.168.1.xxx. I need to send broadcast traffic from a pc connected to a accesspoint to the android device wirelessly after connecting with a network through WiFi.

running iperf command iperf -c 192.168.1.255 -i 2 -t 60 -b 10000 -u on a Ubuntu 12.04 machine and running the command iperf -s -i 2 -u in adb shell.
But the client is unable to get the broadcast traffic and gives error as :

```<code> read failed : connection refused.
</code>```

答:
You can leverage DHCP's properties, DHCP is advertised with a broadcast DISCORVERY package, so by putting a DHCP-server and a DHCP-client (normal host) at the ends of your network you can test broadcast traffic within it.
If you get an address -> you're OK
If you keep waiting and nothing happens -> something went wrong

Hope this helps you ;)

Title: run iperf broadcast traffic on linux

Body:
I am in the domain 192.168.1.xxx. I need to send broadcast traffic from a pc connected to a accesspoint to the android device wirelessly after connecting with a network through WiFi.

running iperf command iperf -c 192.168.1.255 -i 2 -t 60 -b 10000 -u on a Ubuntu 12.04 machine and running the command iperf -s -i 2 -u in adb shell.
But the client is unable to get the broadcast traffic and gives error as :

 read failed : connection refused.