问:
Set the marking on a viz through IPython
Similar to this question but not quite the same: Spotfire: "limit data using markings" by python script

I have a script that currently looks like this:

```<code>from Spotfire.Dxp import Data
from Spotfire.Dxp.Application.Visuals import *

#Remove the current Marking Filter
for filtering in vis.As[VisualContent]().Data.Filterings:
    vis.As[VisualContent]().Data.Filterings.Remove(filtering)

#Set the new Marking Filter
vis.As[VisualContent]().Data.Filterings.Add(Document.Data.Markings["Marking (4)"])

#Set the new Marking
#Need code here
</code>```

I need to set a new marking for the visualization so that I can then use that for another visualization. Specifically, I need to set this box:

UPDATE
I am able to set markings using this piece of code:

```<code>vc = vis.As[VisualContent]()
marking = vc.Data.MarkingReference
marking.SetSelection(marking.GetSelection(dataTable),dataTable)
</code>```

This does mark the records I want, but because it does not change the setting in the Marking box, it will not let me drill down further (filtered to the same marking it is setting).

答:
This script ultimately worked for me:

```<code>from Spotfire.Dxp import Data
from Spotfire.Dxp.Application.Visuals import *

if Document.Properties['KPIHierLevel'] == '<[SBA_NAME] NEST [MARKET_NAME]>':
    Document.Properties['KPIHierLevel'] = '<[MARKET_NAME] NEST [BRAND]>'
    for filtering in vis.As[VisualContent]().Data.Filterings:
        vis.As[VisualContent]().Data.Filterings.Remove(filtering)
    vis.As[VisualContent]().Data.Filterings.Add(Document.ActiveMarkingSelectionReference)
    vis.As[VisualContent]().Data.MarkingReference = (Document.Data.Markings["Marking (7)"])
elif Document.Properties['KPIHierLevel'] == '<[MARKET_NAME] NEST [BRAND]>':
    Document.Properties['KPIHierLevel'] = '<[BRAND] NEST [PRODUCT]>'
    for filtering in vis.As[VisualContent]().Data.Filterings:
        vis.As[VisualContent]().Data.Filterings.Remove(filtering)
    vis.As[VisualContent]().Data.Filterings.Add(Document.ActiveMarkingSelectionReference)
    vis.As[VisualContent]().Data.MarkingReference = (Document.ActiveMarkingSelectionReference)
</code>```

I also created a Reset script that is similar to this but sets the marking back to something other than Marking (7).

Body:
Similar to this question but not quite the same: Spotfire: "limit data using markings" by python script

I have a script that currently looks like this:

from Spotfire.Dxp import Data
from Spotfire.Dxp.Application.Visuals import *

#Remove the current Marking Filter
for filtering in vis.As[VisualContent]().Data.Filterings:
    vis.As[VisualContent]().Data.Filterings.Remove(filtering)

#Set the new Marking Filter
vis.As[VisualContent]().Data.Filterings.Add(Document.Data.Markings["Marking (4)"])

#Set the new Marking
#Need code here

I need to set a new marking for the visualization so that I can then use that for another visualization. Specifically, I need to set this box:

UPDATE
I am able to set markings using this piece of code:

vc = vis.As[VisualContent]()
marking = vc.Data.MarkingReference
marking.SetSelection(marking.GetSelection(dataTable),dataTable)

This does mark the records I want, but because it does not change the setting in the Marking box, it will not let me drill down further (filtered to the same marking it is setting).

Body:
This script ultimately worked for me:

from Spotfire.Dxp import Data
from Spotfire.Dxp.Application.Visuals import *

if Document.Properties['KPIHierLevel'] == '<[SBA_NAME] NEST [MARKET_NAME]>':
    Document.Properties['KPIHierLevel'] = '<[MARKET_NAME] NEST [BRAND]>'
    for filtering in vis.As[VisualContent]().Data.Filterings:
        vis.As[VisualContent]().Data.Filterings.Remove(filtering)
    vis.As[VisualContent]().Data.Filterings.Add(Document.ActiveMarkingSelectionReference)
    vis.As[VisualContent]().Data.MarkingReference = (Document.Data.Markings["Marking (7)"])
elif Document.Properties['KPIHierLevel'] == '<[MARKET_NAME] NEST [BRAND]>':
    Document.Properties['KPIHierLevel'] = '<[BRAND] NEST [PRODUCT]>'
    for filtering in vis.As[VisualContent]().Data.Filterings:
        vis.As[VisualContent]().Data.Filterings.Remove(filtering)
    vis.As[VisualContent]().Data.Filterings.Add(Document.ActiveMarkingSelectionReference)
    vis.As[VisualContent]().Data.MarkingReference = (Document.ActiveMarkingSelectionReference)

I also created a Reset script that is similar to this but sets the marking back to something other than Marking (7).


来源: stackexchange

问:
AIR Native Process works on Mac, but not Windows
I'm building an AIR application with Flash CC, so that I can use Native Processes. Before I even got to integrating it into my full project, I created a small test project to see if it would work. I tried it in Windows and it didn't work. I switched over to Mac and got it to work there, though.

The Native Process is triggered by a key press. The file is published as a Windows installer, not an Air package. I have made sure to include extendedDesktop in the xml file. I have double checked the file paths. Are there any other reasons this wouldn't work?

```<code>package  {

    import flash.display.MovieClip;
    import flash.filesystem.File;
    import flash.events.KeyboardEvent;
    import flash.desktop.NativeProcess;
    import flash.desktop.NativeProcessStartupInfo;

    public class Main extends MovieClip {

        var exe:File = new File("C:\Windows\System32\notepad.exe");
        var nativeProcess:NativeProcess = new NativeProcess();
        var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
        var args:Vector.<String> = new Vector.<String>();

        public function startProcess(event:KeyboardEvent):void
        {
            if (event.keyCode == 65) {
                nativeProcessStartupInfo.executable = exe;
                args.push("C:/Users/Tristan/Documents/TVCR/airTestFile.rtf");
                nativeProcessStartupInfo.arguments = args;
                nativeProcess.start(nativeProcessStartupInfo);
            }
        }
    }
}
</code>```

答:
It seems that the file path I was using wasn't in the correct format.

```<code>C:\Windows\System32\notepad.exe
</code>```

should be

```<code>C:\\Windows\\System32\\notepad.exe
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm building an AIR application with Flash CC, so that I can use Native Processes. Before I even got to integrating it into my full project, I created a small test project to see if it would work. I tried it in Windows and it didn't work. I switched over to Mac and got it to work there, though.

The Native Process is triggered by a key press. The file is published as a Windows installer, not an Air package. I have made sure to include extendedDesktop in the xml file. I have double checked the file paths. Are there any other reasons this wouldn't work?

package  {

    import flash.display.MovieClip;
    import flash.filesystem.File;
    import flash.events.KeyboardEvent;
    import flash.desktop.NativeProcess;
    import flash.desktop.NativeProcessStartupInfo;

    public class Main extends MovieClip {

        var exe:File = new File("C:\Windows\System32\notepad.exe");
        var nativeProcess:NativeProcess = new NativeProcess();
        var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
        var args:Vector.<String> = new Vector.<String>();

        public function startProcess(event:KeyboardEvent):void
        {
            if (event.keyCode == 65) {
                nativeProcessStartupInfo.executable = exe;
                args.push("C:/Users/Tristan/Documents/TVCR/airTestFile.rtf");
                nativeProcessStartupInfo.arguments = args;
                nativeProcess.start(nativeProcessStartupInfo);
            }
        }
    }
}

Body:
It seems that the file path I was using wasn't in the correct format.

C:\Windows\System32\notepad.exe

should be

C:\\Windows\\System32\\notepad.exe


问:
sha256 string starting with custom like aaaaaa
i want to generate a SHA256 string but I want it first 15 characters are same like aaaaaaaa....

and how can I do that?

```<code>FOUND: 9481011 aaaaaa4da30538b171d69304aba8a3a3d8bf4b83761c1fa30b8e40dd2f97b899
</code>```

I need the exact string encrypted and decrypted so I need two strings

I need it created so when checked by other side it must be validated

```<code>don't down vote if you cant able to solve this
</code>```

答:
The way to get the SHA256 string is as follows:

```<code>var crypto = require('crypto');
function sha256(data) {
    return crypto.createHash("sha256").update(data).digest("base64");
}
</code>```

To get the first 15 characters to be repeated as, you can either overwrite the first 15 characters or append 15 as, as follows:

Overwrite:

```<code>var str = sha256("hello");
for (var i = 0; i < 15; i++) {
    str = str.substr(0,index) + 'a' + str.substr(index+1);
}
</code>```

Append:

```<code>var a = 'aaaaaaaaaaaaaaa';
var str = a + sha256("hello");
</code>```

Body:
i want to generate a SHA256 string but I want it first 15 characters are same like aaaaaaaa....

and how can I do that?

FOUND: 9481011 aaaaaa4da30538b171d69304aba8a3a3d8bf4b83761c1fa30b8e40dd2f97b899

I need the exact string encrypted and decrypted so I need two strings

I need it created so when checked by other side it must be validated

don't down vote if you cant able to solve this

Body:
The way to get the SHA256 string is as follows:

var crypto = require('crypto');
function sha256(data) {
    return crypto.createHash("sha256").update(data).digest("base64");
}

To get the first 15 characters to be repeated as, you can either overwrite the first 15 characters or append 15 as, as follows:

Overwrite:

var str = sha256("hello");
for (var i = 0; i < 15; i++) {
    str = str.substr(0,index) + 'a' + str.substr(index+1);
}

Append:

var a = 'aaaaaaaaaaaaaaa';
var str = a + sha256("hello");


问:
Pip can't uninstall this package
I have a problem with pip. I want to run a program that needs Box2d. But when I run the program I get an error like this:

```<code>...(removed)...
  File "/usr/local/lib/python2.7/dist-packages/Box2D/__init__.py", line 20, in <module>
    from .Box2D import *
  File "/usr/local/lib/python2.7/dist-packages/Box2D/Box2D.py", line 434, in <module>
    RAND_LIMIT = _Box2D.RAND_LIMIT
