问:
Give the columnrange different colors
I have built some HighChart and I would like to give the 3 columnrange different colors (And not just blue as the current highChart Please see the jsfiddel link below)  to make it simple for persons to see the difference when taking a look at my HighChart.

https://jsfiddle.net/LLExL/7281/

```<code>Highcharts.chart('container',
 {
     chart: {
         type: 'columnrange',
         inverted: true,
         height: 200,
         spacingLeft: 30
     },
     credits: {
         enabled: false
     },
     title: {
         text: null,
         style: {
             "fontSize": "10px"
         }
     },
     subTitle: {
         text: null
     },
     legend: {
         enabled: false,
     },
     plotOptions: {
         series: {
             pointWidth: 30
         }
     },
     xAxis: {
         min: 1,
         max: 1,
         categories: ['', ''],
         title: {
             text: null
         },
         labels: {
             rotation: 90
         },
         gridLineWidth: 0
     },
     yAxis: {
         type: 'datetime',
         title: {
             text: null
         },
         labels: {
             rotation: -45,
             style: {
                 "fontSize": "10px"
             }
         },
         tickInterval: 1800000,
         gridLineWidth: 1
     },
     series: [{
         data: [
             [1, 1483337940000, 1483338000000],
             [1, 1483338300000, 1483339740000],
             [1, 1483340580000, 1483340640000],
             [1, 1483340640000, 1483340820000],
             [1, 1483340820000, 1483341000000],
             [1, 1483342800000, 1483342860000],
             [1, 1483342860000, 1483342920000],
             [1, 1483342920000, 1483342980000],
             [1, 1483346460000, 1483346520000],
             [1, 1483347120000, 1483347180000],
             [1, 1483347180000, 1483348440000],
             [1, 1483348440000, 1483348620000],
             [1, 1483348620000, 1483348740000],
             [1, 1483350180000, 1483350240000],
             [1, 1483350420000, 1483351380000],
             [1, 1483353300000, 1483353420000],
             [1, 1483355280000, 1483355340000],
             [1, 1483358580000, 1483359780000],
         ]
     }]
 }

);
</code>```

答:
You can replace the each point array with object and declare separate color.

```<code>{x:1, low: 1483337940000, high:1483338000000,color: 'red'},
</code>```

Example:

https://jsfiddle.net/ch4683os/

Title: Give the columnrange different colors

Body:
I have built some HighChart and I would like to give the 3 columnrange different colors (And not just blue as the current highChart Please see the jsfiddel link below)  to make it simple for persons to see the difference when taking a look at my HighChart.

https://jsfiddle.net/LLExL/7281/

Highcharts.chart('container',
 {
     chart: {
         type: 'columnrange',
         inverted: true,
         height: 200,
         spacingLeft: 30
     },
     credits: {
         enabled: false
     },
     title: {
         text: null,
         style: {
             "fontSize": "10px"
         }
     },
     subTitle: {
         text: null
     },
     legend: {
         enabled: false,
     },
     plotOptions: {
         series: {
             pointWidth: 30
         }
     },
     xAxis: {
         min: 1,
         max: 1,
         categories: ['', ''],
         title: {
             text: null
         },
         labels: {
             rotation: 90
         },
         gridLineWidth: 0
     },
     yAxis: {
         type: 'datetime',
         title: {
             text: null
         },
         labels: {
             rotation: -45,
             style: {
                 "fontSize": "10px"
             }
         },
         tickInterval: 1800000,
         gridLineWidth: 1
     },
     series: [{
         data: [
             [1, 1483337940000, 1483338000000],
             [1, 1483338300000, 1483339740000],
             [1, 1483340580000, 1483340640000],
             [1, 1483340640000, 1483340820000],
             [1, 1483340820000, 1483341000000],
             [1, 1483342800000, 1483342860000],
             [1, 1483342860000, 1483342920000],
             [1, 1483342920000, 1483342980000],
             [1, 1483346460000, 1483346520000],
             [1, 1483347120000, 1483347180000],
             [1, 1483347180000, 1483348440000],
             [1, 1483348440000, 1483348620000],
             [1, 1483348620000, 1483348740000],
             [1, 1483350180000, 1483350240000],
             [1, 1483350420000, 1483351380000],
             [1, 1483353300000, 1483353420000],
             [1, 1483355280000, 1483355340000],
             [1, 1483358580000, 1483359780000],
         ]
     }]
 }

);

Body:
You can replace the each point array with object and declare separate color.

{x:1, low: 1483337940000, high:1483338000000,color: 'red'},

Example:

https://jsfiddle.net/ch4683os/


来源: stackexchange

问:
How to repeat last command in python interpreter shell?
How do I repeat the last command? The usual keys: Up, Ctrl+Up, Alt-p don't work. They produce nonsensical characters.</p>

```<code>(ve)[kakarukeys@localhost ve]$ python
Python 2.6.6 (r266:84292, Nov 15 2010, 21:48:32)
[GCC 4.4.4 20100630 (Red Hat 4.4.4-10)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print "hello world"
hello world
>>> ^[[A
  File "<stdin>", line 1
    ^
SyntaxError: invalid syntax
>>> ^[[1;5A
  File "<stdin>", line 1
    [1;5A
    ^
SyntaxError: invalid syntax
>>> ^[p
  File "<stdin>", line 1
    p
    ^
SyntaxError: invalid syntax
>>>
</code>```

答:
I find information that I copied below answer the question

Adapt yourself to IDLE: Instead of hitting the up arrow to bring back a previous command, if you just put your cursor on the previous command you want to repeat and then press "enter", that command will be repeated at the current command prompt. Press enter again, and the command gets executed.

Force IDLE to adapt itself to you: If you insist on making the arrow keys in the IDLE command prompt window work like those in every other command prompt, you can do this. Go to the "Options" menu, select "Configure IDLE", and then "Keys". Changing the key that is associated with the "previous command" and "next command" actions to be the up arrow, and down arrow, respectively.

source

ContentLicense: CC BY-SA 2.5

Body:
How do I repeat the last command? The usual keys: Up, Ctrl+Up, Alt-p don't work. They produce nonsensical characters.

