问:
Stop Duplicate Ajax Submisions?
I am wondering what is the best way to stop duplciate submissions when using jquery and ajax?

I come up with 2 possible ways but not sure if these are the only 2.

On Ajax start disable all buttons till request is done. 2 problems I see with this though is I use jquery model dialog so I don't know how easy it would be to disable those button as I not sure if they have id's. Second I if the the request hangs the user has really no way to try again since all the buttons are disabled.

I am looking into something called AjaxQueue at this time I have no clue if it is what I need or how it works since the site where the plugin is apparently down for maintenance.

http://docs.jquery.com/AjaxQueue

Edit

I think this is a spin off of what I was looking at.

http://www.protofunc.com/scripts/jquery/ajaxManager/

The only problem I see with this ajaxManager is that I think I have to change all my $.post, $.get and $.ajax ones to their type.

But what happens if I need a special parameter from $.ajax? Or that fact I like using .post and .get.

Edit 2

I think it can take in all $.ajax options. I am still looking into it. However what I am unsure about now is can I use the same constructor for all requests that will use the same options.

```<code>First you have to construct/configure a new Ajaxmanager
//create an ajaxmanager named someAjaxProfileName
var someManagedAjax = $.manageAjax.create('someAjaxProfileName', {
    queue: true,
    cacheResponse: true
});
</code>```

Or do I have to make the above every single time?

答:
```<code>$.xhrPool = {};
$.xhrPool['hash'] = []
$.ajaxSetup({
    beforeSend: function(jqXHR,settings) {
        var hash = settings.url+settings.data
        if ( $.xhrPool['hash'].indexOf(hash) === -1 ){
            jqXHR.url   = settings.url;
            jqXHR.data  = settings.data;
            $.xhrPool['hash'].push(hash);
        }else{
            console.log('Duplicate request cancelled!');
            jqXHR.abort();
        }
    },
    complete: function(jqXHR,settings) {
        var hash = jqXHR.url+jqXHR.data
            if (index > -1) {
                $.xhrPool['hash'].splice(index, 1);
            }
        }
    });
</code>```

Title: Stop Duplicate Ajax Submisions?

Body:
I am wondering what is the best way to stop duplciate submissions when using jquery and ajax?

I come up with 2 possible ways but not sure if these are the only 2.

On Ajax start disable all buttons till request is done. 2 problems I see with this though is I use jquery model dialog so I don't know how easy it would be to disable those button as I not sure if they have id's. Second I if the the request hangs the user has really no way to try again since all the buttons are disabled.

I am looking into something called AjaxQueue at this time I have no clue if it is what I need or how it works since the site where the plugin is apparently down for maintenance.

http://docs.jquery.com/AjaxQueue

Edit

I think this is a spin off of what I was looking at.

http://www.protofunc.com/scripts/jquery/ajaxManager/

The only problem I see with this ajaxManager is that I think I have to change all my $.post, $.get and $.ajax ones to their type.

But what happens if I need a special parameter from $.ajax? Or that fact I like using .post and .get.

Edit 2

I think it can take in all $.ajax options. I am still looking into it. However what I am unsure about now is can I use the same constructor for all requests that will use the same options.

First you have to construct/configure a new Ajaxmanager
//create an ajaxmanager named someAjaxProfileName
var someManagedAjax = $.manageAjax.create('someAjaxProfileName', {
    queue: true,
    cacheResponse: true
});

Or do I have to make the above every single time?


来源: stackexchange

问:
Call a variadic function using a variable template
Consider the following code:

```<code>template<typename T, typename... Args>
void foo(const Args&... args)
{
    //...
}

template<typename... Args>
auto fooChar = foo<char, Args...>;

template<typename... Args>
auto fooInt = foo<int, Args...>;
</code>```

To be able to make use of these variable templates, I need to explicitely type the template parameters, like so:

```<code>fooChar<int, char, const char*>(5, 'a', "bar");
</code>```

However, in a standard variadic function call, the template parameters are implicitely deduced based on the actual function parameters type. In other words, I would like to be able to use the variable templates like so, but the extra level of indirection seems to restrict this:

```<code>fooChar(5, 'a', "bar");
</code>```

Obviously, I could simply define simple wrapper functions instead of variable templates, like so:

```<code>template<typename... Args>
void fooChar(const Args&... args)
{
    return foo<char>(args...);
}

template<typename... Args>
void fooInt(const Args&... args)
{
    return foo<int>(args...);
}
</code>```

But overall, it just seems bulkier and less convenient. So, is there any way I could achieve the same result while using variable templates? If not, why is it impossible for the compiler to "forward" the parameters to the aliased function and thus deduce the variadic types?

答:
You could wrap foo() in a struct:

```<code>template <class T>
struct fooWrapper {
    template <class... Args>
    void operator()(Args const&... args) const {
        foo<T>(args...);
    }
};
</code>```

Now make your variable templates be instantiations of this wrapper:

```<code>fooWrapper<char> fooChar;
fooWrapper<int> fooInt;
</code>```

With the added bonus that you can pass fooChar to a function template, since it itself is not a function template.

ContentLicense: CC BY-SA 3.0

Body:
Consider the following code:

template<typename T, typename... Args>
void foo(const Args&... args)
{
    //...
}

template<typename... Args>
auto fooChar = foo<char, Args...>;

template<typename... Args>
auto fooInt = foo<int, Args...>;

To be able to make use of these variable templates, I need to explicitely type the template parameters, like so:

fooChar<int, char, const char*>(5, 'a', "bar");

However, in a standard variadic function call, the template parameters are implicitely deduced based on the actual function parameters type. In other words, I would like to be able to use the variable templates like so, but the extra level of indirection seems to restrict this:

fooChar(5, 'a', "bar");

Obviously, I could simply define simple wrapper functions instead of variable templates, like so:

template<typename... Args>
void fooChar(const Args&... args)
{
    return foo<char>(args...);
}

template<typename... Args>
void fooInt(const Args&... args)
{
    return foo<int>(args...);
}

But overall, it just seems bulkier and less convenient. So, is there any way I could achieve the same result while using variable templates? If not, why is it impossible for the compiler to "forward" the parameters to the aliased function and thus deduce the variadic types?

Body:
You could wrap foo() in a struct:

template <class T>
struct fooWrapper {
    template <class... Args>
    void operator()(Args const&... args) const {
        foo<T>(args...);
    }
};

Now make your variable templates be instantiations of this wrapper:

fooWrapper<char> fooChar;
fooWrapper<int> fooInt;

With the added bonus that you can pass fooChar to a function template, since it itself is not a function template.


问:
DocuSign API: Sign Here Tab - Optional signature
I see there is an 'Optional' parameter for the Sign Here Tab. I am wondering if it is possible to make it so that if a signature is not given within x number of days, to consider the recipient complete and move on to the next recipient. Is something like this doable with Docusign API?

In other words, give the signer x number of days to sign, or else move on to next recipient so the envelope can be completed in timely fashion.

Thanks

答:
The expiration date can be set at an envelope level.  DocuSign does NOT support setting per recipient expiration for an envelope.

See this blog for more information


问:
How to add another graph to AmCharts Gantt to show custom icons
I have a gantt chart with a few minor tweaks but basically a clone of This gantt example with dates.

What I am trying to do is have a number of icons next to the segment based off some info included in the segment data. My case involves having 3 different binary variables and including different icons depending the values.

```<code>  var chartData = [{
        category: task.name,
        segments: [
          {
            start: task.parallel ? lastStart : moment(latestEnd).format(string),
            end: task.parallel ? moment(lastStart).add(time,'m').format(string) : moment(latestEnd).add(time,'m').format(string),
            color: '#1C7DDB',
            time: task.time,
            indicator1: task.checkOne== 1 ? '../img/path_to_icon.svg' : '',
            indicator2: task.checkTwo== 1 ? '../img/path_to_icon2.svg' : '',
            indicator3: task.checkThree== 1 ? '../img/path_to_icon3.svg': ''
          }
        ]
      },
      ...
      }]
</code>```

So far this works OK when I set the customeBullet to one of the variables:

However I want to be able to have the ability to have all 3 (or none) of the icons shown.

I think what I need to do is add the segment data first then add the icons as three graphs to the gantt with no visible line.

My current chart init code is here, I tried changing graph: {} to graphs: [] but that causes an error.

```<code>var chart = AmCharts.makeChart( "plannerChart", {
      "type": "gantt",
      "marginRight": 70,
      "period": "DD",
      "dataDateFormat": "YYYY-MM-DD HH:mm",
      "columnWidth": 0.75,
      "addClassNames": true,
      "valueAxis": {
        "type": "date",
        "guides": [
          {
            "value": AmCharts.stringToDate( start, "YYYY-MM-DD HH:NN"),
            "toValue": AmCharts.stringToDate( moment(start).add(timeWindow,'h').format('YYYY-MM-DD HH:mm'), "YYYY-MM-DD HH:NN"),
            "lineAlpha": 0.2,
            "lineColor": guideColor,
            "lineThickness": 3,
            "fillAlpha": 0.1,
            "fillColor": guideColor,
            "label": "Available time",
            "inside": false
          }
        ]
      },
      "brightnessStep": 7,
      "graph": {
        "fillAlphas": 1,
        "lineAlpha": 1,
        "bulletOffset": 25,
        "bulletSize": 20,
        "customBulletField": "indicator1",
        "lineColor": "#0F238C",
        "fillAlphas": 0.85,
        "balloonText": "<b>Start</b>: [[start]]<br /><b>Finish</b>: [[end]]"
      },
      "rotate": true,
      "categoryField": "category",
      "segmentsField": "segments",
      "colorField": "color",
      "startDateField": "start",
      "endDateField": "end",
      "dataProvider": chartData,
      "chartCursor": {
        "cursorColor": "#0F238C",
        "valueBalloonsEnabled": false,
        "cursorAlpha": 0,
        "valueLineAlpha": 0.5,
        "valueLineBalloonEnabled": true,
        "valueLineEnabled": true,
        "zoomable": false,
        "valueZoomable": false
      },
    } );
  }
</code>```

Any help appreciated!

M

答:
This isn't possible in a Gantt chart as it only takes a single graph object, as you noticed when trying to use an array.

You can emulate a Gantt chart by making a multi-segmented floating  bar chart, using the graph's openField property to simulate where the column starts. You can extend this to add your additional graph objects for your indicators and use a date-based valueAxis for your values (note that valueAxes require date objects or millisecond timestamps, so strings won't work) or use relative values like in the demo. Note that this is a little clunker than the Gantt chart in that you have to define multiple graph objects to simulate the segments on the same category.

Body:
I have a gantt chart with a few minor tweaks but basically a clone of This gantt example with dates.

What I am trying to do is have a number of icons next to the segment based off some info included in the segment data. My case involves having 3 different binary variables and including different icons depending the values.

  var chartData = [{
        category: task.name,
        segments: [
          {
            start: task.parallel ? lastStart : moment(latestEnd).format(string),
            end: task.parallel ? moment(lastStart).add(time,'m').format(string) : moment(latestEnd).add(time,'m').format(string),
            color: '#1C7DDB',
            time: task.time,
            indicator1: task.checkOne== 1 ? '../img/path_to_icon.svg' : '',
            indicator2: task.checkTwo== 1 ? '../img/path_to_icon2.svg' : '',
            indicator3: task.checkThree== 1 ? '../img/path_to_icon3.svg': ''
          }
        ]
      },
      ...
      }]

So far this works OK when I set the customeBullet to one of the variables:

However I want to be able to have the ability to have all 3 (or none) of the icons shown.

I think what I need to do is add the segment data first then add the icons as three graphs to the gantt with no visible line.

My current chart init code is here, I tried changing graph: {} to graphs: [] but that causes an error.