AttributeError: 'module' object has no attribute 'RAND_LIMIT'
</code>```

I decided to uninstall Box2d and install it again. I tried the uninstall command in pip but it wasn't able to uninstall it. (pip says that the packages has been removed but the Box2d forlder is still in the dist-packages folder). Shouldn't pip remove it with that command?

Any solution to remove Box2d or fix the error?

答:
Just delete the folder in dist-packages. Then make sure there are no other references to the package in sys.path folders:

#in 2.7.13 in `-c' mode, `print' adds `\n' even with `,' at the end
python -c 'import sys; sys.stdout.write("\0".join(sys.path))' | xargs -0 -I ARG find ARG -type f -print0 | xargs -0 grep -iHe 'box2d'
```

(Note: this doesn't search .zips, packed .eggs and such.)

Title: Pip can't uninstall this package

Body:
I have a problem with pip. I want to run a program that needs Box2d. But when I run the program I get an error like this:

...(removed)...
  File "/usr/local/lib/python2.7/dist-packages/Box2D/__init__.py", line 20, in <module>
    from .Box2D import *
  File "/usr/local/lib/python2.7/dist-packages/Box2D/Box2D.py", line 434, in <module>
    RAND_LIMIT = _Box2D.RAND_LIMIT
AttributeError: 'module' object has no attribute 'RAND_LIMIT'

I decided to uninstall Box2d and install it again. I tried the uninstall command in pip but it wasn't able to uninstall it. (pip says that the packages has been removed but the Box2d forlder is still in the dist-packages folder). Shouldn't pip remove it with that command?

Any solution to remove Box2d or fix the error?

Body:
Just delete the folder in dist-packages. Then make sure there are no other references to the package in sys.path folders:

#in 2.7.13 in `-c' mode, `print' adds `\n' even with `,' at the end
python -c 'import sys; sys.stdout.write("\0".join(sys.path))' | xargs -0 -I ARG find ARG -type f -print0 | xargs -0 grep -iHe 'box2d'

