问:
MVC 5 - can not get globalisation running
I want to add globalization because the site asks the user for a date. And my german user want to type "31.12.1966" and not "1966-12-31".

So I add the nuget-Packages
"jQuery.Validation.Globalize" and
"jquery-globalize"
to the project.

Now I am not able to configure my BundleConfig! From my research I know, that I Need globalize.js and some other files. So I try to make a bündle:

```<code> bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                    "~/Scripts/jquery-{version}.js"));

        bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
            "~/Scripts/jquery.validate*"));

        bundles.Add(new ScriptBundle("~/bundles/global").Include(
           "~/Scripts/globalize.js",
           "~/Scripts/cldr.js").IncludeDirectory("~/Scripts/cldr/",
           "~/Scripts/globalize/")
           );
</code>```

The using in the view:

```<code>...
@section Scripts {

@Scripts.Render("~/bundles/global")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/unobtrusiveajax")

<script type="text/javascript">

    $(function () {
        $.validator.methods.date = function (value, element) {
            Globalize.culture("de-DE");
            // you can alternatively pass the culture to parseDate instead of
            // setting the culture above, like so:
            // parseDate(value, null, "en-AU")
            return this.optional(element) || Globalize.parseDate(value) !== null;
        }
    });
</script>
}
</code>```

But I get an error:

```<code>Error at line 9, column 5 in http://localhost:58289/Scripts/jquery.validate.globalize.js
0x800a138f - runtimeerror in JavaScript:
The property "methods" of a undefindes or null-pointer can not bei called
</code>```

I translated the message from this german original:

```<code>Ausnahmefehler in Zeile 9, Spalte 5 in http://localhost:58289/Scripts/jquery.validate.globalize.js
0x800a138f - Laufzeitfehler in JavaScript:
Die Eigenschaft "methods" eines undefinierten oder Nullverweises kann nicht abgerufen werden.
</code>```

Need I more/other files in the bundle?

What can I do? Any help?

Sincerly
Peter

答:
I solved it this way:

In my view is the following script block:

```<code><script src="~/Scripts/jquery.validate.unobtrusive.js"></script>

<script src="~/Scripts/cldr.js"></script>
<script src="~/Scripts/cldr/event.js"></script>
<script src="~/Scripts/cldr/supplemental.js"></script>
<script src="~/Scripts/cldr/unresolved.js"></script>

<script src="~/Scripts/globalize.js"></script>
<script src="~/Scripts/globalize/currency.js"></script>
<script src="~/Scripts/globalize/number.js"></script>
<script src="~/Scripts/globalize/date.js"></script>
<script src="~/Scripts/globalize/plural.js"></script>
<script src="~/Scripts/globalize/relative-time.js"></script>
<script src="~/Scripts/globalize/unit.js"></script>
<script src="~/Scripts/jquery.validate.globalize.js"></script>

<script>
    $(document).ready(function () {
        // Use $.getJSON instead of $.get if your server is not configured to return the
        // right MIME type for .json files.
        $.when(
            $.get("/Scripts/cldr/main/de/ca-gregorian.json"),
            $.get("/Scripts/cldr/main/de/numbers.json"),
            $.get("/Scripts/cldr/supplemental/likelySubtags.json"),
            $.get("/Scripts/cldr/supplemental/timeData.json"),
            $.get("/Scripts/cldr/supplemental/weekData.json")
        ).then(function () {
            // Normalize $.get results, we only need the JSON, not the request statuses.
            return [].slice.apply(arguments, [0]).map(function (result) {
                return result[0];
            });
        }).then(Globalize.load)
    .then(function () {
        Globalize.locale("de-DE");
    });
    });
</code>```

My data-class has an annotiation like this:

```<code>...
[Required]
    [DataType(DataType.DateTime)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd.MM.yyyy}")]
    public DateTime Geburtsdatum { get; set; }
...
</code>```

And - very important!! - you must get the data-files!
This is nessecary because the clrd-data is not part of the NuGet-Packages "jQuery.Validation.Globalize" / "jquery-globalize".
(Yes, it is mentioned on the Project-page - but I didn't see it... :-( )

I installed Bower (per NuGet) and installed then via Bower the Cldr-data. Example:

```<code> bower install cldr-dates-full
</code>```

(see overview over packages and install instruction 1)

Then I moved the needed json-files (here you find an online-tool for file-selection 2) from Directory "bower_components" to "scripts\cldr\main\de" respectively "scripts\cldr\supplemental".

I add them to the project and mark them as "Content", "no copy".

So finally it works!!! :-)

If I manage it to bundle the js- and json-files, I will update the answer.

Body:
I want to add globalization because the site asks the user for a date. And my german user want to type "31.12.1966" and not "1966-12-31".

So I add the nuget-Packages
"jQuery.Validation.Globalize" and
"jquery-globalize"
to the project.

Now I am not able to configure my BundleConfig! From my research I know, that I Need globalize.js and some other files. So I try to make a bündle:

 bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                    "~/Scripts/jquery-{version}.js"));

        bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
            "~/Scripts/jquery.validate*"));

        bundles.Add(new ScriptBundle("~/bundles/global").Include(
           "~/Scripts/globalize.js",
           "~/Scripts/cldr.js").IncludeDirectory("~/Scripts/cldr/",
           "~/Scripts/globalize/")
           );

The using in the view:

...
@section Scripts {

@Scripts.Render("~/bundles/global")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/unobtrusiveajax")

}

But I get an error:

Error at line 9, column 5 in http://localhost:58289/Scripts/jquery.validate.globalize.js
0x800a138f - runtimeerror in JavaScript:
The property "methods" of a undefindes or null-pointer can not bei called

I translated the message from this german original:

Ausnahmefehler in Zeile 9, Spalte 5 in http://localhost:58289/Scripts/jquery.validate.globalize.js
0x800a138f - Laufzeitfehler in JavaScript:
Die Eigenschaft "methods" eines undefinierten oder Nullverweises kann nicht abgerufen werden.

Need I more/other files in the bundle?

What can I do? Any help?

Sincerly
Peter

Body:
I solved it this way:

In my view is the following script block:

<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>

<script src="~/Scripts/cldr.js"></script>
<script src="~/Scripts/cldr/event.js"></script>
<script src="~/Scripts/cldr/supplemental.js"></script>
<script src="~/Scripts/cldr/unresolved.js"></script>

<script src="~/Scripts/globalize.js"></script>
<script src="~/Scripts/globalize/currency.js"></script>
<script src="~/Scripts/globalize/number.js"></script>
<script src="~/Scripts/globalize/date.js"></script>
<script src="~/Scripts/globalize/plural.js"></script>
<script src="~/Scripts/globalize/relative-time.js"></script>
<script src="~/Scripts/globalize/unit.js"></script>
<script src="~/Scripts/jquery.validate.globalize.js"></script>

<script>
    $(document).ready(function () {
        // Use $.getJSON instead of $.get if your server is not configured to return the
        // right MIME type for .json files.
        $.when(
            $.get("/Scripts/cldr/main/de/ca-gregorian.json"),
            $.get("/Scripts/cldr/main/de/numbers.json"),
            $.get("/Scripts/cldr/supplemental/likelySubtags.json"),
            $.get("/Scripts/cldr/supplemental/timeData.json"),
            $.get("/Scripts/cldr/supplemental/weekData.json")
        ).then(function () {
            // Normalize $.get results, we only need the JSON, not the request statuses.
            return [].slice.apply(arguments, [0]).map(function (result) {
                return result[0];
            });
        }).then(Globalize.load)
    .then(function () {
        Globalize.locale("de-DE");
    });
    });

My data-class has an annotiation like this:

...
[Required]
    [DataType(DataType.DateTime)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd.MM.yyyy}")]
    public DateTime Geburtsdatum { get; set; }
...

And - very important!! - you must get the data-files!
This is nessecary because the clrd-data is not part of the NuGet-Packages "jQuery.Validation.Globalize" / "jquery-globalize".
(Yes, it is mentioned on the Project-page - but I didn't see it... :-( )

I installed Bower (per NuGet) and installed then via Bower the Cldr-data. Example:

 bower install cldr-dates-full

(see overview over packages and install instruction 1)

Then I moved the needed json-files (here you find an online-tool for file-selection 2) from Directory "bower_components" to "scripts\cldr\main\de" respectively "scripts\cldr\supplemental".

I add them to the project and mark them as "Content", "no copy".

So finally it works!!! :-)

If I manage it to bundle the js- and json-files, I will update the answer.


来源: stackexchange

问:
Hangman Game - Duplicate characters issue in lists
I've been making a hangman game and ran into a problem with the lists. If the user input matches any of the characters in the list, the letter's place in said list is found and then added to that position in a blank list. However, words such as "television" that contain duplicate characters don't work. Instead, it will print "tel_vis_on". Sorry if this is a vague post, I don't know the terminology.</p>

```<code>def guess():
    letter = input ("Please enter a letter:")
    if letter in word:
        print ("Correct!")
        letterPlace = word.index(letter)
        answer[letterPlace] = letter
        print (*answer)
    else:
        print ("Wrong!")

    if answer == word :
        print ("You guessed it! Well Done!")
        #end here
    else:
        guess()

from random import choice
objects = ["computer","television"]
word = choice(objects)
word = (list(word))
wordcount = len(word)
answer = ["_"]*wordcount
print (*answer)
guess()
</code>```

答:
In that part:

```<code>if letter in word:
    print ("Correct!")
    letterPlace = word.index(letter)
    answer[letterPlace] = letter
</code>```

word.index(letter) will return the index of the first occurrence of the letter.

So you'll replace only the first underscore by the letter. Do that instead:

```<code>if letter in word:
    print ("Correct!")
    for letterPlace in (idx for idx,l in enumerate(word) if l==letter):
        answer[letterPlace] = letter
</code>```

the code loops and if it finds the letter, the generator expression yields the index, to replace the underscore.

ContentLicense: CC BY-SA 3.0

Body:
I've been making a hangman game and ran into a problem with the lists. If the user input matches any of the characters in the list, the letter's place in said list is found and then added to that position in a blank list. However, words such as "television" that contain duplicate characters don't work. Instead, it will print "tel_vis_on". Sorry if this is a vague post, I don't know the terminology.

def guess():
    letter = input ("Please enter a letter:")
    if letter in word:
        print ("Correct!")
        letterPlace = word.index(letter)
        answer[letterPlace] = letter
        print (*answer)
    else:
        print ("Wrong!")

    if answer == word :
        print ("You guessed it! Well Done!")
        #end here
    else:
        guess()