var chart = AmCharts.makeChart( "plannerChart", {
      "type": "gantt",
      "marginRight": 70,
      "period": "DD",
      "dataDateFormat": "YYYY-MM-DD HH:mm",
      "columnWidth": 0.75,
      "addClassNames": true,
      "valueAxis": {
        "type": "date",
        "guides": [
          {
            "value": AmCharts.stringToDate( start, "YYYY-MM-DD HH:NN"),
            "toValue": AmCharts.stringToDate( moment(start).add(timeWindow,'h').format('YYYY-MM-DD HH:mm'), "YYYY-MM-DD HH:NN"),
            "lineAlpha": 0.2,
            "lineColor": guideColor,
            "lineThickness": 3,
            "fillAlpha": 0.1,
            "fillColor": guideColor,
            "label": "Available time",
            "inside": false
          }
        ]
      },
      "brightnessStep": 7,
      "graph": {
        "fillAlphas": 1,
        "lineAlpha": 1,
        "bulletOffset": 25,
        "bulletSize": 20,
        "customBulletField": "indicator1",
        "lineColor": "#0F238C",
        "fillAlphas": 0.85,
        "balloonText": "Start: [[start]]
Finish: [[end]]"
      },
      "rotate": true,
      "categoryField": "category",
      "segmentsField": "segments",
      "colorField": "color",
      "startDateField": "start",
      "endDateField": "end",
      "dataProvider": chartData,
      "chartCursor": {
        "cursorColor": "#0F238C",
        "valueBalloonsEnabled": false,
        "cursorAlpha": 0,
        "valueLineAlpha": 0.5,
        "valueLineBalloonEnabled": true,
        "valueLineEnabled": true,
        "zoomable": false,
        "valueZoomable": false
      },
    } );
  }

Any help appreciated!

M


问:
Python Sort string by frequency - cannot sort with sorted() function

I have an issue with sorting a simple string by frequency (I get a string as an input, and I need to give a sorted string back as an output in descending order).
Let me give you an example (the original word contains 4 e's, 2 s's, 1 t, 1 r and 1 d; so these get sorted):

In [1]: frequency_sort("treeseeds")
Out [1]: "eeeesstrd"
```

<p>Most solutions on Stack Overflow state that I should use the <code>sorted()</code> function to get my results, however, it only seems to work with certain cases.</p>

<p>I made two functions that supposed to work, but none of them seems to do the trick with my specific inputs (see below).</p>

<p><b>First function:</b></p>

<pre class="lang-py prettyprint-override"><code>def frequency_sort(s):
    s_sorted = sorted(s, key=s.count, reverse=True)
    s_sorted = ''.join(c for c in s_sorted)
    return s_sorted
</code>```

Second function:

import collections
def frequency_sort_with_counter(s):
    counter = collections.Counter(s)
    s_sorted = sorted(s, key=counter.get, reverse=True)
    s_sorted = ''.join(c for c in s_sorted)
    return s_sorted
```

<p>With both functions my outputs look like this:</p>

<p>The first output is okay:</p>

<pre class="lang-py prettyprint-override"><code>In [1]: frequency_sort("loveleee")
Out [1]: "eeeellov"
</code>```

The second output is not so much

In [2]: frequency_sort("loveleel")
Out [2]: "leleelov"
```

<p>The third output is totally messy:</p>

<pre class="lang-py prettyprint-override"><code>In [3]: frequency_sort("oloveleelo")
Out [3]: "oloeleelov"
</code>```

What could have gone wrong? Is it connected to the 'o' and 'l' characters somehow? Or am I just missing something?

答:
In your third case, 3 letters have the same count that's why they are put together, you can sort it first(by alphabet) then sort it by frequency to arrange the letters as the following:

```<code>s_sorted = ''.join(sorted(sorted(s), key=lambda x: s.count(x), reverse=True))
</code>```

output:

```<code>eeellloooav
</code>```

or you can reverse it:

```<code>s_sorted = ''.join(sorted(sorted(s, reverse=True), key=lambda x: s.count(x), reverse=True))
</code>```

output:

```<code>ooollleeeva
</code>```

Body:
I have an issue with sorting a simple string by frequency (I get a string as an input, and I need to give a sorted string back as an output in descending order).
Let me give you an example (the original word contains 4 e's, 2 s's, 1 t, 1 r and 1 d; so these get sorted):

In [1]: frequency_sort("treeseeds")
Out [1]: "eeeesstrd"

Most solutions on Stack Overflow state that I should use the sorted() function to get my results, however, it only seems to work with certain cases.

I made two functions that supposed to work, but none of them seems to do the trick with my specific inputs (see below).

First function:

def frequency_sort(s):
    s_sorted = sorted(s, key=s.count, reverse=True)
    s_sorted = ''.join(c for c in s_sorted)
    return s_sorted

Second function:

import collections
def frequency_sort_with_counter(s):
    counter = collections.Counter(s)
    s_sorted = sorted(s, key=counter.get, reverse=True)
    s_sorted = ''.join(c for c in s_sorted)
    return s_sorted

With both functions my outputs look like this:

The first output is okay:

In [1]: frequency_sort("loveleee")
Out [1]: "eeeellov"

The second output is not so much

In [2]: frequency_sort("loveleel")
Out [2]: "leleelov"

The third output is totally messy:

In [3]: frequency_sort("oloveleelo")
Out [3]: "oloeleelov"

What could have gone wrong? Is it connected to the 'o' and 'l' characters somehow? Or am I just missing something?

Body:
In your third case, 3 letters have the same count that's why they are put together, you can sort it first(by alphabet) then sort it by frequency to arrange the letters as the following:

s_sorted = ''.join(sorted(sorted(s), key=lambda x: s.count(x), reverse=True))

output:

eeellloooav

or you can reverse it:

s_sorted = ''.join(sorted(sorted(s, reverse=True), key=lambda x: s.count(x), reverse=True))

output:

ooollleeeva


问:
how to use indexof in array set in angularjs
```<code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('myctrl', function($scope) {
    $scope.state = [{name:'TamilNadu', code:1}, {name:'Kerala', code:2}, {name:'Karnataka', code:3}];
    $scope.onChange = function() {
            var a = this.drop.state;  }
});
</script>
<body>

<div ng-app="myApp" ng-controller="myctrl">
State :
<select id="stat" ng-model="drop.state" ng-change="onChange()">
<option ng-repeat = "x in state"> {{x.name}} </option>
<select>
</div>
</body>
</code>```

In this code, I can be able to get the selected value from the textbox in the variable a. Now, I need to get the code value of the name selected. Is it possible using indexof(). And I need it in dynamic ie., when the 'state' is selected I need that corresponding 'code' from the array set.

答:
You can bind data to a single property., and can access both. with preferred ng-options .

    State :
    <select id="stat" ng-model="drop.state" ng-options= "x as x.name for x in state" ng-change="onChange()"> </select>

```

Body:
State :
<select id="stat" ng-model="drop.state" ng-change="onChange()">
<option ng-repeat = "x in state"> {{x.name}} </option>
<select>

In this code, I can be able to get the selected value from the textbox in the variable a. Now, I need to get the code value of the name selected. Is it possible using indexof(). And I need it in dynamic ie., when the 'state' is selected I need that corresponding 'code' from the array set.

Body:
You can bind data to a single property., and can access both. with preferred ng-options .

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
  var app = angular.module('myApp', []);
  app.controller('myctrl', function($scope) {
    $scope.state = [{
      name: 'TamilNadu',
      code: 1
    }, {
      name: 'Kerala',
      code: 2
    }, {
      name: 'Karnataka',
      code: 3
    }];
    $scope.onChange = function() {
     alert(this.drop.state.name);
     alert(this.drop.state.code);
    }
  });
</script>

<body>

  <div ng-app="myApp" ng-controller="myctrl">
    State :
    <select id="stat" ng-model="drop.state" ng-options= "x as x.name for x in state" ng-change="onChange()"> </select>

</div>
</body>


问:
MySQL backup - warning password insecure
I made this little script with Python to create a backup of a table from a database:

```<code>import subprocess
sql_cmd = 'mysql -B -u User -pPassword  -e Database "SELECT * FROMdevice;" > file.csv'
subprocess.run([sql_cmd], shell=True)
</code>```

It is working, but I got this warning message: mysql: [Warning] Using a password on the command line interface can be insecure.

I would like to hide or delete the warning if possible.

答:
Get the password from input</p>

```<code>import subprocess
import getpass

pswd = getpass.getpass('Password:')
sql_cmd = 'mysql -B -u User -p pswd  -e Database "SELECT * FROMdevice;" >
file.csv'
subprocess.run([sql_cmd], shell=True)
</code>```

Body:
I made this little script with Python to create a backup of a table from a database:

import subprocess
sql_cmd = 'mysql -B -u User -pPassword  -e Database "SELECT * FROMdevice;" > file.csv'
subprocess.run([sql_cmd], shell=True)

It is working, but I got this warning message: mysql: [Warning] Using a password on the command line interface can be insecure.

I would like to hide or delete the warning if possible.

Body:
Get the password from input

import subprocess
import getpass

pswd = getpass.getpass('Password:')
sql_cmd = 'mysql -B -u User -p pswd  -e Database "SELECT * FROMdevice;" >
file.csv'
subprocess.run([sql_cmd], shell=True)


答:
The problem is that sort and sorted are stable sorts. So if two values are "equal" (in this case key(item1) == key(item2)) they will appear in the same order as they were before the sort.

For example in your last case you have:

```<code>>>> from collections import Counter

>>> Counter("oloveleelo")
Counter({'e': 3, 'l': 3, 'o': 3, 'v': 1})
</code>```

So 'e', 'l' and 'o' have the same key, so they will appear just like they did originally: "oloeleelo" and then just comes the only character that has a different count: 'v'.

If you don't care about the order of elements with equal counts (just that they are grouped by character) you don't even need sorted, just flatten the result of Counter.most_common:

```<code>>>> ''.join([item for item, cnt in Counter("oloveleelo").most_common() for _ in range(cnt)])
'llleeeooov'
>>> ''.join([item for item, cnt in Counter("loveleel").most_common() for _ in range(cnt)])
'eeelllov'
>>> ''.join([item for item, cnt in Counter("loveleee").most_common() for _ in range(cnt)])
'eeeellov'
</code>```

Title: Python Sort string by frequency - cannot sort with sorted() function

Body:
The problem is that sort and sorted are stable sorts. So if two values are "equal" (in this case key(item1) == key(item2)) they will appear in the same order as they were before the sort.

For example in your last case you have:

>>> from collections import Counter

>>> Counter("oloveleelo")
Counter({'e': 3, 'l': 3, 'o': 3, 'v': 1})

So 'e', 'l' and 'o' have the same key, so they will appear just like they did originally: "oloeleelo" and then just comes the only character that has a different count: 'v'.

If you don't care about the order of elements with equal counts (just that they are grouped by character) you don't even need sorted, just flatten the result of Counter.most_common:

>>> ''.join([item for item, cnt in Counter("oloveleelo").most_common() for _ in range(cnt)])
'llleeeooov'
>>> ''.join([item for item, cnt in Counter("loveleel").most_common() for _ in range(cnt)])
'eeelllov'
>>> ''.join([item for item, cnt in Counter("loveleee").most_common() for _ in range(cnt)])
'eeeellov'


问:
WAMP server: change wireless SSID and server not reachable
This is a really strange thing.
I got a working WAMP server on my laptop, installed Laravel and a web application available to my clients on the local wireless network. Everything is working flawlessy. I can communicate between my android app via the wireless AP TP-Link to the WAMP server. No need of internet, this is a LAN just for devices behind.
Now, I decide to change the SSID of the AP. Change from "Zapp" to "Polls".
Restart everything: AP, laptop, mobile phone. The server is not more reachable by my mobile phone.
I can ping the IP address using a terminal app, but I can't access to it anymore. This, just changing the SSID. If I revert to "Zapp" SSID, everything work again.
I checked IP's: the change of SSID not change IP's of clients.

Could anyone explain and help?

Technical devices:
AP: TP-LINK TL-WR841R
Server WAMP v. 3.0.6 on a Toshiba Laptop
Android Phone OS 7.1 OnePlus3

答: Check Windows firewall profile. It might classify the network with the other SSID as Public and ports are not opened?</p>


问:
How to change security configutarion in IE8 for Intranet pages, such that Javascript can close a Window without asking?
I am developing a system that uses a little Internet page as a front-end for the whole program. Since I need to use ActiveX (sigh), the page must work on Internet Explorer.

However, after some actions have been done the page needs to close itself. Using window.close() on Javascript it works, but before closing it prompts the user if it wants to close the Window. The ideal would be that it closes automatically.

Is there any way to make IE8 (changing an option on the browser, not a code-only solution) not to prompt before closing the Window?

答: You must have the Windows Administrator mark the domain that the intranet site runs on as a trusted domain. That will set the site to run in "trusted" mode which will allow Javascript to run normally and things like NTLM authentication to be used.</p>

ContentLicense: CC BY-SA 2.5


问:
how can i achieve FibonacciSecret in php
I'm trying to get all the characters in that message at positions that are present in the Fibonacci sequence (a sequence formed by the the Fibonacci number sorted in ascending order). Please ignore whitespace characters and use the extended Fibonacci.

Return the obtained characters capitalized and connected by the '-' character.

Example

For message = "The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown",

the output should be

FibonacciSecret(message) = "T-H-H-E-D-V-C-E-M-T".

The first Fibonacci is 0 then the first letter is T

The second Fibonacci is 1 then the second letter is H

The third Fibonacci is 1 then the third letter is H ... and so on.

Thus, the answer should be "T-H-H-E-D-V-C-E-M-T".

Tried Code

```<code><?php
$message = 'The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown';
$str_split = str_split($message);