(Note: this doesn't search .zips, packed .eggs and such.)


问:
To check if internet connection is available or not despite of WIFI turned on?
I am trying to build an app ,where in I first need to check if internet connection is available or not,even if it is connected to the WIFI router which does not have a internet connectivity?From sources I came to know ,in order to check this I need to ping the site for e.g.(www.google.com).Please help me with the exact snippet I need to include?
Thanks </p>

答:
Try this:</p>

```<code> public static boolean hasInternet(Context context) {
    ConnectivityManager connMgr = (ConnectivityManager)
            context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    return networkInfo != null && networkInfo.isConnected();
}
</code>```

Body:
Try this:

 public static boolean hasInternet(Context context) {
    ConnectivityManager connMgr = (ConnectivityManager)
            context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    return networkInfo != null && networkInfo.isConnected();
}


问:
Unable to trigger jquery function on checkbox check
I have built a form and am trying to trigger a function when the singular checkbox is clicked, but the function I am using as shown below does not work. Basically every response I could find related to this question points to using the same method that I am using from what I can tell, but I must be doing something wrong here.

```<code><form>
  <fieldset>
    <div class="row">
      <div class="col-sm-12">
        <div class="checkbox" id="check-3dAnimationVisualEffects">
          <input type="checkbox" id="filter-3dAnimationVisualEffects" name="3dAnimationVisualEffects" value="1" class="form-checkbox"/>
          <label for="filter-3dAnimationVisualEffects" data-toggle="tooltip" data-placement="top"><span>3D Animation Visual Effects</span></label>
        </div>
      </div>
    </div>
  </fieldset>
</form>

<script>
jQuery(document).ready(function($){
  if ($('#filter-3dAnimationVisualEffects').is(':checked')) {
    alert("Checked!");
  }
});
</script>
</code>```

How can I get this function to run when the checkbox is checked?

答:
Your form and jQuery function work fine but there is a misunderstanding in how your code logic actually work:

```<code>if ($('#filter-3dAnimationVisualEffects').is(':checked')) {
    alert("Checked!");
}
</code>```

This condition only work when your checkbox is already checked before executing this jQuery function.

If you try to check and then uncheck it, it won't work as you expected

You should add a click event callback function to perform an action when a checkbox is checked or unchecked :

```<code>$('#filter-3dAnimationVisualEffects').on('click', function(){
    if ( $(this).is(':checked') ) {
        alert("Checked!");
    }
});
</code>```

Body:
I have built a form and am trying to trigger a function when the singular checkbox is clicked, but the function I am using as shown below does not work. Basically every response I could find related to this question points to using the same method that I am using from what I can tell, but I must be doing something wrong here.

<form>
  <fieldset>

          <input type="checkbox" id="filter-3dAnimationVisualEffects" name="3dAnimationVisualEffects" value="1" class="form-checkbox"/>
          3D Animation Visual Effects

  </fieldset>
</form>

How can I get this function to run when the checkbox is checked?

Body:
Your form and jQuery function work fine but there is a misunderstanding in how your code logic actually work:

if ($('#filter-3dAnimationVisualEffects').is(':checked')) {
    alert("Checked!");
}

This condition only work when your checkbox is already checked before executing this jQuery function.

If you try to check and then uncheck it, it won't work as you expected

You should add a click event callback function to perform an action when a checkbox is checked or unchecked :

$('#filter-3dAnimationVisualEffects').on('click', function(){
    if ( $(this).is(':checked') ) {
        alert("Checked!");
    }
});


问:
Using a FreeTDS ODBC driver to connect Linux PHP to a SQL Server
I just set up my freetds.conf file with a new virtual account to connect to a SQL Server database but I am not sure when and where I tell my PHP script which database to connect to below are my settings

odbc.ini

```<code>[McDo]
ServerName = server1
Driver  = FreeTDS
Description = MyServer
Trace   = Yes
</code>```

freetds.conf

```<code>[server1]
host = 66.111.xxx.xxx
port = 1433
tds version = 7.0
</code>```

And here is my PHP connect script. Now sure where I tell the script to connect to which database.

```<code>putenv('ODBCINI=/etc/odbc.ini');

$connect = odbc_connect("server1", "username", "password");

//$query = "SELECT name_ID  FROM ext_name";

if(!$connect){
echo "not connected";

}else{
echo "connected";
}

odbc_close($connect);
</code>```

答:
The php manual shows:</p>

```<code>// Microsoft SQL Server using the SQL Native Client 10.0 ODBC Driver - allows connection to SQL 7, 2000, 2005 and 2008
$connection = odbc_connect("Driver={SQL Server Native Client 10.0};Server=$server;Database=$database;", $user, $password);</code>```

ContentLicense: CC BY-SA 2.5

Body:
I just set up my freetds.conf file with a new virtual account to connect to a SQL Server database but I am not sure when and where I tell my PHP script which database to connect to below are my settings

odbc.ini

[McDo]
ServerName = server1
Driver  = FreeTDS
Description = MyServer
Trace   = Yes

freetds.conf

[server1]
host = 66.111.xxx.xxx
port = 1433
tds version = 7.0

And here is my PHP connect script. Now sure where I tell the script to connect to which database.

putenv('ODBCINI=/etc/odbc.ini');

$connect = odbc_connect("server1", "username", "password");

//$query = "SELECT name_ID  FROM ext_name";

if(!$connect){
echo "not connected";

}else{
echo "connected";
}

odbc_close($connect);

Body:
The php manual shows:

// Microsoft SQL Server using the SQL Native Client 10.0 ODBC Driver - allows connection to SQL 7, 2000, 2005 and 2008
$connection = odbc_connect("Driver={SQL Server Native Client 10.0};Server=$server;Database=$database;", $user, $password);


问:
Dynamic HTML controls through jQuery?
I have the following section of javascript/jQuery trying to create a grid overlay on a picture:

```<code>var $tbl = $('<table></table>');
for (var y = 1; y <= $rows; y++) {
    var $tr = $('<tr></tr>');
    for (var x = 1; x <= $cols; x++) {
        var $td = $('<td><input class = "chkDamage" type="checkbox" /></td>'); // hidden="hidden"

        $td.css('width', $gsize + 'px').css('height', $gsize + 'px');
        $td.addClass('unselected');
        $tr.append($td);

    }
    $tbl.append($tr);
}
</code>```

What I would like to do is to dynamically have a class name or id associated with each of the td elements so that I'm able to grab which squares are checked for later usage.  Is something like that possible?

答:
I hope that's what you're looking for: (code is working, so it should be self-explanatory)

$rows = 5;
$cols = 5;
$gsize = 15;
var $tbl = $('

');

for (var y = 1; y <= $rows; y++) {
    var $tr = $('

');
    for (var x = 1; x <= $cols; x++) {

        var $td = $('<input class = "chkDamage" type="checkbox" />	'); // hidden="hidden"

        $td.css('width', $gsize + 'px').css('height', $gsize + 'px');
        $td.addClass('unselected');
        $td.addClass('r-'+y);
        $td.addClass('c-'+x);
        $tr.append($td);

    }
    $tbl.append($tr);
}
$('body').append($tbl)
setTimeout(()=>{console.log($('.r-3.c-4'),$('.r-3.c-4 input').prop('checked'))},2000)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Title: Dynamic HTML controls through jQuery?

Body:
I have the following section of javascript/jQuery trying to create a grid overlay on a picture:

var $tbl = $('

');
for (var y = 1; y <= $rows; y++) {
    var $tr = $('

');
    for (var x = 1; x <= $cols; x++) {
        var $td = $('<input class = "chkDamage" type="checkbox" />	'); // hidden="hidden"

        $td.css('width', $gsize + 'px').css('height', $gsize + 'px');
        $td.addClass('unselected');
        $tr.append($td);

    }
    $tbl.append($tr);
}

What I would like to do is to dynamically have a class name or id associated with each of the td elements so that I'm able to grab which squares are checked for later usage.  Is something like that possible?

Body:
I hope that's what you're looking for: (code is working, so it should be self-explanatory)

$rows = 5;
$cols = 5;
$gsize = 15;
var $tbl = $('<table></table>');

for (var y = 1; y <= $rows; y++) {
    var $tr = $('<tr></tr>');
    for (var x = 1; x <= $cols; x++) {

        var $td = $('<td><input class = "chkDamage" type="checkbox" /></td>'); // hidden="hidden"

        $td.css('width', $gsize + 'px').css('height', $gsize + 'px');
        $td.addClass('unselected');
        $td.addClass('r-'+y);
        $td.addClass('c-'+x);
        $tr.append($td);

    }
    $tbl.append($tr);
}
$('body').append($tbl)
setTimeout(()=>{console.log($('.r-3.c-4'),$('.r-3.c-4 input').prop('checked'))},2000)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
Removing punctuation and placing it at the end of a string
I'm trying to write a function that upon execution will remove punctuation marks from a word and place the mark at the end. The removal bit was working fine until I appended the part which adds that same mark at the end; now instead of removing the punc. inside of the string, it leaves it there and adds it to the end, which is not what I want. My code is the following:

```<code>function containsPunctuation(word) {
    var new_word;
    new_word = word.replace(".", "");
    new_word = word.replace("!", "");
    new_word = word.replace(";", "");
    new_word = word.replace(",", "");
    new_word = word.replace("?", "");
    if (word.includes(".") === true) {
        new_word = new_word + ".";
    }
    return new_word;
}
</code>```

答:
In your code here, the line  new_word = word.replace(".", ""); is replacing the string new_word with the expected value from word (without the .)
The variable word though, is not actually having the . removed, but just the value you are setting to, new_word.  So when the replace for ! comes, the value word in word.replace still contains the . from the first replace because it was only replaced in new word.  So something like this would work in your scenario, could be improved but just a point of concept.

```<code>function containsPunctuation(word) {
        var new_word;
        new_word = word.replace(".", "");
        new_word = new_word.replace("!", "");
        new_word = new_word.replace(";", "");
        new_word = new_word.replace(",", "");
        new_word = new_word.replace("?", "");
        if (word.includes(".") === true) {
            new_word = new_word + ".";
        }
        return new_word;
    }
</code>```

Body:
I'm trying to write a function that upon execution will remove punctuation marks from a word and place the mark at the end. The removal bit was working fine until I appended the part which adds that same mark at the end; now instead of removing the punc. inside of the string, it leaves it there and adds it to the end, which is not what I want. My code is the following:

function containsPunctuation(word) {
    var new_word;
    new_word = word.replace(".", "");
    new_word = word.replace("!", "");
    new_word = word.replace(";", "");
    new_word = word.replace(",", "");
    new_word = word.replace("?", "");
    if (word.includes(".") === true) {
        new_word = new_word + ".";
    }
    return new_word;
}

Body:
In your code here, the line  new_word = word.replace(".", ""); is replacing the string new_word with the expected value from word (without the .)
The variable word though, is not actually having the . removed, but just the value you are setting to, new_word.  So when the replace for ! comes, the value word in word.replace still contains the . from the first replace because it was only replaced in new word.  So something like this would work in your scenario, could be improved but just a point of concept.

function containsPunctuation(word) {
        var new_word;
        new_word = word.replace(".", "");
        new_word = new_word.replace("!", "");
        new_word = new_word.replace(";", "");
        new_word = new_word.replace(",", "");
        new_word = new_word.replace("?", "");
        if (word.includes(".") === true) {
            new_word = new_word + ".";
        }
        return new_word;
    }


问:
How to resolve BufferError: Existing exports of data: object cannot be re-sized in tornado
I am a new user to Tornado web server.While streaming the data I got buffer error.Currently, I am using 4.5.1 version.Can anyone suggest the reason and resolve buffer error. </p>

答: This error is discussed in Tornado issue 2008. The current theory is that it only happens when threads are being used incorrectly, but this is not certain. If you can rule out threading problems or provide more detail about how to reproduce it, please add comments to the issue.</p>


问:
Why does C# handle command line args inconsistently?
In C#, getting command line arguments directly from Main() omits the exe name, contrary to the tradition of C.

Getting those same command line args via Environment.GetCommandLineArgs includes it.

Is there some good logical reason I'm missing for this apparent inconsistency?

```<code>class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(string.Format("args.Length = {0}", args.Length));

        foreach(string arg in args)
        {
            Console.WriteLine(string.Format("args = {0}", arg));
        }

        Console.WriteLine("");

        string[] Eargs = Environment.GetCommandLineArgs();
        Console.WriteLine(string.Format("Eargs.Length = {0}", Eargs.Length));
        foreach (string arg in Eargs)
        {
            Console.WriteLine(string.Format("Eargs = {0}", arg));
        }

    }
}
</code>```

Output:

```<code>C:\\ConsoleApplication1\ConsoleApplication1\bin\Debug>consoleapplication1 xx zz aa
args.Length = 3
args = xx
args = zz
args = aa
Eargs.Length = 4
Eargs = consoleapplication1
Eargs = xx
Eargs = zz
Eargs = aa
</code>```

答:
To me, the reason the two methods return different results is due to Context.

The Environment class is used to manipulate the current environement and process, and it makes sense that Environment.GetCommandLineArgs(); returns the executable name, since it is part of the process.

As for the args array, to me it makes sense to exclude the executable name. I know that I am calling the executable and in the context of running my application I want to know what arguments were sent to it.

At the end of the day, it is powerful to have a way to get at both alternatives.

Body:
In C#, getting command line arguments directly from Main() omits the exe name, contrary to the tradition of C.

Getting those same command line args via Environment.GetCommandLineArgs includes it.

Is there some good logical reason I'm missing for this apparent inconsistency?

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(string.Format("args.Length = {0}", args.Length));

        foreach(string arg in args)
        {
            Console.WriteLine(string.Format("args = {0}", arg));
        }

        Console.WriteLine("");

        string[] Eargs = Environment.GetCommandLineArgs();
        Console.WriteLine(string.Format("Eargs.Length = {0}", Eargs.Length));
        foreach (string arg in Eargs)
        {
            Console.WriteLine(string.Format("Eargs = {0}", arg));
        }

    }
}

Output:

C:\\ConsoleApplication1\ConsoleApplication1\bin\Debug>consoleapplication1 xx zz aa
args.Length = 3
args = xx
args = zz
args = aa
Eargs.Length = 4
Eargs = consoleapplication1
Eargs = xx
Eargs = zz
Eargs = aa


问:
CheckBox to switch interior color of all cells
Hi I want to make a macro that switch the backgroung color of all cells with a specific color RGB(252, 252, 250) to another color RGB(217, 217, 217) in entire workbook</p>

答:
You can Record Macro of Replace Format:</p>

```<code>Application.FindFormat.Clear
Application.FindFormat.Interior.Color = RGB(252, 252, 250)
Application.ReplaceFormat.Clear
Application.ReplaceFormat.Interior.Color = RGB(217, 217, 217)

Cells.Replace "", "", SearchFormat:=True, ReplaceFormat:=True
</code>```

Body:
You can Record Macro of Replace Format:

Application.FindFormat.Clear
Application.FindFormat.Interior.Color = RGB(252, 252, 250)
Application.ReplaceFormat.Clear
Application.ReplaceFormat.Interior.Color = RGB(217, 217, 217)

Cells.Replace "", "", SearchFormat:=True, ReplaceFormat:=True


问:
Angular - How to validate multiple fields loaded dynamically (in various components)
I am creating classifieds site on Angular.
Main component of the route consist from:

static fields (name, email, phone, location, etc.) described in it's template

component loaded dynamically, with it's own template (separate fields)

I use Reactive Forms Model to validate static fields in main component.
And if field is valid I write it's value to the service property.

How can I validate fields that loaded with dynamic component and gather data from main and dynamic component to one object/array?

答:
The form that is being loaded dynamically can built using the same method used to build dynamic forms. I would build the dynamic form grammatically using reactive forms.

Building Dynamic Forms

From there if there is a parent child relationship between the components you could use Viewchild to get the validation state/values of the dynamically rendered form.

Otherwise you can always use a service to store and share information between components including the validation state of the form(s).


问:
Doctrine custom repository chaining filters?
What is the right way to chain custom repository methods in order to create one composed query that returns the entities based on multiple conditions.

Here is what I did:

```<code>use Doctrine\ORM\EntityRepository;

class ingredientRepository extends EntityRepository
{

    private $query;

    public function initNewQuery()
    {
       $this->query = $this->createQueryBuilder('i')->join('i.product', 'p');
       return $this;
    }

    public function clearQuery()
    {
       $this->query = null;
       return $this;
    }

    public function getResult(){
      $r = $this->query->getQuery()->getResult();
      $this->clearQuery();
      return $r;
    }

    public function filterByProductName( $productName )
    {

      if(!$this->query) $this->initNewQuery();

      $this->query->andWhere('p.name LIKE :name')->setParameter('name', '%'.$productName.'%');

      return $this;
    }

    public function filterByMinContenu( $contenu )
    {

      if(!$this->query) $this->initNewQuery();

      $this->query->andWhere('p.contenu > :contenu')->setParameter('contenu', $contenu);

      return $this;
    }

    public function filterByType( $type ){

      if(!$this->query) $this->initNewQuery();

      $this->query->andWhere('i.type = :type')->setParameter('type', $type);

      return $this;

    }

}
</code>```

This allows me to do things like:

```<code>$ingredients = $em->getRepository('ingredient')->initNewQuery()->filterByType(4)->getResult();

$ingredients = $em->getRepository('ingredient')->initNewQuery()->filterByProductName('ell')->filterByMinContenu(10)->getResult();
</code>```

Which is exactly what I want !
But ... I don't really like it.
First, this is not how the default methods like findBy and so on work. These all return the results directly. So that doesn't seem right to mix those two behaviours.
And secondly, when calling only the filterByType method and then return the results, the query will use a join that it doesn't need. I guess I could find a way to do the join only if I need it, but again, doesn't seem right.

Any ideas on how to do this clean an simple ?

答:
Fast answer without testing:)

```<code>use Doctrine\ORM\EntityRepository;

class ingredientRepository extends EntityRepository
{
    private $query;

    private function initNewQuery()
    {
        $this->query = $this->createQueryBuilder('i');
    }

    public function findBy($filterArray)
    {
        $this->initNewQuery();
        if (array_key_exists('productName', $filterArray)) {
            $this->filterByProductName($filterArray['productName']);
        }
        if (array_key_exists('minContenu', $filterArray)) {
            $this->filterByMinContenu($filterArray['minContenu']);
        }
        if (array_key_exists('type', $filterArray)) {
            $this->filterByType($filterArray['type']);
        }
        return $this->query->getQuery()->getResult();
    }

    private function filterByProductName($productName)
    {
        $this->query->join('i.product', 'p');
        $this->query->andWhere('p.name LIKE :name')->setParameter('name', '%'.$productName.'%');
    }

    private function filterByMinContenu($contenu)
    {
        $this->query->andWhere('p.contenu > :contenu')->setParameter('contenu', $contenu);
    }

    private function filterByType($type)
    {
        $this->query->andWhere('i.type = :type')->setParameter('type', $type);
    }
}
</code>```

call:

```<code>$ingredients = $em->getRepository('ingredient')->findBy(['type'=>4]);

$ingredients = $em->getRepository('ingredient')->findBy(['productName'=>'ell', 'minContenu' => 10]);
</code>```

Body:
What is the right way to chain custom repository methods in order to create one composed query that returns the entities based on multiple conditions.

Here is what I did:

use Doctrine\ORM\EntityRepository;

class ingredientRepository extends EntityRepository
{

    private $query;

    public function initNewQuery()
    {
       $this->query = $this->createQueryBuilder('i')->join('i.product', 'p');
       return $this;
    }

    public function clearQuery()
    {
       $this->query = null;
       return $this;
    }

    public function getResult(){
      $r = $this->query->getQuery()->getResult();
      $this->clearQuery();
      return $r;
    }

    public function filterByProductName( $productName )
    {

      if(!$this->query) $this->initNewQuery();

      $this->query->andWhere('p.name LIKE :name')->setParameter('name', '%'.$productName.'%');

      return $this;
    }

    public function filterByMinContenu( $contenu )
    {

      if(!$this->query) $this->initNewQuery();

      $this->query->andWhere('p.contenu > :contenu')->setParameter('contenu', $contenu);

      return $this;
    }

    public function filterByType( $type ){

      if(!$this->query) $this->initNewQuery();

      $this->query->andWhere('i.type = :type')->setParameter('type', $type);

      return $this;

    }

}

This allows me to do things like:

$ingredients = $em->getRepository('ingredient')->initNewQuery()->filterByType(4)->getResult();

$ingredients = $em->getRepository('ingredient')->initNewQuery()->filterByProductName('ell')->filterByMinContenu(10)->getResult();

Which is exactly what I want !
But ... I don't really like it.
First, this is not how the default methods like findBy and so on work. These all return the results directly. So that doesn't seem right to mix those two behaviours.
And secondly, when calling only the filterByType method and then return the results, the query will use a join that it doesn't need. I guess I could find a way to do the join only if I need it, but again, doesn't seem right.

Any ideas on how to do this clean an simple ?

Body:
Fast answer without testing:)

use Doctrine\ORM\EntityRepository;

class ingredientRepository extends EntityRepository
{
    private $query;

    private function initNewQuery()
    {
        $this->query = $this->createQueryBuilder('i');
    }

    public function findBy($filterArray)
    {
        $this->initNewQuery();
        if (array_key_exists('productName', $filterArray)) {
            $this->filterByProductName($filterArray['productName']);
        }
        if (array_key_exists('minContenu', $filterArray)) {
            $this->filterByMinContenu($filterArray['minContenu']);
        }
        if (array_key_exists('type', $filterArray)) {
            $this->filterByType($filterArray['type']);
        }
        return $this->query->getQuery()->getResult();
    }

    private function filterByProductName($productName)
    {
        $this->query->join('i.product', 'p');
        $this->query->andWhere('p.name LIKE :name')->setParameter('name', '%'.$productName.'%');
    }

    private function filterByMinContenu($contenu)
    {
        $this->query->andWhere('p.contenu > :contenu')->setParameter('contenu', $contenu);
    }

    private function filterByType($type)
    {
        $this->query->andWhere('i.type = :type')->setParameter('type', $type);
    }
}

call:

$ingredients = $em->getRepository('ingredient')->findBy(['type'=>4]);

$ingredients = $em->getRepository('ingredient')->findBy(['productName'=>'ell', 'minContenu' => 10]);


问:
AJAX request, redirect with params
```<code> $.ajax({
               url: baseUrl,
               type: "post",
               contentType: "application/json",
               dataType: "json",
               success: function (data) {
                window.location = ('http://localhost:9000/#/home.html?' +  (data.search))
               },
               data: JSON.stringify(body),
             });
             return false;
           }
         };
</code>```

this is my ajax request, it sends as JSON and it returns an object

ie. search = {firstName: km, lastname: b}

However, ajax isnt setting the content type to JSON for the params in the redirect. It is still sending as an object. JSON stringify does not work. Is there a way to set the content type to JSON inside the success/redirect function?

JSON.stringify just decodes the object into

```<code>%7B%22clientName%22:%blah%22,%22em%22:%22mLigDACsBihAL2RETse06351MuCNehZQ%22,%22partnercode%22:%blah%22%7D
</code>```

答:
You can use $.param:

```<code>var qs = $.param(data.search);
window.location = 'http://localhost:9000/#/home.html?' + qs;
</code>```

Title: AJAX request, redirect with params

Body:
 $.ajax({
               url: baseUrl,
               type: "post",
               contentType: "application/json",
               dataType: "json",
               success: function (data) {
                window.location = ('http://localhost:9000/#/home.html?' +  (data.search))
               },
               data: JSON.stringify(body),
             });
             return false;
           }
         };