from random import choice
objects = ["computer","television"]
word = choice(objects)
word = (list(word))
wordcount = len(word)
answer = ["_"]*wordcount
print (*answer)
guess()

Body:
In that part:

if letter in word:
    print ("Correct!")
    letterPlace = word.index(letter)
    answer[letterPlace] = letter

word.index(letter) will return the index of the first occurrence of the letter.

So you'll replace only the first underscore by the letter. Do that instead:

if letter in word:
    print ("Correct!")
    for letterPlace in (idx for idx,l in enumerate(word) if l==letter):
        answer[letterPlace] = letter

the code loops and if it finds the letter, the generator expression yields the index, to replace the underscore.


问:
No return after executing passwd command using ssh in script
I have one script which reads hosts IP from /etc/hosts file, do ssh and update the passwords there for the given user. However, the script is closed after setting password for the first host and not able to set password for rest of the hosts. Please find below files-

/etc/hosts file-

172.x.x.x  host1

    172.x.x.x  host2

    172.x.x.x  host3

Script I am using is as-

```<code>key=$1
user=$2
password=$3
filename='/etc/hosts'
while IFS= read -r line; do
   IFS=' ' read -r -a array <<< $line
   ssh -i $key centos@${array[0]} "echo "$password" | sudo passwd $user --stdin"
done <$filename
</code>```

Script is simple. but it is getting closed after setting password for host1 from file. Does anyone has any idea, what I am missing?

答:
By default ssh reads from stdin which is your input file.ssh consumes the     rest of the file and your while loop terminates.So try using</p>

```<code>       ssh -n
</code>```

Body:
I have one script which reads hosts IP from /etc/hosts file, do ssh and update the passwords there for the given user. However, the script is closed after setting password for the first host and not able to set password for rest of the hosts. Please find below files-

/etc/hosts file-

172.x.x.x  host1

    172.x.x.x  host2

    172.x.x.x  host3

Script I am using is as-

key=$1
user=$2
password=$3
filename='/etc/hosts'
while IFS= read -r line; do
   IFS=' ' read -r -a array <<< $line
   ssh -i $key centos@${array[0]} "echo "$password" | sudo passwd $user --stdin"
done <$filename

Script is simple. but it is getting closed after setting password for host1 from file. Does anyone has any idea, what I am missing?

Body:
By default ssh reads from stdin which is your input file.ssh consumes the     rest of the file and your while loop terminates.So try using

       ssh -n


问:
Implement php into WordPress
Implementing php inside WordPress proves more difficult than I've expected.
I've made a file where all my useful functions are in, called useful_functions.inc.php, like data validation etc.

When I run my script I get to see a form and when the user submits the form all the user input gets checked via the useful_functions.inc.php.

Outside Wordpress this all works perfect, but inside is an other story.
At the moment I don't even get to see my form. Am I complete missing this up or am I missing a small detail?

```<code><?php
include_once ('scripts/useful_functions.inc.php');
global $wpdb;

if (($_SERVER["REQUEST_METHOD"] == "POST")&& $voornaamErr== "" && $familienaamErr== "" && $emailErr== "" && $telErr== "" && $afileErr== "") {
    try {
        $table = $wpdb->prefix.'sollicitaties';
        $file = rand(1000,100000)."-".$_FILES['afile']['name'];
        $file_size = $_FILES['afile']['size'];
        $file_type = $_FILES['afile']['type'];
        $file_loc = $_FILES['afile']['tmp_name'];
        $folder="wp-content/themes/jobify-extended/uploads/";
        $data = array(
            'voornaam' => $_POST['avoornaam'],
            'familienaam' => $_POST['afamilienaam'],
            'email' => $_POST['email'],
            'tel' => $_POST['tel'],
            'file' => rand(1000,100000)."-".$_FILES['afile']['name'],
            'size' => $_FILES['afile']['size'],
            'type' => $_FILES['afile']['type'],
        );
        $new_size = $file_size/1024;
        $new_file_name = strtolower($file);
        $final_file=str_replace(' ','-',$new_file_name);
        $format = array(
            '%s',
            '%s'
        );

        if(move_uploaded_file($file_loc,$folder.$final_file))
        {
            $success=$wpdb->insert( $table, $data, $format,$folder);
            if($success){
            ?>
               <script>
                alert('successfully uploaded');
                </script>
                <?php

                exit();
              }
            }
          catch(PDOException $e)
              {
              echo "Error: " . $e->getMessage();
              }

          $conn->null;

    }

    else {?>

        <form action="" method="post" enctype="multipart/form-data">
            <div class="field-wrap">
                <label>Voornaam</label><span class="error">* <?php echo $voornaamErr;?></span>
                    <input type="text" name="voornaam" value="">
            </div> <!-- /field-wrap-->

            <div class="field-wrap">
                <label>Familienaam</label><span class="error">* <?php echo $familienaamErr;?></span>
                    <input type="text" name="familienaam" value="<?= isset($_POST['familienaam']) ? $_POST['familienaam'] : ''; ?>">
            </div> <!-- /field-wrap-->

            <div class="field-wrap">
                <label>Email Adres</label><span class="error">* <?php echo $emailErr;?></span>
                    <input type="email" name="email" value="<?= isset($_POST['email']) ? $_POST['email'] : ''; ?>">
            </div> <!-- /field-wrap-->

            <div class="field-wrap">
                <label>Telefoon/GSM</label><span class="error">* <?php echo $telErr;?></span>
                    <input type="text" name="tel" value="<?= isset($_POST['tel']) ? $_POST['tel'] : ''; ?>">
            </div> <!-- /field-wrap-->

            <div class="field-wrap">
                <label>CV</label><span class="error">* <?php echo $afileErr;?></span>
                    <input type="file" name="afile" >
            </div> <!-- /field-wrap-->

        <button type="submit" class="button button-block" />Get Started</button>
        </form>
    <?php
    }
}
?>
</code>```

答:
You should use a plugin for a form, for example contact form 7.  Or develop code that would get the form data via wp-ajax or wp rest api.

That how usually its done in WordPress.

Title: Implement php into WordPress

Body:
Implementing php inside WordPress proves more difficult than I've expected.
I've made a file where all my useful functions are in, called useful_functions.inc.php, like data validation etc.

When I run my script I get to see a form and when the user submits the form all the user input gets checked via the useful_functions.inc.php.

Outside Wordpress this all works perfect, but inside is an other story.
At the moment I don't even get to see my form. Am I complete missing this up or am I missing a small detail?

<?php
include_once ('scripts/useful_functions.inc.php');
global $wpdb;

if (($_SERVER["REQUEST_METHOD"] == "POST")&& $voornaamErr== "" && $familienaamErr== "" && $emailErr== "" && $telErr== "" && $afileErr== "") {
    try {
        $table = $wpdb->prefix.'sollicitaties';
        $file = rand(1000,100000)."-".$_FILES['afile']['name'];
        $file_size = $_FILES['afile']['size'];
        $file_type = $_FILES['afile']['type'];
        $file_loc = $_FILES['afile']['tmp_name'];
        $folder="wp-content/themes/jobify-extended/uploads/";
        $data = array(
            'voornaam' => $_POST['avoornaam'],
            'familienaam' => $_POST['afamilienaam'],
            'email' => $_POST['email'],
            'tel' => $_POST['tel'],
            'file' => rand(1000,100000)."-".$_FILES['afile']['name'],
            'size' => $_FILES['afile']['size'],
            'type' => $_FILES['afile']['type'],
        );
        $new_size = $file_size/1024;
        $new_file_name = strtolower($file);
        $final_file=str_replace(' ','-',$new_file_name);
        $format = array(
            '%s',
            '%s'
        );

        if(move_uploaded_file($file_loc,$folder.$final_file))
        {
            $success=$wpdb->insert( $table, $data, $format,$folder);
            if($success){
            ?>

                <?php

                exit();
              }
            }
          catch(PDOException $e)
              {
              echo "Error: " . $e->getMessage();
              }

          $conn->null;

    }

    else {?>

        <form action="" method="post" enctype="multipart/form-data">

                Voornaam* <?php echo $voornaamErr;?>
                    <input type="text" name="voornaam" value="">

                Familienaam* <?php echo $familienaamErr;?>
                    <input type="text" name="familienaam" value="<?= isset($_POST['familienaam']) ? $_POST['familienaam'] : ''; ?>">

                Email Adres* <?php echo $emailErr;?>
                    <input type="email" name="email" value="<?= isset($_POST['email']) ? $_POST['email'] : ''; ?>">

                Telefoon/GSM* <?php echo $telErr;?>
                    <input type="text" name="tel" value="<?= isset($_POST['tel']) ? $_POST['tel'] : ''; ?>">

                CV* <?php echo $afileErr;?>
                    <input type="file" name="afile" >

        <button type="submit" class="button button-block" />Get Started</button>
        </form>
    <?php
    }
}
?>


问:
How to Swagger Annotate a Spring GET @RequestMapping having a complex Object
The issue is that I have a complex Object as Request Param for a GET-Request and after I place the Swagger Annotations inside the Object. The Swagger UI shows that the entry param is a body in which i have to place the Params.

```<code> body: {
      "modelId": 0,
      "makeId": 0
    }
</code>```

My REST controller looks like this

```<code>  @RequestMapping(method = RequestMethod.GET, value = "/model")
  public SearchModelsResponse searchModels(
      @ApiParam(value = "Search for something",
          required = true) final ModelSearch search) {...}
</code>```

And the Request object

```<code>public class ModelSearch {

  @ApiParam(value = "Something important)", required = true)
  private Long modelId;

  @ApiParam(value = "Something else important)", required = false)
  @Nullable
  private Long makeId;

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

Is there a Way to Annotate it correctly so Swagger shows it as correctly as Request Parameters and not as a body construct ?

答:
OK the solution in this kind of scenario is to manually define the Parameters, this is possible with the @ApiImplicitParam annotation.

So as result this looks like this.

```<code>  @ApiImplicitParams({
    @ApiImplicitParam(name = "modelId", value = "this is modelId", required = true, dataType = "string", paramType = "query"),
    @ApiImplicitParam(name = "makeId", value = "this is makeId", required = true, dataType = "string", paramType = "query")
  })
  @RequestMapping(method = RequestMethod.GET, value = "/model")
  public SearchModelsResponse searchModels(
      final ModelSearch search) {...}