$x = 0;
$y = 1;

for($i=0;$i<=10;$i++)
{
    $z = $x + $y;
    $farray[] = $z;
    $x=$y;
    $y=$z;
}

foreach($farray as $key=>$fvalue){
       echo $str_split[$fvalue]."-";
}

?>
</code>```

Output

```<code>h-T-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-T-h-h-T-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-T-
</code>```

Expected Output

the answer should be "T-H-H-E-D-V-C-E-M-T".

Can anyone tell me. Where im going wrong in this one ?

答:
I think your Fibonacci logic is off. I munged up an example I found here:
https://www.easycalculation.com/code-php-program-fibonacci-series.html

Sequence:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34;

```<code><?php
$message = 'The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown';
$str_split = str_split(str_replace(' ', '', $message));

$n_value = 10;
$first_value = 0;
$second_value = 1;
$next_value = 0;
$c_value = 0;
$letters = [];

for ( $c_value = 0 ; $c_value < $n_value ; $c_value++ )
{
    if ( $c_value <= 1 ) {
         $next_value = $c_value;
    } else {
         $next_value = $first_value + $second_value;
         $first_value = $second_value;
         $second_value = $next_value;
    }
    $letters[] = $str_split[$next_value];
}

echo implode($letters, "-");
</code>```

Output:

T-h-h-e-D-V-c-e-m-t

Run it here:
http://sandbox.onlinephpfunctions.com/code/45c72df556c19e239e09ba0e334ace1e40ce809c

Here's an interesting reference thread for PHP fibonacci:
PHP Fibonacci Sequence

Body:
I'm trying to get all the characters in that message at positions that are present in the Fibonacci sequence (a sequence formed by the the Fibonacci number sorted in ascending order). Please ignore whitespace characters and use the extended Fibonacci.

Return the obtained characters capitalized and connected by the '-' character.

Example

For message = "The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown",

the output should be

FibonacciSecret(message) = "T-H-H-E-D-V-C-E-M-T".

The first Fibonacci is 0 then the first letter is T

The second Fibonacci is 1 then the second letter is H

The third Fibonacci is 1 then the third letter is H ... and so on.

Thus, the answer should be "T-H-H-E-D-V-C-E-M-T".

Tried Code

<?php
$message = 'The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown';
$str_split = str_split($message);

$x = 0;
$y = 1;

for($i=0;$i<=10;$i++)
{
    $z = $x + $y;
    $farray[] = $z;
    $x=$y;
    $y=$z;
}

foreach($farray as $key=>$fvalue){
       echo $str_split[$fvalue]."-";
}

?>

Output

h-T-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-T-h-h-T-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-T-

Expected Output

the answer should be "T-H-H-E-D-V-C-E-M-T".

Can anyone tell me. Where im going wrong in this one ?

Body:
I think your Fibonacci logic is off. I munged up an example I found here:
https://www.easycalculation.com/code-php-program-fibonacci-series.html

Sequence:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34;

<?php
$message = 'The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown';
$str_split = str_split(str_replace(' ', '', $message));

$n_value = 10;
$first_value = 0;
$second_value = 1;
$next_value = 0;
$c_value = 0;
$letters = [];

for ( $c_value = 0 ; $c_value < $n_value ; $c_value++ )
{
    if ( $c_value <= 1 ) {
         $next_value = $c_value;
    } else {
         $next_value = $first_value + $second_value;
         $first_value = $second_value;
         $second_value = $next_value;
    }
    $letters[] = $str_split[$next_value];
}

echo implode($letters, "-");

Output:

T-h-h-e-D-V-c-e-m-t

Run it here:
http://sandbox.onlinephpfunctions.com/code/45c72df556c19e239e09ba0e334ace1e40ce809c

Here's an interesting reference thread for PHP fibonacci:
PHP Fibonacci Sequence


问:
Whats the Oracle equivalent of SELECT 'TEST' as MyColumn
In MSSQL I can type into script editor and execute the following:

```<code>SELECT 'TEST' AS MyColumn
</code>```

Which will output a single row containing TEST in a column called MyColumn

What is the equivalent in Oracle?

答:
add 'from dual' at the end so</p>

```<code>select 'Test' AS MyColumn from dual;
</code>```

Body:
In MSSQL I can type into script editor and execute the following:

SELECT 'TEST' AS MyColumn

Which will output a single row containing TEST in a column called MyColumn

What is the equivalent in Oracle?

Body:
add 'from dual' at the end so

select 'Test' AS MyColumn from dual;


问:
Controller is loaded in DOM but the view not loaded and can't find controller- oclazyload with jade(pugjs)
I am using angular 1.6 for my project and angular-ui-routing for routing with PugJs for HTML templates.
I am trying to implement Lazyload in my application, but somehow its not working may be due to jade.
code :

```<code>var app = angular.module('myApp',['ui.router','oc.lazyLoad']);
app.config(['$ocLazyLoadProvider', function($ocLazyLoadProvider
 {
   $ocLazyLoadProvider.config({
   debug: true,
   modules: [{
   name: 'js',
   files: ['js/*']
 }]
});
}]);

.state("exampleState", {
        url: '/example',
        templateUrl: '/example',
        controller:'exampleCtrl',

        resolve: {
            deps: ['$ocLazyLoad', function($ocLazyLoad) {
                return $ocLazyLoad.load({
                    files: ['/js/exampleCtrl.js']
                })
            }]
        }
    })
</code>```

Controller :

```<code>app.controller('exampleCtrl',function($scope){
  console.log('controller loaded');
});
</code>```

and on the frontend I am using node to convert these jade into HTML, so when 'templateUrl' is accessed by routing services it would be redirected to this code:

```<code>app.get('/example', function(req, res) {
    res.render('/example');
});
</code>```

this loads the example.jade in view.
I am getting this in console

[$controller:ctrlreg] The controller with the name 'exampleCtrl' is not registered.

Even after controller file is loaded in DOM and also view is not rendering. any help regarding issue welcomed. Thank you

答:
After too much search and try i have found the solution, the problem was global variable for the module when constructing controller. Instead of using

```<code>app.controller('exampleCtrl',function($scope){
  console.log('controller loaded');
});
</code>```

I used angular.module('myApp').controller(,,,);

Reference : ocLazyLoad Issues

Body:
I am using angular 1.6 for my project and angular-ui-routing for routing with PugJs for HTML templates.
I am trying to implement Lazyload in my application, but somehow its not working may be due to jade.
code :

var app = angular.module('myApp',['ui.router','oc.lazyLoad']);
app.config(['$ocLazyLoadProvider', function($ocLazyLoadProvider
 {
   $ocLazyLoadProvider.config({
   debug: true,
   modules: [{
   name: 'js',
   files: ['js/*']
 }]
});
}]);

.state("exampleState", {
        url: '/example',
        templateUrl: '/example',
        controller:'exampleCtrl',

        resolve: {
            deps: ['$ocLazyLoad', function($ocLazyLoad) {
                return $ocLazyLoad.load({
                    files: ['/js/exampleCtrl.js']
                })
            }]
        }
    })

Controller :

app.controller('exampleCtrl',function($scope){
  console.log('controller loaded');
});

and on the frontend I am using node to convert these jade into HTML, so when 'templateUrl' is accessed by routing services it would be redirected to this code:

app.get('/example', function(req, res) {
    res.render('/example');
});

this loads the example.jade in view.
I am getting this in console

[$controller:ctrlreg] The controller with the name 'exampleCtrl' is not registered.

Even after controller file is loaded in DOM and also view is not rendering. any help regarding issue welcomed. Thank you

Body:
After too much search and try i have found the solution, the problem was global variable for the module when constructing controller. Instead of using

app.controller('exampleCtrl',function($scope){
  console.log('controller loaded');
});

I used angular.module('myApp').controller(,,,);

Reference : ocLazyLoad Issues


问:
Confused about perl's Entities.pm
Ok, I'm a bit confused here.

I am trying to create a feed for an iPhone app encoded in utf8.

There are many latin characters (accute, etc) for our Spanish content. I use the decode_entities function from the Entities.pm lib, but I'm noticing that the char values that it converts to are breaking my feed -- what I mean is that the feed is not valid, even though there are CDATA tags around the title field. Upon further investigation, I've discovered that this lib is converting from an html entity to it's corresponding unicode value but it is using the ISO-8859 instead of utf8.

How do I convert from an html-entity to utf8?

答:
```<code>use Encode;
use HTML::Entities;

my $x = decode_utf8(decode_entities("α — ω"));

binmode STDOUT, ":utf8";
print $x;
</code>```

<p>(You'll get "wide characters in print" warning if you print $x outright). </p>

Title: Confused about perl's Entities.pm

Body:
use Encode;
use HTML::Entities;

my $x = decode_utf8(decode_entities("&alpha; &mdash; &omega;"));

binmode STDOUT, ":utf8";
print $x;

(You'll get "wide characters in print" warning if you print $x outright).


问:
How to visually resolve conflicts from rebase in SourceTree
I am using SourceTree for Windows and attempting to rebase entirely with SourceTree. I would like to perform a visual resolution of the files.  I do not understand how to setup the configuration so that git -rebase will popup diffmerge window with Launch external merge tool command from SourceTree
Is this possible? What would be the config if it is possible?

My .gitconfig file looks like this

```<code>[merge]
        tool = diffmerge
[diff]
        tool = diffmerge
[difftool "diffmerge"]
        cmd = diffmerge \"$LOCAL\" \"$REMOTE\"
[difftool "sourcetree"]
    cmd = 'C:/DiffMerge_4_2_0_697_stable_x64/sgdm.exe' \"$LOCAL\" \"$REMOTE\"
[mergetool "sourcetree"]
    cmd = 'C:/DiffMerge_4_2_0_697_stable_x64/sgdm.exe' -merge -result=\"$MERGED\" \"$LOCAL\" \"$BASE\" \"$REMOTE\"
    trustExitCode = true
</code>```

答:
Do you possibly mean SourceGear instead of Sourcetree?  The paths you are listing point to the SourceGear DiffMerge.

Git on Windows needs the configuration to match what is posted on this page in order to launch diffmerge:  http://www.sourcegear.com/diffmerge/webhelp/sec__git__windows__github.html.

After that you can either just call DiffMerge if all your files are on your disk, or you can use git diff and then specify the tool in the options.  Check out this post here on SourceGear's forum:  https://support.sourcegear.com/viewtopic.php?f=33&t=22329&p=77867#p77867.

Body:
I am using SourceTree for Windows and attempting to rebase entirely with SourceTree. I would like to perform a visual resolution of the files.  I do not understand how to setup the configuration so that git -rebase will popup diffmerge window with Launch external merge tool command from SourceTree
Is this possible? What would be the config if it is possible?

My .gitconfig file looks like this

[merge]
        tool = diffmerge
[diff]
        tool = diffmerge
[difftool "diffmerge"]
        cmd = diffmerge \"$LOCAL\" \"$REMOTE\"
[difftool "sourcetree"]
    cmd = 'C:/DiffMerge_4_2_0_697_stable_x64/sgdm.exe' \"$LOCAL\" \"$REMOTE\"
[mergetool "sourcetree"]
    cmd = 'C:/DiffMerge_4_2_0_697_stable_x64/sgdm.exe' -merge -result=\"$MERGED\" \"$LOCAL\" \"$BASE\" \"$REMOTE\"
    trustExitCode = true


问:
Insert text at the beginning of every new line
I'm having an issue. I'm making a video transcription solution. When I hit Enter, I need to add a time flag — so that the user could type until they hit Enter again, but all I get is the time flag at the end of each line.

I appreciate any help.

Expected Result

```<code>[hh:mm:ss] my text
</code>```

Actual Result

```<code>my text [hh:mm:ss]
my new text
</code>```

Code

```<code>//if (!(start_element.hasAttribute('title'))) {
  start_element.setAttributes({
    'title': tim
  });

  var charCode = (evt.which) ? evt.which : event.keyCode;

  console.log(evt.data.keyCode);

  if (evt.data.keyCode == 13) {
    CKEDITOR.instances.editor1.insertHtml('[' + tim + ']');
  }
//}
</code>```

答:
Can just add a line break before the timecode?

```<code>if (evt.data.keyCode == 13) {
    CKEDITOR.instances.editor1.insertHtml('\n[' + tim + ']');
    evt.preventDefault(); // do not insert line break, because we already did this
}
</code>```

But this adds timecode to the next line. If you want to add to current line, you can do something like

```<code>if (evt.data.keyCode == 13) {
    // get all current lines
    var lines = CKEDITOR.instances.editor1.innerHtml.split('\n');
    // add timecode to beginning of last line
    lines[lines.length - 1] = '[' + tim + ']' + lines[lines.length - 1];
    // join all lines and write back to editor
    CKEDITOR.instances.editor1.innerHtml = lines.join('\n');
}
</code>```

Body:
I'm having an issue. I'm making a video transcription solution. When I hit Enter, I need to add a time flag — so that the user could type until they hit Enter again, but all I get is the time flag at the end of each line.

I appreciate any help.

Expected Result

[hh:mm:ss] my text

Actual Result

my text [hh:mm:ss]
my new text

Code

//if (!(start_element.hasAttribute('title'))) {
  start_element.setAttributes({
    'title': tim
  });

  var charCode = (evt.which) ? evt.which : event.keyCode;

  console.log(evt.data.keyCode);

  if (evt.data.keyCode == 13) {
    CKEDITOR.instances.editor1.insertHtml('[' + tim + ']');
  }
//}

Body:
Can just add a line break before the timecode?

if (evt.data.keyCode == 13) {
    CKEDITOR.instances.editor1.insertHtml('\n[' + tim + ']');
    evt.preventDefault(); // do not insert line break, because we already did this
}

But this adds timecode to the next line. If you want to add to current line, you can do something like

if (evt.data.keyCode == 13) {
    // get all current lines
    var lines = CKEDITOR.instances.editor1.innerHtml.split('\n');
    // add timecode to beginning of last line
    lines[lines.length - 1] = '[' + tim + ']' + lines[lines.length - 1];
    // join all lines and write back to editor
    CKEDITOR.instances.editor1.innerHtml = lines.join('\n');
}


问:
JavaFx: How to update text of dynimically created TextFields inside GridPane?
I'm developing an app in JavaFx, in which which I'm dynamically creating TextFeids and CheckBoxes inside GridPane like this:

I'm adding numbers which user will enter in TextField 1 and TextField 2 and displaying in TextField 3 like this using listener:

Problem: What I want is when user will check the CheckBox it should add 10 to the value already present in the TextField 3 of (same row as of triggered CheckBox) and update the text of TextField 3, and when user will uncheck the CheckBox it should subtract 10 from the value present in the TextField 3 of (same row as of triggered CheckBox) and update the text of TextField 3. I tried to do it but it's not working (not adding and removing):

This is how I'm creating GridPane:

```<code> public static GridPane table(int rows){
        GridPane table = new GridPane();

        for(int i=0; i<rows; i++){
            TextField textField = new TextField();
            textField.setAlignment(Pos.CENTER);
            TextField textField2 = new TextField();
            textField2.setAlignment(Pos.CENTER);
            CheckBox checkBox = new CheckBox("Check Box");
            checkBox.setTextFill(Color.WHITE);
            checkBox.setAlignment(Pos.CENTER);
            TextField textField3 = new TextField();
            textField3.setAlignment(Pos.CENTER);

            table.add(textField, 0, i);
            table.add(textField2, 1, i);
            table.add(checkBox , 2, i);
            table.add(textField3,3, i);

            GridPane.setMargin(textField, new Insets(5));
            GridPane.setMargin(textField2, new Insets(5));
            GridPane.setMargin(checkBox, new Insets(5));
            GridPane.setMargin(textField3, new Insets(5));
         }
        table.setAlignment(Pos.CENTER);

        return table;
    }
</code>```

A method to return a component from Table at specific row and column

```<code>public static Node getComponent (int row, int column, GridPane table) {
     for (Node component : table.getChildren()) {
         if(GridPane.getRowIndex(component) == row &&
                         GridPane.getColumnIndex(component) == column) {
             return component;
         }
     }

     return null;
 }
</code>```

This is how I'm adding:

```<code>    public void add(GridPane table, int numRows){

       for(int i=0; i<numRows; i++){
           try {

                int valueA = Integer.parseInt(((TextField)(getComponent (i, 0, table))).getText());
                System.out.println(valueA);
                int valueB = Integer.parseInt(((TextField)(getComponent (i, 1, table))).getText());
                System.out.println(valueB);

                int add = valueA+valueB;

                String addToString = Integer.toString(add);

                ((TextField)(getComponent (i, 3, table))).setText(addToString);

                } catch (NullPointerException e) {
                  System.out.print("Caught the NullPointerException");
                    }
       }

    }
</code>```

Problem: Addition and subtraction using CheckBox:

```<code>     public void addPause(GridPane table, int numRows){

                for(int i=0; i<numRows; i++){

                boolean pause = ((CheckBox)(getComponent (i, 2, table))).isSelected();
                int getTextValue = Integer.parseInt(((TextField)(getComponent (i, 3, table))).getText());

                int addPause = getTextValue+10;
                int removePause = addPause-10;

                String addPToString = Integer.toString(addPause);
                String removePToString = Integer.toString(removePause);

                if (pause) {
                    ((TextField)(getComponent (i, 3, table))).setText(addPToString);
                } else {
                    ((TextField)(getComponent (i, 3, table))).setText(removePToString);
                }
       }
    }
</code>```

This is how I'm triggering using listeners:

```<code>        for(Node node : table.getChildren()){
          if(node instanceof TextField){
             ((TextField)node).textProperty().addListener((obs, old, newV)->{
               add(table, numRows);
           });
         }
          else if(node instanceof CheckBox){
              ((CheckBox)node).selectedProperty().addListener((obs, old, newV)->{
                addPause(table, numRows);
             });
           }
       }
</code>```

答:
As I suggested in your previous question, just register the listeners for the controls at the point you create them.

You can actually just use a single listener (in each row) for the two text fields and check box, and update the third text box when any of those change. For example:

```<code>public static GridPane table(int rows){
    GridPane table = new GridPane();

    for(int i=0; i<rows; i++){
        TextField textField = new TextField();
        textField.setAlignment(Pos.CENTER);
        TextField textField2 = new TextField();
        textField2.setAlignment(Pos.CENTER);
        CheckBox checkBox = new CheckBox("Check Box");
        checkBox.setTextFill(Color.WHITE);
        checkBox.setAlignment(Pos.CENTER);
        TextField textField3 = new TextField();
        textField3.setAlignment(Pos.CENTER);

        table.add(textField, 0, i);
        table.add(textField2, 1, i);
        table.add(checkBox , 2, i);
        table.add(textField3,3, i);

        ChangeListener<Object> listener = (obs, oldValue, newValue) ->
            updateTotalField(textField.getText(), textField2.getText(), checkBox.isSelected(), textField3);

        textField.textProperty().addListener(listener);
        textField2.textProperty().addListener(listener);
        checkBox.selectedProperty().addListener(listener);

        GridPane.setMargin(textField, new Insets(5));
        GridPane.setMargin(textField2, new Insets(5));
        GridPane.setMargin(checkBox, new Insets(5));
        GridPane.setMargin(textField3, new Insets(5));
     }
    table.setAlignment(Pos.CENTER);

    return table;
}

private static void updateTotalField(String text1, String text2, boolean addPause, TextField output) {
    int value1 = parseText(text1);
    int value2 = parseText(text2);
    int total = value1 + value2 ;
    if (addPause) {
        total += 10 ;
    }
    output.setText(Integer.toString(total));
}

private static int parseText(String text) {
    // if text is a valid integer:
    if (text.matches("\\d+")) {
        return Integer.parseInt(text);
    } else {
        return 0 ;
    }
}
</code>```

Now you can get rid of the add and addPause method, and the chunk of code you posted where you iterate through the child nodes of the grid pane and add listeners. You may be able to get rid of the getComponent() method to, unless you need it elsewhere.

Here is the code as a SSCCE

```<code>import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class TableOfControlsInGridPane extends Application {

    @Override
    public void start(Stage primaryStage) {
        Scene scene = new Scene(table(10));
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public GridPane table(int rows){
        GridPane table = new GridPane();

        for(int i=0; i<rows; i++){
            TextField textField = new TextField();
            textField.setAlignment(Pos.CENTER);
            TextField textField2 = new TextField();
            textField2.setAlignment(Pos.CENTER);
            CheckBox checkBox = new CheckBox("Check Box");
            checkBox.setTextFill(Color.WHITE);
            checkBox.setAlignment(Pos.CENTER);
            TextField textField3 = new TextField();
            textField3.setAlignment(Pos.CENTER);

            table.add(textField, 0, i);
            table.add(textField2, 1, i);
            table.add(checkBox , 2, i);
            table.add(textField3,3, i);

            ChangeListener<Object> listener = (obs, oldValue, newValue) ->
                updateTotalField(textField.getText(), textField2.getText(), checkBox.isSelected(), textField3);

            textField.textProperty().addListener(listener);
            textField2.textProperty().addListener(listener);
            checkBox.selectedProperty().addListener(listener);

            GridPane.setMargin(textField, new Insets(5));
            GridPane.setMargin(textField2, new Insets(5));
            GridPane.setMargin(checkBox, new Insets(5));
            GridPane.setMargin(textField3, new Insets(5));
         }
        table.setAlignment(Pos.CENTER);

        return table;
    }

    private void updateTotalField(String text1, String text2, boolean addPause, TextField output) {
        int value1 = parseText(text1);
        int value2 = parseText(text2);
        int total = value1 + value2 ;
        if (addPause) {
            total += 10 ;
        }
        output.setText(Integer.toString(total));
    }

    private int parseText(String text) {
        // if text is a valid integer:
        if (text.matches("\\d+")) {
            return Integer.parseInt(text);
        } else {
            return 0 ;
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

and a screenshot:

Since Java is an object-oriented language, it would probably seem more appropriate to do this in an object-oriented way in the first place. I have no idea what data you are representing in this view, but you should define a class that encapsulates the data in a single row:

```<code>import javafx.beans.binding.Bindings;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ReadOnlyIntegerProperty;
import javafx.beans.property.ReadOnlyIntegerWrapper;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleIntegerProperty;

// Obviously use a more sensible name for the class:
public class RowData {

    private final IntegerProperty firstValue = new SimpleIntegerProperty();
    private final IntegerProperty secondValue = new SimpleIntegerProperty();
    private final BooleanProperty includePause = new SimpleBooleanProperty();
    private final ReadOnlyIntegerWrapper total = new ReadOnlyIntegerWrapper();

    public RowData() {
        total.bind(Bindings.createIntegerBinding(() -> {
            int total = getFirstValue() + getSecondValue() ;
            if (isIncludePause()) {
                total += 10 ;
            }
            return total ;
        }, firstValue, secondValue, includePause));
    }

    public final IntegerProperty firstValueProperty() {
        return this.firstValue;
    }

    public final int getFirstValue() {
        return this.firstValueProperty().get();
    }

    public final void setFirstValue(final int firstValue) {
        this.firstValueProperty().set(firstValue);
    }

    public final IntegerProperty secondValueProperty() {
        return this.secondValue;
    }

    public final int getSecondValue() {
        return this.secondValueProperty().get();
    }

    public final void setSecondValue(final int secondValue) {
        this.secondValueProperty().set(secondValue);
    }

    public final BooleanProperty includePauseProperty() {
        return this.includePause;
    }

    public final boolean isIncludePause() {
        return this.includePauseProperty().get();
    }

    public final void setIncludePause(final boolean includePause) {
        this.includePauseProperty().set(includePause);
    }

    public final ReadOnlyIntegerProperty totalProperty() {
        return this.total.getReadOnlyProperty();
    }

    public final int getTotal() {
        return this.totalProperty().get();
    }

}
</code>```

Then a class to display those data:

```<code>import javafx.beans.binding.Bindings;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;

public class RowDataView {

    private final TextField firstValueField ;
    private final TextField secondValueField ;
    private final CheckBox includePauseBox ;
    private final TextField totalField ;

    public RowDataView(RowData data) {

        firstValueField = new TextField();
        bindToStringProperty(data.firstValueProperty(), firstValueField.textProperty());

        secondValueField = new TextField();
        bindToStringProperty(data.secondValueProperty(), secondValueField.textProperty());

        includePauseBox = new CheckBox();
        data.includePauseProperty().bind(includePauseBox.selectedProperty());

        totalField = new TextField();
        totalField.setEditable(false);
        totalField.textProperty().bind(data.totalProperty().asString());
    }

    public void addToGridPane(GridPane pane, int row, int firstValueColumn, int secondValueColumn, int checkboxColumn, int totalColumn) {
        pane.add(firstValueField, firstValueColumn, row);
        pane.add(secondValueField, secondValueColumn, row);
        pane.add(includePauseBox, checkboxColumn, row);
        pane.add(totalField, totalColumn, row);
    }

    public void addToGridPane(GridPane pane, int row, int column) {
        addToGridPane(pane, row, column, column+1, column+2, column+3);
    }

    public void addToGridPane(GridPane pane, int row) {
        addToGridPane(pane, row, 0);
    }

    private void bindToStringProperty(IntegerProperty p, StringProperty s) {
        p.bind(Bindings.createIntegerBinding(
                () -> {
                    if (s.get().matches("\\d+")) {
                        return Integer.parseInt(s.get());
                    }
                    return 0 ;
                }, s));
    }
}
</code>```

and here is some test code:

```<code>import java.util.ArrayList;
import java.util.List;

import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

public class TableOfControlsInGridPane extends Application {

    private final List<RowData> data = new ArrayList<>();

    @Override
    public void start(Stage primaryStage) {
        Scene scene = new Scene(table(10), 800, 800);
        scene.getStylesheets().add("style.css");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public GridPane table(int rows){
        GridPane table = new GridPane();
        table.getStyleClass().add("data-grid");

        data.clear();

        for(int i=0; i<rows; i++){

            RowData rowData = new RowData();
            data.add(rowData);

            RowDataView rowDataView = new RowDataView(rowData);
            rowDataView.addToGridPane(table, i);
         }
        table.setAlignment(Pos.CENTER);
        return table;
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

I moved the styles to the style sheet (style.css):

.data-grid {
    -fx-background-color: purple ;
    -fx-hgap: 10 ;
    -fx-vgap: 10 ;
}
.data-grid .text-field, .data-grid .check-box {
    -fx-alignment: center ;
}
.data-grid .check-box {
    -fx-text-fill: white ;
}
```

Body:
I'm developing an app in JavaFx, in which which I'm dynamically creating TextFeids and CheckBoxes inside GridPane like this:

I'm adding numbers which user will enter in TextField 1 and TextField 2 and displaying in TextField 3 like this using listener:

Problem: What I want is when user will check the CheckBox it should add 10 to the value already present in the TextField 3 of (same row as of triggered CheckBox) and update the text of TextField 3, and when user will uncheck the CheckBox it should subtract 10 from the value present in the TextField 3 of (same row as of triggered CheckBox) and update the text of TextField 3. I tried to do it but it's not working (not adding and removing):

This is how I'm creating GridPane:

 public static GridPane table(int rows){
        GridPane table = new GridPane();

        for(int i=0; i<rows; i++){
            TextField textField = new TextField();
            textField.setAlignment(Pos.CENTER);
            TextField textField2 = new TextField();
            textField2.setAlignment(Pos.CENTER);
            CheckBox checkBox = new CheckBox("Check Box");
            checkBox.setTextFill(Color.WHITE);
            checkBox.setAlignment(Pos.CENTER);
            TextField textField3 = new TextField();
            textField3.setAlignment(Pos.CENTER);

            table.add(textField, 0, i);
            table.add(textField2, 1, i);
            table.add(checkBox , 2, i);
            table.add(textField3,3, i);

            GridPane.setMargin(textField, new Insets(5));
            GridPane.setMargin(textField2, new Insets(5));
            GridPane.setMargin(checkBox, new Insets(5));
            GridPane.setMargin(textField3, new Insets(5));
         }
        table.setAlignment(Pos.CENTER);

        return table;
    }

A method to return a component from Table at specific row and column

public static Node getComponent (int row, int column, GridPane table) {
     for (Node component : table.getChildren()) {
         if(GridPane.getRowIndex(component) == row &&
                         GridPane.getColumnIndex(component) == column) {
             return component;
         }
     }

     return null;
 }

This is how I'm adding:

    public void add(GridPane table, int numRows){

       for(int i=0; i<numRows; i++){
           try {

                int valueA = Integer.parseInt(((TextField)(getComponent (i, 0, table))).getText());
                System.out.println(valueA);
                int valueB = Integer.parseInt(((TextField)(getComponent (i, 1, table))).getText());
                System.out.println(valueB);

                int add = valueA+valueB;

                String addToString = Integer.toString(add);

                ((TextField)(getComponent (i, 3, table))).setText(addToString);

                } catch (NullPointerException e) {
                  System.out.print("Caught the NullPointerException");
                    }
       }

    }

Problem: Addition and subtraction using CheckBox:

     public void addPause(GridPane table, int numRows){

                for(int i=0; i<numRows; i++){

                boolean pause = ((CheckBox)(getComponent (i, 2, table))).isSelected();
                int getTextValue = Integer.parseInt(((TextField)(getComponent (i, 3, table))).getText());

                int addPause = getTextValue+10;
                int removePause = addPause-10;

                String addPToString = Integer.toString(addPause);
                String removePToString = Integer.toString(removePause);

                if (pause) {
                    ((TextField)(getComponent (i, 3, table))).setText(addPToString);
                } else {
                    ((TextField)(getComponent (i, 3, table))).setText(removePToString);
                }
       }
    }

This is how I'm triggering using listeners:

        for(Node node : table.getChildren()){
          if(node instanceof TextField){
             ((TextField)node).textProperty().addListener((obs, old, newV)->{
               add(table, numRows);
           });
         }
          else if(node instanceof CheckBox){
              ((CheckBox)node).selectedProperty().addListener((obs, old, newV)->{
                addPause(table, numRows);
             });
           }
       }

Body:
As I suggested in your previous question, just register the listeners for the controls at the point you create them.

You can actually just use a single listener (in each row) for the two text fields and check box, and update the third text box when any of those change. For example:

public static GridPane table(int rows){
    GridPane table = new GridPane();

    for(int i=0; i<rows; i++){
        TextField textField = new TextField();
        textField.setAlignment(Pos.CENTER);
        TextField textField2 = new TextField();
        textField2.setAlignment(Pos.CENTER);
        CheckBox checkBox = new CheckBox("Check Box");
        checkBox.setTextFill(Color.WHITE);
        checkBox.setAlignment(Pos.CENTER);
        TextField textField3 = new TextField();
        textField3.setAlignment(Pos.CENTER);

        table.add(textField, 0, i);
        table.add(textField2, 1, i);
        table.add(checkBox , 2, i);
        table.add(textField3,3, i);

        ChangeListener<Object> listener = (obs, oldValue, newValue) ->
            updateTotalField(textField.getText(), textField2.getText(), checkBox.isSelected(), textField3);

        textField.textProperty().addListener(listener);
        textField2.textProperty().addListener(listener);
        checkBox.selectedProperty().addListener(listener);

        GridPane.setMargin(textField, new Insets(5));
        GridPane.setMargin(textField2, new Insets(5));
        GridPane.setMargin(checkBox, new Insets(5));
        GridPane.setMargin(textField3, new Insets(5));
     }
    table.setAlignment(Pos.CENTER);

    return table;
}

private static void updateTotalField(String text1, String text2, boolean addPause, TextField output) {
    int value1 = parseText(text1);
    int value2 = parseText(text2);
    int total = value1 + value2 ;
    if (addPause) {
        total += 10 ;
    }
    output.setText(Integer.toString(total));
}

private static int parseText(String text) {
    // if text is a valid integer:
    if (text.matches("\\d+")) {
        return Integer.parseInt(text);
    } else {
        return 0 ;
    }
}

Now you can get rid of the add and addPause method, and the chunk of code you posted where you iterate through the child nodes of the grid pane and add listeners. You may be able to get rid of the getComponent() method to, unless you need it elsewhere.

Here is the code as a SSCCE

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class TableOfControlsInGridPane extends Application {

    @Override
    public void start(Stage primaryStage) {
        Scene scene = new Scene(table(10));
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public GridPane table(int rows){
        GridPane table = new GridPane();

        for(int i=0; i<rows; i++){
            TextField textField = new TextField();
            textField.setAlignment(Pos.CENTER);
            TextField textField2 = new TextField();
            textField2.setAlignment(Pos.CENTER);
            CheckBox checkBox = new CheckBox("Check Box");
            checkBox.setTextFill(Color.WHITE);
            checkBox.setAlignment(Pos.CENTER);
            TextField textField3 = new TextField();
            textField3.setAlignment(Pos.CENTER);

            table.add(textField, 0, i);
            table.add(textField2, 1, i);
            table.add(checkBox , 2, i);
            table.add(textField3,3, i);

            ChangeListener<Object> listener = (obs, oldValue, newValue) ->
                updateTotalField(textField.getText(), textField2.getText(), checkBox.isSelected(), textField3);

            textField.textProperty().addListener(listener);
            textField2.textProperty().addListener(listener);
            checkBox.selectedProperty().addListener(listener);

            GridPane.setMargin(textField, new Insets(5));
            GridPane.setMargin(textField2, new Insets(5));
            GridPane.setMargin(checkBox, new Insets(5));
            GridPane.setMargin(textField3, new Insets(5));
         }
        table.setAlignment(Pos.CENTER);

        return table;
    }

    private void updateTotalField(String text1, String text2, boolean addPause, TextField output) {
        int value1 = parseText(text1);
        int value2 = parseText(text2);
        int total = value1 + value2 ;
        if (addPause) {
            total += 10 ;
        }
        output.setText(Integer.toString(total));
    }

    private int parseText(String text) {
        // if text is a valid integer:
        if (text.matches("\\d+")) {
            return Integer.parseInt(text);
        } else {
            return 0 ;
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

and a screenshot:

Since Java is an object-oriented language, it would probably seem more appropriate to do this in an object-oriented way in the first place. I have no idea what data you are representing in this view, but you should define a class that encapsulates the data in a single row:

import javafx.beans.binding.Bindings;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ReadOnlyIntegerProperty;
import javafx.beans.property.ReadOnlyIntegerWrapper;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleIntegerProperty;

// Obviously use a more sensible name for the class:
public class RowData {

    private final IntegerProperty firstValue = new SimpleIntegerProperty();
    private final IntegerProperty secondValue = new SimpleIntegerProperty();
    private final BooleanProperty includePause = new SimpleBooleanProperty();
    private final ReadOnlyIntegerWrapper total = new ReadOnlyIntegerWrapper();

    public RowData() {
        total.bind(Bindings.createIntegerBinding(() -> {
            int total = getFirstValue() + getSecondValue() ;
            if (isIncludePause()) {
                total += 10 ;
            }
            return total ;
        }, firstValue, secondValue, includePause));
    }

    public final IntegerProperty firstValueProperty() {
        return this.firstValue;
    }

    public final int getFirstValue() {
        return this.firstValueProperty().get();
    }

    public final void setFirstValue(final int firstValue) {
        this.firstValueProperty().set(firstValue);
    }

    public final IntegerProperty secondValueProperty() {
        return this.secondValue;
    }

    public final int getSecondValue() {
        return this.secondValueProperty().get();
    }

    public final void setSecondValue(final int secondValue) {
        this.secondValueProperty().set(secondValue);
    }

    public final BooleanProperty includePauseProperty() {
        return this.includePause;
    }

    public final boolean isIncludePause() {
        return this.includePauseProperty().get();
    }

    public final void setIncludePause(final boolean includePause) {
        this.includePauseProperty().set(includePause);
    }

    public final ReadOnlyIntegerProperty totalProperty() {
        return this.total.getReadOnlyProperty();
    }

    public final int getTotal() {
        return this.totalProperty().get();
    }

}

Then a class to display those data:

import javafx.beans.binding.Bindings;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;

public class RowDataView {

    private final TextField firstValueField ;
    private final TextField secondValueField ;
    private final CheckBox includePauseBox ;
    private final TextField totalField ;

    public RowDataView(RowData data) {

        firstValueField = new TextField();
        bindToStringProperty(data.firstValueProperty(), firstValueField.textProperty());

        secondValueField = new TextField();
        bindToStringProperty(data.secondValueProperty(), secondValueField.textProperty());

        includePauseBox = new CheckBox();
        data.includePauseProperty().bind(includePauseBox.selectedProperty());

        totalField = new TextField();
        totalField.setEditable(false);
        totalField.textProperty().bind(data.totalProperty().asString());
    }

    public void addToGridPane(GridPane pane, int row, int firstValueColumn, int secondValueColumn, int checkboxColumn, int totalColumn) {
        pane.add(firstValueField, firstValueColumn, row);
        pane.add(secondValueField, secondValueColumn, row);
        pane.add(includePauseBox, checkboxColumn, row);
        pane.add(totalField, totalColumn, row);
    }

    public void addToGridPane(GridPane pane, int row, int column) {
        addToGridPane(pane, row, column, column+1, column+2, column+3);
    }

    public void addToGridPane(GridPane pane, int row) {
        addToGridPane(pane, row, 0);
    }

    private void bindToStringProperty(IntegerProperty p, StringProperty s) {
        p.bind(Bindings.createIntegerBinding(
                () -> {
                    if (s.get().matches("\\d+")) {
                        return Integer.parseInt(s.get());
                    }
                    return 0 ;
                }, s));
    }
}

and here is some test code:

import java.util.ArrayList;
import java.util.List;

import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

public class TableOfControlsInGridPane extends Application {

    private final List<RowData> data = new ArrayList<>();

    @Override
    public void start(Stage primaryStage) {
        Scene scene = new Scene(table(10), 800, 800);
        scene.getStylesheets().add("style.css");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public GridPane table(int rows){
        GridPane table = new GridPane();
        table.getStyleClass().add("data-grid");

        data.clear();

        for(int i=0; i<rows; i++){

            RowData rowData = new RowData();
            data.add(rowData);

            RowDataView rowDataView = new RowDataView(rowData);
            rowDataView.addToGridPane(table, i);
         }
        table.setAlignment(Pos.CENTER);
        return table;
    }

    public static void main(String[] args) {
        launch(args);
    }
}

I moved the styles to the style sheet (style.css):

.data-grid {
    -fx-background-color: purple ;
    -fx-hgap: 10 ;
    -fx-vgap: 10 ;
}
.data-grid .text-field, .data-grid .check-box {
    -fx-alignment: center ;
}
.data-grid .check-box {
    -fx-text-fill: white ;
}


问:
cakephp performances in a big project
I have to develop a big application (an advertising platform, will get more than 10K users and 100K's of listings ) Is it a good idea to choose cakephp for building such a site ?

Thank a  lot

答:
Rasmus(inventor PHP) did not like cakephp much because it had(he benchmarked it a while back so things could have changed) real bad performance. He liked codeigniter the most because it had the best performance. Below the numbers(performance):

cakephp:

```<code>Response time:              0.19 secs
Transaction rate:          25.88 trans/sec
</code>```

codeigniter:

```<code>Response time:              0.03 secs
Transaction rate:         305.90 trans/sec
</code>```

As you can see it was slow as hell(could have changed. You should do a simple benchmark and test to be certain I guess).

The no-framework Framework

He also has this article explaining how he would write his architecture(without framework for best performance).

in the conclusion he says:

Many frameworks may look very
  appealing at first glance because they
  seem to reduce web application
  development to a couple of trivial
  steps leading to some code generation
  and often automatic schema detection,
  but these same shortcuts are likely to
  be your bottlenecks as well since they
  achieve this simplicity by sacrifizing
  flexibility and performance.

Going to disc will be a real performance killer.

This is the most important tip you should keep in mind.

My performance tips

Use the latest php(5.3) because I read it has massive speed improvement over the older versions.

Make sure you have enough memory. You need to store a lot of data in memory to get good performance.

You really need APC(configure it properly) to achieve good performance because it will put PHP opcode in memory which will give you a huge boost.

You should keep your active dataset in memory by using redis/memcached/etc.

If you have to do long running tasks process them via a message queue(redis/gearmand/kestrel/etc)

Follow YAHOO's best practices to speed up your website.

Don't use a heavy PHP framework. Use something like Codeigniter(Benchmark it).

Title: cakephp performances in a big project

Body:
Rasmus(inventor PHP) did not like cakephp much because it had(he benchmarked it a while back so things could have changed) real bad performance. He liked codeigniter the most because it had the best performance. Below the numbers(performance):

cakephp:

Response time:              0.19 secs
Transaction rate:          25.88 trans/sec

codeigniter:

Response time:              0.03 secs
Transaction rate:         305.90 trans/sec

As you can see it was slow as hell(could have changed. You should do a simple benchmark and test to be certain I guess).

The no-framework Framework

He also has this article explaining how he would write his architecture(without framework for best performance).

in the conclusion he says:

Many frameworks may look very
  appealing at first glance because they
  seem to reduce web application
  development to a couple of trivial
  steps leading to some code generation
  and often automatic schema detection,
  but these same shortcuts are likely to
  be your bottlenecks as well since they
  achieve this simplicity by sacrifizing
  flexibility and performance.

Going to disc will be a real performance killer.

This is the most important tip you should keep in mind.

My performance tips

Use the latest php(5.3) because I read it has massive speed improvement over the older versions.

Make sure you have enough memory. You need to store a lot of data in memory to get good performance.

You really need APC(configure it properly) to achieve good performance because it will put PHP opcode in memory which will give you a huge boost.

You should keep your active dataset in memory by using redis/memcached/etc.

If you have to do long running tasks process them via a message queue(redis/gearmand/kestrel/etc)

Follow YAHOO's best practices to speed up your website.

Don't use a heavy PHP framework. Use something like Codeigniter(Benchmark it).


问:
Using CSS :hover to change style but only when adjacent to particular class
I'm experimenting with Bootstrap.js panels that can collapse. I'd like to see if it's possible to change styling of a panel-heading element but only when it's adjacent to a panel-collapse element. The selector below will change all headings obviously.

```<code>.panel-heading:hover {}
</code>```

Because I'm trying to look ahead to see if the target element is followed by a particular class I'm not sure I see if CSS can support this.

```<code><!-- This should change style of panel-heading when hovering over the panel-heading element -->
<div class="panel">
    <div class="panel-heading">
    </div>
    <div class="panel-collapse">
    </div>
</div>

<!-- This should NOT change the style of the panel-heading when hovering over the panel-heading element -->
<div class="panel">
    <div class="panel-heading">
    </div>
    <div class="panel-body">
    </div>
</div>
</code>```

答:
There is no way to currently do this in CSS3, however there is something being proposed in CSS Selectors Level 4. This feature has been widely requested.

Relational Pseudo-class: :has()

Such that you could do something like:

```<code>.panel:has(.panel-collapse) .panel-heading {

}
</code>```

Meaning, apply styles to all .panel-heading classes that are a child of .panel classes containing .panel-collapse

This is a great article on upcoming CSS Selectors Level 4: https://www.sitepoint.com/future-generation-css-selectors-level-4/

In the meantime, you'll have to use something like jQuery. You could add a class like .panel-hoverable to all .panel elements that contain elements with the class .panel-collapse

Body:
I'm experimenting with Bootstrap.js panels that can collapse. I'd like to see if it's possible to change styling of a panel-heading element but only when it's adjacent to a panel-collapse element. The selector below will change all headings obviously.

.panel-heading:hover {}

Because I'm trying to look ahead to see if the target element is followed by a particular class I'm not sure I see if CSS can support this.

Body:
There is no way to currently do this in CSS3, however there is something being proposed in CSS Selectors Level 4. This feature has been widely requested.

Relational Pseudo-class: :has()

Such that you could do something like:

.panel:has(.panel-collapse) .panel-heading {

}

Meaning, apply styles to all .panel-heading classes that are a child of .panel classes containing .panel-collapse

This is a great article on upcoming CSS Selectors Level 4: https://www.sitepoint.com/future-generation-css-selectors-level-4/

In the meantime, you'll have to use something like jQuery. You could add a class like .panel-hoverable to all .panel elements that contain elements with the class .panel-collapse


问:
Using xdebug with PhpStorm
I can't get my PhpStorm IDE to work with xdebug.

My current setup is the following:

PhpStorm 2017.1.4

MacOS Sierra 10.12.5

Here are the steps that I followed.

I have installed php with the following command. I have added the postgres parameter because I need it later to connect to a PostgreSQL database.

```<code>brew install php71 --with-postgresql
</code>```

The next step is to install XDebug with the following command

```<code>brew install php71-xdebug
</code>```

So the next step that I got from the documentation (https://www.jetbrains.com/help/phpstorm/configuring-xdebug.html) is to edit the php.ini file with the following content:

```<code>[Xdebug]
zend_extension="<path to php_xdebug.dll>"
xdebug.remote_enable=1
xdebug.remote_port="<the port for Xdebug to listen to>" (the default port is 9000)
xdebug.profiler_enable=1
xdebug.profiler_output_dir="<AMP home\tmp>"
</code>```

Just some questions about those fields and XDebug.

So I guess XDebug is some kind of service that runs on the remote_port and that PhpStorm is using to write data to? Or do you have to specify the port where the application you want to test is running?

What exactly is the profiler thing? And can the output dir be anything I can choose?

So this is my php.ini file that I think it should be:

```<code>[xdebug]
zend_extension="/usr/local/Cellar/php71-xdebug/2.5.4/xdebug.so"
xdebug.remote_enable=1
xdebug.remote_host=localhost
xdebug.remote_port=9000
xdebug.profiler_enable=1
xdebug.profiler_output_dir="/usr/tmp"
</code>```

That's it for the php.ini. So I have to check the settings in my PhpStorm IDE. And those are the following:

So that is my setup. In my project I just have one index.php with <?php echo phpinfo(); ?> I just click the Chrome icon so it opens directly in the browser to check if XDebug is there. I see the following result.

So I thought to myself ok let's try some debugging. So I changed my index.php file to the following

```<code>$i = 2;
$j = $i + 2;
echo $j
</code>```

I've put a breakpoint on the 2nd line. And when I run it, it never stops at the breakpoint. What is needed to do that or am I wrong in my configuration somewhere?

答:
To make Xdebug remote debugging working on your page, you need to set a cookie in your browser, telling the server you want to debug the page, there are many extensions for that, the most known is Xdebug helper in Chrome.

I also suggest you to follow this tutorial Zero-configuration debugging, it is very detailed and clear IMO.

If you still have problems i'll try to help you with pleasure :)

Title: Using xdebug with PhpStorm

Body:
I can't get my PhpStorm IDE to work with xdebug.

My current setup is the following:

PhpStorm 2017.1.4

MacOS Sierra 10.12.5

Here are the steps that I followed.

I have installed php with the following command. I have added the postgres parameter because I need it later to connect to a PostgreSQL database.

brew install php71 --with-postgresql

The next step is to install XDebug with the following command

brew install php71-xdebug

So the next step that I got from the documentation (https://www.jetbrains.com/help/phpstorm/configuring-xdebug.html) is to edit the php.ini file with the following content:

[Xdebug]
zend_extension="<path to php_xdebug.dll>"
xdebug.remote_enable=1
xdebug.remote_port="<the port for Xdebug to listen to>" (the default port is 9000)
xdebug.profiler_enable=1
xdebug.profiler_output_dir="<AMP home\tmp>"

Just some questions about those fields and XDebug.

So I guess XDebug is some kind of service that runs on the remote_port and that PhpStorm is using to write data to? Or do you have to specify the port where the application you want to test is running?

What exactly is the profiler thing? And can the output dir be anything I can choose?

So this is my php.ini file that I think it should be:

[xdebug]
zend_extension="/usr/local/Cellar/php71-xdebug/2.5.4/xdebug.so"
xdebug.remote_enable=1
xdebug.remote_host=localhost
xdebug.remote_port=9000
xdebug.profiler_enable=1
xdebug.profiler_output_dir="/usr/tmp"

That's it for the php.ini. So I have to check the settings in my PhpStorm IDE. And those are the following:

So that is my setup. In my project I just have one index.php with <?php echo phpinfo(); ?> I just click the Chrome icon so it opens directly in the browser to check if XDebug is there. I see the following result.

So I thought to myself ok let's try some debugging. So I changed my index.php file to the following

$i = 2;
$j = $i + 2;
echo $j

I've put a breakpoint on the 2nd line. And when I run it, it never stops at the breakpoint. What is needed to do that or am I wrong in my configuration somewhere?


问:
How to add on-screen virtual keyboard to a HTML5/Javascript/Canvas mobile game?
I'm using HTML5 and canvas to design a game for which I need a keyboard input element. I do NOT want to use the device's keyboard, but instead, would like to make a custom keyboard that will be "fixed" to the screen/canvas for the duration of gameplay. I've seen NETTUT's sample of a CSS/JS/HTML5 keyboard. I would love to recreate the IOS-like interface in that example. However, I'm interested in a keyboard that is integrated into the canvas (in other words, no CSS). Is that possible? If so, what are the different methods that I use in order to draw the keyboard and give it functionality WITHIN the canvas using javascript? Scaling is also a concern. I'm extremely comfortable with HTML5/CSS but I am brand new to Javascript, so PLEASE break it ALL the way down. Thanks!</p>

答:
I do this in my library project (visual-js game engine) please this post Virtual keyboar in canvas2d .

Live example : hosted on jsfiddle

Problem for can be implementation (it is not pure and native to make easy copy paste) . In v-js ge you can draw custom canvas2d code. I will suggest you to look at :

keyboard.js

Here is idea. Create object with (x,y,w,h) and create in click event calculating method 'is it clicked in object bounds' . Best way is to put it all(obj's) in array then in click event check for whose obj's reseive clicks.

for example draws for that object can be :

```<code>if (obj.visible == true) {
 ctx.fillRect( obj.x , obj.y , obj.w , obj.h )
 ctx.fillText( obj.TEXT ,  obj.x -obj.w/2 , obj.y  ) // dont use height for ipad/iphone
 //  set up middle positon of text
}
</code>```

You can use samo model object for keyboard elements and also textbox element in canvas .(i dont talk about html tags)

In your game something action is done and you will need to create for every character uniq object with one char ( "A" , "SHIFT", "ENTER" etc ... ) make position for every obj. Draw all keyboard obj's .

'
Now you need some flag to know what is current ACTIVE_ELEMENT (any param in your game).

There is one big problem in moment when you append char (some special chars) they have some text format deforms. I ask but there is no answer (i will post that question later) .

In this code block is solution for that problem (i cant simple pass value for current keycode) Looks like hardcode but it is only solution for me :

```<code>ROOT.CAPTURE_CHAR = "";
ROOT.CLEAR_CAPTURE_ON_PRESS_ENTER = true;
ROOT.LAST_CAPTURE_CHAR = "";
ROOT.ENTER_PRESSED = false;
ROOT.SHIFT_PRESSED = false;
ROOT.ACTION_ON_KEY_DOWN = function(){};
</code>```

...

```<code>//@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@@@@@@@@@@@@@@@@@@@@@@@@@
// SPECIAL FOR TEXTBOX
//@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@@@@@@@@@@@@@@@@@@@@@@@@@
SYS.DEBUG.LOG("KEYBOARD-->> Show users types : " + e.keyCode );
var keynum;
if(window.event){ keynum = e.keyCode;}else{if(e.which){ keynum = e.which;}}
//console.log(String.fromCharCode(keynum));

if (e.keyCode == 16){
ROOT.SHIFT_PRESSED = true;
}

if (e.keyCode == 8) {
SYS.DEBUG.LOG("textbox delete last char!");
ROOT.CAPTURE_CHAR = remove_last( ROOT.CAPTURE_CHAR );

}
else if(e.keyCode == 13){
ROOT.ENTER_PRESSED = true;
}
else {

if (ROOT.SHIFT_PRESSED == false) {

   if (e.keyCode == 189) {
    ROOT.CAPTURE_CHAR+="_";
    ROOT.LAST_CAPTURE_CHAR ="_";
  }
  else if (e.keyCode == 187) {
    ROOT.CAPTURE_CHAR+="+";
    ROOT.LAST_CAPTURE_CHAR ="+";
  }
  else if (e.keyCode == 187) {
    ROOT.CAPTURE_CHAR+="+";
    ROOT.LAST_CAPTURE_CHAR ="+";
  }
  else if (e.keyCode == 188) {
    ROOT.CAPTURE_CHAR+=",";
    ROOT.LAST_CAPTURE_CHAR =",";
  }
  else if (e.keyCode == 190) {
    ROOT.CAPTURE_CHAR+=".";
    ROOT.LAST_CAPTURE_CHAR =".";
  }
  else if (e.keyCode == 191) {
    ROOT.CAPTURE_CHAR+="/";
    ROOT.LAST_CAPTURE_CHAR ="/";
  }
  else if (e.keyCode == 186) {
    ROOT.CAPTURE_CHAR+=";";
    ROOT.LAST_CAPTURE_CHAR =";";
  }
  else if (e.keyCode == 222) {
    ROOT.CAPTURE_CHAR+="'";
    ROOT.LAST_CAPTURE_CHAR ="'";
  }
  else if (e.keyCode == 220) {
    ROOT.CAPTURE_CHAR+= "\\";
    ROOT.LAST_CAPTURE_CHAR ='\\';
  }
  else if (e.keyCode == 219) {
    ROOT.CAPTURE_CHAR+='[';
    ROOT.LAST_CAPTURE_CHAR ='[';
  }
  else if (e.keyCode == 221) {
    ROOT.CAPTURE_CHAR+=']';
    ROOT.LAST_CAPTURE_CHAR =']';
  }
  else{

    ROOT.CAPTURE_CHAR+=(String.fromCharCode(keynum).toLowerCase());
    ROOT.LAST_CAPTURE_CHAR = (String.fromCharCode(keynum).toLowerCase());

  }

}
else {

  if (e.keyCode == 50) {
    ROOT.CAPTURE_CHAR+="@";
    ROOT.LAST_CAPTURE_CHAR ="@";
  }
  else if (e.keyCode == 49) {
    ROOT.CAPTURE_CHAR+="!";
    ROOT.LAST_CAPTURE_CHAR ="!";
  }
  else if (e.keyCode == 51) {
    ROOT.CAPTURE_CHAR+="#";
    ROOT.LAST_CAPTURE_CHAR ="#";
  }
  else if (e.keyCode == 52) {
    ROOT.CAPTURE_CHAR+="$";
    ROOT.LAST_CAPTURE_CHAR ="$";
  }
  else if (e.keyCode == 53) {
    ROOT.CAPTURE_CHAR+="%";
    ROOT.LAST_CAPTURE_CHAR ="%";
  }
  else if (e.keyCode == 54) {
    ROOT.CAPTURE_CHAR+="^";
    ROOT.LAST_CAPTURE_CHAR ="^";
  }
  else if (e.keyCode == 55) {
    ROOT.CAPTURE_CHAR+="&";
    ROOT.LAST_CAPTURE_CHAR ="&";
  }
  else if (e.keyCode == 56) {
    ROOT.CAPTURE_CHAR+="*";
    ROOT.LAST_CAPTURE_CHAR ="*";
  }
  else if (e.keyCode == 57) {
    ROOT.CAPTURE_CHAR+="(";
    ROOT.LAST_CAPTURE_CHAR ="(";
  }
  else if (e.keyCode == 48) {
    ROOT.CAPTURE_CHAR+=")";
    ROOT.LAST_CAPTURE_CHAR =")";
  }
  else if (e.keyCode == 189) {
    ROOT.CAPTURE_CHAR+="_";
    ROOT.LAST_CAPTURE_CHAR ="_";
  }
  else if (e.keyCode == 187) {
    ROOT.CAPTURE_CHAR+="+";
    ROOT.LAST_CAPTURE_CHAR ="+";
  }
  else if (e.keyCode == 187) {
    ROOT.CAPTURE_CHAR+="+";
    ROOT.LAST_CAPTURE_CHAR ="+";
  }
  else if (e.keyCode == 188) {
    ROOT.CAPTURE_CHAR+="<";
    ROOT.LAST_CAPTURE_CHAR ="<";
  }
  else if (e.keyCode == 190) {
    ROOT.CAPTURE_CHAR+=">";
    ROOT.LAST_CAPTURE_CHAR =">";
  }
  else if (e.keyCode == 191) {
    ROOT.CAPTURE_CHAR+="?";
    ROOT.LAST_CAPTURE_CHAR ="?";
  }
  else if (e.keyCode == 186) {
    ROOT.CAPTURE_CHAR+=":";
    ROOT.LAST_CAPTURE_CHAR =":";
  }
  else if (e.keyCode == 222) {
    ROOT.CAPTURE_CHAR+='"';
    ROOT.LAST_CAPTURE_CHAR ='"';
  }
  else if (e.keyCode == 220) {
    ROOT.CAPTURE_CHAR+='|';
    ROOT.LAST_CAPTURE_CHAR ='|';
  }
  else if (e.keyCode == 219) {
    ROOT.CAPTURE_CHAR+='{';
    ROOT.LAST_CAPTURE_CHAR ='{';
  }
  else if (e.keyCode == 221) {
    ROOT.CAPTURE_CHAR+='}';
    ROOT.LAST_CAPTURE_CHAR ='}';
  }

  else {

    ROOT.CAPTURE_CHAR+=(String.fromCharCode(keynum).toUpperCase());
    ROOT.LAST_CAPTURE_CHAR = (String.fromCharCode(keynum).toUpperCase());

  }

}

}

ROOT.ACTION_ON_KEY_DOWN();

//@@@@@@@@@@@@@@@@@@@@@@@@@

if (typeof ROOT.TARGET_MODUL != 'undefined' && typeof ROOT.TARGET != 'undefined' ) {

      ROOT.CAPTURE_CHAR = ROOT.CAPTURE_CHAR.replace(/[^\x00-\x7F]/g, "");
      ROOT.CAPTURE_CHAR = ROOT.CAPTURE_CHAR.replace(/[^A-Za-z 0-9 \.,\?""!#\$%\^&\*\(\)-_=\+;:<>\/\\\|\}\{\[\]`~]*/g, '');

   window[ROOT.PROGRAM_NAME].ENGINE.MODULES.ACCESS(ROOT.TARGET_MODUL).GAME_OBJECTS.ACCESS(ROOT.TARGET).TEXTBOX.TEXT = ROOT.CAPTURE_CHAR;
    if (ROOT.ENTER_PRESSED == true) {

        window[ROOT.PROGRAM_NAME].ENGINE.MODULES.ACCESS(ROOT.TARGET_MODUL).GAME_OBJECTS.ACCESS(ROOT.TARGET).TEXTBOX.ON_PRESS_ENTER();

         if ( ROOT.CLEAR_CAPTURE_ON_PRESS_ENTER == true )
         {

             ROOT.CAPTURE_CHAR = '';

         }
    }
}
ROOT.ENTER_PRESSED = false;
//local_go.TEXTBOX.TEXT =  ROOT_EVENTS.ROOT_ENGINE.KEYBOARD.CAPTURE_CHAR;
//@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@@@@@@@@@@@@@@@@@@@@@@@@@
</code>```

Body:
I do this in my library project (visual-js game engine) please this post Virtual keyboar in canvas2d .

Live example : hosted on jsfiddle

Problem for can be implementation (it is not pure and native to make easy copy paste) . In v-js ge you can draw custom canvas2d code. I will suggest you to look at :

keyboard.js

Here is idea. Create object with (x,y,w,h) and create in click event calculating method 'is it clicked in object bounds' . Best way is to put it all(obj's) in array then in click event check for whose obj's reseive clicks.

for example draws for that object can be :

if (obj.visible == true) {
 ctx.fillRect( obj.x , obj.y , obj.w , obj.h )
 ctx.fillText( obj.TEXT ,  obj.x -obj.w/2 , obj.y  ) // dont use height for ipad/iphone
 //  set up middle positon of text
}

You can use samo model object for keyboard elements and also textbox element in canvas .(i dont talk about html tags)

In your game something action is done and you will need to create for every character uniq object with one char ( "A" , "SHIFT", "ENTER" etc ... ) make position for every obj. Draw all keyboard obj's .

'
Now you need some flag to know what is current ACTIVE_ELEMENT (any param in your game).

There is one big problem in moment when you append char (some special chars) they have some text format deforms. I ask but there is no answer (i will post that question later) .

In this code block is solution for that problem (i cant simple pass value for current keycode) Looks like hardcode but it is only solution for me :

ROOT.CAPTURE_CHAR = "";
ROOT.CLEAR_CAPTURE_ON_PRESS_ENTER = true;
ROOT.LAST_CAPTURE_CHAR = "";
ROOT.ENTER_PRESSED = false;
ROOT.SHIFT_PRESSED = false;
ROOT.ACTION_ON_KEY_DOWN = function(){};

...

//@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@@@@@@@@@@@@@@@@@@@@@@@@@
// SPECIAL FOR TEXTBOX
//@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@@@@@@@@@@@@@@@@@@@@@@@@@
SYS.DEBUG.LOG("KEYBOARD-->> Show users types : " + e.keyCode );
var keynum;
if(window.event){ keynum = e.keyCode;}else{if(e.which){ keynum = e.which;}}
//console.log(String.fromCharCode(keynum));

if (e.keyCode == 16){
ROOT.SHIFT_PRESSED = true;
}

if (e.keyCode == 8) {
SYS.DEBUG.LOG("textbox delete last char!");
ROOT.CAPTURE_CHAR = remove_last( ROOT.CAPTURE_CHAR );

}
else if(e.keyCode == 13){
ROOT.ENTER_PRESSED = true;
}
else {

if (ROOT.SHIFT_PRESSED == false) {

   if (e.keyCode == 189) {
    ROOT.CAPTURE_CHAR+="_";
    ROOT.LAST_CAPTURE_CHAR ="_";
  }
  else if (e.keyCode == 187) {
    ROOT.CAPTURE_CHAR+="+";
    ROOT.LAST_CAPTURE_CHAR ="+";
  }
  else if (e.keyCode == 187) {
    ROOT.CAPTURE_CHAR+="+";
    ROOT.LAST_CAPTURE_CHAR ="+";
  }
  else if (e.keyCode == 188) {
    ROOT.CAPTURE_CHAR+=",";
    ROOT.LAST_CAPTURE_CHAR =",";
  }
  else if (e.keyCode == 190) {
    ROOT.CAPTURE_CHAR+=".";
    ROOT.LAST_CAPTURE_CHAR =".";
  }
  else if (e.keyCode == 191) {
    ROOT.CAPTURE_CHAR+="/";
    ROOT.LAST_CAPTURE_CHAR ="/";
  }
  else if (e.keyCode == 186) {
    ROOT.CAPTURE_CHAR+=";";
    ROOT.LAST_CAPTURE_CHAR =";";
  }
  else if (e.keyCode == 222) {
    ROOT.CAPTURE_CHAR+="'";
    ROOT.LAST_CAPTURE_CHAR ="'";
  }
  else if (e.keyCode == 220) {
    ROOT.CAPTURE_CHAR+= "\\";
    ROOT.LAST_CAPTURE_CHAR ='\\';
  }
  else if (e.keyCode == 219) {
    ROOT.CAPTURE_CHAR+='[';
    ROOT.LAST_CAPTURE_CHAR ='[';
  }
  else if (e.keyCode == 221) {
    ROOT.CAPTURE_CHAR+=']';
    ROOT.LAST_CAPTURE_CHAR =']';
  }
  else{

    ROOT.CAPTURE_CHAR+=(String.fromCharCode(keynum).toLowerCase());
    ROOT.LAST_CAPTURE_CHAR = (String.fromCharCode(keynum).toLowerCase());

  }

}
else {

  if (e.keyCode == 50) {
    ROOT.CAPTURE_CHAR+="@";
    ROOT.LAST_CAPTURE_CHAR ="@";
  }
  else if (e.keyCode == 49) {
    ROOT.CAPTURE_CHAR+="!";
    ROOT.LAST_CAPTURE_CHAR ="!";
  }
  else if (e.keyCode == 51) {
    ROOT.CAPTURE_CHAR+="#";
    ROOT.LAST_CAPTURE_CHAR ="#";
  }
  else if (e.keyCode == 52) {
    ROOT.CAPTURE_CHAR+="$";
    ROOT.LAST_CAPTURE_CHAR ="$";
  }
  else if (e.keyCode == 53) {
    ROOT.CAPTURE_CHAR+="%";
    ROOT.LAST_CAPTURE_CHAR ="%";
  }
  else if (e.keyCode == 54) {
    ROOT.CAPTURE_CHAR+="^";
    ROOT.LAST_CAPTURE_CHAR ="^";
  }
  else if (e.keyCode == 55) {
    ROOT.CAPTURE_CHAR+="&";
    ROOT.LAST_CAPTURE_CHAR ="&";
  }
  else if (e.keyCode == 56) {
    ROOT.CAPTURE_CHAR+="*";
    ROOT.LAST_CAPTURE_CHAR ="*";
  }
  else if (e.keyCode == 57) {
    ROOT.CAPTURE_CHAR+="(";
    ROOT.LAST_CAPTURE_CHAR ="(";
  }
  else if (e.keyCode == 48) {
    ROOT.CAPTURE_CHAR+=")";
    ROOT.LAST_CAPTURE_CHAR =")";
  }
  else if (e.keyCode == 189) {
    ROOT.CAPTURE_CHAR+="_";
    ROOT.LAST_CAPTURE_CHAR ="_";
  }
  else if (e.keyCode == 187) {
    ROOT.CAPTURE_CHAR+="+";
    ROOT.LAST_CAPTURE_CHAR ="+";
  }
  else if (e.keyCode == 187) {
    ROOT.CAPTURE_CHAR+="+";
    ROOT.LAST_CAPTURE_CHAR ="+";
  }
  else if (e.keyCode == 188) {
    ROOT.CAPTURE_CHAR+="<";
    ROOT.LAST_CAPTURE_CHAR ="<";
  }
  else if (e.keyCode == 190) {
    ROOT.CAPTURE_CHAR+=">";
    ROOT.LAST_CAPTURE_CHAR =">";
  }
  else if (e.keyCode == 191) {
    ROOT.CAPTURE_CHAR+="?";
    ROOT.LAST_CAPTURE_CHAR ="?";
  }
  else if (e.keyCode == 186) {
    ROOT.CAPTURE_CHAR+=":";
    ROOT.LAST_CAPTURE_CHAR =":";
  }
  else if (e.keyCode == 222) {
    ROOT.CAPTURE_CHAR+='"';
    ROOT.LAST_CAPTURE_CHAR ='"';
  }
  else if (e.keyCode == 220) {
    ROOT.CAPTURE_CHAR+='|';
    ROOT.LAST_CAPTURE_CHAR ='|';
  }
  else if (e.keyCode == 219) {
    ROOT.CAPTURE_CHAR+='{';
    ROOT.LAST_CAPTURE_CHAR ='{';
  }
  else if (e.keyCode == 221) {
    ROOT.CAPTURE_CHAR+='}';
    ROOT.LAST_CAPTURE_CHAR ='}';
  }

  else {

    ROOT.CAPTURE_CHAR+=(String.fromCharCode(keynum).toUpperCase());
    ROOT.LAST_CAPTURE_CHAR = (String.fromCharCode(keynum).toUpperCase());

  }

}

}

ROOT.ACTION_ON_KEY_DOWN();

//@@@@@@@@@@@@@@@@@@@@@@@@@

if (typeof ROOT.TARGET_MODUL != 'undefined' && typeof ROOT.TARGET != 'undefined' ) {

      ROOT.CAPTURE_CHAR = ROOT.CAPTURE_CHAR.replace(/[^\x00-\x7F]/g, "");
      ROOT.CAPTURE_CHAR = ROOT.CAPTURE_CHAR.replace(/[^A-Za-z 0-9 \.,\?""!#\$%\^&\*\(\)-_=\+;:<>\/\\\|\}\{\[\]`~]*/g, '');

   window[ROOT.PROGRAM_NAME].ENGINE.MODULES.ACCESS(ROOT.TARGET_MODUL).GAME_OBJECTS.ACCESS(ROOT.TARGET).TEXTBOX.TEXT = ROOT.CAPTURE_CHAR;
    if (ROOT.ENTER_PRESSED == true) {

        window[ROOT.PROGRAM_NAME].ENGINE.MODULES.ACCESS(ROOT.TARGET_MODUL).GAME_OBJECTS.ACCESS(ROOT.TARGET).TEXTBOX.ON_PRESS_ENTER();

         if ( ROOT.CLEAR_CAPTURE_ON_PRESS_ENTER == true )
         {

             ROOT.CAPTURE_CHAR = '';

         }
    }
}
ROOT.ENTER_PRESSED = false;
//local_go.TEXTBOX.TEXT =  ROOT_EVENTS.ROOT_ENGINE.KEYBOARD.CAPTURE_CHAR;
//@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@@@@@@@@@@@@@@@@@@@@@@@@@