this is my ajax request, it sends as JSON and it returns an object

ie. search = {firstName: km, lastname: b}

However, ajax isnt setting the content type to JSON for the params in the redirect. It is still sending as an object. JSON stringify does not work. Is there a way to set the content type to JSON inside the success/redirect function?

JSON.stringify just decodes the object into

%7B%22clientName%22:%blah%22,%22em%22:%22mLigDACsBihAL2RETse06351MuCNehZQ%22,%22partnercode%22:%blah%22%7D

Body:
You can use $.param:

var qs = $.param(data.search);
window.location = 'http://localhost:9000/#/home.html?' + qs;


问:
Changing Selenium from Py3 to Py2
I installed a Selenium server using Python 3.6. However, I found that the tests I am working on are written in Python2. My shop has asked me to change my Selenium installation so that it can process Python2 code, but I have been unable to successfully make the change.

I have installed Python 2.7.10 and have changed the Windows path to the new Py2. I have tried re-downloading the Selenium server, to no avail. I have also tried pip install selenium in a Py2 environment, and have confirmed the files are in my C:/Python27 folder. Even with the OS pointed at Python 2, Selenium remains pointed at Python 3. How can I change Selenium to run Python2 code instead of Python3?

OS: Win10-64bit

Python: 2.7.10 (formerly 3.6)

答:
The Selenium files were installed in my local Python36 folder. After removing all Selenium files from the Python36 folder, I reinstalled Selenium using the .whl files provided at https://pypi.python.org/pypi/selenium (download, then extract and install using pip install <filename>.whl) and ensured the extracted and installed files were in my /Python27 folder.

This, coupled with a similar procedure for nosetests (shell program used to perform my testing), reset Selenium to execute Python2 code. If anyone has a more elegant solution, please share. Until then, I hope this helps the next poor soul who has to deal with this.

Title: Changing Selenium from Py3 to Py2


问:
Why doesn't */%/x match a/b/x, in a Makefile?
Explained in Makefile code…

```<code>PATH = a/b/x
$(patsubst a/%/x,%,$(PATH))    # => b
$(patsubst */%/x,%,$(PATH))    # => a/b/x
</code>```

It seems like both of these should produce the same result, b, as the * should match anything. Why is this not the case? How do I write one expression to capture the center term with any prefix, not just 'a'?

答:
Make simply doesn't have very good ability to handle wildcards. Your $(patsubst */%/x,%,$(PATH)) doesn't work because there is no * in your $(PATH). But you can get the effect you want with this kludge:

```<code>$(word 2, $(subst /, ,$(PATH)))
</code>```

Body:
Explained in Makefile code…

PATH = a/b/x
$(patsubst a/%/x,%,$(PATH))    # => b
$(patsubst */%/x,%,$(PATH))    # => a/b/x

It seems like both of these should produce the same result, b, as the * should match anything. Why is this not the case? How do I write one expression to capture the center term with any prefix, not just 'a'?

Body:
Make simply doesn't have very good ability to handle wildcards. Your $(patsubst */%/x,%,$(PATH)) doesn't work because there is no * in your $(PATH). But you can get the effect you want with this kludge:

$(word 2, $(subst /, ,$(PATH)))


问:
Running a macro from a non-activeX button
Is it possible to run a macro in Powerpoint from a non-ActiveX button? For instance just a circle shape I place on the slide? I haven't found a way to connect a macro to anything but an ActiveX button. However there are some smart people here that may know a work around.</p>

答:
Yes. First, make sure the subroutine containing the code is declared as Public.

Then add an Action Setting to your circle/other shape.  Set the action setting to Run Macro: [choose the macro to run]

Note: you can also do this, which is sometimes quite useful:

Public Sub MyMacro (oSh as Shape)
   Msgbox "You clicked a shape called " & oSh.Name _
   & VbCRLF _
   & "on slide " & Cstr(oSh.Parent.SlideIndex)
End Sub

By getting a reference to the shape, you can find out what slide it's on or, depending on the shape type or name or any of a number of other attributes, perform different actions.

This is broken on Mac PPT.  There's a way around it described on my PPT FAQ site, here:

Determine which shape was clicked
http://www.pptfaq.com/FAQ00141_Determine_which_shape_was_clicked.htm


问:
Add two quotes in JavaScript
I have a code like this :

 var event = {
  "temperature" : 12.45,
  "humidite" : 45.78,
  "built" : "charone",
  "fire" : "chartwo",
  "topic" : "sk1_001/data"
 };

var keys = Object.keys(event);

 valeurs_d = "";
 for (var i = 0; i < keys.length -1 ; i++)
 valeurs_d += event[keys[i]] + ", ";
 var str5 = ",";
 var str6 = str5.concat(valeurs_d);
 var valeurs = str6.substring (0, str6.length - 2);  console.log(valeurs); ```
</div>
</div>
</p>

<p>I want to have everything between two quotes in variable <code>valeurs</code> like this:</p>

<pre class="lang-none prettyprint-override"><code>, '12 .45 ', '45 .78', 'charone', 'chartwo'
</code>```

Or, just have the character strings between two quotes:

, 12.45, 45.78, 'charone', 'chartwo'
```

I can have in my JSON other strings.

How can I do this in JavaScript?

答:
Try replacing this line:

valeurs_d += event[keys[i]] + ", ";

for this one

valeurs_d += "'" + event[keys[i]] + "', ";

Title: Add two quotes in JavaScript

Body:
I have a code like this :

 var event = {
  "temperature" : 12.45,
  "humidite" : 45.78,
  "built" : "charone",
  "fire" : "chartwo",
  "topic" : "sk1_001/data"
 };

var keys = Object.keys(event);

 valeurs_d = "";
 for (var i = 0; i < keys.length -1 ; i++)
 valeurs_d += event[keys[i]] + ", ";
 var str5 = ",";
 var str6 = str5.concat(valeurs_d);
 var valeurs = str6.substring (0, str6.length - 2);  console.log(valeurs);

I want to have everything between two quotes in variable valeurs like this:

, '12 .45 ', '45 .78', 'charone', 'chartwo'

Or, just have the character strings between two quotes:

, 12.45, 45.78, 'charone', 'chartwo'

I can have in my JSON other strings.

How can I do this in JavaScript?


答:
Try this, you can also trigger events when it is unchecked.

$(document).ready(function() {
  $('#filter-3dAnimationVisualEffects').on('change', function() {
    if ($(this).is(':checked'))
      alert('checked');
    else
      alert('not checked');
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form>
  <fieldset>
    <div class="row">
      <div class="col-sm-12">
        <div class="checkbox" id="check-3dAnimationVisualEffects">
          <input type="checkbox" id="filter-3dAnimationVisualEffects" name="3dAnimationVisualEffects" value="1" class="form-checkbox" />
          <label for="filter-3dAnimationVisualEffects" data-toggle="tooltip" data-placement="top"><span>3D Animation Visual Effects</span></label>
        </div>
      </div>
    </div>
  </fieldset>
</form></code>```

Title: Unable to trigger jquery function on checkbox check

Body:
I have built a form and am trying to trigger a function when the singular checkbox is clicked, but the function I am using as shown below does not work. Basically every response I could find related to this question points to using the same method that I am using from what I can tell, but I must be doing something wrong here.

<form>
  <fieldset>

          <input type="checkbox" id="filter-3dAnimationVisualEffects" name="3dAnimationVisualEffects" value="1" class="form-checkbox"/>
          3D Animation Visual Effects

  </fieldset>
</form>

How can I get this function to run when the checkbox is checked?

Body:
Try this, you can also trigger events when it is unchecked.