</code>```

It's not a beautifull solution since I actually want swagger to interprete my code but the result gives the option to show it as request parameters not as a body construct.

Body:
The issue is that I have a complex Object as Request Param for a GET-Request and after I place the Swagger Annotations inside the Object. The Swagger UI shows that the entry param is a body in which i have to place the Params.

 body: {
      "modelId": 0,
      "makeId": 0
    }

My REST controller looks like this

  @RequestMapping(method = RequestMethod.GET, value = "/model")
  public SearchModelsResponse searchModels(
      @ApiParam(value = "Search for something",
          required = true) final ModelSearch search) {...}

And the Request object

public class ModelSearch {

  @ApiParam(value = "Something important)", required = true)
  private Long modelId;

  @ApiParam(value = "Something else important)", required = false)
  @Nullable
  private Long makeId;

  ....
  }

Is there a Way to Annotate it correctly so Swagger shows it as correctly as Request Parameters and not as a body construct ?

Body:
OK the solution in this kind of scenario is to manually define the Parameters, this is possible with the @ApiImplicitParam annotation.

So as result this looks like this.

  @ApiImplicitParams({
    @ApiImplicitParam(name = "modelId", value = "this is modelId", required = true, dataType = "string", paramType = "query"),
    @ApiImplicitParam(name = "makeId", value = "this is makeId", required = true, dataType = "string", paramType = "query")
  })
  @RequestMapping(method = RequestMethod.GET, value = "/model")
  public SearchModelsResponse searchModels(
      final ModelSearch search) {...}

It's not a beautifull solution since I actually want swagger to interprete my code but the result gives the option to show it as request parameters not as a body construct.


问:
How to get the date from jQuery UI datepicker (yes...again)
I am a beginner here and cannot seem to get the value out of my "inline" datepicker to be used latter as an 'attribute' with a value 'date'.  If I use the 'input' instead of the inline (called with div) then I have no problems and my conditional check also works.

But trying to make the conditional check and return the selected date as the 'date' attribute doesn't work.

Can someone please suggest the correction I need to make to the code below? Very grateful for any help.

```<code>{{ '//code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css' | stylesheet_tag }}
{{ '//ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js' | script_tag }}

<div style="clear:both;">
  <p>
<label for="date">Select DELIVERY DATE:</label>
<div id="date" type="hidden" name="attributes[Delivery Date]" value="{{ cart.attributes.date }}"/>
<span style="display:block" class="instructions"> </span>
</code>```

```<code><script>
  jQuery(function() {
  jQuery("#date").datepicker( {
    minDate: 0,
    maxDate: '+3M',
    dateFormat: "dd/mm/yy",
    beforeShowDay: noSunday
      });
      function noSunday(date){
          var day = date.getDay();
                  return [(day > 0), ''];
      };
});
</script>

<script>
jQuery("#date").datepicker({
   onSelect: function(dateText, inst) {
      var dateAsString = dateText; //the first parameter of this function
      var dateAsObject = $(this).datepicker( 'getDate' ); //the getDate method
   }
});
</script>

<script>
    jQuery(document).ready(function() {

    jQuery('input[name="checkout"], input[name="goto_pp"], input[name="goto_gc"]').click(function() {
        if (jQuery('#date').val() == '') {
            alert("You must pick a delivery date before proceeding to checkout");
            return false;
        } else {
            jQuery(this).submit();
        }
    });
});
</script>
</code>```

答:
To get the date of a jQueryUI datepicker, you have to call getDate on it like this:

```<code>var currentDate = $(".selector").datepicker("getDate");
</code>```

currentDate is a javascript Date object (not a string).

If you want to make some operations, checks, ... on dates, I suggest you to take a look to MomentJS (http://momentjs.com/)

Body:
I am a beginner here and cannot seem to get the value out of my "inline" datepicker to be used latter as an 'attribute' with a value 'date'.  If I use the 'input' instead of the inline (called with div) then I have no problems and my conditional check also works.

But trying to make the conditional check and return the selected date as the 'date' attribute doesn't work.

Can someone please suggest the correction I need to make to the code below? Very grateful for any help.

{{ '//code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css' | stylesheet_tag }}
{{ '//ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js' | script_tag }}

Select DELIVERY DATE:

Body:
To get the date of a jQueryUI datepicker, you have to call getDate on it like this:

var currentDate = $(".selector").datepicker("getDate");

currentDate is a javascript Date object (not a string).

If you want to make some operations, checks, ... on dates, I suggest you to take a look to MomentJS (http://momentjs.com/)


问:
Simultaneously assign many instances' properties
Suppose I have a class:

```<code>class Foo:
    def __init__(self):
        self.prop = None
</code>```

I need to do:

```<code>[foo1.prop, foo2.prop, ..., fooN.prop] = [prop_value1, prop_value2, ..., prop_value3]
</code>```

Obviously, N is not the same always, so I should do it dynamically. The first approach is do it with a for loop:

```<code>for foo, value in zip(foo_list, value_list):
    foo.prop = value
</code>```

But the question is... Is there a better approach in Python? I mean higher performance.

By the way, N > 1000.

答:
"Is there a better approach in Python? I mean higher performance."

I don't believe there is. Let's do a few timed experiments. First, consider an alternative way of performing your assignment: You can use a setter for your class, and call that setter inside a comprehension/map.

```<code>class Foo:
    def __init__(self):
        self.prop = None
    def setProp(self, prop):
        self.prop = prop
</code>```

Now, you can do this:

```<code>from functools import partial
f = partial(Foo.setProp)

fooList = [...]
propList = [...]

list(map(f, fooList, propList))
</code>```

This works as expected. We can use timeit to get some timed results with N = 1000:

For loop approach

10000 loops, best of 3: 95.8 µs per loop

Map approach

1000 loops, best of 3: 199 µs per loop

Conclusion: It seems that the timings differ by a factor of 2. I believe that nothing can beat a for loop for this particular use case, it's a syntax of the language and faster than using any function.

ContentLicense: CC BY-SA 4.0

Body:
Suppose I have a class:

class Foo:
    def __init__(self):
        self.prop = None

I need to do:

[foo1.prop, foo2.prop, ..., fooN.prop] = [prop_value1, prop_value2, ..., prop_value3]

Obviously, N is not the same always, so I should do it dynamically. The first approach is do it with a for loop:

for foo, value in zip(foo_list, value_list):
    foo.prop = value

But the question is... Is there a better approach in Python? I mean higher performance.

By the way, N > 1000.

Body:
"Is there a better approach in Python? I mean higher performance."

I don't believe there is. Let's do a few timed experiments. First, consider an alternative way of performing your assignment: You can use a setter for your class, and call that setter inside a comprehension/map.

class Foo:
    def __init__(self):
        self.prop = None
    def setProp(self, prop):
        self.prop = prop

Now, you can do this:

from functools import partial
f = partial(Foo.setProp)

fooList = [...]
propList = [...]

list(map(f, fooList, propList))

This works as expected. We can use timeit to get some timed results with N = 1000:

For loop approach

10000 loops, best of 3: 95.8 µs per loop

Map approach

1000 loops, best of 3: 199 µs per loop

Conclusion: It seems that the timings differ by a factor of 2. I believe that nothing can beat a for loop for this particular use case, it's a syntax of the language and faster than using any function.


问:
Search for key inside dictionary and print values- Javascript
I have a dictionary that looks a little like this:

```<code>var index = {
  "Italian": [
    {
      "name": "Il Brigante",
      "rating": "5.0"
    },
    {
      "name": "Giardino Doro Ristorante",
      "rating": "5.0"
    }
  ],
  "Mexican": [
    {
      "name": "Cosme",
      "rating": "5.0"
    }
  ]
}
</code>```

I also have a search bar that people can enter queries into. What I want to do is take the query and search for it inside index.

Example: search = "italian", results = {"name": "Il Brigante", "rating": "5.0"}, {"name": "Giardino Doro Ristorante", "rating": "5.0"}

Is that kind of search possible? Any help would be appreciated. Thanks so much in advance. Happy 4th!

Cheers,
Theoi

答:
You can use hasOwnProperty directly, but that will only return exact matches.  Simplest way is to loop through the index properties and look for a match and return the resulting value.

var index = {
  "Italian": [
    {
      "name": "Il Brigante",
      "rating": "5.0"
    },
    {
      "name": "Giardino Doro Ristorante",
      "rating": "5.0"
    }
  ],
  "Mexican": [
    {
      "name": "Cosme",
      "rating": "5.0"
    }
  ]
}

console.log(index.hasOwnProperty('italian'));
console.log(index.hasOwnProperty('Italian'));
console.log(dictionarySearch('Italian', index));

function dictionarySearch(term, dictionary)
{
  var found = false;
  if (typeof dictionary === 'object') {
    for(property in dictionary) {
      if (dictionary.hasOwnProperty(property)) {
        if (property.toLowerCase() === term.toLowerCase()) {
          found = dictionary[property];
        }
      }
    }
  }

  return found;
}```

Body:
I have a dictionary that looks a little like this:

var index = {
  "Italian": [
    {
      "name": "Il Brigante",
      "rating": "5.0"
    },
    {
      "name": "Giardino Doro Ristorante",
      "rating": "5.0"
    }
  ],
  "Mexican": [
    {
      "name": "Cosme",
      "rating": "5.0"
    }
  ]
}

I also have a search bar that people can enter queries into. What I want to do is take the query and search for it inside index.

Example: search = "italian", results = {"name": "Il Brigante", "rating": "5.0"}, {"name": "Giardino Doro Ristorante", "rating": "5.0"}

Is that kind of search possible? Any help would be appreciated. Thanks so much in advance. Happy 4th!

Cheers,
Theoi


问:
Symfony 3 - Asset:install - Permission error
Doing the php bin/console assets:install --symlink command doesn't do anything.
To be clear : the folder /bundles is created but it's empty.

With the verbose, I get this :