(ve)[kakarukeys@localhost ve]$ python
Python 2.6.6 (r266:84292, Nov 15 2010, 21:48:32)
[GCC 4.4.4 20100630 (Red Hat 4.4.4-10)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print "hello world"
hello world
>>> ^[[A
  File "<stdin>", line 1
    ^
SyntaxError: invalid syntax
>>> ^[[1;5A
  File "<stdin>", line 1
    [1;5A
    ^
SyntaxError: invalid syntax
>>> ^[p
  File "<stdin>", line 1
    p
    ^
SyntaxError: invalid syntax
>>>

ContentLicense: CC BY-SA 3.0


问:
URL in Ajax open()
This is my first Ajax program and I can't fix the code because I'm not sure where/what the problem is.

The error(which I'm unable to interpret) while using the debugger is,
XMLHttpRequest cannot load http://localhost/function.txt. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

```<code>function calling()
{
    var x;
    if (window.XMLHttpRequest) {
    x = new XMLHttpRequest();
    } else {

    x = new ActiveXObject("Microsoft.XMLHTTP");
    }

    x.onreadystatechange = function(){
        if(this.readyState == 4 && this.status == 200)
        {
            document.getElementById("block").innerHTML = this.responseText;
        }

    };
    x.open("GET", "http://localhost/function.txt",true);
    x.send();
}
</code>```

function.txt

```<code><html>
<head></head>
<body>
<h2>Ajax is working</h2>
</body>
</html>
</code>```

答:
Is your js located at the same location as your function.txt?

For more information about CORS, have a look at this link: https://www.html5rocks.com/en/tutorials/cors/

UPDATE:
This works for me, I think there is maybe something with your Apache settings...

```<code>function calling()
{
  var xhr = new XMLHttpRequest(),
      method = "GET",
      url = "function.txt";

  xhr.open(method, url, true);
  xhr.onreadystatechange = function () {
          if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
              alert(xhr.responseText);
          }
      };
  xhr.send();
}

calling();
</code>```

Title: URL in Ajax open()

Body:
This is my first Ajax program and I can't fix the code because I'm not sure where/what the problem is.

The error(which I'm unable to interpret) while using the debugger is,
XMLHttpRequest cannot load http://localhost/function.txt. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

function calling()
{
    var x;
    if (window.XMLHttpRequest) {
    x = new XMLHttpRequest();
    } else {

    x = new ActiveXObject("Microsoft.XMLHTTP");
    }

    x.onreadystatechange = function(){
        if(this.readyState == 4 && this.status == 200)
        {
            document.getElementById("block").innerHTML = this.responseText;
        }

    };
    x.open("GET", "http://localhost/function.txt",true);
    x.send();
}

function.txt

Ajax is working

Body:
Is your js located at the same location as your function.txt?

For more information about CORS, have a look at this link: https://www.html5rocks.com/en/tutorials/cors/

UPDATE:
This works for me, I think there is maybe something with your Apache settings...

function calling()
{
  var xhr = new XMLHttpRequest(),
      method = "GET",
      url = "function.txt";

  xhr.open(method, url, true);
  xhr.onreadystatechange = function () {
          if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
              alert(xhr.responseText);
          }
      };
  xhr.send();
}

calling();


问:
Insert a string at a specific index
How can I insert a string at a specific index of another string?

```<code> var txt1 = "foo baz"
</code>```

Suppose I want to insert "bar " after the "foo" how can I achieve that?

I thought of substring(), but there must be a simpler more straight forward way.

答:
Inserting at a specific index (rather than, say, at the first space character) has to use string slicing/substring:</p>

```<code>var txt2 = txt1.slice(0, 3) + "bar" + txt1.slice(3);
</code>```

ContentLicense: CC BY-SA 4.0

Title: Insert a string at a specific index

Body:
How can I insert a string at a specific index of another string?

 var txt1 = "foo baz"

Suppose I want to insert "bar " after the "foo" how can I achieve that?

I thought of substring(), but there must be a simpler more straight forward way.

Body:
Inserting at a specific index (rather than, say, at the first space character) has to use string slicing/substring:

var txt2 = txt1.slice(0, 3) + "bar" + txt1.slice(3);


问:
Update buffer and reset the locking-mode back to original one
Lets say we have a procedure which takes in a buffer-parameter:

myprocedure.p:

```<code>DEF PARAM BUFFER bufferParameter FOR DatabaseTable.

/* Get the same buffer in EXCLUSIVE-LOCK for updating */
FIND CURRENT bufferParameter EXCLUSIVE-LOCK.

/* Update the value */
ASSIGN bufferParameter.MyField = "new value".

/* Reset the locking mode back to the original one? */
FIND CURRENT bufferParameter NO-LOCK.
</code>```

The problem with this approach is that it is possibly changing the original locking-mode of the passed buffer parameter. It is possible that the buffer was in EXCLUSIVE-LOCK or f.ex in NO-LOCK. By changing the locking-mode, this procedure could invoke updating errors in some other programs using this same buffer.

Another solution would be to create a new temporary buffer for the same table, and then update the database thru that buffer (without touching the passed parameter buffer). The con of this approach is that the original passed buffer parameter will become 'out-of-date'. It would require a new database query to update it's 'MyField' value to match the one in the database.

How I could reset the buffer's locking-mode back to the original one after updating it's fields?

答:
I think your second solution would be the one to use. Define a local buffer (no need to call it a temporary buffer which is not a clearly defined term in OpenEdge IMO), load the record of the parameter into this buffer using rowid (basically a free operation, if the parameter buffer was locked already) and change your local buffer.
Don't worry about anything getting out of date. Quoting http://knowledgebase.progress.com/articles/Article/P4548 (please read the complete article)

Only a single copy of a record is allowed to exist at any one time in the client record pool.  This means that in the following case shows two buffers pointing at the same physical copy of customer 1.
  This means after executing the following code

```<code>DEFINE BUFFER cust FOR customer.
DEFINE BUFFER cust1 FOR customer.
FIND FIRST cust no-lock.
FIND cust1 where rowid(cust1) = rowid(cust) exclusive-lock.
cust1.name = 'xyz':U.
</code>```

cust.name would also have the value 'xyz'.
I just tried the code to be sure. Indeed I also confirmed that the lock is not on the buffer but on the record. I could also assign cust.name even though the find to cust uses no-lock.
If there is not already a transaction outside your program/procedure then the lock will be released when leaving the procedure.
Definitely don't try to work with _lock unless it's necessary to show the user who is locking the record he wants to change (or similar purposes).

Body:
Lets say we have a procedure which takes in a buffer-parameter:

myprocedure.p:

DEF PARAM BUFFER bufferParameter FOR DatabaseTable.

/* Get the same buffer in EXCLUSIVE-LOCK for updating */
FIND CURRENT bufferParameter EXCLUSIVE-LOCK.

/* Update the value */
ASSIGN bufferParameter.MyField = "new value".

/* Reset the locking mode back to the original one? */
FIND CURRENT bufferParameter NO-LOCK.

The problem with this approach is that it is possibly changing the original locking-mode of the passed buffer parameter. It is possible that the buffer was in EXCLUSIVE-LOCK or f.ex in NO-LOCK. By changing the locking-mode, this procedure could invoke updating errors in some other programs using this same buffer.

Another solution would be to create a new temporary buffer for the same table, and then update the database thru that buffer (without touching the passed parameter buffer). The con of this approach is that the original passed buffer parameter will become 'out-of-date'. It would require a new database query to update it's 'MyField' value to match the one in the database.

How I could reset the buffer's locking-mode back to the original one after updating it's fields?

Body:
I think your second solution would be the one to use. Define a local buffer (no need to call it a temporary buffer which is not a clearly defined term in OpenEdge IMO), load the record of the parameter into this buffer using rowid (basically a free operation, if the parameter buffer was locked already) and change your local buffer.
Don't worry about anything getting out of date. Quoting http://knowledgebase.progress.com/articles/Article/P4548 (please read the complete article)

Only a single copy of a record is allowed to exist at any one time in the client record pool.  This means that in the following case shows two buffers pointing at the same physical copy of customer 1.
  This means after executing the following code

DEFINE BUFFER cust FOR customer.
DEFINE BUFFER cust1 FOR customer.
FIND FIRST cust no-lock.
FIND cust1 where rowid(cust1) = rowid(cust) exclusive-lock.
cust1.name = 'xyz':U.

cust.name would also have the value 'xyz'.
I just tried the code to be sure. Indeed I also confirmed that the lock is not on the buffer but on the record. I could also assign cust.name even though the find to cust uses no-lock.
If there is not already a transaction outside your program/procedure then the lock will be released when leaving the procedure.
Definitely don't try to work with _lock unless it's necessary to show the user who is locking the record he wants to change (or similar purposes).


问:
Is there any way to swap columns in visual composer on mobile responsive?
Is there any way to swap columns in visual composer on mobile responsive?
I want to know it. such as we can swap columns in bootstrap using push or pull class. so can we make something like this in visual composer? i have uploaded images for assistance.

Actual Image: http://imgur.com/a/a1rqp

What i want: http://imgur.com/a/AA9aD

答:
Yes. You can do that using flex-direction:column-reverse

Add display:flex to your row and then, with media queries, in mobile add flex-direction:column-reverse to the same row. It will reverse the column order and so the one that is on right in desktop will move up, and the one on the left will move down.

display:flex you can add it before mobile ( in general styles ) or just in mobile version when you need to add also flex-direction:column-reverse

See example below or jsfiddle

.vc_row { display:flex;}
.col { padding:0 15px;height:100px;border:1px solid red}

@media only screen and (max-width: 767px) {
  .vc_row { flex-direction:column-reverse}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="vc_row">
    <div class="col">
    text on left in desktop and on bottom in mobile
    </div>
    <div class="col">
    text on right in desktop and on top in mobile
    </div>
</div></code>```

Read more about flex-direction -> Flex direction docs

for iPhone ( safari ) users flex-direction: column-reverse might not work as intended. Use

```<code>{
  flex-direction: column;
  flex-wrap: wrap-reverse
}
</code>```

Body:
Yes. You can do that using flex-direction:column-reverse

Add display:flex to your row and then, with media queries, in mobile add flex-direction:column-reverse to the same row. It will reverse the column order and so the one that is on right in desktop will move up, and the one on the left will move down.

display:flex you can add it before mobile ( in general styles ) or just in mobile version when you need to add also flex-direction:column-reverse

See example below or jsfiddle

.vc_row { display:flex;}
.col { padding:0 15px;height:100px;border:1px solid red}

@media only screen and (max-width: 767px) {
  .vc_row { flex-direction:column-reverse}
}

<div class="vc_row">
    <div class="col">
    text on left in desktop and on bottom in mobile
    </div>
    <div class="col">
    text on right in desktop and on top in mobile
    </div>
</div>

Read more about flex-direction -> Flex direction docs

for iPhone ( safari ) users flex-direction: column-reverse might not work as intended. Use

{
  flex-direction: column;
  flex-wrap: wrap-reverse
}


问:
Warning : The referenced component 'NuGet.Core' could not be found
I am working on a developed desktop application in Visual Studio 2010. Till yesterday everything was fine but from today as soon as I open the project in Visual Studio it is giving me warning,"The referenced component 'NuGet.Core' could not be found". I searched in Solution Explorer and found that in the Project-> References, NuGet.Core with an exclamation mark. Is something got deleted or corrupted I don't know. Please Help!! I am not able to find the reason behind this. Searched for the solution but no success.Image:This is what I got while searching in Solution Explorer</p>

答:
The exclamation mark means that the project has lost the location of the reference, but it knows it should be there. If you manually delete the reference (right click on the component and then select delete) and then re add it (project -> add reference -> then find the file location [you should not need to re add it using Nuget]) to you project it should get your project working again.

With regard to why this is happening, something may have changed somewhere that caused VS to lose the reference. This could be the location of the reference, or source control, or something else. Often I am unable to find the reason for this.


问:
Canplayer won't replay candump files
I'm trying to use canplayer to replay some candump files, with no success. When I try to run the canplayer it just executes and returns, giving me no clue of what is happening.

What I've tried up to now:

Setup 1

Set up a vcan interface

Sent data to the vcan interface using cansend and cangen, with success (verified with candump).

Recorded a candump file from vcan0 when running cangen. Recorded files with absolute timestamps (-t a) and without.

Tried using canplayer to reproduce the file. Tried using several arguments, no avail. canplayer just returns immediately without any complaint. If I mess up the the file or arguments it complains.

Setup 2

Connected 2 PEAK CAN USB adapter devices to the PC.

Connected the adapters to each other using a 120ohm terminated cable

Started cangen pointing to can0 and verified that the messages got to can1 using candump

Recorded candump files from can0 interface.

Tried using canplayer to reproduce the file., with no success.

I've tried these tests on two different machines, both running Ubuntu 12.04, with the same results.

Do you know what might be the cause of it?

答:
I found this article with some great information about using can and vcan. After taking a log of a physical CAN bus with candump using

$ candump -l can0

as stated in the previous answer. I used the following to play it back over a virtual CAN bus.

$ canplayer vcan0=can0 -I candump-may-14-2015.log

Title: Canplayer won't replay candump files


问:
Facebook Page Plugin is not working - only for one site
I have integrated the page plugin in my directory.

ruhrlink.de info.php?schluessel=150991 dont work, others do.

When I enter the web adress manually in the developers site -> Page plugin
it dont works there, too.

https://www.facebook.com/Geschirr-Service-Ch-Dittrich-607545982758149/

What is so special with this adress?

答:
The page has some sort of access restriction set. The page plugin only works for public pages without any restrictions.

https://developers.facebook.com/docs/plugins/page-plugin#privacy:

Privacy Restricted Pages

  Facebook Pages with privacy restrictions cannot be embedded.


问:
How do I build JSON dynamically in javascript?
```<code>var myJSON = {
              "list1" : [ "1", "2" ],
              "list2" : [ "a", "b" ],
              "list3" : [ { "key1" : "value1" }, { "key2" : "value2" } ],
              "not_a_list" : "11"
             };
</code>```

How do I dynamically build this JSON structure in javascript? Google tells me to use use some push command, but I've only found specific cases. So what do I write to enter data to "listX" and "not_a_list". Appending as well as creating a new list. The whole procedure begninning with:

```<code>var myJSON = {};
</code>```

答:
As myJSON is an object you can just set its properties, for example:

```<code>myJSON.list1 = ["1","2"];
</code>```

If you dont know the name of the properties, you have to use the array access syntax:

```<code>myJSON['list'+listnum] = ["1","2"];
</code>```

If you want to add an element to one of the properties, you can do;

```<code>myJSON.list1.push("3");
</code>```

Body:
var myJSON = {
              "list1" : [ "1", "2" ],
              "list2" : [ "a", "b" ],
              "list3" : [ { "key1" : "value1" }, { "key2" : "value2" } ],
              "not_a_list" : "11"
             };

How do I dynamically build this JSON structure in javascript? Google tells me to use use some push command, but I've only found specific cases. So what do I write to enter data to "listX" and "not_a_list". Appending as well as creating a new list. The whole procedure begninning with:

var myJSON = {};

Body:
As myJSON is an object you can just set its properties, for example:

myJSON.list1 = ["1","2"];

If you dont know the name of the properties, you have to use the array access syntax:

myJSON['list'+listnum] = ["1","2"];

If you want to add an element to one of the properties, you can do;

myJSON.list1.push("3");


问:
how to take user input while in a in loop android?
is it possible to wait for user input before going to next iteration of for loop in android. ?
I generate a textview programmatically according to the String array given.When the loops runs a textview is created and its visibility is set to invisible .Now, what I want to do is when the first iteration of the loop runs i.e when i=0 the textviews options1 options2 options3
are assigned random values with one being equal to arr[i](the correct one).after the options are created the user will input his/her guess  if it is the correct one the dynamic textviews visibility is set to VISIBLE and after that the next next iteration of the loop should run i.e i=1 with new options and so on.. It is possible to do this?

so far my code is like this:

```<code>    String[] arr = {"a", "b", "c"};
    TextView option_1 = (TextView) findViewById(R.id.txtv1);
    TextView option_2 = (TextView) findViewById(R.id.txtv2);
    TextView option_3 = (TextView) findViewById(R.id.txtv3);
    for(int i = 0; i < arr.length; i++) {
        final TextView textView = new TextView(this);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);
        textView.setLayoutParams(new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, 48));
        textView.setGravity(Gravity.CENTER_VERTICAL);
        textView.setPadding(20, 0, 0, 0);
        textView.setText(arr[i]);
        textView.setId(i + 1);
        textViewIds[i] = textView.getId();
        textView.setVisibility(View.INVISIBLE);
        final int[] textViewIds = new int[]{R.id.txtv1, R.id.txtv1, R.id.txtv1};
        Random r = new Random();
        int Rand_Tv_no = r.nextInt(textViewIds.length);
        ((TextView) findViewById(textViewIds[Rand_Tv_no])).setText(code[i]);

    }
</code>```

答:
Yes it's possible by using AlertDialog boxes. Create AlertDialog in loop, it will generate according by to your loop and create EditText box in your alert dialogue.
This is sample code for creating AlertDialog

```<code>   AlertDialog alert = new AlertDialog.Builder(AnalogyActivity.this)
                        .setTitle("Are You Sure?")
                        .setCancelable(true)
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                               Log.e(TAG, "click: No");

                            }
                        })
                        .create();
                alert.setCanceledOnTouchOutside(true);
                alert.show();
</code>```

Body:
is it possible to wait for user input before going to next iteration of for loop in android. ?
I generate a textview programmatically according to the String array given.When the loops runs a textview is created and its visibility is set to invisible .Now, what I want to do is when the first iteration of the loop runs i.e when i=0 the textviews options1 options2 options3
are assigned random values with one being equal to arr[i](the correct one).after the options are created the user will input his/her guess  if it is the correct one the dynamic textviews visibility is set to VISIBLE and after that the next next iteration of the loop should run i.e i=1 with new options and so on.. It is possible to do this?

so far my code is like this:

    String[] arr = {"a", "b", "c"};
    TextView option_1 = (TextView) findViewById(R.id.txtv1);
    TextView option_2 = (TextView) findViewById(R.id.txtv2);
    TextView option_3 = (TextView) findViewById(R.id.txtv3);
    for(int i = 0; i < arr.length; i++) {
        final TextView textView = new TextView(this);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);
        textView.setLayoutParams(new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, 48));
        textView.setGravity(Gravity.CENTER_VERTICAL);
        textView.setPadding(20, 0, 0, 0);
        textView.setText(arr[i]);
        textView.setId(i + 1);
        textViewIds[i] = textView.getId();
        textView.setVisibility(View.INVISIBLE);
        final int[] textViewIds = new int[]{R.id.txtv1, R.id.txtv1, R.id.txtv1};
        Random r = new Random();
        int Rand_Tv_no = r.nextInt(textViewIds.length);
        ((TextView) findViewById(textViewIds[Rand_Tv_no])).setText(code[i]);

    }

Body:
Yes it's possible by using AlertDialog boxes. Create AlertDialog in loop, it will generate according by to your loop and create EditText box in your alert dialogue.
This is sample code for creating AlertDialog

   AlertDialog alert = new AlertDialog.Builder(AnalogyActivity.this)
                        .setTitle("Are You Sure?")
                        .setCancelable(true)
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                               Log.e(TAG, "click: No");

                            }
                        })
                        .create();
                alert.setCanceledOnTouchOutside(true);
                alert.show();


问:
AJAX function not works (ASP.NET MVC)
I have AJAX function in my View to pass data to Controller

Here is code of script

```<code> stop.onclick = function () {
    record.disabled = false;
    stop.disabled = true;
    window.onbeforeunload = null; //Solve trouble with deleting video
    preview.src = '';

    fileName = Math.round(Math.random() * 99999999) + 99999999;
    console.log(fileName);
    var full_url = document.URL; // Get current url
    var url_array = full_url.split('/') // Split the string into an array with / as separator
    var id = url_array[url_array.length - 1];  // Get the last part of the array (-1)
    function save() {
        $.ajax({
            type: 'Post',
            dataType: 'Json',
            data: {
                link: fileName.val(),
                id: id.val(),
            },
            url: '@Url.Action("LinkWriter", "Interwier")',
            success: function (da) {
                if (da.Result === "Success") {

                    alert("lol");

                } else {

                    alert('Error' + da.Message);
                }
            },
            error: function (da) {
                alert('Error');
            }
        });
    }
</code>```

Not works this part of code

```<code> function save() {
        $.ajax({
            type: 'Post',
            dataType: 'Json',
            data: {
                link: fileName.val(),
                id: id.val(),
            },
            url: '@Url.Action("LinkWriter", "Interwier")',
            success: function (da) {
                if (da.Result === "Success") {

                    alert("lol");

                } else {

                    alert('Error' + da.Message);
                }
            },
            error: function (da) {
                alert('Error');
            }
        });
    }
</code>```

Here is code in Controller

```<code>[HttpPost]
    public ActionResult LinkWriter(string link, int id) {

        Link link_ = new Link
        {
            Link1 = link,
            Interwier_Id = id,

        };

        db.Link.Add(link_);
        db.SaveChanges();
        return Json(new { Result = "Success", Message = "Saved Successfully" });
    }
</code>```

I don't understand why it not works

I think I doing all right

Can you help me?

答:
try to catch value in controller using _POST :

```<code>Link1 = _POST['link'];
Interwier_Id = _POST['id'];
</code>```

also remove the controller's function params :

```<code>public ActionResult LinkWriter() {
</code>```

Title: AJAX function not works (ASP.NET MVC)

Body:
I have AJAX function in my View to pass data to Controller

Here is code of script

 stop.onclick = function () {
    record.disabled = false;
    stop.disabled = true;
    window.onbeforeunload = null; //Solve trouble with deleting video
    preview.src = '';

    fileName = Math.round(Math.random() * 99999999) + 99999999;
    console.log(fileName);
    var full_url = document.URL; // Get current url
    var url_array = full_url.split('/') // Split the string into an array with / as separator
    var id = url_array[url_array.length - 1];  // Get the last part of the array (-1)
    function save() {
        $.ajax({
            type: 'Post',
            dataType: 'Json',
            data: {
                link: fileName.val(),
                id: id.val(),
            },
            url: '@Url.Action("LinkWriter", "Interwier")',
            success: function (da) {
                if (da.Result === "Success") {

                    alert("lol");

                } else {

                    alert('Error' + da.Message);
                }
            },
            error: function (da) {
                alert('Error');
            }
        });
    }

Not works this part of code

 function save() {
        $.ajax({
            type: 'Post',
            dataType: 'Json',
            data: {
                link: fileName.val(),
                id: id.val(),
            },
            url: '@Url.Action("LinkWriter", "Interwier")',
            success: function (da) {
                if (da.Result === "Success") {

                    alert("lol");

                } else {

                    alert('Error' + da.Message);
                }
            },
            error: function (da) {
                alert('Error');
            }
        });
    }

Here is code in Controller

[HttpPost]
    public ActionResult LinkWriter(string link, int id) {

        Link link_ = new Link
        {
            Link1 = link,
            Interwier_Id = id,

        };

        db.Link.Add(link_);
        db.SaveChanges();
        return Json(new { Result = "Success", Message = "Saved Successfully" });
    }

I don't understand why it not works

I think I doing all right

Can you help me?

Body:
try to catch value in controller using _POST :

Link1 = _POST['link'];
Interwier_Id = _POST['id'];

also remove the controller's function params :

public ActionResult LinkWriter() {


问:
Left function in sql server
In table 'Period' there is a column 'Date' ,example data is FEBRUARY 3,2010

Now in where condition Left(Date,3)='Feb' also gives results,Is the Left function case insensitive?

答:
You can set the collate in your query, for example

```<code>Declare @YourTable table (Col varchar(25))
Insert Into @YourTable values
('February'),
('february'),
('FEBRUARY')

Select *
 From  @YourTable
 Where left(Col,3) = 'Feb' COLLATE SQL_Latin1_General_CP1_CS_AS
</code>```

Returns

```<code>February
</code>```

Conversely, if set to SQL_Latin1_General_CP1_CI_AS  (insensitive)

You'll get

```<code>February
february
FEBRUARY
</code>```

Title: Left function in sql server

Body:
You can set the collate in your query, for example

Declare @YourTable table (Col varchar(25))
Insert Into @YourTable values
('February'),
('february'),
('FEBRUARY')

Select *
 From  @YourTable
 Where left(Col,3) = 'Feb' COLLATE SQL_Latin1_General_CP1_CS_AS

Returns

February

Conversely, if set to SQL_Latin1_General_CP1_CI_AS  (insensitive)

You'll get

February
february
FEBRUARY


问:
How to avoid overfitting Recurrent Neural Network
I have been training Bidirectional LSTM based RNN for Speech Recognition, and the network appears to forget the old context as soon as a new context arrives. I am unsure how to explain its behaviour though; it appears that the network is being overfit such that it remembers only one specific case at a time.

The link to code is https://github.com/rajkumarcm15/Speech-Recognition/blob/master/MFCC_SWN_BN_Affine/train.py and its output in https://github.com/rajkumarcm15/Speech-Recognition/blob/master/MFCC_SWN_BN_Affine/Results.pdf.

Need some help in understanding its output pattern.

答:
I haven't studied your output that much but have you taken a look at dropout to minimize overfitting?

e.g.

```<code>cell = GRUCell(num_neurons)  # Or LSTMCell(num_neurons)
cell = DropoutWrapper(cell, output_keep_prob=dropout)
cell = MultiRNNCell([cell] * num_layers)
</code>```

About dropout

Body:
I haven't studied your output that much but have you taken a look at dropout to minimize overfitting?

e.g.

cell = GRUCell(num_neurons)  # Or LSTMCell(num_neurons)
cell = DropoutWrapper(cell, output_keep_prob=dropout)
cell = MultiRNNCell([cell] * num_layers)

About dropout


答:
You cannot make Ajax calls to a url from a different domain if said domain does not explicitly allow it (via 'Access-Control-Allow-Origin' header).
Your error means that you're making your Ajax call from another domain. If your function.txt file is located at the same location as your js, try using relative path in your .open().

Title: URL in Ajax open()


问:
How to read Stored Procedure source code from a java program?
I need to read the contents(text inside a stored procedure) of a stored procedure of a particular schema from a Java program.

Example. suppose I have a sp in oracle named mySp.

I need to read the text inside the sp.

How i can achieve this from a java program.

答:
I think you can use something like this..Better refer JDBC MetaData API..Hope this helps

http://docs.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.html

```<code>DatabaseMetaData dbMetaData = conn.getMetaData();
ResultSet rs = dbMetaData.getProcedureColumns(conn.getCatalog(),
                      null,
                      "mySp",
                      "");

while(rs.next()) {
  /
}
</code>```

Body:
I think you can use something like this..Better refer JDBC MetaData API..Hope this helps

http://docs.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.html

DatabaseMetaData dbMetaData = conn.getMetaData();
ResultSet rs = dbMetaData.getProcedureColumns(conn.getCatalog(),
                      null,
                      "mySp",
                      "");

while(rs.next()) {
  /
}


问:
Appium with Android Hydrid App doesn't recognise element
I am writing automation tests for a Hydrid App on Android. I have 2 problems:

From Appium Inspector, I see an element with attribute

```<code>resource-id: login_button
</code>```

so I click this button with

```<code>androidDriver.findElement(By.id("login-button")).click();
</code>```

and I get this error:

```<code>"An element could not be located with..."
</code>```

Of course if I find element with

```<code>classname "android.widget.Button"
</code>```

then it works. I asked developer, normally, resource-id would be like

```<code>resource-id: <APP_PACKAGE_NAME>:id/login_button
</code>```

But he said for hydrid app he doesn't have bundleID (APP_PACKAGE_NAME). Is it correct that we don't have bundleID for Hydrid APP? And why Appium Inspector can see

```<code>"resource-id: login_button"
</code>```

but this element could not be found and clickable?

So I also tried to switch context to WEBVIEW, with this code:

```<code>Set<String> contextHandles = appiumDriver.getContextHandles();
Map<String,String> hashMap= new HashMap<String,String>();
    for (String contextname : contextHandles){
        if (contextname.contains("NATIVE")){
            hashMap.put("native", contextname);
        } else {
            hashMap.put("webview", contextname);
        }
    }
    //webview
    androidDriver.context(hashMap.get("webview"));
</code>```

contextHandles has 2 values: NATIVE_APP and WEBVIEW_<APP_PACKAGE_NAME>. But when I set context to webview, I get error:

```<code>"There is no such context"
</code>```

Can anyone please help? Thanks

答:
Hybrid application means - An application build by combination of both Native App View and Web View.

But at a time only one view will be available either Native or Web

If the view is Native, then you can inspect elements from UI Automator.

If the view is webview, then the UI automator will not show any hierarchy. For that you have to inspect in browser using the url - chrome://inspect/#devices

In your case you are saying that you are able to click on login if you use class name, but unable to click when you are using resource-id

There might be multiple locators having the same resource-id. Please check once and make sure you are using unique locator that might be Xpath or class name etc

Body:
I am writing automation tests for a Hydrid App on Android. I have 2 problems:

From Appium Inspector, I see an element with attribute

resource-id: login_button

so I click this button with

androidDriver.findElement(By.id("login-button")).click();

and I get this error:

"An element could not be located with..."

Of course if I find element with

classname "android.widget.Button"

then it works. I asked developer, normally, resource-id would be like

resource-id: <APP_PACKAGE_NAME>:id/login_button

But he said for hydrid app he doesn't have bundleID (APP_PACKAGE_NAME). Is it correct that we don't have bundleID for Hydrid APP? And why Appium Inspector can see

"resource-id: login_button"

but this element could not be found and clickable?

So I also tried to switch context to WEBVIEW, with this code:

Set<String> contextHandles = appiumDriver.getContextHandles();
Map<String,String> hashMap= new HashMap<String,String>();
    for (String contextname : contextHandles){
        if (contextname.contains("NATIVE")){
            hashMap.put("native", contextname);
        } else {
            hashMap.put("webview", contextname);
        }
    }
    //webview
    androidDriver.context(hashMap.get("webview"));

contextHandles has 2 values: NATIVE_APP and WEBVIEW_<APP_PACKAGE_NAME>. But when I set context to webview, I get error:

"There is no such context"

Can anyone please help? Thanks


问:
Why is the ternary operator used to define 1 and 0 in a macro?
I'm using an SDK for an embedded project. In this source code I found some code which at least I found peculiar. In many places in the SDK there is source code in this format:

```<code>#define ATCI_IS_LOWER( alpha_char )  ( ( (alpha_char >= ATCI_char_a) && (alpha_char <= ATCI_char_z) ) ? 1 : 0 )

#define ATCI_IS_UPPER( alpha_char )  ( ( (alpha_char >= ATCI_CHAR_A) && (alpha_char <= ATCI_CHAR_Z) ) ? 1 : 0 )
</code>```

Does the use of the ternary operator here make any difference?

Isn't

```<code>#define FOO (1 > 0)
</code>```

the same as

```<code>#define BAR ( (1 > 0) ? 1 : 0)
</code>```

?

I tried evaluating it by using

```<code>printf("%d", FOO == BAR);
</code>```

and get the result 1, so it seems that they are equal. Is there a reason to write the code like they did?

答:
There's a bug in the SDK code, and the ternary was probably a kludge to fix it.

Being a macro the arguments (alpha_char) can be any expression and should be parenthesized because expressions such as 'A' && 'c' will fail the test.

```<code>#define IS_LOWER( x ) ( ( (x >= 'a') && (x <= 'z') ) ?  1 : 0 )
std::cout << IS_LOWER('A' && 'c');
**1**
std::cout << IS_LOWER('c' && 'A');
**0**
</code>```

This is why one should always parenthesize macro arguments in the expansion.

So in your example (but with parameters), these are both bugged.

```<code>#define FOO(x) (x > 0)
#define BAR(x) ((x > 0) ? 1 : 0)
</code>```

They would most correctly be replaced by

```<code>#define BIM(x) ((x) > 0)
</code>```

@CiaPan Makes a great point in following comment which is that using a parameter more than once leads to undefinable results. For instance

```<code>#define IS_LOWER( x ) (((x) >= 'a') && ((x) <= 'z'))
char ch = 'y';
std::cout << IS_LOWER(ch++);
**1**
**BUT ch is now '{'**
</code>```

Body:
I'm using an SDK for an embedded project. In this source code I found some code which at least I found peculiar. In many places in the SDK there is source code in this format:

#define ATCI_IS_LOWER( alpha_char )  ( ( (alpha_char >= ATCI_char_a) && (alpha_char <= ATCI_char_z) ) ? 1 : 0 )

#define ATCI_IS_UPPER( alpha_char )  ( ( (alpha_char >= ATCI_CHAR_A) && (alpha_char <= ATCI_CHAR_Z) ) ? 1 : 0 )

Does the use of the ternary operator here make any difference?

Isn't

#define FOO (1 > 0)

the same as

#define BAR ( (1 > 0) ? 1 : 0)

?

I tried evaluating it by using

printf("%d", FOO == BAR);

and get the result 1, so it seems that they are equal. Is there a reason to write the code like they did?

Body:
There's a bug in the SDK code, and the ternary was probably a kludge to fix it.

Being a macro the arguments (alpha_char) can be any expression and should be parenthesized because expressions such as 'A' && 'c' will fail the test.

#define IS_LOWER( x ) ( ( (x >= 'a') && (x <= 'z') ) ?  1 : 0 )
std::cout << IS_LOWER('A' && 'c');
**1**
std::cout << IS_LOWER('c' && 'A');
**0**

This is why one should always parenthesize macro arguments in the expansion.

So in your example (but with parameters), these are both bugged.

#define FOO(x) (x > 0)
#define BAR(x) ((x > 0) ? 1 : 0)

They would most correctly be replaced by

#define BIM(x) ((x) > 0)

@CiaPan Makes a great point in following comment which is that using a parameter more than once leads to undefinable results. For instance

#define IS_LOWER( x ) (((x) >= 'a') && ((x) <= 'z'))
char ch = 'y';
std::cout << IS_LOWER(ch++);
**1**
**BUT ch is now '{'**


问:
Get custom property set in Outlook Add-In via Microsoft Graph
Let's say I have in my Outlook Add-In (using Office.js) following code running on a compose form of an appointment:

const item = Office.context.mailbox.item;
item.loadCustomPropertiesAsync((result) => {
    const props = result.value;
    const testProp = props.get("my_prop");
    console.log("CUSTOM_PROP", testProp);
    props.set("my_prop", "test_value");
    props.saveAsync((saveResult) =>
        console.log("SAVE_CUSTOM_PROP", saveResult));
});
```

I see, that it actually is saved on the event.

And now a bunch of questions regarding those custom properties:

But are those somehow related to extended properties?

Are those properties somehow accessible through Outlook REST API or Microsoft Graph?

Can I create a push notifications subscription using Microsoft Graph with a filter based on those properties? (I know I can based on extended properties)

If the answer to above question is "no", and the custom properties are only accessible through the add-in which created them, is there a way to create a extended property to an event from the add-in, even if it's not saved?

To explain why I'm asking - I'm creating an add-in, which allows to "connect" an appointment with our 3rd party system, and keep that appointment in sync with our object.

So when a button is clicked on the compose form, I:

save the appointment and get the event-id,

store it in our system, to do the sync from our system to the appointment.

add an extended property in our system using Microsoft Graph for that appointment

In the first use of the add-in, the user authenticates, and I create a push notification subscription for events with our extended property, to do the sync from Outlook to our system.

It works great on OWA, but now as we really need to support desktop, two major issues are arising:

Outlook for Mac: no saveAsync method, thus no way to get the event's id, I was thinking about adding some custom property, and then let the push notification inform our system, that an event was created which needs to be synced with out system.

Outlook for PC: there is the saveAsync method, but the callback is executed when the appointment is saved locally, not on the server, thus I can't know when exactly the event has been created and I can do some Microsoft Graph calls on that event.

Answer to my first question, and/or any tips about my use case would be more than welcome.

答:
Per MS-OXCEXT, the interoperability doc on how add-ins store stuff in Outlook, custom properties are stored as a JSON dictionary in a MAPI extended property (gory details at that link). That means you should be able to access them via Graph extended properties, you would just have to parse the value yourself.

Should be using extended properties and the "{type} {guid} Name {name}" format.

I don't see why not.

The answer isn't no, but I'll answer your follow up anyway :). Sure you can do this if you use the REST API from your add-in.

Body:
Let's say I have in my Outlook Add-In (using Office.js) following code running on a compose form of an appointment:

const item = Office.context.mailbox.item;
item.loadCustomPropertiesAsync((result) => {
    const props = result.value;
    const testProp = props.get("my_prop");
    console.log("CUSTOM_PROP", testProp);
    props.set("my_prop", "test_value");
    props.saveAsync((saveResult) =>
        console.log("SAVE_CUSTOM_PROP", saveResult));
});

I see, that it actually is saved on the event.

And now a bunch of questions regarding those custom properties:

But are those somehow related to extended properties?

Are those properties somehow accessible through Outlook REST API or Microsoft Graph?

Can I create a push notifications subscription using Microsoft Graph with a filter based on those properties? (I know I can based on extended properties)

If the answer to above question is "no", and the custom properties are only accessible through the add-in which created them, is there a way to create a extended property to an event from the add-in, even if it's not saved?

To explain why I'm asking - I'm creating an add-in, which allows to "connect" an appointment with our 3rd party system, and keep that appointment in sync with our object.

So when a button is clicked on the compose form, I:

save the appointment and get the event-id,

store it in our system, to do the sync from our system to the appointment.

add an extended property in our system using Microsoft Graph for that appointment

In the first use of the add-in, the user authenticates, and I create a push notification subscription for events with our extended property, to do the sync from Outlook to our system.

It works great on OWA, but now as we really need to support desktop, two major issues are arising:

Outlook for Mac: no saveAsync method, thus no way to get the event's id, I was thinking about adding some custom property, and then let the push notification inform our system, that an event was created which needs to be synced with out system.

Outlook for PC: there is the saveAsync method, but the callback is executed when the appointment is saved locally, not on the server, thus I can't know when exactly the event has been created and I can do some Microsoft Graph calls on that event.

Answer to my first question, and/or any tips about my use case would be more than welcome.


答:
You don't need val() as long as you got numbers in your variables:

```<code>data: {
   link: fileName,
   id: id,
},
</code>```

Title: AJAX function not works (ASP.NET MVC)

Body:
You don't need val() as long as you got numbers in your variables:

data: {
   link: fileName,
   id: id,
},


问:
Multiple text insertion in Linux
Can someone help me how to write a piece of command that will insert some text in multiple places (given column and row) of a given file that already contains data. For example: old_data is a file that contains:

```<code>A
</code>```

And I wish to get new_data that will contain:

```<code>A 1
</code>```

I read something about awk and sed commands, but I don't believe to understand how to incorporate these, to get what I want.

I would like to add up, that this command I would like to use as a part of script

```<code>for b in ./*/ ; do (cd "$b" && command); done
</code>```

If we imagine content of old_data as a matrix of elements {An*m} where n corresponds to number of row and m to number of column of this matrix, I wish to manipulate with matrix so that I could add new elements. A in old-data has coordinates (1,1). In new_data therefore, I wish to assign 1 to a matrix element that has coordinates (1,3).
If we compare content of old_data and new_data we see that (1,2) element corresponds to space (it is empty).

答:
This bash & unix tools code works:

```<code># make the input files.
echo {A..D} | tr ' ' '\n' > abc ; echo {1..4} | tr ' ' '\n' > 123
# print as per previous OP spec
head -1q abc 123 ; paste abc 123 123 | tail -n +2
</code>```

Output:

```<code>A
1
B   2   2
C   3   3
D   4   4
</code>```

Version #3, (using commas as more visible separators), as per newest OP spec:

```<code># for the `sed` code change the `2` to whatever column needs deleting.
paste -d, abc 123 123 | sed 's/[^,]*//2'
</code>```

Output:

```<code>A,,1
B,,2
C,,3
D,,4
</code>```

The same, with tab delimiters (less visually obvious):

```<code>paste abc 123 123 | sed 's/[^\t]*//2'
A       1
B       2
C       3
D       4
</code>```

Title: Multiple text insertion in Linux

Body:
Can someone help me how to write a piece of command that will insert some text in multiple places (given column and row) of a given file that already contains data. For example: old_data is a file that contains:

A

And I wish to get new_data that will contain:

A 1

I read something about awk and sed commands, but I don't believe to understand how to incorporate these, to get what I want.

I would like to add up, that this command I would like to use as a part of script

for b in ./*/ ; do (cd "$b" && command); done

If we imagine content of old_data as a matrix of elements {An*m} where n corresponds to number of row and m to number of column of this matrix, I wish to manipulate with matrix so that I could add new elements. A in old-data has coordinates (1,1). In new_data therefore, I wish to assign 1 to a matrix element that has coordinates (1,3).
If we compare content of old_data and new_data we see that (1,2) element corresponds to space (it is empty).

Body:
This bash & unix tools code works:

# make the input files.
echo {A..D} | tr ' ' '\n' > abc ; echo {1..4} | tr ' ' '\n' > 123
# print as per previous OP spec
head -1q abc 123 ; paste abc 123 123 | tail -n +2

Output:

A
1
B   2   2
C   3   3
D   4   4

Version #3, (using commas as more visible separators), as per newest OP spec:

# for the `sed` code change the `2` to whatever column needs deleting.
paste -d, abc 123 123 | sed 's/[^,]*//2'

Output:

A,,1
B,,2
C,,3
D,,4

The same, with tab delimiters (less visually obvious):

paste abc 123 123 | sed 's/[^\t]*//2'
A       1
B       2
C       3
D       4


问:
Is PHP used for quick and easy website where other languages are used in more complex websites?
I just put this question in serverfault.com and I know that this question may be rejected in Stackoverflow.

But I thought programmers know better.

This stat shows that PHP is used by 75.2% of all the websites whose server-side programming language.

http://w3techs.com/technologies/overview/programming_language/all

And this page shows that PHP is the least used server-side language in ranked by usage on top websites

http://w3techs.com/technologies/topsite/programming_language

Q1. Does this mean PHP is used for quick and easy website where other languages are used in more complex websites?

Q2. Why PHP is ranked at the bottom? Or why big company tend to use other language than PHP?

Update: I know that facebook and other biggies uses PHP. But it does not tell why there are more other languages are used in top websites.

答: Facebook, Wikipedia (MediaWiki), Flickr, Digg are all running on PHP. And they are definitely not quick and easy websites ;) Each one of them has an huge user base and hosts and deals with huge amounts of data.</p>


问:
run pycharm and scapy with proper permissions
I want to develop with the scapy network package for python using PyCharm.  It requires root access to craft certain packets and go over certain ports.  I am currently running PyCharm as root but am wondering if there is a more secure way to do this.  I tried to set python with SUID which is probably worse but scapy still would not run.  Any suggestions would be appreciated.  </p>

答:
You're on the right track. Running PyCharm as root is messy. You want to get PyCharm to execute the python script that uses scapy with root permissions. Setting the setuid bit on the python program itself is close but not sufficient.

The best I've found is a set of instructions that say "whenever I run python, do it automatically using sudo".

The full details can be found here: rundebug-as-root-in-pycharm

Good luck!


Title: 31 days on the highcharts x-axis

Body:
I have a graph that i am plotting but i need to show 31 days of the month on the x-axis.

If you look at this  http://jsfiddle.net/codebreaker87/7hq6ueeb/2/show/

it only shows 31 days but the 31st is missing.  This is the code

http://jsfiddle.net/codebreaker87/7hq6ueeb/6/

How can i have the 31st day displayed?.

This is my code so far

Highcharts.chart('container', {
    chart: {
        type: 'line'
    },
    title: {
        text: 'SMS Volumes'
    },
    subtitle: {
        text: 'Source: Textify'
    },
    xAxis: {
        categories: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12','13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24','25','26','27','28','29','30','31']
    },
    yAxis: {
        title: {
            text: 'Volumes(1000)'
        }
    },
    plotOptions: {
        line: {
            dataLabels: {
                enabled: true
            },
            enableMouseTracking: false
        }
    },
    series: [{
        name: 'Inbox',
        data: [7.0, 6.9, 9.5, 14.5, 18.4, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6,7.0, 6.9, 9.5, 14.5, 18.4, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6,7.0, 6.9, 9.5, 14.5, 18.4, 21.5]
    }, {
        name: 'Outbox',
        data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8,3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8,3.9, 4.2, 5.7, 8.5, 11.9, 15.2]
    }]
});

Body:
You can set xAxis.max value as 30 (categories are indexed from 0).

xAxis: {
    categories: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12','13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24','25','26','27','28','29','30','31'],
    max: 30
},

Example:

http://jsfiddle.net/psnjdo4o/


问:
Exception (Unknown Property) 'yii\base\UnknownPropertyException' with message 'Getting unknown property: app\models\User::repeat_password'
I am new in Yii framework. This is my first post in stackoverflow for related framework. My problem is how to show non model input field in the view page. Please check my controler and view code.

controllers

```<code>public function actionRegister() {
    $model = new User();
    if ($model->load(Yii::$app->request->post()) && $model->validate()) {
        //Insert data code here...
        return $this->render('entry-confirm', ['model' => $model]);
    } else {
        return $this->render('entry', ['model' => $model]);
    }
}
</code>```

views(entry.php)

```<code><?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>
<?php $form = ActiveForm::begin(); ?>

<?= $form->field($model, 'username') ?>
<?= $form->field($model, 'email') ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<?= $form->field($model, 'repeat_password')->passwordInput() ?>

<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
</div>

<?php ActiveForm::end(); ?>
</code>```

models(User.php)

```<code>namespace app\models;

use Yii;
class User extends \yii\db\ActiveRecord {

    public static function tableName() {
        return 'user';
    }

    public function rules() {
        return [
            [['username', 'password', 'email'], 'required'],
            [['username', 'password', 'email'], 'string', 'max' => 128],
            ['email', 'email', 'message' => "The email isn't correct"],
            ['email', 'unique', 'message' => 'Email already exists!'],

            ['repeat_password', 'required'],
            [['repeat_password'], 'string', 'min'=>6, 'max'=>40],
            ['password', 'compare', 'compareAttribute'=>'repeat_password'],
        ];
    }

    public function attributeLabels() {
        return [
            'id' => 'ID',
            'username' => 'Username',
            'password' => 'Password',
            'email' => 'Email',
        ];
    }

}
</code>```

Output

I have 3 column in my user table. Columns are username, email and password but repeat_password is not in my table column. This is a non model input field. So I am getting above error message. Please help me and let me know how to fix it.

答:
You have to add new public property to User.php (model class file) as

```<code>class User extends ActiveRecord
{
    public $repeat_password;
</code>```

Please refer to this first

http://www.yiiframework.com/doc-2.0/guide-structure-models.html
http://www.yiiframework.com/doc-2.0/guide-start-forms.html

It will not take much time.

Don't forget to add its validation rules  in rules method of User.php
http://www.yiiframework.com/doc-2.0/guide-structure-models.html#safe-attributes

Body:
I am new in Yii framework. This is my first post in stackoverflow for related framework. My problem is how to show non model input field in the view page. Please check my controler and view code.

controllers

public function actionRegister() {
    $model = new User();
    if ($model->load(Yii::$app->request->post()) && $model->validate()) {
        //Insert data code here...
        return $this->render('entry-confirm', ['model' => $model]);
    } else {
        return $this->render('entry', ['model' => $model]);
    }
}

views(entry.php)

<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>
<?php $form = ActiveForm::begin(); ?>

<?= $form->field($model, 'username') ?>
<?= $form->field($model, 'email') ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<?= $form->field($model, 'repeat_password')->passwordInput() ?>

<?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>

<?php ActiveForm::end(); ?>

models(User.php)

namespace app\models;

use Yii;
class User extends \yii\db\ActiveRecord {

    public static function tableName() {
        return 'user';
    }

    public function rules() {
        return [
            [['username', 'password', 'email'], 'required'],
            [['username', 'password', 'email'], 'string', 'max' => 128],
            ['email', 'email', 'message' => "The email isn't correct"],
            ['email', 'unique', 'message' => 'Email already exists!'],

            ['repeat_password', 'required'],
            [['repeat_password'], 'string', 'min'=>6, 'max'=>40],
            ['password', 'compare', 'compareAttribute'=>'repeat_password'],
        ];
    }

    public function attributeLabels() {
        return [
            'id' => 'ID',
            'username' => 'Username',
            'password' => 'Password',
            'email' => 'Email',
        ];
    }

}

Output

I have 3 column in my user table. Columns are username, email and password but repeat_password is not in my table column. This is a non model input field. So I am getting above error message. Please help me and let me know how to fix it.

Body:
You have to add new public property to User.php (model class file) as

class User extends ActiveRecord
{
    public $repeat_password;

Please refer to this first

http://www.yiiframework.com/doc-2.0/guide-structure-models.html
http://www.yiiframework.com/doc-2.0/guide-start-forms.html

It will not take much time.

Don't forget to add its validation rules  in rules method of User.php
http://www.yiiframework.com/doc-2.0/guide-structure-models.html#safe-attributes


问:
google map from dismo::gmap() and ggplot2
I obtained a map with the function dismo::gmap() and want to plot it with ggplot2 because I want to add different feautures using geom_point and other ggplot functions. I prefer to use dismo::gmap instead of ggmap::get_map() to download the google map layer. This is because dismo::gmap(), unlike ggmap::get_map(), returns a raster layer from package raster including complete CRS information and therefore is should be possible to modify the projection of the layer.

```<code>> head(data_info$latitude, 20)
#[1] 49.11306 49.39333 48.78083 51.85000 53.57361 50.67806 52.69083 52.21389 53.46361 50.99917 53.99750 53.54528 53.61417 48.00556 48.01306 53.45000
#[17] 51.93667 54.53083 51.95500 54.29639
> head(data_info$longitude, 20)
#[1] 13.134722 12.323056 13.803889 12.177778 14.143611 13.175833 12.649444 13.454167 11.629722 10.906111 11.415556  8.426944  7.160000 11.123889 10.786111
#[16] 12.766667 11.987222 13.091389 10.967500 13.684167

   e = extent(-14 , 58 , 28 , 64)
mapImageData2 <- gmap(e, type = c("terrain"), lonlat = TRUE,
                      path = "&style=feature:all|element:labels|visibility:off&style=feature:administrative.country|element:geometry.stroke|visibility:off")

mapImageData2_proj <- projectExtent(mapImageData2, crs = "+proj=utm +zone=31 +datum=WGS84")

# plot the points on the map
ggplot(mapImageData2_proj, extent = "device") +
  geom_point(inherit.aes = FALSE, aes(x = data_info$longitude, y = data_info$latitude),
             data = gps, colour = "red", size = 1, pch = 20)
</code>```

After trying this, I get the following error:

Error: ggplot2 doesn't know how to deal with data of class
  RasterLayer

If I try this

```<code>plot(mapImageData2_proj)
</code>```

Error in .plotraster2(x, col = col, maxpixels = maxpixels, add = add,
  :    no values associated with this RasterLayer

答:
To directly plot a Raster* object in ggplot, you can use the library RasterVis as follows:

```<code>r <- raster(system.file("external/test.grd", package="raster"))
s <- stack(r, r*2)
names(s) <- c('meuse', 'meuse x 2')

library(ggplot2)

theme_set(theme_bw())
gplot(s) + geom_tile(aes(fill = value)) +
          facet_wrap(~ variable) +
          scale_fill_gradient(low = 'white', high = 'blue') +
          coord_equal()
</code>```

As you see, we use gplot and not ggplot.
This function is for Raster* objects as it allows to load only a part of the Raster* object in RAM. You can even choose the maximum number of pixels to load on the map with gplot(s, maxpixels=50000).

Indeed, I recommend not to transform your Raster as points, because, if your raster is huge, you will not be able to load it in the RAM...

Body:
I obtained a map with the function dismo::gmap() and want to plot it with ggplot2 because I want to add different feautures using geom_point and other ggplot functions. I prefer to use dismo::gmap instead of ggmap::get_map() to download the google map layer. This is because dismo::gmap(), unlike ggmap::get_map(), returns a raster layer from package raster including complete CRS information and therefore is should be possible to modify the projection of the layer.

> head(data_info$latitude, 20)
#[1] 49.11306 49.39333 48.78083 51.85000 53.57361 50.67806 52.69083 52.21389 53.46361 50.99917 53.99750 53.54528 53.61417 48.00556 48.01306 53.45000
#[17] 51.93667 54.53083 51.95500 54.29639
> head(data_info$longitude, 20)
#[1] 13.134722 12.323056 13.803889 12.177778 14.143611 13.175833 12.649444 13.454167 11.629722 10.906111 11.415556  8.426944  7.160000 11.123889 10.786111
#[16] 12.766667 11.987222 13.091389 10.967500 13.684167

   e = extent(-14 , 58 , 28 , 64)
mapImageData2 <- gmap(e, type = c("terrain"), lonlat = TRUE,
                      path = "&style=feature:all|element:labels|visibility:off&style=feature:administrative.country|element:geometry.stroke|visibility:off")

mapImageData2_proj <- projectExtent(mapImageData2, crs = "+proj=utm +zone=31 +datum=WGS84")

# plot the points on the map
ggplot(mapImageData2_proj, extent = "device") +
  geom_point(inherit.aes = FALSE, aes(x = data_info$longitude, y = data_info$latitude),
             data = gps, colour = "red", size = 1, pch = 20)

After trying this, I get the following error:

Error: ggplot2 doesn't know how to deal with data of class
  RasterLayer

If I try this

plot(mapImageData2_proj)

Error in .plotraster2(x, col = col, maxpixels = maxpixels, add = add,
  :    no values associated with this RasterLayer

Body:
To directly plot a Raster* object in ggplot, you can use the library RasterVis as follows:

r <- raster(system.file("external/test.grd", package="raster"))
s <- stack(r, r*2)
names(s) <- c('meuse', 'meuse x 2')

library(ggplot2)

theme_set(theme_bw())
gplot(s) + geom_tile(aes(fill = value)) +
          facet_wrap(~ variable) +
          scale_fill_gradient(low = 'white', high = 'blue') +
          coord_equal()

As you see, we use gplot and not ggplot.
This function is for Raster* objects as it allows to load only a part of the Raster* object in RAM. You can even choose the maximum number of pixels to load on the map with gplot(s, maxpixels=50000).

Indeed, I recommend not to transform your Raster as points, because, if your raster is huge, you will not be able to load it in the RAM...


问:
How do I split file removals into a separate changeset in git
I have a massive git changeset on a local branch. It contains file additions, file modifications and file deletions.

How do I split the file deletions into a separate subsequent changeset? (To make the additions and modifications easier to review.)

(In case it matters, this is git-cinnabar, not plain git.)

答:
You will need to use partial add

instead of ding a simple git add . add the -p flag and you will see the option s to split the big changes into a smaller one.

If the change is not enough for you you can split it even more with the e edit mode.


问:
Secure typescript model
I'm using angularjs2 + Meteor for development. Problen here is that I've write model in following style -

```<code>export interface temp {
  name: string;
  count: number;
}
</code>```

Problem here is that, I'm using typescript for file extention, so after compiling it converted into original text. So this model is not secure. User can able to insert any type of data, This is the main problem.

In meteor + reactJs app, I've used Meteor.collection which is gives security. But here how can we make model more secure in typescript ?

答:
TypeScript does not provide runtime type checking. You would have to write that yourself.

```<code>ensureArgIsTemp(arg: temp): arg is temp {
  if (!arg
      || Object.keys(arg).length !== 2
      || typeof arg.name !== "string"
      || typeof arg.count !== "number")
    throw new Error("The given object does not match the interface `temp`");

  return true;
}
</code>```

You might be able to automate some of this by using the experimental decorators. See http://blog.wolksoftware.com/decorators-metadata-reflection-in-typescript-from-novice-to-expert-part-4

Title: Secure typescript model

Body:
I'm using angularjs2 + Meteor for development. Problen here is that I've write model in following style -

export interface temp {
  name: string;
  count: number;
}

Problem here is that, I'm using typescript for file extention, so after compiling it converted into original text. So this model is not secure. User can able to insert any type of data, This is the main problem.

In meteor + reactJs app, I've used Meteor.collection which is gives security. But here how can we make model more secure in typescript ?

Body:
TypeScript does not provide runtime type checking. You would have to write that yourself.

ensureArgIsTemp(arg: temp): arg is temp {
  if (!arg
      || Object.keys(arg).length !== 2
      || typeof arg.name !== "string"
      || typeof arg.count !== "number")
    throw new Error("The given object does not match the interface `temp`");

  return true;
}

You might be able to automate some of this by using the experimental decorators. See http://blog.wolksoftware.com/decorators-metadata-reflection-in-typescript-from-novice-to-expert-part-4


问:
Postgres SQL for joining parent-child audit tables
We're using a "1 audit table for each monitored Table" design; However, in our case emp(PARENT) table has a child table emp_address which also needs to be monitored, so we have emp_audit and emp_addr_audit tables.

postgres audit SQL  : how to join PARENT and CHILD tables for reporting purposes.

```<code>/* Employee table */
create table emp (
 emp_id integer primary key,
 empnum  integer,
 empname varchar(50),
);

/* Address table */
create table emp_addr (
 addr_id integer primary key,
 emp_id integer, -- references table emp
 line1 varchar(30),
);

/* Audit table for emp table */
create table emp_audit (
 operation   character(1),
 emp_id integer,
 empnum  integer,
 empname varchar(50),
 updatetime timestamp,
 txid bigint
);

/* Audit table for emp_addr table */
create table emp_addr_audit (
 operation   character(1),
 addr_id integer,
 emp_id integer,
 line1 varchar(30),
 updatetime timestamp,
 txid bigint
);
</code>```

We're using hibernate(java) for persistence and hibernate updates only those tables whose columns were modified in the update operation. Given this, I might have multiple(say, 5) rows in the emp_addr_audit table for 1 row in emp_audit table. And vice-versa as well.

The report needs 1 row for each transaction(modification).
The report will have the following columns

empname, line1, operation(insert/delete/update), updatetime

Let's consider 2 scenarios to understand what's needed:

In the initial transaction only emp attributes are created. Then in a separate transaction, the corresponding row in emp_addr is created. So, now, we have 1 row in emp_audit table and 1 row in emp_addr_audit table. The report will have 2 rows (one each for each transaction).

Both emp and emp_addr attributes are created in a single transaction. This will ensure that there is 1 row in emp_audit and 1 row in emp_addr_audit. Now, the report will have ONLY 1 row (since both table rows were created in a single transaction).

Scenario :

Transaction #1 : I insert a row into both emp and emp_addr. This results in a row each in emp_audit and emp_addr_audit.(INSERT)

Transaction #2 : I update the above emp' attribute. This results in a UPDATE row in emp_audit.

Transaction #3 : I update the above emp_addr's attribute. This results in a UPDATE row in emp_addr_audit.

I tried the following SQL #1 and it returned 3 rows (as expected);

SQL #1

```<code>SELECT emp.*, addr.*
 FROM  emp_audit emp
 FULL OUTER JOIN emp_addr_audit addr USING(emp_id, txid);
</code>```

However, when I added a where clause to the SQL, it returns only 2 rows. The missing row was the result of  Transaction #3, where only emp_addr table row was UPDATED and emp table row was untouched.

SQL #2

```<code>SELECT emp.*, addr.*
 FROM  emp_audit emp
        FULL OUTER JOIN emp_addr_audit addr USING(emp_id, txid);
WHERE  emp.empnum = 20;
</code>```

What SQL will STILL be able to get me 3 rows for the 3 transactions so that I can still filter out based on empnum ?

答:
The FULL JOIN will create a table from both tables and fill in empty (non matching) rows with NULL values. When you select only the rows with emp.empnum = 20 it will of course not return the last row that has NULL in emp.empnum.

Maybe you can JOIN only on emp_id and then do some GROUP BY txid. But this wont be so easy. You might have to make always an update on both tables. Or use some more advanced logic (something like: select all transaction of one emp_id where one side is null until the next full row and fill the missing parts with the last full row).

Body:
We're using a "1 audit table for each monitored Table" design; However, in our case emp(PARENT) table has a child table emp_address which also needs to be monitored, so we have emp_audit and emp_addr_audit tables.

postgres audit SQL  : how to join PARENT and CHILD tables for reporting purposes.

/* Employee table */
create table emp (
 emp_id integer primary key,
 empnum  integer,
 empname varchar(50),
);

/* Address table */
create table emp_addr (
 addr_id integer primary key,
 emp_id integer, -- references table emp
 line1 varchar(30),
);

/* Audit table for emp table */
create table emp_audit (
 operation   character(1),
 emp_id integer,
 empnum  integer,
 empname varchar(50),
 updatetime timestamp,
 txid bigint
);

/* Audit table for emp_addr table */
create table emp_addr_audit (
 operation   character(1),
 addr_id integer,
 emp_id integer,
 line1 varchar(30),
 updatetime timestamp,
 txid bigint
);

We're using hibernate(java) for persistence and hibernate updates only those tables whose columns were modified in the update operation. Given this, I might have multiple(say, 5) rows in the emp_addr_audit table for 1 row in emp_audit table. And vice-versa as well.

The report needs 1 row for each transaction(modification).
The report will have the following columns

empname, line1, operation(insert/delete/update), updatetime

Let's consider 2 scenarios to understand what's needed:

In the initial transaction only emp attributes are created. Then in a separate transaction, the corresponding row in emp_addr is created. So, now, we have 1 row in emp_audit table and 1 row in emp_addr_audit table. The report will have 2 rows (one each for each transaction).

Both emp and emp_addr attributes are created in a single transaction. This will ensure that there is 1 row in emp_audit and 1 row in emp_addr_audit. Now, the report will have ONLY 1 row (since both table rows were created in a single transaction).

Scenario :

Transaction #1 : I insert a row into both emp and emp_addr. This results in a row each in emp_audit and emp_addr_audit.(INSERT)

Transaction #2 : I update the above emp' attribute. This results in a UPDATE row in emp_audit.

Transaction #3 : I update the above emp_addr's attribute. This results in a UPDATE row in emp_addr_audit.

I tried the following SQL #1 and it returned 3 rows (as expected);

SQL #1

SELECT emp.*, addr.*
 FROM  emp_audit emp
 FULL OUTER JOIN emp_addr_audit addr USING(emp_id, txid);

However, when I added a where clause to the SQL, it returns only 2 rows. The missing row was the result of  Transaction #3, where only emp_addr table row was UPDATED and emp table row was untouched.

SQL #2

SELECT emp.*, addr.*
 FROM  emp_audit emp
        FULL OUTER JOIN emp_addr_audit addr USING(emp_id, txid);
WHERE  emp.empnum = 20;

What SQL will STILL be able to get me 3 rows for the 3 transactions so that I can still filter out based on empnum ?


答:
The problem is related  to the fact you are using a

```<code>  <?= $form->field($model, 'repeat_password') ?>
</code>```

that not exist for the User Model ..

you should create a a FormModel (eg: UserInput with also this repeat_password field  )  for manage the correct input and then in action mange properly the assigment from your formModel/UserInput model and User model   for store

for build a proper form model class you can take a looka at this  guide  http://www.yiiframework.com/doc-2.0/guide-start-forms.html

Title: Exception (Unknown Property) 'yii\base\UnknownPropertyException' with message 'Getting unknown property: app\models\User::repeat_password'

Body:
The problem is related  to the fact you are using a

  <?= $form->field($model, 'repeat_password') ?>

that not exist for the User Model ..

you should create a a FormModel (eg: UserInput with also this repeat_password field  )  for manage the correct input and then in action mange properly the assigment from your formModel/UserInput model and User model   for store

for build a proper form model class you can take a looka at this  guide  http://www.yiiframework.com/doc-2.0/guide-start-forms.html


问:
Alexa skill 2 intents and open slot
Is it possible that Alexa reacts right when I have in a sample utterances something like this, opened slots?

```<code>MyNameIsIntent {firstname}
ProjektIntent {projekt}
</code>```

Right now she always goes back to  MyNameIsIntent even if she ask a question for a ProjektIntent

The bad conversation:

```<code>Alexa: Welcome, what is your name?
Me: Frank
Alexa Hi Frank, Tell me what project is interesting for you?
Me: Teleshoping
Alexa: Hi Teleshoping, Tell me what project is interesting for you?
</code>```

Im totally new to Alexa, could you give me please a tip if it is possible that Alexa answers the right question? I tried to do it with a session atributes but it doesn't work

答:
You can use States do react differently on the same intents depending on the state of your application.

See https://github.com/alexa/alexa-skills-kit-sdk-for-nodejs#making-skill-state-management-simpler for the official documentation.

You create a dictionary of StateHandlers like this (in Node.js 4.3):

```<code>var askNameStateHandlers = Alexa.CreateStateHandler("askNameState",
    {
         "MyIntent": function () { /* ... */ }
        // more handlers ...
    });
</code>```

Then you register your handlers like this, assuming you have a dictionary of handlers without states defaultHandlers and two with handlers for a specific state askNameStateHandlers and askProjectStateHandlers:

```<code>exports.handler = function(event, context, callback) {
    var alexa = Alexa.handler(event, context);
    alexa.registerHandlers(defaultHandlers, askNameStateHandlers, askProjectStateHandlers);
    alexa.execute();
};
</code>```

To change the state of your application, simply assign it like this inside a handler function:

```<code>this.handler.state = "askNameState";
</code>```

The alexa-sdk will then take care of calling the right handler depending on your application state.

There is also a full example implementation at https://github.com/alexa/skill-sample-nodejs-highlowgame

Note that this way, you will only have one intent MyIntent who accepts the answers to both questions, deciding which of your functions should handle the result based on the application state only.

Title: Alexa skill 2 intents and open slot

Body:
Is it possible that Alexa reacts right when I have in a sample utterances something like this, opened slots?

MyNameIsIntent {firstname}
ProjektIntent {projekt}

Right now she always goes back to  MyNameIsIntent even if she ask a question for a ProjektIntent

The bad conversation:

Alexa: Welcome, what is your name?
Me: Frank
Alexa Hi Frank, Tell me what project is interesting for you?
Me: Teleshoping
Alexa: Hi Teleshoping, Tell me what project is interesting for you?

Im totally new to Alexa, could you give me please a tip if it is possible that Alexa answers the right question? I tried to do it with a session atributes but it doesn't work

Body:
You can use States do react differently on the same intents depending on the state of your application.

See https://github.com/alexa/alexa-skills-kit-sdk-for-nodejs#making-skill-state-management-simpler for the official documentation.

You create a dictionary of StateHandlers like this (in Node.js 4.3):

var askNameStateHandlers = Alexa.CreateStateHandler("askNameState",
    {
         "MyIntent": function () { /* ... */ }
        // more handlers ...
    });

Then you register your handlers like this, assuming you have a dictionary of handlers without states defaultHandlers and two with handlers for a specific state askNameStateHandlers and askProjectStateHandlers:

exports.handler = function(event, context, callback) {
    var alexa = Alexa.handler(event, context);
    alexa.registerHandlers(defaultHandlers, askNameStateHandlers, askProjectStateHandlers);
    alexa.execute();
};

To change the state of your application, simply assign it like this inside a handler function:

this.handler.state = "askNameState";

The alexa-sdk will then take care of calling the right handler depending on your application state.

There is also a full example implementation at https://github.com/alexa/skill-sample-nodejs-highlowgame

Note that this way, you will only have one intent MyIntent who accepts the answers to both questions, deciding which of your functions should handle the result based on the application state only.


问:
PHP Function to generate an infinite unique indentifier
I'm making a new project in Zend 3 that requires me to have a unique ID or HASH which I can use in several places later.

I looked at many examples on Google, and could not find a function that can satisfy my requirements because this needs to be 99% unique all the time, and it needs to be able to generate hundreds, millions of "hashes" unique all the time.

The following function caught my attention:

```<code>  function uniqidReal($lenght = 13) {
        // uniqid gives 13 chars, but you could adjust it to your needs.
        if (function_exists("random_bytes")) {
            $bytes = random_bytes(ceil($lenght / 2));
        } elseif (function_exists("openssl_random_pseudo_bytes")) {
            $bytes = openssl_random_pseudo_bytes(ceil($lenght / 2));
        } else {
            throw new Exception("no cryptographically secure random function available");
        }
        return substr(bin2hex($bytes), 0, $lenght);
    }
</code>```

A simple test:

```<code>echo "```";

for($i = 0; $i < 100; $i++)
{
    echo $this->uniqidReal(25) .PHP_EOL ;
}
```

<p>The result:</p>

```a8ba1942ad99d09f496d3d564
5b24746d09cada4b2dc9816bd
c6630c35bc9b4ed0907c803e0
48e04958b633e8a5ead137bb1
643a4ce1bcbca66cea397e85e
d2cd4c6f8dc7054dd0636075f
d9c78bae38720b7e0cc6361f2
54e5f852862adad2ad7bc3349
16c4e42e4f63f62bf9653f96e
c63d64af261e601e4b124e38f
29a3efa07a4d77406349e3020
107d78fdfca13571c152441f2
591b25ebdb695c8259ccc7fe9
105c4f2cc5266bb82222480ba
84e9ad8fd76226f86c89c1ac1
39381d31f494d320abc538a8e
7f8141db50a41b15a85599548
7b15055f6d9fb1228b7438d2a
659182c7bcd5b050befd3fc4c
06f70d134a3839677caa0d246
600b15c9dc53ef7a4551b8a90
a9c8af631c5361e8e1e1b8d9d
4b4b0aca3bbf15d35dd7d1050
f77024a07ee0dcee358dc1f5e
408c007b9d771718263b536e1
2de08e01684805a189224db75
c3838c034ae22d21f27e5d040
b15e9b0bab6ef6a56225a5983
251809396beb9d24b384f5fe8
cec6d262803311152db31b723
95d271ffdfe9df5861eefbaa4
7c11f3401530790b9ef510e55
e363390e2829097e7762bddc4
7ef34c69d9b8e38d72c6db29f
309a84490a7e387aaff1817ca
c214af2927c683954894365df
9f70859880b7ffa4b28265dbb
608e2f2f9e38025d92a1a4f03
c457a54d2da30a4a517edf14c
8670acbded737b1d2febdd954
99899b74b6469e366122b658c
3066408f5b4e86ef84bdb3fb9
010715f4955f66da3402bfa7b
fa01675690435b914631b46e1
2c5e234c5868799f31a6c983c
8345da31809ab2d9714a01d05
7b4e0e507dd0a8b6d7170a265
5aa71aded9fe7afa9a93a98c5
3714fb9f061398d4bb6af909d
165dd0af233cce64cefec12ed
849dda54070b868b50f356068
fe5f6e408eda6e9d429fa34ed
cd13f8da95c5b92b16d9d2781
65d0f69b41ea996ae2f8783a5
5742caf7a922eb3aaa270df30
f381ac4b84f3315e9163f169e
8c2afa1ab32b6fe402bf97ba3
a9f431efe6fc98aa64dbecbc2
8f0746e4e9529326d087f828b
bfc3cbea4d7f5c4495a14fc49
e4bf2d1468c6482570612360e
f1c7238766acdb7f199049487
60ae8a1ffd6784f7bbbc7b437
30afd67f207de6e893f7c9f42
dfa151daccb0e8d64d100f719
07be6a7d4aab21ccd9942401b
73ca1a54fcc40f7a46f46afbd
94ed2888fb93cb65d819d9d52
b7317773c6a15aa0bdf25fa01
edbb7f20f7523d9d941f3ebce
99a3c204b9f2036d3c38342bb
a0585424b8ab2ffcabee299d5
64e669fe2490522451cf10f85
18b8be34d4c560cda5280a103
9524d1f024b3c9864a3fccf75
0e7e94e7974894c98442241bc
4a17cc5e3d2baabaa338f592e
b070eaf38f390516f5cf61aa7
cc7832ea327b7426d8d2b8c2b
0df0a1d4833ebbb5d463c56bf
1bb610a8bb4e241996c9c756a
34ac2fdeb4b88fe6321a1d9c3
f0b20f8e79090dcb65195524c
307252efdd2b833228e0c301f
3908e63b405501782e629ac0b
29e66717adf14fb30c626103d
c8abd48af5f9332b322dffad0
80cd4e162bc7e8fb3a756b48c
825c00cec2294061eb328dd97
106205a2e24609652d149bc17
f1f896657fbc6f6287e7dee20
0fbd16ade658e24d69f76a225
4ab3b5eeeda86fa81afba796a
11d34f3d2ffb61d55da560ddb
013d6151bad187906fcc579a4
4509279a28f34bcf5327dd4c0
3c0eb47b3f9dc5a2f794bb9ad
1e6506906f23542c889330836
e7b1c5012390f3c7c48def9f3
d86caa695cb5fa1e0a2ead4cc
```

But I cannot confirm that this does guarantee me a 99% success rate for my production environment.

If someone can advise me, or provide me an example I would much appreciate it!

答:
Function random_bytes generates cryptographically secure random bytes

For openssl_random_pseudo_bytes add the crypto_strong paramdeter to ensure the algorithm used is cryptographically strong.

Since your requirement is only 99% unique cryptographically secure random bytes will meet your requirement.

Body:
I'm making a new project in Zend 3 that requires me to have a unique ID or HASH which I can use in several places later.

I looked at many examples on Google, and could not find a function that can satisfy my requirements because this needs to be 99% unique all the time, and it needs to be able to generate hundreds, millions of "hashes" unique all the time.

The following function caught my attention:

  function uniqidReal($lenght = 13) {
        // uniqid gives 13 chars, but you could adjust it to your needs.
        if (function_exists("random_bytes")) {
            $bytes = random_bytes(ceil($lenght / 2));
        } elseif (function_exists("openssl_random_pseudo_bytes")) {
            $bytes = openssl_random_pseudo_bytes(ceil($lenght / 2));
        } else {
            throw new Exception("no cryptographically secure random function available");
        }
        return substr(bin2hex($bytes), 0, $lenght);
    }

A simple test:

echo "
";

for($i = 0; $i < 100; $i++)
{
    echo $this->uniqidReal(25) .PHP_EOL ;
}

The result:

a8ba1942ad99d09f496d3d564
5b24746d09cada4b2dc9816bd
c6630c35bc9b4ed0907c803e0
48e04958b633e8a5ead137bb1
643a4ce1bcbca66cea397e85e
d2cd4c6f8dc7054dd0636075f
d9c78bae38720b7e0cc6361f2
54e5f852862adad2ad7bc3349
16c4e42e4f63f62bf9653f96e
c63d64af261e601e4b124e38f
29a3efa07a4d77406349e3020
107d78fdfca13571c152441f2
591b25ebdb695c8259ccc7fe9
105c4f2cc5266bb82222480ba
84e9ad8fd76226f86c89c1ac1
39381d31f494d320abc538a8e
7f8141db50a41b15a85599548
7b15055f6d9fb1228b7438d2a
659182c7bcd5b050befd3fc4c
06f70d134a3839677caa0d246
600b15c9dc53ef7a4551b8a90
a9c8af631c5361e8e1e1b8d9d
4b4b0aca3bbf15d35dd7d1050
f77024a07ee0dcee358dc1f5e
408c007b9d771718263b536e1
2de08e01684805a189224db75
c3838c034ae22d21f27e5d040
b15e9b0bab6ef6a56225a5983
251809396beb9d24b384f5fe8
cec6d262803311152db31b723
95d271ffdfe9df5861eefbaa4
7c11f3401530790b9ef510e55
e363390e2829097e7762bddc4
7ef34c69d9b8e38d72c6db29f
309a84490a7e387aaff1817ca
c214af2927c683954894365df
9f70859880b7ffa4b28265dbb
608e2f2f9e38025d92a1a4f03
c457a54d2da30a4a517edf14c
8670acbded737b1d2febdd954
99899b74b6469e366122b658c
3066408f5b4e86ef84bdb3fb9
010715f4955f66da3402bfa7b
fa01675690435b914631b46e1
2c5e234c5868799f31a6c983c
8345da31809ab2d9714a01d05
7b4e0e507dd0a8b6d7170a265
5aa71aded9fe7afa9a93a98c5
3714fb9f061398d4bb6af909d
165dd0af233cce64cefec12ed
849dda54070b868b50f356068
fe5f6e408eda6e9d429fa34ed
cd13f8da95c5b92b16d9d2781
65d0f69b41ea996ae2f8783a5
5742caf7a922eb3aaa270df30
f381ac4b84f3315e9163f169e
8c2afa1ab32b6fe402bf97ba3
a9f431efe6fc98aa64dbecbc2
8f0746e4e9529326d087f828b
bfc3cbea4d7f5c4495a14fc49
e4bf2d1468c6482570612360e
f1c7238766acdb7f199049487
60ae8a1ffd6784f7bbbc7b437
30afd67f207de6e893f7c9f42
dfa151daccb0e8d64d100f719
07be6a7d4aab21ccd9942401b
73ca1a54fcc40f7a46f46afbd
94ed2888fb93cb65d819d9d52
b7317773c6a15aa0bdf25fa01
edbb7f20f7523d9d941f3ebce
99a3c204b9f2036d3c38342bb
a0585424b8ab2ffcabee299d5
64e669fe2490522451cf10f85
18b8be34d4c560cda5280a103
9524d1f024b3c9864a3fccf75
0e7e94e7974894c98442241bc
4a17cc5e3d2baabaa338f592e
b070eaf38f390516f5cf61aa7
cc7832ea327b7426d8d2b8c2b
0df0a1d4833ebbb5d463c56bf
1bb610a8bb4e241996c9c756a
34ac2fdeb4b88fe6321a1d9c3
f0b20f8e79090dcb65195524c
307252efdd2b833228e0c301f
3908e63b405501782e629ac0b
29e66717adf14fb30c626103d
c8abd48af5f9332b322dffad0
80cd4e162bc7e8fb3a756b48c
825c00cec2294061eb328dd97
106205a2e24609652d149bc17
f1f896657fbc6f6287e7dee20
0fbd16ade658e24d69f76a225
4ab3b5eeeda86fa81afba796a
11d34f3d2ffb61d55da560ddb
013d6151bad187906fcc579a4
4509279a28f34bcf5327dd4c0
3c0eb47b3f9dc5a2f794bb9ad
1e6506906f23542c889330836
e7b1c5012390f3c7c48def9f3
d86caa695cb5fa1e0a2ead4cc

But I cannot confirm that this does guarantee me a 99% success rate for my production environment.

If someone can advise me, or provide me an example I would much appreciate it!


问:
How to get return value from startcmd.sh OdiStarScen
I am triggering scenarios by calling startcmd.sh OdiStartscen it executes the scenario, but I would like to know if this execution failed or successed without checking the ODI.

Is there a way to elevate return code from OdiStartScen to startcmd.sh

Thanks,

答:
Isn't it as simple as in case of any other OS command?
Once successful any OS should internally return success code (0 in linux) back to the parent process. Otherwise it would be error code (non-zero).

That means you simply need to handle 'success' and 'failure' paths in your ODI package (green and red lines). Simply put some nonsense in the startcmd.sh OdiStartScen call for some quick test so see if it behaves as expected in case of failures. Alternatively you may use same step for both paths (red and green) and test using getPrevStep() function for errors (cf. STATUS property).

Two things worth mentioning:

This makes only sense for synchronous calls (so it waits for your Scenario to finish).

Why don't you use ODIStartScen() as an ODI Tool type of package/procedure step instead? Seems lot more elegant. Same answer applies.


问:
Initializing data in datatable from angular js controller
I'm facing data initialization issue in Jquery datatable from Angular controller. Please find the approach below.
I've one angular controller as:

```<code>app.controller('CompanyController', ['$scope', 'CompanyService',function($scope, companyService) {
var self = this;
self.companies=[];

self.fetchAllCompanies = function() {
  companyService.fetchAllCompanies().then(function(d) {
       self.companies = d;
       },
    function(errResponse) {
        console.error('Error while fetching Compnies');
    });
 };
//self.fetchAllCompanies();
$scope.dataTableOpt = {
      "aLengthMenu": [[10, 50, 100,-1], [10, 50, 100,'All']],
      "searching": true
};
}]);
</code>```

HTML Code is:

```<code><div class="row" ng-controller="CompanyController as ctrl">
<table id="company-details" class="table table-bordered table-striped" ui-jq="dataTable" ui-options="dataTableOpt">
<thead>
<tr>
  <th>Company Name</th>
  <th class="text-center">Created Date</th>
  <th class="text-center">Modified Date</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="company in ctrl.companies">
  <td>{{company.companyName}}</td>
  <td class="text-center">{{company.createdDate | date:'MMM dd, yyyy'}}</td>
  <td class="text-center">{{company.modifiedDate | date:'MMM dd, yyyy'}}</td>
</tr>
</tbody>
<tfoot>
<tr>
  <th>Company Name</th>
  <th class="text-center">Created Date</th>
  <th class="text-center">Modified Date</th>
</tr>
</tfoot>
</table></div>
</code>```

I'm using angular datatable and this is working as expected but there is one issue:
if I uncomment line //self.fetchAllCompanies();  from my controller then data table load data but while using some search of sort data is gone.
 But if I assign a hardcoded json to self.companies=[]; in my controller then data table work all the way, now problem is that I'm initializing data by calling method self.fetchAllCompanies() it loads the data but other functionalities initialization gone.

Please help.
Thanks
Jitender

答: I see jquery ui in your page. try to understand the behavior of jqui and deal with this code in a directive.</p>

Body:
I'm facing data initialization issue in Jquery datatable from Angular controller. Please find the approach below.
I've one angular controller as:

app.controller('CompanyController', ['$scope', 'CompanyService',function($scope, companyService) {
var self = this;
self.companies=[];

self.fetchAllCompanies = function() {
  companyService.fetchAllCompanies().then(function(d) {
       self.companies = d;
       },
    function(errResponse) {
        console.error('Error while fetching Compnies');
    });
 };
//self.fetchAllCompanies();
$scope.dataTableOpt = {
      "aLengthMenu": [[10, 50, 100,-1], [10, 50, 100,'All']],
      "searching": true
};
}]);

HTML Code is:

  Company Name
  Created Date
  Modified Date

  {{company.companyName}}
  {{company.createdDate | date:'MMM dd, yyyy'}}
  {{company.modifiedDate | date:'MMM dd, yyyy'}}

  Company Name
  Created Date
  Modified Date

I'm using angular datatable and this is working as expected but there is one issue:
if I uncomment line //self.fetchAllCompanies();  from my controller then data table load data but while using some search of sort data is gone.
 But if I assign a hardcoded json to self.companies=[]; in my controller then data table work all the way, now problem is that I'm initializing data by calling method self.fetchAllCompanies() it loads the data but other functionalities initialization gone.

Please help.
Thanks
Jitender