$(document).ready(function() {
  $('#filter-3dAnimationVisualEffects').on('change', function() {
    if ($(this).is(':checked'))
      alert('checked');
    else
      alert('not checked');
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form>
  <fieldset>
    <div class="row">
      <div class="col-sm-12">
        <div class="checkbox" id="check-3dAnimationVisualEffects">
          <input type="checkbox" id="filter-3dAnimationVisualEffects" name="3dAnimationVisualEffects" value="1" class="form-checkbox" />
          <label for="filter-3dAnimationVisualEffects" data-toggle="tooltip" data-placement="top"><span>3D Animation Visual Effects</span></label>
        </div>
      </div>
    </div>
  </fieldset>
</form>


问:
Reduce redundant SQLite nested query?
How can I reduce this nested query so that X,Y,Z are filtered prior to checking AA?
This works but is expensive since it calculates X,Y,Z for each subquery.
Only AA needs to be checked in each.</p>

```<code>SELECT 3*b3.bin3 + 2*b2.bin2 + b1.bin1 FROM
  (SELECT count(*) AS bin1 FROM `TD` WHERE
  `X` = 1 AND
  `Y` >= 2 AND
  `Z` >= 2 AND
  `AA` >= 1 AND `AA` <= 2) b1
  JOIN
  (SELECT count(*) AS bin2 FROM `TD` WHERE
  `X` = 1 AND
  `Y` >= 2 AND
  `Z` >= 2 AND
  `AA` >= 2.01 AND `AA` <= 3) b2
  JOIN
  (SELECT count(*) AS bin3 FROM `TD` WHERE
  `X` = 1 AND
  `Y` >= 2 AND
  `Z` >= 2 AND
  `AA` >= 3.01 AND `AA` <= 4) b3;
</code>```

答:
```<code>--REDUCED FORM from Golden Ratio's hint.
WITH `v` AS
(SELECT `AA` FROM `TD` WHERE
  `X` = 1 AND
  `Y` >= 2 AND
  `Z` >= 2)
SELECT 3*bin3 + 2*bin2 + bin1 FROM
  (SELECT count(*) AS bin1 FROM `v` WHERE
  `AA` >= 1 AND `AA` <= 2)
  JOIN
  (SELECT count(*) AS bin2 FROM `v` WHERE
  `AA` >= 2.01 AND `AA` <= 3)
  JOIN
  (SELECT count(*) AS bin3 FROM `v` WHERE
  `AA` >= 3.01 AND `AA` <= 4);
</code>```

Title: Reduce redundant SQLite nested query?

Body:
How can I reduce this nested query so that X,Y,Z are filtered prior to checking AA?
This works but is expensive since it calculates X,Y,Z for each subquery.
Only AA needs to be checked in each.

SELECT 3*b3.bin3 + 2*b2.bin2 + b1.bin1 FROM
  (SELECT count(*) AS bin1 FROM `TD` WHERE
  `X` = 1 AND
  `Y` >= 2 AND
  `Z` >= 2 AND
  `AA` >= 1 AND `AA` <= 2) b1
  JOIN
  (SELECT count(*) AS bin2 FROM `TD` WHERE
  `X` = 1 AND
  `Y` >= 2 AND
  `Z` >= 2 AND
  `AA` >= 2.01 AND `AA` <= 3) b2
  JOIN
  (SELECT count(*) AS bin3 FROM `TD` WHERE
  `X` = 1 AND
  `Y` >= 2 AND
  `Z` >= 2 AND
  `AA` >= 3.01 AND `AA` <= 4) b3;


答:
You can add the quotes directly into the string that you are building, like in this example:

var event = {
  "temperature": 12.45,
  "humidite": 45.78,
  "built": "charone",
  "fire": "chartwo",
  "topic": "sk1_001/data"
};

var keys = Object.keys(event);

var valeurs_d = "";
for (var i = 0; i < keys.length - 1; i++) {
  valeurs_d += "'" + event[keys[i]] + "', ";
}

console.info(valeurs_d);```

Title: Add two quotes in JavaScript


答:
Consider this if it is a string:</p>

```<code>var str = "chartwo"
var str_with_qoutes =  "'" + str + "'";
</code>```

Title: Add two quotes in JavaScript

Body:
Consider this if it is a string:

var str = "chartwo"
var str_with_qoutes =  "'" + str + "'";


问:
AngularJS disable double click
I have a problem with a button which contacts server on click. If you do a double click (or any number of clicks for that matter) you will call the server that number of times.

```<code><div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">{{ 'ADMIN.CONTENT.DELIVERIES.BODY.CLOSE' | translate }}</button>
    <a class="btn btn-danger" ng-click="vm.markDelivered()" ng-dblclick="return" ng-disabled="flag">{{ 'MANAGER.CONTENT.DELIVERIES.BODY.DELETE_PANEL.CONFIRM' | translate }}</a>
</div>
</code>```

I have tried with ng-disabled but for some reason it doesn't work, as it is saying that that element is not allowed there. I tried changing a to button, but that seems the same. ng-dblclick="return" does nothing also.

答:
So with Bootstrap buttons you won't be able to use ng-disabled. You would have to do it this way:

```<code><div class="btn btn-default" ng-class="{'disabled': idDisabled}" ng-click="doSomething()">I'm a button!</div>
</code>```

where you are setting the class disabled on the button. But this does not disable the action itself. So when the button is pressed you would need to check that isDisabled variable and if it is true just return and don't do the intended action.

So for example:

```<code>doSomething() {
   if (isDisabled) {
       return
   } else {
       // do your server call
       // when call is finished set isDisabled = false
   }
}
</code>```

Title: AngularJS disable double click

Body:
I have a problem with a button which contacts server on click. If you do a double click (or any number of clicks for that matter) you will call the server that number of times.

    <button type="button" class="btn btn-default" data-dismiss="modal">{{ 'ADMIN.CONTENT.DELIVERIES.BODY.CLOSE' | translate }}</button>
    {{ 'MANAGER.CONTENT.DELIVERIES.BODY.DELETE_PANEL.CONFIRM' | translate }}

I have tried with ng-disabled but for some reason it doesn't work, as it is saying that that element is not allowed there. I tried changing a to button, but that seems the same. ng-dblclick="return" does nothing also.

Body:
So with Bootstrap buttons you won't be able to use ng-disabled. You would have to do it this way:

<div class="btn btn-default" ng-class="{'disabled': idDisabled}" ng-click="doSomething()">I'm a button!</div>

where you are setting the class disabled on the button. But this does not disable the action itself. So when the button is pressed you would need to check that isDisabled variable and if it is true just return and don't do the intended action.

So for example:

doSomething() {
   if (isDisabled) {
       return
   } else {
       // do your server call
       // when call is finished set isDisabled = false
   }
}


问:
Writing a C program to call another program without using any built-in libraries
I am trying to write a simple 'go-command' for boot-loader that takes me to specific address in RAM say 0x18000000 and it should execute a program that blinks led. I have two .c files say led.c and go.c in which led.c blinks two leds. But I am wondering and don't know that how can I pass a control/invoke its main() to this go.c file to go to that address and start blinking leds? But it should be done without including other header files, libraries, etc. Kindly help me!! Thanks in advance. Below code is for led.c

```<code>void delay ()
{
    volatile int i;
    for(i=0;i<1000000;i++)
    {}

}
int main(void)
{
    *led0=0;
    *led1=0;
    while(1)
    {
        *led0=1;
        delay();
        *led0=0;
        *led1=1;
        delay();
        *led1=0;
    }
}
</code>```

In my go.c file I want to pass a control to invoke this led.c main() func

Body:
I am trying to write a simple 'go-command' for boot-loader that takes me to specific address in RAM say 0x18000000 and it should execute a program that blinks led. I have two .c files say led.c and go.c in which led.c blinks two leds. But I am wondering and don't know that how can I pass a control/invoke its main() to this go.c file to go to that address and start blinking leds? But it should be done without including other header files, libraries, etc. Kindly help me!! Thanks in advance. Below code is for led.c

void delay ()
{
    volatile int i;
    for(i=0;i<1000000;i++)
    {}

}
int main(void)
{
    *led0=0;
    *led1=0;
    while(1)
    {
        *led0=1;
        delay();
        *led0=0;
        *led1=1;
        delay();
        *led1=0;
    }
}

In my go.c file I want to pass a control to invoke this led.c main() func

Body:
So I have an sifive riscv board, going to be a little different than yours but here is an led blinker program (compiled version):

Disassembly of section .text:

80001000 <_start>:
80001000:   80004137            lui x2,0x80004
80001004:   016000ef            jal x1,8000101a <notmain>
80001008:   9002                    ebreak
8000100a:   a001                    j   8000100a <_start+0xa>

8000100c <dummy>:
8000100c:   8082                    ret

8000100e <PUT32>:
8000100e:   00b52023            sw  x11,0(x10)
80001012:   8082                    ret

80001014 <GET32>:
80001014:   00052503            lw  x10,0(x10)
80001018:   8082                    ret

8000101a <notmain>:
8000101a:   1101                    addi    x2,x2,-32
8000101c:   c84a                    sw  x18,16(x2)
8000101e:   10012937            lui x18,0x10012
80001022:   00890513            addi    x10,x18,8 # 10012008 <_start-0x6ffeeff8>
80001026:   006805b7            lui x11,0x680
8000102a:   ce06                    sw  x1,28(x2)
8000102c:   ca26                    sw  x9,20(x2)
8000102e:   c64e                    sw  x19,12(x2)
80001030:   cc22                    sw  x8,24(x2)
80001032:   3ff1                    jal 8000100e <PUT32>
80001034:   00c90513            addi    x10,x18,12
80001038:   006805b7            lui x11,0x680
8000103c:   3fc9                    jal 8000100e <PUT32>
8000103e:   04090513            addi    x10,x18,64
80001042:   4581                    li  x11,0
80001044:   001e84b7            lui x9,0x1e8
80001048:   37d9                    jal 8000100e <PUT32>
8000104a:   006809b7            lui x19,0x680
8000104e:   0931                    addi    x18,x18,12
80001050:   48048493            addi    x9,x9,1152 # 1e8480 <_start-0x7fe18b80>
80001054:   85ce                    mv  x11,x19
80001056:   854a                    mv  x10,x18
80001058:   3f5d                    jal 8000100e <PUT32>
8000105a:   4401                    li  x8,0
8000105c:   8522                    mv  x10,x8
8000105e:   0405                    addi    x8,x8,1
80001060:   3775                    jal 8000100c <dummy>
80001062:   fe941de3            bne x8,x9,8000105c <notmain+0x42>
80001066:   4581                    li  x11,0
80001068:   854a                    mv  x10,x18
8000106a:   3755                    jal 8000100e <PUT32>
8000106c:   4401                    li  x8,0
8000106e:   8522                    mv  x10,x8
80001070:   0405                    addi    x8,x8,1
80001072:   3f69                    jal 8000100c <dummy>
80001074:   fe941de3            bne x8,x9,8000106e <notmain+0x54>
80001078:   bff1                    j   80001054 <notmain+0x3a>

the disassembly spacing is a little broken but thats okay.  The entry point IS NOT AT MAIN() for a normal program it is at the start in this case 0x80001000 NOT 0x8000101A which I intentionally name something other than main on purpose (for bare metal)...There should be no reason for you to to enter at main you should enter at the entry point...I will let you simply fail if you continue to try otherwise, you are on your own with that.

So this represents an srec of the above.

S00F00006E6F746D61696E2E737265631F
S3158000100037410080EF006001029001A0828023209A
S31580001010B500828003250500828001114AC83729E0
S31580001020011013058900B705680006CE26CA4EC68C
S3158000103022CCF13F1305C900B7056800C93F1305E7
S3158000104009048145B7841E00D937B709680031097C
S3158000105093840448CE854A855D3F014422850504F4
S315800010607537E31D94FE81454A85553701442285AF
S30F800010700504693FE31D94FEF1BFFD
S705800010006A

I/we assume you are not actually downloading that to ram as is, that will never execute, your bootloader has to parse that then write the program to ram, two different things (the program itself and a file format that describes that program).

Assuming you get to that point, all you need to do is branch to 0x80001000 in my case or 0x18000000 in yours.

so taking the answer already provided to you you can do this to launch the downloaded program

void hop ( void )
{
    void *func_ptr = (void *)0x80001000;
    goto *func_ptr;
}

which results in

Disassembly of section .text:

00000000 <hop>:
   0:   800017b7            lui x15,0x80001
   4:   8782                    jr  x15

Or my personal preference would be:

.globl HOP
HOP:
    jr x11

which from C I would call with

HOP(0x80001000);

that way I can insure the instruction I wanted is used. YMMV.

How far along this path have you gotten?  Are you stuck at the last step?  Simone provided an answer that should work just fine, there are other variations on that theme from C that you can use, but that one already appears to work.


问:
HMAC SHA512 using CommonCrypto in Swift 3.1
I'm trying to encrypt data to send to the API.

The API requires the data to be sent as hmac_sha512 encrypted hash.

I've found various examples of how it possibly could have been done for sha1 and others (not sha512) and also in older versions of Swift.

None of the examples that I tried work for swift 3.1

Any help in the right direction will be appreciated.

Edit:

In PHP, I successfully send it using:

```<code>    $sign = hash_hmac('sha512', $post_data, $this->secret);
</code>```

Edit 2:

I did add briding header, I don't know what to do next! As the code examples followed after that don't work for swift 3.1 :(

Edit 3:

Solved! Guess what, I was creating briding header incorrectly! :(

P.S I'm trying to avoid CryptoSwift, focusing on CommonCrypto.

The answer given below is not proper, as it doesn't allow hmac to get a key for encryption. I did research and finally got it working. This post contains the working example project for hmac: https://github.com/nabtron/hmacTest

答:
I think the best thing to do is using Crypto pod which is a wrapper for common crypto. In case you want to use directly commonCrypto you should add the bridging header to the project and import common crypto using: #import <CommonCrypto/CommonCrypto.h>

Edit 1

Create a swift class and add the following code to it:

```<code>import Foundation

extension String {
    var md5: String {
        return HMAC.hash(inp: self, algo: HMACAlgo.MD5)
    }

    var sha1: String {
        return HMAC.hash(inp: self, algo: HMACAlgo.SHA1)
    }

    var sha224: String {
        return HMAC.hash(inp: self, algo: HMACAlgo.SHA224)
    }

    var sha256: String {
        return HMAC.hash(inp: self, algo: HMACAlgo.SHA256)
    }

    var sha384: String {
        return HMAC.hash(inp: self, algo: HMACAlgo.SHA384)
    }

    var sha512: String {
        return HMAC.hash(inp: self, algo: HMACAlgo.SHA512)
    }
}

public struct HMAC {

    static func hash(inp: String, algo: HMACAlgo) -> String {
        if let stringData = inp.data(using: String.Encoding.utf8, allowLossyConversion: false) {
            return hexStringFromData(input: digest(input: stringData as NSData, algo: algo))
        }
        return ""
    }

    private static func digest(input : NSData, algo: HMACAlgo) -> NSData {
        let digestLength = algo.digestLength()
        var hash = [UInt8](repeating: 0, count: digestLength)
        switch algo {
        case .MD5:
            CC_MD5(input.bytes, UInt32(input.length), &hash)
            break
        case .SHA1:
            CC_SHA1(input.bytes, UInt32(input.length), &hash)
            break
        case .SHA224:
            CC_SHA224(input.bytes, UInt32(input.length), &hash)
            break
        case .SHA256:
            CC_SHA256(input.bytes, UInt32(input.length), &hash)
            break
        case .SHA384:
            CC_SHA384(input.bytes, UInt32(input.length), &hash)
            break
        case .SHA512:
            CC_SHA512(input.bytes, UInt32(input.length), &hash)
            break
        }
        return NSData(bytes: hash, length: digestLength)
    }

    private static func hexStringFromData(input: NSData) -> String {
        var bytes = [UInt8](repeating: 0, count: input.length)
        input.getBytes(&bytes, length: input.length)

        var hexString = ""
        for byte in bytes {
            hexString += String(format:"%02x", UInt8(byte))
        }

        return hexString
    }
}

enum HMACAlgo {
    case MD5, SHA1, SHA224, SHA256, SHA384, SHA512

    func digestLength() -> Int {
        var result: CInt = 0
        switch self {
        case .MD5:
            result = CC_MD5_DIGEST_LENGTH
        case .SHA1:
            result = CC_SHA1_DIGEST_LENGTH
        case .SHA224:
            result = CC_SHA224_DIGEST_LENGTH
        case .SHA256:
            result = CC_SHA256_DIGEST_LENGTH
        case .SHA384:
            result = CC_SHA384_DIGEST_LENGTH
        case .SHA512:
            result = CC_SHA512_DIGEST_LENGTH
        }
        return Int(result)
    }
}
</code>```

then use it simply by stringName.sha512

this class extends the String class which gives the ability to use the hashing as a function in the string class.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to encrypt data to send to the API.

The API requires the data to be sent as hmac_sha512 encrypted hash.

I've found various examples of how it possibly could have been done for sha1 and others (not sha512) and also in older versions of Swift.

None of the examples that I tried work for swift 3.1

Any help in the right direction will be appreciated.

Edit:

In PHP, I successfully send it using:

    $sign = hash_hmac('sha512', $post_data, $this->secret);

Edit 2:

I did add briding header, I don't know what to do next! As the code examples followed after that don't work for swift 3.1 :(

Edit 3:

Solved! Guess what, I was creating briding header incorrectly! :(

P.S I'm trying to avoid CryptoSwift, focusing on CommonCrypto.

The answer given below is not proper, as it doesn't allow hmac to get a key for encryption. I did research and finally got it working. This post contains the working example project for hmac: https://github.com/nabtron/hmacTest

Body:
I think the best thing to do is using Crypto pod which is a wrapper for common crypto. In case you want to use directly commonCrypto you should add the bridging header to the project and import common crypto using: #import <CommonCrypto/CommonCrypto.h>

Edit 1

Create a swift class and add the following code to it:

import Foundation

extension String {
    var md5: String {
        return HMAC.hash(inp: self, algo: HMACAlgo.MD5)
    }

    var sha1: String {
        return HMAC.hash(inp: self, algo: HMACAlgo.SHA1)
    }

    var sha224: String {
        return HMAC.hash(inp: self, algo: HMACAlgo.SHA224)
    }

    var sha256: String {
        return HMAC.hash(inp: self, algo: HMACAlgo.SHA256)
    }

    var sha384: String {
        return HMAC.hash(inp: self, algo: HMACAlgo.SHA384)
    }

    var sha512: String {
        return HMAC.hash(inp: self, algo: HMACAlgo.SHA512)
    }
}

public struct HMAC {

    static func hash(inp: String, algo: HMACAlgo) -> String {
        if let stringData = inp.data(using: String.Encoding.utf8, allowLossyConversion: false) {
            return hexStringFromData(input: digest(input: stringData as NSData, algo: algo))
        }
        return ""
    }

    private static func digest(input : NSData, algo: HMACAlgo) -> NSData {
        let digestLength = algo.digestLength()
        var hash = [UInt8](repeating: 0, count: digestLength)
        switch algo {
        case .MD5:
            CC_MD5(input.bytes, UInt32(input.length), &hash)
            break
        case .SHA1:
            CC_SHA1(input.bytes, UInt32(input.length), &hash)
            break
        case .SHA224:
            CC_SHA224(input.bytes, UInt32(input.length), &hash)
            break
        case .SHA256:
            CC_SHA256(input.bytes, UInt32(input.length), &hash)
            break
        case .SHA384:
            CC_SHA384(input.bytes, UInt32(input.length), &hash)
            break
        case .SHA512:
            CC_SHA512(input.bytes, UInt32(input.length), &hash)
            break
        }
        return NSData(bytes: hash, length: digestLength)
    }

    private static func hexStringFromData(input: NSData) -> String {
        var bytes = [UInt8](repeating: 0, count: input.length)
        input.getBytes(&bytes, length: input.length)

        var hexString = ""
        for byte in bytes {
            hexString += String(format:"%02x", UInt8(byte))
        }

        return hexString
    }
}

enum HMACAlgo {
    case MD5, SHA1, SHA224, SHA256, SHA384, SHA512

    func digestLength() -> Int {
        var result: CInt = 0
        switch self {
        case .MD5:
            result = CC_MD5_DIGEST_LENGTH
        case .SHA1:
            result = CC_SHA1_DIGEST_LENGTH
        case .SHA224:
            result = CC_SHA224_DIGEST_LENGTH
        case .SHA256:
            result = CC_SHA256_DIGEST_LENGTH
        case .SHA384:
            result = CC_SHA384_DIGEST_LENGTH
        case .SHA512:
            result = CC_SHA512_DIGEST_LENGTH
        }
        return Int(result)
    }
}

then use it simply by stringName.sha512

this class extends the String class which gives the ability to use the hashing as a function in the string class.


问:
System.Threading.Timer equivalent in PCL
System.Threading.Timer is not available for PCL(Portable Class Library)

```<code>System.Threading.Timer tmr = new System.Threading.Timer(this.Method1,"Obj", 10000, System.Threading.Timeout.Infinite);
</code>```

I couldn't find anything equivalent in PCL.

I found something near to that

```<code>System.Threading.Tasks.Task.Delay(10000)
</code>```

But this blocking the UI

while system.Threading.timer is not blocking the UI

Basically I want to call a method after a delay without blocking the UI from PCL

Kindly clarify this.

答:
You can start this:

```<code>System.Threading.Tasks.Task.Delay(10000)
</code>```

In a background worker.
And if the timer is done you can give a feedback, so that you can call your function.
This way will not block your UI...

Body:
System.Threading.Timer is not available for PCL(Portable Class Library)

System.Threading.Timer tmr = new System.Threading.Timer(this.Method1,"Obj", 10000, System.Threading.Timeout.Infinite);

I couldn't find anything equivalent in PCL.

I found something near to that

System.Threading.Tasks.Task.Delay(10000)

But this blocking the UI

while system.Threading.timer is not blocking the UI

Basically I want to call a method after a delay without blocking the UI from PCL

Kindly clarify this.

Body:
You can start this:

System.Threading.Tasks.Task.Delay(10000)

In a background worker.
And if the timer is done you can give a feedback, so that you can call your function.
This way will not block your UI...


问:
scroll event on Hostlistener
I have defined template

```<code>@Component({
    selector: 'name',
    directives: [ ... ],
    templateUrl: 'name.html'
})
</code>```

and class

```<code>export class ProductGridComponent implements OnInit {
    @HostListener('scroll', ['$event'])
    onScroll(e) {
        alert(window.pageYOffset)
    }

    products = [];
}
</code>```

But it does not shot anything , however when i replace scroll and onScroll with click and onClick it indeed show the alert.

Why does not it work with scroll , does angular2 has any other implementation for it?

Thanks

答: Set (scroll)="yourFunction($event)" within the template at the corresponding element.

Title: scroll event on Hostlistener

Body:
I have defined template

@Component({
    selector: 'name',
    directives: [ ... ],
    templateUrl: 'name.html'
})

and class

export class ProductGridComponent implements OnInit {
    @HostListener('scroll', ['$event'])
    onScroll(e) {
        alert(window.pageYOffset)
    }

    products = [];
}

But it does not shot anything , however when i replace scroll and onScroll with click and onClick it indeed show the alert.

Why does not it work with scroll , does angular2 has any other implementation for it?

Thanks


问:
Using two WHERE conditions when extracting data from a Nested SELECT query
I am currently stuck with a relatively straight-forward SQL query.

Working_schedule table is

```<code>Work_ID   Work_grade   Work_shift       Work_Process    pay_grade
-----------------------------------------------------------------
1         senior       day              manual          1
2         mid          day              auto            5
3         mid          day              auto            2
4         junior       night            manual          1
</code>```

Query:

```<code>SELECT COUNT(Work_shift)
FROM Working_schedule
WHERE Work_shift = 'night'
  AND Work_grade = 'senior'
(SELECT Work_id
FROM Working_schedule ws
INNER JOIN Area_branch ab
  ON ab.Area_Branch_ID = ws.FK_Area_Branch_ID
INNER JOIN regional_branch rb
  ON rb.regional_branch_id = ab.FK_regional_branch_id
INNER JOIN Country c
  ON.c.country_location = rb.FK_country_location
WHERE c.Company_origin = 'Spain')
</code>```

I have to count how many night workers, who are also seniors work companies of Spanish origin.

Currently I am able to filter for all night workers who are seniors, but I am unsure of how to check to see if they work for companies of Spanish origin.

I can also get filter for all companies of Spanish origin and (through a series of inner joins) find out the work_ids in the Working schedule table.

My question is how do I connect the two queries (or even can I)? If not, how should I resolve this problem? I have attempted this with INTERSECT, UNION and UNION ALL but nothing has worked.

The output anticipated is a number - number of work_shifts at night that are also work_grade senior.

答:
```<code>SELECT COUNT(ws.Work_shift)
FROM Working_schedule ws
     INNER JOIN Area_branch ab ON ab.Area_Branch_ID = ws.FK_Area_Branch_ID
     INNER JOIN regional_branch rb ON rb.regional_branch_id = ab.FK_regional_branch_id
     INNER JOIN Country c ON.c.country_location = rb.FK_country_location
                            AND c.Company_origin = 'Spain'
WHERE ws.Work_shift = 'night'
      AND ws.Work_grade = 'senior';
</code>```

<p>This method uses an inner join to filter out all data except for that where the company_origin = 'Spain'  </p>

Body:
I am currently stuck with a relatively straight-forward SQL query.

Working_schedule table is

Work_ID   Work_grade   Work_shift       Work_Process    pay_grade
-----------------------------------------------------------------
1         senior       day              manual          1
2         mid          day              auto            5
3         mid          day              auto            2
4         junior       night            manual          1

Query:

SELECT COUNT(Work_shift)
FROM Working_schedule
WHERE Work_shift = 'night'
  AND Work_grade = 'senior'
(SELECT Work_id
FROM Working_schedule ws
INNER JOIN Area_branch ab
  ON ab.Area_Branch_ID = ws.FK_Area_Branch_ID
INNER JOIN regional_branch rb
  ON rb.regional_branch_id = ab.FK_regional_branch_id
INNER JOIN Country c
  ON.c.country_location = rb.FK_country_location
WHERE c.Company_origin = 'Spain')

I have to count how many night workers, who are also seniors work companies of Spanish origin.

Currently I am able to filter for all night workers who are seniors, but I am unsure of how to check to see if they work for companies of Spanish origin.

I can also get filter for all companies of Spanish origin and (through a series of inner joins) find out the work_ids in the Working schedule table.

My question is how do I connect the two queries (or even can I)? If not, how should I resolve this problem? I have attempted this with INTERSECT, UNION and UNION ALL but nothing has worked.

The output anticipated is a number - number of work_shifts at night that are also work_grade senior.

Body:
SELECT COUNT(ws.Work_shift)
FROM Working_schedule ws
     INNER JOIN Area_branch ab ON ab.Area_Branch_ID = ws.FK_Area_Branch_ID
     INNER JOIN regional_branch rb ON rb.regional_branch_id = ab.FK_regional_branch_id
     INNER JOIN Country c ON.c.country_location = rb.FK_country_location
                            AND c.Company_origin = 'Spain'
WHERE ws.Work_shift = 'night'
      AND ws.Work_grade = 'senior';

This method uses an inner join to filter out all data except for that where the company_origin = 'Spain'


问:
How to dynamically change div text of a dynamic div
Apologies for asking something already answered. I have tried to resolve this but i am unable to get this working(Might be because i am not a javascript guy and it confuses me.)

I want to change text of a div which is generated dynamically from a js library that i am using for show error messages.

I have tried to change the element using jQuery by its class like

```<code>$('document').ready(function () {
    $('.error-message')[item_number].innerText.replace('old string','new string');
}
</code>```

I have tried checking if the element is undefined and put a condition for that and also tried to use simple javascript. But i think the problem is not that, but that the function is not running dynamically and changing the values on the fly as this works in js console.

I would appreciate if someone answers what i need to learn and use for this. I don't think this needs ajax and i should be able to do this via pure js or jquery. But please let me know if i need the delve deeper into ajax to handle this.

Please note that i am able to change the text in js console as i want. Its just the i am unable to handle this on the fly as the div which i am trying to change is also generated on the fly.

答:
Solution

$(function()
{
  $('.add_div').click(function(event)
  {
    // Dynamically add div
    var $new_div = $('
').text('default text');

    // Prepend so you don't have to scroll to see the div update
    $('.div_container').prepend($new_div);
    flash_first_div();
  });

  $('.update_text').click(function(event)
  {
    var date = new Date(),
        hour = date.getHours(),
        minutes = date.getMinutes(),
        seconds = date.getSeconds();

    // UPDATE LAST DYNAMICALLY CREATED DIV
    $('.new_div').first().text('text updated at ' + hour + ':' + minutes + ':' + seconds);
    flash_first_div();
  });

  // Just a helper function to highlight the targeted div
  function flash_first_div()
  {
    var $last_div = $('.new_div').first();

    $last_div.addClass('flash');

    window.setTimeout(function(){$last_div.removeClass('flash');},500);
  };
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>button{font-size:16px}
div{transition: background 1s;margin-bottom:10px}
.new_div{padding:0.5em;border:1px solid #000000}
.flash{background:yellow}</code>```

<!DOCTYPE html>

  <button class='add_div'>Add Div</button>
  <button class='update_text'>Update text of last created div</button>

```

Body:
Apologies for asking something already answered. I have tried to resolve this but i am unable to get this working(Might be because i am not a javascript guy and it confuses me.)

I want to change text of a div which is generated dynamically from a js library that i am using for show error messages.

I have tried to change the element using jQuery by its class like

$('document').ready(function () {
    $('.error-message')[item_number].innerText.replace('old string','new string');
}

I have tried checking if the element is undefined and put a condition for that and also tried to use simple javascript. But i think the problem is not that, but that the function is not running dynamically and changing the values on the fly as this works in js console.

I would appreciate if someone answers what i need to learn and use for this. I don't think this needs ajax and i should be able to do this via pure js or jquery. But please let me know if i need the delve deeper into ajax to handle this.

Please note that i am able to change the text in js console as i want. Its just the i am unable to handle this on the fly as the div which i am trying to change is also generated on the fly.

Body:
Solution

$(function()
{
  $('.add_div').click(function(event)
  {
    // Dynamically add div
    var $new_div = $('<div class="new_div"/>').text('default text');

    // Prepend so you don't have to scroll to see the div update
    $('.div_container').prepend($new_div);
    flash_first_div();
  });

  $('.update_text').click(function(event)
  {
    var date = new Date(),
        hour = date.getHours(),
        minutes = date.getMinutes(),
        seconds = date.getSeconds();

    // UPDATE LAST DYNAMICALLY CREATED DIV
    $('.new_div').first().text('text updated at ' + hour + ':' + minutes + ':' + seconds);
    flash_first_div();
  });

  // Just a helper function to highlight the targeted div
  function flash_first_div()
  {
    var $last_div = $('.new_div').first();

    $last_div.addClass('flash');

    window.setTimeout(function(){$last_div.removeClass('flash');},500);
  };
});

button{font-size:16px}
div{transition: background 1s;margin-bottom:10px}
.new_div{padding:0.5em;border:1px solid #000000}
.flash{background:yellow}

<!DOCTYPE html>
<html>
<body>
<div id='buttons'>
  <button class='add_div'>Add Div</button>
  <button class='update_text'>Update text of last created div</button>
</div>
<div class='div_container'></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</body>
</html>


问:
How to specify JAR location of a Maven dependency as plugin parameter?
I've tried to follow the configuration from this response on SO to use the jar location in my local repo as a plugin parameter, but it doesn't seem to work.  I don't know if this due to a newer Maven version than the response (I'm using Maven 3.2.5).

In my pom.xml, I need to add a javaagent to my surefire plugin definition.  The javaagent jar file is a dependency in my project.

I have tried the following:

```<code><dependencies>
        <dependency>
            <groupId>org.jmockit</groupId>
            <artifactId>jmockit</artifactId>
            <version>${jmockit.version}</version>
            <scope>test</scope>
        </dependency>
</dependencies>

...
        <!-- Configuration to use jmockit on IBM J9 -->
        <plugin>
            <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
                <argLine>-javaagent:${org.jmockit:jmockit:jar}</argLine>
            </configuration>
        </plugin>
</code>```

I was expecting that the ${org.jmockit:jmockit:jar} would be expanded to the location of the jar, but in my mvn console I see the following error:

```<code>[ERROR] Command wascmd.exe /X /C "C:\IBM\SDP\jdk\jre\bin\java -javaagent:${org.jmockit:jmockit:jar} -jar C:\dev\Eclipse\rtc-connector\target\surefire\surefirebooter1389906134960134.jar C:\dev\Eclipse\rtc-connector\target\surefire\surefire5488684370604495471tmp C:\dev\Eclipse\rtc-connector\target\surefire\surefire_05402037720997438783tmp"
</code>```

So obviously the parameter is not getting expanded.  I was hoping/expecting to see something like -javaagent:c:\users\eric\.m2\repository\org.jmockit\1.20\jmockit-1.20.jar or something similar.

Is there a clean way I can reference the jar from my dependency in my plugin configuration?  I know I can use the dependency-plugin to copy the jar to a known location in my target folder and then point to that, but I was hoping there would be an easier solution that doesn't require the intermediary step.

答:
To be variable expanded need to add maven-dependency-plugin:

```<code>        <!-- obtain ${*:*:jar} properties -->
        <plugin>
            <artifactId>maven-dependency-plugin</artifactId>
            <executions>
                <execution>
                    <id>getClasspathFilenames</id>
                    <goals>
                        <goal>properties</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
                <argLine>-javaagent:${org.jmockit:jmockit:jar}</argLine>
            </configuration>
        </plugin>
</code>```

Body:
I've tried to follow the configuration from this response on SO to use the jar location in my local repo as a plugin parameter, but it doesn't seem to work.  I don't know if this due to a newer Maven version than the response (I'm using Maven 3.2.5).

In my pom.xml, I need to add a javaagent to my surefire plugin definition.  The javaagent jar file is a dependency in my project.

I have tried the following:

<dependencies>
        <dependency>
            <groupId>org.jmockit</groupId>
            <artifactId>jmockit</artifactId>
            <version>${jmockit.version}</version>
            <scope>test</scope>
        </dependency>
</dependencies>

...

        <plugin>
            <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
                <argLine>-javaagent:${org.jmockit:jmockit:jar}</argLine>
            </configuration>
        </plugin>

I was expecting that the ${org.jmockit:jmockit:jar} would be expanded to the location of the jar, but in my mvn console I see the following error:

[ERROR] Command wascmd.exe /X /C "C:\IBM\SDP\jdk\jre\bin\java -javaagent:${org.jmockit:jmockit:jar} -jar C:\dev\Eclipse\rtc-connector\target\surefire\surefirebooter1389906134960134.jar C:\dev\Eclipse\rtc-connector\target\surefire\surefire5488684370604495471tmp C:\dev\Eclipse\rtc-connector\target\surefire\surefire_05402037720997438783tmp"

So obviously the parameter is not getting expanded.  I was hoping/expecting to see something like -javaagent:c:\users\eric\.m2\repository\org.jmockit\1.20\jmockit-1.20.jar or something similar.

Is there a clean way I can reference the jar from my dependency in my plugin configuration?  I know I can use the dependency-plugin to copy the jar to a known location in my target folder and then point to that, but I was hoping there would be an easier solution that doesn't require the intermediary step.

Body:
To be variable expanded need to add maven-dependency-plugin:

        <!-- obtain ${*:*:jar} properties -->
        <plugin>
            <artifactId>maven-dependency-plugin</artifactId>
            <executions>
                <execution>
                    <id>getClasspathFilenames</id>
                    <goals>
                        <goal>properties</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
                <argLine>-javaagent:${org.jmockit:jmockit:jar}</argLine>
            </configuration>
        </plugin>


问:
How to input an arbitrary number of text files in C++?
so I'm working on a coding project for a class, and I understand the basic things I want to accomplish, but one thing that nobody seems to be able to help me with is inputting an unspecified number of text files. The user is prompted to enter the text files they want to compare (overall purpose of my code), separated by spaces, thus allowing them to compare an arbitrary amount of text files (eg. 2, 3, 8, 16, etc). I know that the getline function is helpful here, as well as searching for the number of "." because files can only contain one ".", all within a for loop. After that logic I am utterly lost. Eventually, I'm going to have to open the text files and put them in sets to compare them against every other file once, and output their similarities and differences into yet another text file. Any ideas?</p>

答:
If you pass the text files on the commandline rather than getting them from a little dialog with the user via stdin life will be easier. Most users will type

```<code>compare *
</code>```

which on Unix type systems is expanded to a list of files. ON DOS you need to match and expand the wild card yourself.

You've got an N squared problem, but the logic is easy, it's just

```<code>int mian(int argc, char **argv)
{
   int i, j;
   for(i=1;i<argc;i++)
      for(j=i+1;j>argc;j++)
         compare(argv[i], argv[j];

}
</code>```

Body:
If you pass the text files on the commandline rather than getting them from a little dialog with the user via stdin life will be easier. Most users will type

compare *

which on Unix type systems is expanded to a list of files. ON DOS you need to match and expand the wild card yourself.

You've got an N squared problem, but the logic is easy, it's just

int mian(int argc, char **argv)
{
   int i, j;
   for(i=1;i<argc;i++)
      for(j=i+1;j>argc;j++)
         compare(argv[i], argv[j];

}


问:
Java JTextfields
Just a quick question,
How do i ensure my JtextField only accepts numeric values?
I want it to to diplsy an error message if the user entered anything else
thank you</p>

答: You can either add a key event listener and check each char typed in or there are document formatters (NumberFormatter) you can install that will not allow you to enter anything but a number.</p>

Title: Java JTextfields


问:
How do I combine multiple files in a directory in linux such that each files data is placed in a new column?
I have 100 files in a directory, with each file containing a single column of 1000 rows of numbers. I want to combine all these files into a single file resulting in 1000 by 100 data frame with each columns name to be the file name. Is there a way to do this in linux (terminal)?</p>

答:
This can be done with little perl script:

merge.pl

```<code>#!/usr/bin/perl

my @lines;
for my $file (@ARGV) {
    open(FI,$file) or die;
    my $i=0;
    while(<FI>) {
        chop;
        $lines[$i].="," if $lines[$i];
        $lines[$i].=$_;
        $i++;
    }
    close(FI);
}

for my $line (@lines) {
    print $line."\n";
}
</code>```

Run it with all file names that you need to merge:

```<code>./merge.pl dir/*
</code>```

Body:
This can be done with little perl script:

merge.pl

#!/usr/bin/perl

my @lines;
for my $file (@ARGV) {
    open(FI,$file) or die;
    my $i=0;
    while(<FI>) {
        chop;
        $lines[$i].="," if $lines[$i];
        $lines[$i].=$_;
        $i++;
    }
    close(FI);
}

for my $line (@lines) {
    print $line."\n";
}

Run it with all file names that you need to merge:

./merge.pl dir/*


问:
ActiveRecord::Fixture::FixtureError: table "users" has no column named "monkey"
Hi I just started coding with rails, following Michael Hartl tutorial, I got this error while writing test for my app, my fixture on test/fixtures/users.yml is:

```<code># Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html

marwane:
  name: Marwane Chahoud
  email: marwane.chahoud@gmail.com
  password_digest: <%= User.digest('password') %>

  monkey:
  name: Sterling Archer
  email: sterling.archer@strange.com
  password_digest: <%= User.digest('password') %>
</code>```

and my db schema is: db/migrate/xxxxxx_create_users.rb :

```<code>class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :name
      t.string :email

      t.timestamps null: false
    end
  end
end
</code>```

I am using ruby version : ruby 2.2.4p230 (2015-12-16 revision 53155) [i386-mingw32]
and rails version : Rails 4.2.6

Any suggestions please ?

答:
ActiveRecord::Fixture::FixtureError: table “users” has no column named
  “monkey”

I believe its due to the indentation problem. YAML files are strict in indenting. It should be

```<code>marwane:
  name: Marwane Chahoud
  email: marwane.chahoud@gmail.com
  password_digest: <%= User.digest('password') %>

monkey:
  name: Sterling Archer
  email: sterling.archer@strange.com
  password_digest: <%= User.digest('password') %>
</code>```

Since the key monkey: is indented wrongly, it is treated as attribute,so is the error.

Body:
Hi I just started coding with rails, following Michael Hartl tutorial, I got this error while writing test for my app, my fixture on test/fixtures/users.yml is:

# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html

marwane:
  name: Marwane Chahoud
  email: marwane.chahoud@gmail.com
  password_digest: <%= User.digest('password') %>

  monkey:
  name: Sterling Archer
  email: sterling.archer@strange.com
  password_digest: <%= User.digest('password') %>

and my db schema is: db/migrate/xxxxxx_create_users.rb :

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :name
      t.string :email

      t.timestamps null: false
    end
  end
end

I am using ruby version : ruby 2.2.4p230 (2015-12-16 revision 53155) [i386-mingw32]
and rails version : Rails 4.2.6

Any suggestions please ?

Body:
ActiveRecord::Fixture::FixtureError: table “users” has no column named
  “monkey”

I believe its due to the indentation problem. YAML files are strict in indenting. It should be

marwane:
  name: Marwane Chahoud
  email: marwane.chahoud@gmail.com
  password_digest: <%= User.digest('password') %>

monkey:
  name: Sterling Archer
  email: sterling.archer@strange.com
  password_digest: <%= User.digest('password') %>

Since the key monkey: is indented wrongly, it is treated as attribute,so is the error.


问:
Toggle Software Keyboard for entire test suite in appium python
Currently I am writing iOS tests using Python Appium and would like to completely hide the software keyboard which pops up whenever you have to type something. I am already aware of driver.hide_keyboard() function but it's a pain to include it everywhere in tests.

I was going over the Appium Desired Capabilites but couldn't find anything that will disable the software keyboard. Appreciate if anyone can help me here?

答:
To disable soft keyboard in iOS simulator do this:

Simulator Menu > Hardware > Keyboard > Connect Hardware Keyboard (enable it)

Even if you quit and reopen the simulator, the selection will stay. I'm not sure what happens when you factory reset the simulator.

screenshots attached.


问:
Setting ImageView width dynamically in a Xamarin Android project
I am trying to dynamically set the ImageView height in Xamarin droid project not in core.

```<code>LinearLayout layout4 = new LinearLayout(Activity);
layout4.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent);
layout4.SetGravity(GravityFlags.Center);
layout4.Orientation = Orientation.Vertical;
</code>```

I am not able to set:

```<code>layout4.Height = 20;
</code>```

Getting error: Property or indexer cannot be assigned, it is read only

答:
Use LayoutParams:</p>

```<code>LinearLayout layout4 = new LinearLayout(this);
LinearLayout.LayoutParams parameters = new LinearLayout.LayoutParams(currentWidth, 20/*desired height*/);
layout4.LayoutParameters = parameters;
</code>```

Body:
I am trying to dynamically set the ImageView height in Xamarin droid project not in core.

LinearLayout layout4 = new LinearLayout(Activity);
layout4.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent);
layout4.SetGravity(GravityFlags.Center);
layout4.Orientation = Orientation.Vertical;

I am not able to set:

layout4.Height = 20;

Getting error: Property or indexer cannot be assigned, it is read only

Body:
Use LayoutParams:

LinearLayout layout4 = new LinearLayout(this);
LinearLayout.LayoutParams parameters = new LinearLayout.LayoutParams(currentWidth, 20/*desired height*/);
layout4.LayoutParameters = parameters;