```<code> Trying to install assets as absolute symbolic links.

13:54:13 DEBUG     [php] Warning: unlink(web/bundles/main): No such file or directory
[
  "exception" => Symfony\Component\Debug\Exception\SilencedErrorContext {
    +count: 1,
    -severity: E_WARNING,
    trace: {
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Filesystem\Filesystem.php:178: {
        :     },
        : } elseif (!@unlink($file) && file_exists($file)) {,
        :     $error = error_get_last();
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Command\AssetsInstallCommand.php:133: {
        : try {,
        :     $this->filesystem->remove($targetDir);,
        :
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Console\Command\Command.php:264: {
        : } else {,
        :     $statusCode = $this->execute($input, $output);,
        : }
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Console\Application.php:887: {
        : if ($event->commandShouldRun()) {,
        :     $exitCode = $command->run($input, $output);,
        : } else {
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Console\Application.php:223: {
        : $this->runningCommand = $command;,
        : $exitCode = $this->doRunCommand($command, $input, $output);,
        : $this->runningCommand = null;
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Console\Application.php:81: {
        : ,
        :     return parent::doRun($input, $output);,
        : }
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Console\Application.php:130: {
        :     $e = null;,
        :     $exitCode = $this->doRun($input, $output);,
        : } catch (\Exception $x) {
      },
      ***\Symfony\bin\console:28: {
        : $application = new Application($kernel);,
        : $application->run($input);,
        :
      }
    }
  }
]
[]
13:54:13 DEBUG     [php] Warning: unlink(web/bundles/coresphereconsole): No such file or directory
[
  "exception" => Symfony\Component\Debug\Exception\SilencedErrorContext {
    +count: 1,
    -severity: E_WARNING,
    trace: {
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Filesystem\Filesystem.php:178: {
        :     },
        : } elseif (!@unlink($file) && file_exists($file)) {,
        :     $error = error_get_last();
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Command\AssetsInstallCommand.php:133: {
        : try {,
        :     $this->filesystem->remove($targetDir);,
        :
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Console\Command\Command.php:264: {
        : } else {,
        :     $statusCode = $this->execute($input, $output);,
        : }
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Console\Application.php:887: {
        : if ($event->commandShouldRun()) {,
        :     $exitCode = $command->run($input, $output);,
        : } else {
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Console\Application.php:223: {
        : $this->runningCommand = $command;,
        : $exitCode = $this->doRunCommand($command, $input, $output);,
        : $this->runningCommand = null;
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Console\Application.php:81: {
        : ,
        :     return parent::doRun($input, $output);,
        : }
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Console\Application.php:130: {
        :     $e = null;,
        :     $exitCode = $this->doRun($input, $output);,
        : } catch (\Exception $x) {
      },
      ***\Symfony\bin\console:28: {
        : $application = new Application($kernel);,
        : $application->run($input);,
        :
      }
    }
  }
]
[]
13:54:13 DEBUG     [php] Warning: unlink(web/bundles\coresphereconsole): Permission denied
[
  "exception" => Symfony\Component\Debug\Exception\SilencedErrorContext {
    +count: 1,
    -severity: E_WARNING,
    trace: {
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Filesystem\Filesystem.php:167: {
        : // See https://bugs.php.net/52176,
        : if (!@(unlink($file) || '\\' !== DIRECTORY_SEPARATOR || rmdir($file)) && file_exists($file)) {,
        :     $error = error_get_last();
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Command\AssetsInstallCommand.php:161: {
        : if (!in_array($dir, $validAssetDirs)) {,
        :     $this->filesystem->remove($dir);,
        : }
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Console\Command\Command.php:264: {
        : } else {,
        :     $statusCode = $this->execute($input, $output);,
        : }
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Console\Application.php:887: {
        : if ($event->commandShouldRun()) {,
        :     $exitCode = $command->run($input, $output);,
        : } else {
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Console\Application.php:223: {
        : $this->runningCommand = $command;,
        : $exitCode = $this->doRunCommand($command, $input, $output);,
        : $this->runningCommand = null;
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Console\Application.php:81: {
        : ,
        :     return parent::doRun($input, $output);,
        : }
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Console\Application.php:130: {
        :     $e = null;,
        :     $exitCode = $this->doRun($input, $output);,
        : } catch (\Exception $x) {
      },
      ***\Symfony\bin\console:28: {
        : $application = new Application($kernel);,
        : $application->run($input);,
        :
      }
    }
  }
]
[]
13:54:13 DEBUG     [php] Warning: unlink(web/bundles\main): Permission denied
[
  "exception" => Symfony\Component\Debug\Exception\SilencedErrorContext {
    +count: 1,
    -severity: E_WARNING,
    trace: {
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Filesystem\Filesystem.php:167: {
        : // See https://bugs.php.net/52176,
        : if (!@(unlink($file) || '\\' !== DIRECTORY_SEPARATOR || rmdir($file)) && file_exists($file)) {,
        :     $error = error_get_last();
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Command\AssetsInstallCommand.php:161: {
        : if (!in_array($dir, $validAssetDirs)) {,
        :     $this->filesystem->remove($dir);,
        : }
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Console\Command\Command.php:264: {
        : } else {,
        :     $statusCode = $this->execute($input, $output);,
        : }
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Console\Application.php:887: {
        : if ($event->commandShouldRun()) {,
        :     $exitCode = $command->run($input, $output);,
        : } else {
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Console\Application.php:223: {
        : $this->runningCommand = $command;,
        : $exitCode = $this->doRunCommand($command, $input, $output);,
        : $this->runningCommand = null;
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Console\Application.php:81: {
        : ,
        :     return parent::doRun($input, $output);,
        : }
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Console\Application.php:130: {
        :     $e = null;,
        :     $exitCode = $this->doRun($input, $output);,
        : } catch (\Exception $x) {
      },
      ***\Symfony\bin\console:28: {
        : $application = new Application($kernel);,
        : $application->run($input);,
        :
      }
    }
  }
]
[]
 ---- ---------------------------------- ------------------
       Bundle                             Method / Error
 ---- ---------------------------------- ------------------
  OK   MainBundle                         absolute symlink
       -> web/bundles/main
  OK   CoreSphereConsoleBundle            absolute symlink
       -> web/bundles/coresphereconsole
 ---- ---------------------------------- ------------------

 [OK] All assets were successfully installed.
</code>```

I launched the console as administrator, cleaned the cache...
It's really weird.

I'm using windows.

I think doing php composer.phar update broke something because it has updated symfony from 3.3.2 to 3.3.3 and installed twig/extensions.

It worked before that...

Thanks for the help !

答:
AUTO ANSWER : https://github.com/symfony/symfony/issues/23373

Seems to be a problem related to Symfony 3.3.3...

Body:
Doing the php bin/console assets:install --symlink command doesn't do anything.
To be clear : the folder /bundles is created but it's empty.

With the verbose, I get this :

 Trying to install assets as absolute symbolic links.

13:54:13 DEBUG     [php] Warning: unlink(web/bundles/main): No such file or directory
[
  "exception" => Symfony\Component\Debug\Exception\SilencedErrorContext {
    +count: 1,
    -severity: E_WARNING,
    trace: {
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Filesystem\Filesystem.php:178: {
        :     },
        : } elseif (!@unlink($file) && file_exists($file)) {,
        :     $error = error_get_last();
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Command\AssetsInstallCommand.php:133: {
        : try {,
        :     $this->filesystem->remove($targetDir);,
        :
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Console\Command\Command.php:264: {
        : } else {,
        :     $statusCode = $this->execute($input, $output);,
        : }
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Console\Application.php:887: {
        : if ($event->commandShouldRun()) {,
        :     $exitCode = $command->run($input, $output);,
        : } else {
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Console\Application.php:223: {
        : $this->runningCommand = $command;,
        : $exitCode = $this->doRunCommand($command, $input, $output);,
        : $this->runningCommand = null;
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Console\Application.php:81: {
        : ,
        :     return parent::doRun($input, $output);,
        : }
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Console\Application.php:130: {
        :     $e = null;,
        :     $exitCode = $this->doRun($input, $output);,
        : } catch (\Exception $x) {
      },
      ***\Symfony\bin\console:28: {
        : $application = new Application($kernel);,
        : $application->run($input);,
        :
      }
    }
  }
]
[]
13:54:13 DEBUG     [php] Warning: unlink(web/bundles/coresphereconsole): No such file or directory
[
  "exception" => Symfony\Component\Debug\Exception\SilencedErrorContext {
    +count: 1,
    -severity: E_WARNING,
    trace: {
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Filesystem\Filesystem.php:178: {
        :     },
        : } elseif (!@unlink($file) && file_exists($file)) {,
        :     $error = error_get_last();
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Command\AssetsInstallCommand.php:133: {
        : try {,
        :     $this->filesystem->remove($targetDir);,
        :
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Console\Command\Command.php:264: {
        : } else {,
        :     $statusCode = $this->execute($input, $output);,
        : }
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Console\Application.php:887: {
        : if ($event->commandShouldRun()) {,
        :     $exitCode = $command->run($input, $output);,
        : } else {
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Console\Application.php:223: {
        : $this->runningCommand = $command;,
        : $exitCode = $this->doRunCommand($command, $input, $output);,
        : $this->runningCommand = null;
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Console\Application.php:81: {
        : ,
        :     return parent::doRun($input, $output);,
        : }
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Console\Application.php:130: {
        :     $e = null;,
        :     $exitCode = $this->doRun($input, $output);,
        : } catch (\Exception $x) {
      },
      ***\Symfony\bin\console:28: {
        : $application = new Application($kernel);,
        : $application->run($input);,
        :
      }
    }
  }
]
[]
13:54:13 DEBUG     [php] Warning: unlink(web/bundles\coresphereconsole): Permission denied
[
  "exception" => Symfony\Component\Debug\Exception\SilencedErrorContext {
    +count: 1,
    -severity: E_WARNING,
    trace: {
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Filesystem\Filesystem.php:167: {
        : // See https://bugs.php.net/52176,
        : if (!@(unlink($file) || '\\' !== DIRECTORY_SEPARATOR || rmdir($file)) && file_exists($file)) {,
        :     $error = error_get_last();
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Command\AssetsInstallCommand.php:161: {
        : if (!in_array($dir, $validAssetDirs)) {,
        :     $this->filesystem->remove($dir);,
        : }
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Console\Command\Command.php:264: {
        : } else {,
        :     $statusCode = $this->execute($input, $output);,
        : }
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Console\Application.php:887: {
        : if ($event->commandShouldRun()) {,
        :     $exitCode = $command->run($input, $output);,
        : } else {
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Console\Application.php:223: {
        : $this->runningCommand = $command;,
        : $exitCode = $this->doRunCommand($command, $input, $output);,
        : $this->runningCommand = null;
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Console\Application.php:81: {
        : ,
        :     return parent::doRun($input, $output);,
        : }
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Console\Application.php:130: {
        :     $e = null;,
        :     $exitCode = $this->doRun($input, $output);,
        : } catch (\Exception $x) {
      },
      ***\Symfony\bin\console:28: {
        : $application = new Application($kernel);,
        : $application->run($input);,
        :
      }
    }
  }
]
[]
13:54:13 DEBUG     [php] Warning: unlink(web/bundles\main): Permission denied
[
  "exception" => Symfony\Component\Debug\Exception\SilencedErrorContext {
    +count: 1,
    -severity: E_WARNING,
    trace: {
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Filesystem\Filesystem.php:167: {
        : // See https://bugs.php.net/52176,
        : if (!@(unlink($file) || '\\' !== DIRECTORY_SEPARATOR || rmdir($file)) && file_exists($file)) {,
        :     $error = error_get_last();
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Command\AssetsInstallCommand.php:161: {
        : if (!in_array($dir, $validAssetDirs)) {,
        :     $this->filesystem->remove($dir);,
        : }
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Console\Command\Command.php:264: {
        : } else {,
        :     $statusCode = $this->execute($input, $output);,
        : }
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Console\Application.php:887: {
        : if ($event->commandShouldRun()) {,
        :     $exitCode = $command->run($input, $output);,
        : } else {
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Console\Application.php:223: {
        : $this->runningCommand = $command;,
        : $exitCode = $this->doRunCommand($command, $input, $output);,
        : $this->runningCommand = null;
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Console\Application.php:81: {
        : ,
        :     return parent::doRun($input, $output);,
        : }
      },
      ***\Symfony\vendor\symfony\symfony\src\Symfony\Component\Console\Application.php:130: {
        :     $e = null;,
        :     $exitCode = $this->doRun($input, $output);,
        : } catch (\Exception $x) {
      },
      ***\Symfony\bin\console:28: {
        : $application = new Application($kernel);,
        : $application->run($input);,
        :
      }
    }
  }
]
[]
 ---- ---------------------------------- ------------------
       Bundle                             Method / Error
 ---- ---------------------------------- ------------------
  OK   MainBundle                         absolute symlink
       -> web/bundles/main
  OK   CoreSphereConsoleBundle            absolute symlink
       -> web/bundles/coresphereconsole
 ---- ---------------------------------- ------------------

 [OK] All assets were successfully installed.

I launched the console as administrator, cleaned the cache...
It's really weird.

I'm using windows.

I think doing php composer.phar update broke something because it has updated symfony from 3.3.2 to 3.3.3 and installed twig/extensions.

It worked before that...

Thanks for the help !


答:
You can try to use this plugin:
https://wordpress.org/plugins/exec-php/

or this one:
https://wordpress.org/plugins/insert-php-code-snippet/

or...
https://wordpress.org/plugins/php-everywhere/

For in the past I used the first one and it worked fine.

Title: Implement php into WordPress


问:
Why is conditional clause comparing dataframe columns causing error even though conditional clause is boolean in nature?
I am trying to build logic that compares two columns in a dataframe after some logic has been verified.

Here is my code, it is pulling historical rates for cryptocurrency data from gdax.com. The test condition I am applying is 'if df.column 4 is greater than sum of df.column4 and df.column3 then buy 10% of account'

```<code>import GDAX
import pandas as pd
import numpy as np

public_client = GDAX.PublicClient()
ticker_call = public_client.getProductHistoricRates(product='LTC-USD')

df = pd.DataFrame(ticker_call)

df['account']=100

if df[4] > df[3] + df[4]:
    df['account_new'] = df['account']-df['account'] *.10
    print df
</code>```

I am getting the error 'ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().' for the if statement, what I dont understand is why? when I run each of the lines in the if statement individually they work. How can I fix this issue?

Why and how do I use a.bool() instead of an if statement?

thank you in advance.

答:
```<code>df[4] > df[3] + df[4]
</code>```

(that actually is equivalent to df[3] < 0) is a pandas.Series of boolean values. When do you want to enter the if statement? When all values are True? then you should use all(). When any of them is True? Then you should use any().

If instead you want to execute that function for any row when the condition is True, you should do something like

```<code>condition = df[4] > df[3] + df[4]
true_df = df[condition]
true_df["account_new"] = true_df['account']-true_df['account'] *.10
</code>```

but now the columns "account_new" exists only in true_df, and not in df.

With something like

```<code>df["account_new"] = true_df["account_new"]
</code>```

now also df has the column "account_new", but in the lines where condition is false you have nans...

Body:
I am trying to build logic that compares two columns in a dataframe after some logic has been verified.

Here is my code, it is pulling historical rates for cryptocurrency data from gdax.com. The test condition I am applying is 'if df.column 4 is greater than sum of df.column4 and df.column3 then buy 10% of account'

import GDAX
import pandas as pd
import numpy as np

public_client = GDAX.PublicClient()
ticker_call = public_client.getProductHistoricRates(product='LTC-USD')

df = pd.DataFrame(ticker_call)

df['account']=100

if df[4] > df[3] + df[4]:
    df['account_new'] = df['account']-df['account'] *.10
    print df

I am getting the error 'ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().' for the if statement, what I dont understand is why? when I run each of the lines in the if statement individually they work. How can I fix this issue?

Why and how do I use a.bool() instead of an if statement?

thank you in advance.

Body:
df[4] > df[3] + df[4]

(that actually is equivalent to df[3] < 0) is a pandas.Series of boolean values. When do you want to enter the if statement? When all values are True? then you should use all(). When any of them is True? Then you should use any().

If instead you want to execute that function for any row when the condition is True, you should do something like

condition = df[4] > df[3] + df[4]
true_df = df[condition]
true_df["account_new"] = true_df['account']-true_df['account'] *.10

but now the columns "account_new" exists only in true_df, and not in df.

With something like

df["account_new"] = true_df["account_new"]

now also df has the column "account_new", but in the lines where condition is false you have nans...


问:
Android Studio error - Inconvertible types, Cannot cast Fragment
enter image description hereTrying to make a simple program using fragments. the exact error I get is :

```<code>"Inconvertible types, Cannot cast android.app.Fragment to com.example.something.something.WorkoutDetailFragment"
</code>```

Code:

```<code>public class MainActivity extends Activity {

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);

         WorkoutDetailFragment frag = (WorkoutDetailFragment) getFragmentManager().findFragmentById(R.id.detail_frag); //ERROR!
         frag.setWorkoutid(1);
     }
</code>```

}

(my activity_main_xml code)

答: Your WorkoutDetailFragment should extends android.app.Fragment, not android.support.v4.app.Fragment. Try it out~</p>

Body:
enter image description hereTrying to make a simple program using fragments. the exact error I get is :

"Inconvertible types, Cannot cast android.app.Fragment to com.example.something.something.WorkoutDetailFragment"

Code:

public class MainActivity extends Activity {

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);

         WorkoutDetailFragment frag = (WorkoutDetailFragment) getFragmentManager().findFragmentById(R.id.detail_frag); //ERROR!
         frag.setWorkoutid(1);
     }

}

(my activity_main_xml code)


问:
PopupWindow how to change icon and background programmatically?
Have is xml file for PopupWindow:

How to programmatically replace the icon and Backgroud in this xml?

答:
```<code>LinearLayout menuLayout= (LinearLayout) activity.getLayoutInflater().inflate(menuId, null);

int layoutCount = menuLayout.getChildCount();
for (int i = 0; i < layoutCount; i++)
{
    View itemView = menuLayout.getChildAt(i);
    if (itemView instanceof LinearLayout)
    {
        LinearLayout itemLayout = (LinearLayout) itemView;
        int count = ((LinearLayout) itemView).getChildCount();
        for (int j = 0; j < count; j++)
        {
            View view = itemLayout.getChildAt(j);
            if (view instanceof ImageView)
                ((ImageView) view).setImageResource(R.drawable.newImage);
        }
    }
 }
</code>```

You can find items using findViewById.

Body:
LinearLayout menuLayout= (LinearLayout) activity.getLayoutInflater().inflate(menuId, null);

int layoutCount = menuLayout.getChildCount();
for (int i = 0; i < layoutCount; i++)
{
    View itemView = menuLayout.getChildAt(i);
    if (itemView instanceof LinearLayout)
    {
        LinearLayout itemLayout = (LinearLayout) itemView;
        int count = ((LinearLayout) itemView).getChildCount();
        for (int j = 0; j < count; j++)
        {
            View view = itemLayout.getChildAt(j);
            if (view instanceof ImageView)
                ((ImageView) view).setImageResource(R.drawable.newImage);
        }
    }
 }

You can find items using findViewById.


问:
mysql - query inside a query
How is it possible to do the following :
(i am using mysql - phpmyadmin )

this query returns a table name :

```<code>Select table_name from Table1 where id = 1
</code>```

I want to use it inside another query , like :

```<code>select val from (Select table_name from Table1 where id = 1)
</code>```

but this sure does not work, and since phpmyadmin does not support calling stored procedures, could there be any possible solution for this ?

答:
You cannot really do it in a single SQL statement.

You are trying to use data (field value) as metadata (table name), and SQL does not allow this.

You could break it in two statements or write dynamic SQL in a stored procedure. Note that not all client layers support returning resultsets from stored procedures.

ContentLicense: CC BY-SA 2.5

Title: mysql - query inside a query

Body:
How is it possible to do the following :
(i am using mysql - phpmyadmin )

this query returns a table name :

Select table_name from Table1 where id = 1

I want to use it inside another query , like :

select val from (Select table_name from Table1 where id = 1)

but this sure does not work, and since phpmyadmin does not support calling stored procedures, could there be any possible solution for this ?


问:
spring JNDI logging before logback is initialized
I've got a spring boot app that is outputing around 1500 lines of JNDI debug logging to stdout at startup before logback is initialized. Does anyone know what's causing this and if there is a way to get logback initialized before this? I've got -Dlogback.debug=true but it doesn't help much.</p>

```<code>10:44:56.453 [main] DEBUG org.springframework.jndi.JndiTemplate - Looking up JNDI object with name [java:comp/env/logging.exception-conversion-word]
10:44:56.457 [main] DEBUG jndi - InitialContextFactory.getInitialContext()
10:44:56.457 [main] DEBUG jndi - Created initial context delegate for local namespace:org.eclipse.jetty.jndi.local.localContextRoot@564fabc8
10:44:56.457 [main] DEBUG org.eclipse.jetty.jndi.java.javaURLContextFactory - >>> new root context requested
10:44:56.457 [main] DEBUG jndi - Looking up name="comp/env/logging.exception-conversion-word"
10:44:56.457 [main] DEBUG jndi - Trying thread context classloader
10:44:56.457 [main] DEBUG jndi - Looking up name="env/logging.exception-conversion-word"
10:44:56.458 [main] DEBUG org.springframework.jndi.JndiLocatorDelegate - Converted JNDI name [java:comp/env/logging.exception-conversion-word] not found - trying original name [logging.exception-conversion-word]. javax.naming.NameNotFoundException; remaining name 'env/logging.exception-conversion-word'
10:44:56.458 [main] DEBUG org.springframework.jndi.JndiTemplate - Looking up JNDI object with name [logging.exception-conversion-word]

...

10:44:56.487 [main] DEBUG jndi - Looking up name="env/LOGGING_PATTERNLEVEL"
10:44:56.487 [main] DEBUG org.springframework.jndi.JndiLocatorDelegate - Converted JNDI name [java:comp/env/LOGGING_PATTERNLEVEL] not found - trying original name [LOGGING_PATTERNLEVEL]. javax.naming.NameNotFoundException; remaining name 'env/LOGGING_PATTERNLEVEL'
10:44:56.487 [main] DEBUG org.springframework.jndi.JndiTemplate - Looking up JNDI object with name [LOGGING_PATTERNLEVEL]
10:44:56.487 [main] DEBUG jndi - InitialContextFactory.getInitialContext()
10:44:56.487 [main] DEBUG jndi - Created initial context delegate for local namespace:org.eclipse.jetty.jndi.local.localContextRoot@bcec361
10:44:56.487 [main] DEBUG jndi - Looking up name="LOGGING_PATTERNLEVEL"
10:44:56.487 [main] DEBUG org.springframework.jndi.JndiPropertySource - JNDI lookup for name [LOGGING_PATTERNLEVEL] threw NamingException with message: null. Returning null.
10:44:56,536 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.ConsoleAppender]
10:44:56,539 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [STDOUT]
10:44:56,543 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
10:44:56,561 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.rolling.RollingFileAppender]
10:44:56,564 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [FILE]
10:44:56,565 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
10:44:56,571 |-INFO in my.log.TimestampRollingPolicy@24fcf36f - Will use the pattern /tmp/logs/qs.%d{yyyyMMdd-HHmmss}.log to archive files
10:44:56,574 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[FILE] - Active log file name: /tmp/logs/qs.log
10:44:56,574 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[FILE] - File property is set to [/tmp/logs/qs.log]
10:44:56,576 |-INFO in ch.qos.logback.classic.joran.action.RootLoggerAction - Setting level of ROOT logger to WARN
10:44:56,576 |-INFO in ch.qos.logback.classic.jul.LevelChangePropagator@4a7f959b - Propagating WARN level on Logger[ROOT] onto the JUL framework
10:44:56,576 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [FILE] to Logger[ROOT]
10:44:56,576 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [STDOUT] to Logger[ROOT]
10:44:56,576 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration.
10:44:56,577 |-INFO in org.springframework.boot.logging.logback.SpringBootJoranConfigurator@32b260fa - Registering current configuration as safe fallback point

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.4.4.RELEASE)

10:44:56,750 |-INFO in c.q.l.co.rolling.helper.RenameUtil - Renaming file [/tmp/logs/qs.log] to [/tmp/logs/qs.20170222-173130.log]
10:44:56 [main] INFO  my.Application - Starting ...
</code>```

答:
I also had the same problem, but I couldn't turn off jndi, because my application is using it on startup. So after some research, I ended up with the solution:

1) rename logback-spring.xml to some other name, for example logback-config.xml

2) put logging.config property into application.properties file.

As the result you configuration will be applied only on spring startup, and this debug logging will be skipped. Also in my case the first solution wasn't working because I needed jndi, in this case you also leave jndi enabled.

Update: this helped only for local environment, to make the same work on remote tomcat and remove this debug log from catalina.log file, I ended up with renaming this logback file to logback.xml, thus it's found on the startup, before jndi lookup.

Body:
I've got a spring boot app that is outputing around 1500 lines of JNDI debug logging to stdout at startup before logback is initialized. Does anyone know what's causing this and if there is a way to get logback initialized before this? I've got -Dlogback.debug=true but it doesn't help much.

10:44:56.453 [main] DEBUG org.springframework.jndi.JndiTemplate - Looking up JNDI object with name [java:comp/env/logging.exception-conversion-word]
10:44:56.457 [main] DEBUG jndi - InitialContextFactory.getInitialContext()
10:44:56.457 [main] DEBUG jndi - Created initial context delegate for local namespace:org.eclipse.jetty.jndi.local.localContextRoot@564fabc8
10:44:56.457 [main] DEBUG org.eclipse.jetty.jndi.java.javaURLContextFactory - >>> new root context requested
10:44:56.457 [main] DEBUG jndi - Looking up name="comp/env/logging.exception-conversion-word"
10:44:56.457 [main] DEBUG jndi - Trying thread context classloader
10:44:56.457 [main] DEBUG jndi - Looking up name="env/logging.exception-conversion-word"
10:44:56.458 [main] DEBUG org.springframework.jndi.JndiLocatorDelegate - Converted JNDI name [java:comp/env/logging.exception-conversion-word] not found - trying original name [logging.exception-conversion-word]. javax.naming.NameNotFoundException; remaining name 'env/logging.exception-conversion-word'
10:44:56.458 [main] DEBUG org.springframework.jndi.JndiTemplate - Looking up JNDI object with name [logging.exception-conversion-word]

...

10:44:56.487 [main] DEBUG jndi - Looking up name="env/LOGGING_PATTERNLEVEL"
10:44:56.487 [main] DEBUG org.springframework.jndi.JndiLocatorDelegate - Converted JNDI name [java:comp/env/LOGGING_PATTERNLEVEL] not found - trying original name [LOGGING_PATTERNLEVEL]. javax.naming.NameNotFoundException; remaining name 'env/LOGGING_PATTERNLEVEL'
10:44:56.487 [main] DEBUG org.springframework.jndi.JndiTemplate - Looking up JNDI object with name [LOGGING_PATTERNLEVEL]
10:44:56.487 [main] DEBUG jndi - InitialContextFactory.getInitialContext()
10:44:56.487 [main] DEBUG jndi - Created initial context delegate for local namespace:org.eclipse.jetty.jndi.local.localContextRoot@bcec361
10:44:56.487 [main] DEBUG jndi - Looking up name="LOGGING_PATTERNLEVEL"
10:44:56.487 [main] DEBUG org.springframework.jndi.JndiPropertySource - JNDI lookup for name [LOGGING_PATTERNLEVEL] threw NamingException with message: null. Returning null.
10:44:56,536 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.ConsoleAppender]
10:44:56,539 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [STDOUT]
10:44:56,543 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
10:44:56,561 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.rolling.RollingFileAppender]
10:44:56,564 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [FILE]
10:44:56,565 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
10:44:56,571 |-INFO in my.log.TimestampRollingPolicy@24fcf36f - Will use the pattern /tmp/logs/qs.%d{yyyyMMdd-HHmmss}.log to archive files
10:44:56,574 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[FILE] - Active log file name: /tmp/logs/qs.log
10:44:56,574 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[FILE] - File property is set to [/tmp/logs/qs.log]
10:44:56,576 |-INFO in ch.qos.logback.classic.joran.action.RootLoggerAction - Setting level of ROOT logger to WARN
10:44:56,576 |-INFO in ch.qos.logback.classic.jul.LevelChangePropagator@4a7f959b - Propagating WARN level on Logger[ROOT] onto the JUL framework
10:44:56,576 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [FILE] to Logger[ROOT]
10:44:56,576 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [STDOUT] to Logger[ROOT]
10:44:56,576 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration.
10:44:56,577 |-INFO in org.springframework.boot.logging.logback.SpringBootJoranConfigurator@32b260fa - Registering current configuration as safe fallback point

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.4.4.RELEASE)

10:44:56,750 |-INFO in c.q.l.co.rolling.helper.RenameUtil - Renaming file [/tmp/logs/qs.log] to [/tmp/logs/qs.20170222-173130.log]
10:44:56 [main] INFO  my.Application - Starting ...


问:
Change scrollbar color on hover CSS
I'm trying to change the scrollbar color on hover in my application and for some reason, when i hover over it, it becomes red. Here's my code:

```<code>    .scroller {
position: absolute;
top: 120px;
bottom: 0;
left: 0;
right: 0;
padding: 0;
margin-bottom: 10px;
overflow: auto;
</code>```

}

```<code>    .scrooler:hover{
      color: blue;
    }
</code>```

With this code, all it does is as soon as I hover over my table, all the text becomes blue. i'm having a hard time getting only the scrollbar since I think it is directly within the table. Is there any way of targeting the scrollbar only?

答:
Try this:</p>

```<code>.scroller::-webkit-scrollbar-thumb:vertical:hover {
    background-color: #000;
}
</code>```

Title: Change scrollbar color on hover CSS

Body:
I'm trying to change the scrollbar color on hover in my application and for some reason, when i hover over it, it becomes red. Here's my code:

    .scroller {
position: absolute;
top: 120px;
bottom: 0;
left: 0;
right: 0;
padding: 0;
margin-bottom: 10px;
overflow: auto;

}

    .scrooler:hover{
      color: blue;
    }

With this code, all it does is as soon as I hover over my table, all the text becomes blue. i'm having a hard time getting only the scrollbar since I think it is directly within the table. Is there any way of targeting the scrollbar only?

Body:
Try this:

.scroller::-webkit-scrollbar-thumb:vertical:hover {
    background-color: #000;
}


问:
How to create an array of non-const C strings on the stack without repetitive code in C++03?
I'm writing a unit test for a module that takes an array of mutable C strings in C++03 with getopt. The function argument is char*const[]. I want to create the arguments on the stack inside the function. My current solution is:

```<code>char args_stor[][1024] = {
    "parser",
    "-o",
    "SomeValue"
};
char* args[] = {
    args_stor[0],
    args_stor[1],
    args_stor[2]
};
</code>```

How can I avoid the repetitive part, and if possible, transform it into one statement?

The function declaration is:

```<code>int getopt(int argc, char* const argv[], const char *optstring);
</code>```

Use case is therefore:

```<code>getopt(3, args, ":o:");
</code>```

答:
how about this?</p>

```<code>// Example program
#include <iostream>
#include <string>

int main()
{
    char *what[] = {"asd", "asd", "asd"};
}
</code>```

Body:
I'm writing a unit test for a module that takes an array of mutable C strings in C++03 with getopt. The function argument is char*const[]. I want to create the arguments on the stack inside the function. My current solution is:

char args_stor[][1024] = {
    "parser",
    "-o",
    "SomeValue"
};
char* args[] = {
    args_stor[0],
    args_stor[1],
    args_stor[2]
};

How can I avoid the repetitive part, and if possible, transform it into one statement?

The function declaration is:

int getopt(int argc, char* const argv[], const char *optstring);

Use case is therefore:

getopt(3, args, ":o:");

Body:
how about this?

// Example program
#include <iostream>
#include <string>

int main()
{
    char *what[] = {"asd", "asd", "asd"};
}


问:
Find several groups of ocurrences in String with regex Scala
I have a String like this:

```<code>val rawData = "askljdld<a>content to extract</a>lkdsjkdj<a>more content to extract</a>sdkdljk
</code>```

and I want to extract the content between the tags

I've tried this, but the end part of the regex is not working as I expected:

```<code>val regex = "<a>(.*)</a>".r
for(m <- regex.findAllIn(rawData)){
      println(m)
    }
</code>```

the output is:

```<code><a>content to extract</a>lkdsjkdj<a>more content to extract</a>
</code>```

I understand what's happening: the regex finds the first  and the last .
How can I have an iterator with the two entries?

```<code><a>content to extract</a>
<a>more content to extract</a>
</code>```

thanks in advance

答:
Your regex is not the right one. You should use (.*?) instead

```<code>val rawData = "askljdld<a>content to extract</a>lkdsjkdj<a>more content to extract</a>sdkdljk"

val regex = "<a>(.*?)</a>".r

regex.findAllIn(rawData).foreach(println)
</code>```

Body:
I have a String like this:

val rawData = "askljdldcontent to extractlkdsjkdjmore content to extractsdkdljk

and I want to extract the content between the tags

I've tried this, but the end part of the regex is not working as I expected:

val regex = "(.*)".r
for(m <- regex.findAllIn(rawData)){
      println(m)
    }

the output is:

content to extractlkdsjkdjmore content to extract

I understand what's happening: the regex finds the first  and the last .
How can I have an iterator with the two entries?

content to extract
more content to extract

thanks in advance

Body:
Your regex is not the right one. You should use <a>(.*?)</a> instead

val rawData = "askljdld<a>content to extract</a>lkdsjkdj<a>more content to extract</a>sdkdljk"

val regex = "<a>(.*?)</a>".r

regex.findAllIn(rawData).foreach(println)


问:
Angular watch doesn't work with controllerAs syntax
Have a problem with watching response.

I have a SettingsCtrl as settings and this is my view:

<input  type="text" class="form-control" ng-model="settings.test.one"  />
<input  type="text" class="form-control" ng-model="settings.test.second"  />```
</div>
</div>
</p>

<p>And this is my Controller:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>app.controller('SettingsCtrl', function ($scope, settingsFactory, Test) {

  var vm = this;

  settingsFactory.test().then(function(response){

     vm.test = response;
  })

  /////  OR

  vm.test = Test; // this is from ui-router resolve

    $scope.$watch(angular.bind('vm', function () {
    return vm.test;
    }), function (newV, oldV) {
    console.log(newV, oldV);
    });

    $scope.$watch(function watch(scope){
     return vm.test;
    }), function handle(newV, oldV) {
    console.log(newV, oldV);
    });

    $scope.$watch('vm', function (newVal, oldVal) {
        console.log('newVal, oldVal', newVal, oldVal);
    });

  });</code>```

I've been searching and have found different solutions, but non of them works.

**** It's watch only first time, when controller is loaded and I see my  console logs, but when I try to make changes watchers do nothing.

What I'm doing wrong?

答:
What worked for me after referring to a github post (https://github.com/johnpapa/angular-styleguide/issues/428) and (http://jsbin.com/levewagufo/edit?html,js,console,output) was to rename the controller from vm = this to (in your case ) settings = this in the beginning of writing the controller. This makes sure the references match up to the "controller as" declaration from the view. Hope this helps

In View:

```<code>ng-controller="AddDetailController as addDetailsCtrl"
</code>```

In Controller Js file:

```<code> $scope.$watch('addDetailsCtrl.currentPage', function (current, original) {
        console.log(current + ":" + original);    });
</code>```

Body:
Have a problem with watching response.

I have a SettingsCtrl as settings and this is my view:

<input  type="text" class="form-control" ng-model="settings.test.one"  />
<input  type="text" class="form-control" ng-model="settings.test.second"  />

And this is my Controller:

app.controller('SettingsCtrl', function ($scope, settingsFactory, Test) {

  var vm = this;

  settingsFactory.test().then(function(response){

     vm.test = response;
  })

  /////  OR

  vm.test = Test; // this is from ui-router resolve

    $scope.$watch(angular.bind('vm', function () {
    return vm.test;
    }), function (newV, oldV) {
    console.log(newV, oldV);
    });

    $scope.$watch(function watch(scope){
     return vm.test;
    }), function handle(newV, oldV) {
    console.log(newV, oldV);
    });

    $scope.$watch('vm', function (newVal, oldVal) {
        console.log('newVal, oldVal', newVal, oldVal);
    });

  });

I've been searching and have found different solutions, but non of them works.

**** It's watch only first time, when controller is loaded and I see my  console logs, but when I try to make changes watchers do nothing.

What I'm doing wrong?

Body:
What worked for me after referring to a github post (https://github.com/johnpapa/angular-styleguide/issues/428) and (http://jsbin.com/levewagufo/edit?html,js,console,output) was to rename the controller from vm = this to (in your case ) settings = this in the beginning of writing the controller. This makes sure the references match up to the "controller as" declaration from the view. Hope this helps

In View:

ng-controller="AddDetailController as addDetailsCtrl"

In Controller Js file:

 $scope.$watch('addDetailsCtrl.currentPage', function (current, original) {
        console.log(current + ":" + original);    });


问:
Hangman Game - Duplicate characters issue in lists
I've been making a hangman game and ran into a problem with the lists. If the user input matches any of the characters in the list, the letter's place in said list is found and then added to that position in a blank list. However, words such as "television" that contain duplicate characters don't work. Instead, it will print "tel_vis_on". Sorry if this is a vague post, I don't know the terminology.</p>

```<code>def guess():
    letter = input ("Please enter a letter:")
    if letter in word:
        print ("Correct!")
        letterPlace = word.index(letter)
        answer[letterPlace] = letter
        print (*answer)
    else:
        print ("Wrong!")

    if answer == word :
        print ("You guessed it! Well Done!")
        #end here
    else:
        guess()

from random import choice
objects = ["computer","television"]
word = choice(objects)
word = (list(word))
wordcount = len(word)
answer = ["_"]*wordcount
print (*answer)
guess()
</code>```

答:
The issue here is that you are replacing only the first occurrence of the letter. In order to replace all occurances, use the re function like this:

```<code>def guess():
    letter = input ("Please enter a letter:")
    if letter in word:
        print ("Correct!")
        letterPlace = [m.start() for m in re.finditer(letter, word)]
        for index in letterPlace:
            answer[index] = letter
</code>```

Body:
I've been making a hangman game and ran into a problem with the lists. If the user input matches any of the characters in the list, the letter's place in said list is found and then added to that position in a blank list. However, words such as "television" that contain duplicate characters don't work. Instead, it will print "tel_vis_on". Sorry if this is a vague post, I don't know the terminology.

def guess():
    letter = input ("Please enter a letter:")
    if letter in word:
        print ("Correct!")
        letterPlace = word.index(letter)
        answer[letterPlace] = letter
        print (*answer)
    else:
        print ("Wrong!")

    if answer == word :
        print ("You guessed it! Well Done!")
        #end here
    else:
        guess()

from random import choice
objects = ["computer","television"]
word = choice(objects)
word = (list(word))
wordcount = len(word)
answer = ["_"]*wordcount
print (*answer)
guess()

Body:
The issue here is that you are replacing only the first occurrence of the letter. In order to replace all occurances, use the re function like this:

def guess():
    letter = input ("Please enter a letter:")
    if letter in word:
        print ("Correct!")
        letterPlace = [m.start() for m in re.finditer(letter, word)]
        for index in letterPlace:
            answer[index] = letter


问:
Create array from PHP string
Let's say I have an string like

```<code>$str = "BKL|bkl,EXH|exh,FFV|ffv,LEC|lec,AUE|aue,SEM|SEM";
</code>```

and i want an array like:

```<code>array( array("title"=>"BKL", "value"=>bkl),
array("title"=>"EXH", "value"=>exh),
array("title"=>"FFV", "value"=>ffv),
array("title"=>"LEC", "value"=>lec),
array("title"=>"AUE", "value"=>aue),
array("title"=>"SEM", "value"=>SEM),
);
</code>```

I have found a solution here: How to create particular array from string in php but this is giving me an array like:

```<code>Array
(
    [BKL] => bkl
    [EXH] => exh
    [FFV] => ffv
    [LEC] => lec
    [AUE] => aue
    [SEM] => sem
)
</code>```

Thanks a lot.

答:
Use Your String which you want to display in foreach with key and values:

Demo: https://eval.in/827426

```<code><?php

$str = "BKL|bkl,EXH|exh,FFV|ffv,LEC|lec,AUE|aue,SEM|sem";

$final = array();

foreach (explode(',', $str) as $pair) {
  list($key, $value) = explode('|', $pair);
  $final[] = ['Title'=>$key .',', 'Value'=>$value];
}

echo "```";
print_r($final);
echo "```";
?>
</code>```

Title: Create array from PHP string

Body:
Let's say I have an string like

$str = "BKL|bkl,EXH|exh,FFV|ffv,LEC|lec,AUE|aue,SEM|SEM";

and i want an array like:

array( array("title"=>"BKL", "value"=>bkl),
array("title"=>"EXH", "value"=>exh),
array("title"=>"FFV", "value"=>ffv),
array("title"=>"LEC", "value"=>lec),
array("title"=>"AUE", "value"=>aue),
array("title"=>"SEM", "value"=>SEM),
);

I have found a solution here: How to create particular array from string in php but this is giving me an array like:

Array
(
    [BKL] => bkl
    [EXH] => exh
    [FFV] => ffv
    [LEC] => lec
    [AUE] => aue
    [SEM] => sem
)

Thanks a lot.

Body:
Use Your String which you want to display in foreach with key and values:

Demo: https://eval.in/827426

<?php

$str = "BKL|bkl,EXH|exh,FFV|ffv,LEC|lec,AUE|aue,SEM|sem";

$final = array();

foreach (explode(',', $str) as $pair) {
  list($key, $value) = explode('|', $pair);
  $final[] = ['Title'=>$key .',', 'Value'=>$value];
}

echo "<pre>";
print_r($final);
echo "</pre>";
?>


问:
Sending many requests from Node.js to an API causes error
I have more than 2000 user in my database , when I try to broadcast a message to all users, it barely sends about 200 request then my server stops and I get an error as below :

```<code>{ Error: connect ETIMEDOUT 31.13.88.4:443
at Object.exports._errnoException (util.js:1026:11)
at exports._exceptionWithHostPort (util.js:1049:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1090:14)
code: 'ETIMEDOUT',
errno: 'ETIMEDOUT',
syscall: 'connect,
address: '31.13.88.4',
port: 443 }
</code>```

Sometimes I get another error that says :

```<code>Error!: Error: socket hang up
</code>```

This is my request :

```<code>function callSendAPI(messageData) {
  request({
    uri: 'https://graph.facebook.com/v2.6/me/messages',
    qs: { access_token: '#####' },
    method: 'POST',
    json: messageData

  }, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      var recipientId = body.recipient_id;
      var messageId = body.message_id;

      if (messageId) {
        console.log("Successfully sent message with id %s to recipient %s",
          messageId, recipientId);
      } else {
      console.log("Successfully called Send API for recipient %s",
        recipientId);
      }
    } else {
      console.error("Failed calling Send API");
      console.log(error)
    }
  });
}
</code>```

I have tried

setTimeout to make the the API calling wait for a while:

```<code> setTimeout(function(){callSendAPI(data)},200);
</code>```

Can anyone help if he/she faced a similar error ?

EDITED

I'm using Messenger Platform which support high rate of calls to the Send API and it is not limited with 200 calls .

答:
You may be hitting Facebook API limits. To throttle the requests you should send every request after some interval from the previous one. You didn't include where you're iterating over all users but I suspect that you maybe do it in a loop and if you use setTimeout to delay every request with flat 200ms delay then you have all requests done at the same time like you did before - just 200ms later.

What you can do is:

You can use setTimeout and add variable delay for every request (not recommended)

You can use Async module's series or parallelLimit (using callbacks)

You can use Bluebird's Promise.mapSeries or Promise.map with concurrency limit (using promises)

The 1 is not recommended because it will still be fire-and-forget (unless you add more complexity to that) and you still risk that you have too much concurrency and go over limit because you only control when the requests start, not how many of outstanding requests are there.

The 2 and 3 are mostly the same but differ by using callbacks or promises. In your example you're using callbacks but your callSendAPI doesn't take its own callback which it should if you want option 2 to work - or, alternatively, it should return a promise if you want option 3 to work.

For more info see the docs:

https://caolan.github.io/async/docs.html#parallelLimit

https://caolan.github.io/async/docs.html#series

http://bluebirdjs.com/docs/api/promise.map.html

http://bluebirdjs.com/docs/api/promise.mapseries.html

Of course there are more ways to do it but those are the most straightforward.

Ideally, if you want to fully utilize the 200 requests per hour limit then you should queue the requests yourself and make the requests at certain intervals that correspond to that limit. Sometimes if you didn't do a lot of requests in an hour then you won't need delays, sometime you will. What you should really do here is to queue all requests centrally and empty the queue at intervals corresponding to the already used up portion to the limit which you should track yourself - but that can be tricky.

Body:
I have more than 2000 user in my database , when I try to broadcast a message to all users, it barely sends about 200 request then my server stops and I get an error as below :

{ Error: connect ETIMEDOUT 31.13.88.4:443
at Object.exports._errnoException (util.js:1026:11)
at exports._exceptionWithHostPort (util.js:1049:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1090:14)
code: 'ETIMEDOUT',
errno: 'ETIMEDOUT',
syscall: 'connect,
address: '31.13.88.4',
port: 443 }

Sometimes I get another error that says :

Error!: Error: socket hang up

This is my request :

function callSendAPI(messageData) {
  request({
    uri: 'https://graph.facebook.com/v2.6/me/messages',
    qs: { access_token: '#####' },
    method: 'POST',
    json: messageData

  }, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      var recipientId = body.recipient_id;
      var messageId = body.message_id;

      if (messageId) {
        console.log("Successfully sent message with id %s to recipient %s",
          messageId, recipientId);
      } else {
      console.log("Successfully called Send API for recipient %s",
        recipientId);
      }
    } else {
      console.error("Failed calling Send API");
      console.log(error)
    }
  });
}

I have tried

setTimeout to make the the API calling wait for a while:

 setTimeout(function(){callSendAPI(data)},200);

Can anyone help if he/she faced a similar error ?

EDITED

I'm using Messenger Platform which support high rate of calls to the Send API and it is not limited with 200 calls .


问:
Sidebar menu issue in my site
How Do I Bring The Drop-down Menu In Front Of Other Graphic?
I just applied this CSS class on my side bar it works perfect and things are normal in full screen mode

```<code>.MYfixed {position:fixed;-webkit-backface-visibility: hidden;}
</code>```

but when I collapsed my side bar the sidebar listing tag does not work perfectly.

what can I do?

Look at this image you can understand what I mean.

答:
here is my css class

for fixed sidebar

```<code>.MYfixed { position:fixed; -webkit-backface-visibility: hidden;}
</code>```

and for dropdown menu

```<code>.myFixed2 { position: absolute;z-index:1000;}
</code>```

and my html code is:

```<code><div class="page-sidebar navbar-collapse collapse MYfixed ">

   <ul class="page-sidebar-menu  page-header-fixed page-sidebar-menu-light" data-slide-speed="200" data-height="585" data-keep-expanded="false" data-auto-scroll="false">
                        <li class="sidebar-search-wrapper"></li>
                        <li class="nav-item start">
                            <a href="/Default.aspx" class="nav-link nav-toggle">
                                <%--<i class="icon-home"></i>--%>
                                <img src="<%= Page.ResolveUrl("~")%>assets/global/img/house.png" />
                                <span class="title">Home</span>
                                <span class="selected"></span>
                            </a>

                        </li>

                        <li class="nav-item myFixed2">
                            <a href="javascript:;" class="nav-link nav-toggle ">
                                <img src="<%= Page.ResolveUrl("~")%>assets/global/img/admin.png" />
                                <span class="title">Administration</span>
                                <span class="selected"></span>
                                <span class="arrow open"></span>
                            </a>
                            <ul class="sub-menu">
                                <li class="nav-item ">
                                    <a href="/Administration/ModulesList.aspx" class="nav-link ">
                                        <span class="sidebarTitle">Modules List</span>
                                    </a>
                                </li>
                                <li class="nav-item  ">
                                    <a href="/Administration/UserSecurity.aspx" class="nav-link ">
                                        <span class="sidebarTitle">User Rights</span>
                                    </a>
                                </li>
                                <li class="nav-item  ">
                                    <a href="/Administration/AddUser.aspx" class="nav-link ">
                                        <span class="sidebarTitle">Add User</span>
                                    </a>
                                </li>
                            </ul>
                        </li>
                    </ul>

 </div>
</code>```

Title: Sidebar menu issue in my site

Body:
How Do I Bring The Drop-down Menu In Front Of Other Graphic?
I just applied this CSS class on my side bar it works perfect and things are normal in full screen mode

.MYfixed {position:fixed;-webkit-backface-visibility: hidden;}

but when I collapsed my side bar the sidebar listing tag does not work perfectly.

what can I do?

Look at this image you can understand what I mean.

Body:
here is my css class

for fixed sidebar

.MYfixed { position:fixed; -webkit-backface-visibility: hidden;}

and for dropdown menu

.myFixed2 { position: absolute;z-index:1000;}

and my html code is:

<div class="page-sidebar navbar-collapse collapse MYfixed ">

   <ul class="page-sidebar-menu  page-header-fixed page-sidebar-menu-light" data-slide-speed="200" data-height="585" data-keep-expanded="false" data-auto-scroll="false">
                        <li class="sidebar-search-wrapper"></li>
                        <li class="nav-item start">
                            <a href="/Default.aspx" class="nav-link nav-toggle">
                                <%--<i class="icon-home"></i>--%>
                                <img src="<%= Page.ResolveUrl("~")%>assets/global/img/house.png" />
                                <span class="title">Home</span>
                                <span class="selected"></span>
                            </a>

                        </li>

                        <li class="nav-item myFixed2">
                            <a href="javascript:;" class="nav-link nav-toggle ">
                                <img src="<%= Page.ResolveUrl("~")%>assets/global/img/admin.png" />
                                <span class="title">Administration</span>
                                <span class="selected"></span>
                                <span class="arrow open"></span>
                            </a>
                            <ul class="sub-menu">
                                <li class="nav-item ">
                                    <a href="/Administration/ModulesList.aspx" class="nav-link ">
                                        <span class="sidebarTitle">Modules List</span>
                                    </a>
                                </li>
                                <li class="nav-item  ">
                                    <a href="/Administration/UserSecurity.aspx" class="nav-link ">
                                        <span class="sidebarTitle">User Rights</span>
                                    </a>
                                </li>
                                <li class="nav-item  ">
                                    <a href="/Administration/AddUser.aspx" class="nav-link ">
                                        <span class="sidebarTitle">Add User</span>
                                    </a>
                                </li>
                            </ul>
                        </li>
                    </ul>

 </div>


答:
you also ma execute dynamic select:</p>

```<code>declare v_table_name VarChar(128);
BEGIN

Select table_name into v_table_name from Table1 where id = 1
SET @s = CONCAT('SELECT * FROM ', v_table_name, ' where id = 1');
PREPARE stmt1 FROM @s;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;

END;
</code>```

Title: mysql - query inside a query

Body:
How is it possible to do the following :
(i am using mysql - phpmyadmin )

this query returns a table name :

Select table_name from Table1 where id = 1

I want to use it inside another query , like :

select val from (Select table_name from Table1 where id = 1)

but this sure does not work, and since phpmyadmin does not support calling stored procedures, could there be any possible solution for this ?

Body:
you also ma execute dynamic select:

declare v_table_name VarChar(128);
BEGIN

Select table_name into v_table_name from Table1 where id = 1
SET @s = CONCAT('SELECT * FROM ', v_table_name, ' where id = 1');
PREPARE stmt1 FROM @s;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;

END;


问:
after pseudo with image not working
I try to get the same wave symbol underneath my headers as shown in this website http://harbr.co/ but it's not working. So far, I have the following CSS:

```<code>H2::after {
content: url ('images/wave.png');
position: absolute;
}
</code>```

Help?

答:
body { background-color: gray; }
h2:after {
content: "";
width: 42px;
height: 8px;
background: url('http://harbr.co/wp-content/themes/harbr2015/img/icons/divWave-sprite.png');
background-size: 100px 250px;
background-position: -50px -50px;
position: absolute;
top: 1em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2></h2></code>```

Title: after pseudo with image not working

Body:
I try to get the same wave symbol underneath my headers as shown in this website http://harbr.co/ but it's not working. So far, I have the following CSS:

H2::after {
content: url ('images/wave.png');
position: absolute;
}

Help?

Body:
body { background-color: gray; }
h2:after {
content: "";
width: 42px;
height: 8px;
background: url('http://harbr.co/wp-content/themes/harbr2015/img/icons/divWave-sprite.png');
background-size: 100px 250px;
background-position: -50px -50px;
position: absolute;
top: 1em;
}

<h2></h2>