答:
No, that isn't possible. But you could always convert the group to a list and print its length:

```<code>for key, group in groupby(x):
    sub_list = list(group)
    print(len(sub_list),'|', sub_list)
</code>```

Output:

```<code>5 | [1, 1, 1, 1, 1]
4 | [2, 2, 2, 2]
3 | [3, 3, 3]
2 | [4, 4]
1 | [5]
</code>```

Title: Python itertools.groupby length key?

Body:
No, that isn't possible. But you could always convert the group to a list and print its length:

for key, group in groupby(x):
    sub_list = list(group)
    print(len(sub_list),'|', sub_list)

Output:

5 | [1, 1, 1, 1, 1]
4 | [2, 2, 2, 2]
3 | [3, 3, 3]
2 | [4, 4]
1 | [5]


来源: stackexchange

答:
The recent versions of data.table allow to melt multiple columns simultaneously.

Unfortunately, both sets of columns start with the letter P. Simply specifying patterns("PH", "P") won't work as P will match the PH columns as well as the P columns resulting in 24 rows instead of 12. The slightly modified regular expressions patterns("PH", "P\\d") will work:

```<code>library(data.table)   # CRAN version 1.10.4 used
graph.dat1 <- melt(setDT(graph.dat), measure.vars = patterns("PH", "P\\d"),
     value.name = c("PH", "P"))
# rename factor levels of variable
graph.dat1[, variable := forcats::lvls_revalue(variable, c("25", "50", "75", "100"))][]
</code>```

```<code>      r_b c variable   PH     P
 1: 0.029 7       25 3.96 1,694
 2: 0.027 7       25 2.86 1,665
 3: 0.023 7       25 3.96 1,580
 4: 0.029 7       50 5.94 1,736
 5: 0.027 7       50 2.86 1,792
 6: 0.023 7       50 5.72 1,560
 7: 0.029 7       75 5.94 1,329
 8: 0.027 7       75 2.86 1,639
 9: 0.023 7       75 5.72 1,156
10: 0.029 7      100 5.94   800
11: 0.027 7      100 2.86 1,335
12: 0.023 7      100 5.72   663
</code>```

Note that it is required to coerce graph.dat to a data.table object by using either setDT(graph.dat) or data.table(graph.dat). Otherwise, reshape2::melt() would be dispatched on a data.frame object which doesn't recognize patterns().

Also note, there is an answer to a similar question here but the required patterns() are quite different.

Data

```<code>library(data.table)
graph.dat <- fread(
"PH25   PH50    PH75    PH100   P25      P50    P75    P100      r_b    c
3.96    5.94    5.94    5.94    1,694   1,736   1,329   800     0.029   7
2.86    2.86    2.86    2.86    1,665   1,792   1,639   1,335   0.027   7
3.96    5.72    5.72    5.72    1,580   1,560   1,156   663     0.023   7",
data.table = FALSE)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Converting data from wide to long for two variables

Body:
I have a dataset with two variables in a wide format that I want to convert to long. I've seen the examples from the cook for R but they are for just one variable.

My dataset (graph.dat) looks like this:

 PH25   PH50    PH75    PH100   P25      P50    P75    P100      r_b    c
3.96    5.94    5.94    5.94    1,694   1,736   1,329   800     0.029   7
2.86    2.86    2.86    2.86    1,665   1,792   1,639   1,335   0.027   7
3.96    5.72    5.72    5.72    1,580   1,560   1,156   663     0.023   7

I want to plot PH (x-axis) versus P(y-axis). So for a PH25 value corresponds a value of P25 (and a value of r_b and c); so the long format will be:

PH       P      r_b         c
3.96    1,694   0.029       7
2.86    1,665   0.027       7
3.96    1,580   0.023       7
5.94    1,736   0.029       7
2.86    1,792   0.027       7
5.72    1,560   0.023       7
5.94    1,329   0.029       7
2.86    1,639   0.027       7
5.72    1,156   0.023       7
5.94    800     0.029       7
2.86    1,335   0.027       7
5.72    663     0.023       7

I try to "melt" it twice but it doesn't work.
Here is what I did:

graph.dat1<- melt(graph.dat, id.vars=c("PH25","PH50","PH75",
                                        "PH100","r_b", "c"),
                             variable.name="P",
                             value.name="Pval")

and the new dataset (graph.dat1) is fine because I've only three values for each "P" (giving me a total of 12 observations). It looks like this:

    PH25    PH50    PH75    PH100   r_b     c    P     Pval
1   3.96    5.94    5.94    5.94    0.029   7   P25    1694
2   2.86    2.86    2.86    2.86    0.027   7   P25    1665
3   3.96    5.72    5.72    5.72    0.023   7   P25    1580
4   3.96    5.94    5.94    5.94    0.029   7   P50    1736
5   2.86    2.86    2.86    2.86    0.027   7   P50     1792
6   3.96    5.72    5.72    5.72    0.023   7   P50     1560
7   3.96    5.94    5.94    5.94    0.029   7   P75     1329
8   2.86    2.86    2.86    2.86    0.027   7   P75     1639
9   3.96    5.72    5.72    5.72    0.023   7   P75     1156
10  3.96    5.94    5.94    5.94    0.029   7   P100    800
11  2.86    2.86    2.86    2.86    0.027   7   P100    1335
12  3.96    5.72    5.72    5.72    0.023   7   P100    663

but when I do the second "melt" it doesn't work and I don't know how to solve it. This is the second step I did:

graph.dat2<- melt (graph.dat1,id.vars=c("r_b", "c", "P", "Pval"),
                   variable.name="PdH",
                   value.name="PH")

but then I get 4 times the number of observations (so instead of 12 observations I get 48 observations). So, my new dataset (graph.dat2) looks like:

    r_b     c   P     Pval  PdH      PH
1   0.029   7   P25   1694  PH25    3.96
2   0.027   7   P25   1665  PH25    2.86
3   0.023   7   P25   1580  PH25    3.96
4   0.029   7   P50   1736  PH25    3.96
5   0.027   7   P50   1792  PH25    2.86
6   0.023   7   P50   1560  PH25    3.96
7   0.029   7   P75   1329  PH25    3.96
8   0.027   7   P75   1639  PH25    2.86
9   0.023   7   P75   1156  PH25    3.96
10  0.029   7   P100   800  PH25    3.96
11  0.027   7   P100  1335  PH25    2.86
12  0.023   7   P100   663  PH25    3.96
13  0.029   7   P25   1694  PH50    5.94
14  0.027   7   P25   1665  PH50    2.86
15  0.023   7   P25   1580  PH50    5.72
...

Body:
The recent versions of data.table allow to melt multiple columns simultaneously.

Unfortunately, both sets of columns start with the letter P. Simply specifying patterns("PH", "P") won't work as P will match the PH columns as well as the P columns resulting in 24 rows instead of 12. The slightly modified regular expressions patterns("PH", "P\\d") will work:

library(data.table)   # CRAN version 1.10.4 used
graph.dat1 <- melt(setDT(graph.dat), measure.vars = patterns("PH", "P\\d"),
     value.name = c("PH", "P"))
# rename factor levels of variable
graph.dat1[, variable := forcats::lvls_revalue(variable, c("25", "50", "75", "100"))][]

      r_b c variable   PH     P
 1: 0.029 7       25 3.96 1,694
 2: 0.027 7       25 2.86 1,665
 3: 0.023 7       25 3.96 1,580
 4: 0.029 7       50 5.94 1,736
 5: 0.027 7       50 2.86 1,792
 6: 0.023 7       50 5.72 1,560
 7: 0.029 7       75 5.94 1,329
 8: 0.027 7       75 2.86 1,639
 9: 0.023 7       75 5.72 1,156
10: 0.029 7      100 5.94   800
11: 0.027 7      100 2.86 1,335
12: 0.023 7      100 5.72   663

Note that it is required to coerce graph.dat to a data.table object by using either setDT(graph.dat) or data.table(graph.dat). Otherwise, reshape2::melt() would be dispatched on a data.frame object which doesn't recognize patterns().

Also note, there is an answer to a similar question here but the required patterns() are quite different.

Data

library(data.table)
graph.dat <- fread(
"PH25   PH50    PH75    PH100   P25      P50    P75    P100      r_b    c
3.96    5.94    5.94    5.94    1,694   1,736   1,329   800     0.029   7
2.86    2.86    2.86    2.86    1,665   1,792   1,639   1,335   0.027   7
3.96    5.72    5.72    5.72    1,580   1,560   1,156   663     0.023   7",
data.table = FALSE)


问:
JavaScript condition in a hidden field conditioned
I have 2 fields (select social network and type usersocial network) conditioned with js so when people select "other" a new field show up and I have a button to add other extra fields to select another social network, everything works perfectly but I can't make work the second conditions for the option "other"
I appreciate your help.

function otherps() {
  if ($("#platform_social").val() !== '') {
    $("#social_user").prop('disabled', false);
    $("#social_user").prop('required', true);
  } else {
    $("#social_user").prop('disabled', true);
    $("#social_user").prop('required', false);
  }
  if ($("#platform_social").val() == "Other") {
    $("#othersocial").css("display", "block");
    $("#otherplatform").prop('required', true);
    //$("input").prop('required',true);
  } else {
    $("#otherplatform").val("");
    $("#otherplatform").prop('required', false);
    $("#othersocial").css("display", "none");
  }
}

//more social
function add_social() {
  var crd = $("#socialadded").val();
  var newblock = '

Other Social Media
';
  newblock += '
';
  newblock += '
';
  newblock += 'Provider / Platform:';
  newblock += '<select name="platform_social' + crd + '" id="platform_social' + crd + '">';
  newblock += '<option value="" selected="selected"> </option>';
  newblock += '<option value="ASKfm">ASKfm</option>';
  newblock += '<option value="Facebook">Facebook</option>';
  newblock += '<option value="Flickr">Flickr</option>';
  newblock += '<option value="GitHub">GitHub</option>';
  newblock += '<option value="Google">Google+</option>';
  newblock += '<option value="Instagram">Instagram</option>';
  newblock += '<option value="JustPaste">JustPaste.it</option>';
  newblock += '<option value="LinkedIn">LinkedIn</option>';
  newblock += '<option value="Tumblr">Tumblr</option>';
  newblock += '<option value="Twitter">Twitter</option>';
  newblock += '<option value="Vine">Vine</option>';
  newblock += '<option value="VKontakte">VKontakte (VK)</option>';
  newblock += '<option value="YouTube">YouTube</option>';
  newblock += '<option value="Other">Other</option>';
  newblock += '</select>';
  newblock += '
';
  newblock += '
';
  newblock += '
Other Platform / Provider *
';
  newblock += '<input type="text" name="otherplatform' + crd + '" id="otherplatform' + crd + '" />
';
  newblock += '
';
  newblock += '
';
  newblock += '
';
  newblock += '
';
  newblock += 'Social Media Identifier:';
  newblock += '<input type="text" name="social_user' + crd + '" id="social_user' + crd + '" disabled />';
  newblock += '
';
  newblock += '
';

  $("#socialextra").append(newblock);
  var whichplatform_social = "#platform_social" + crd;
  var whichsocial_usere = "#social_user" + crd;
  var whichotherplatform = "#otherplatform" + crd;
  var whichothersocial = "#othersocial" + crd;
  $(whichplatform_social).prop('required', true);
  $(whichsocial_user).prop('required', true);
  $(whichotherplatform).prop('required', true);
  $(whichothersocial).css('display', 'block');
  if ($whichotherplatform !== '') {
    $whichsocial_usere.prop('disabled', false);
    $whichsocial_usere.prop('required', true);
  } else {
    $whichsocial_usere.prop('disabled', true);
    $whichsocial_usere.prop('required', false);
  }
  if (whichotherplatform == "Other") {
    $whichothersocial.css("display", "block");
    $whichotherplatform.prop('required', true);
    //$("input").prop('required',true);
  } else {
    $whichotherplatform.val("");
    $whichotherplatform.prop('required', false);
    $whichothersocial.css("display", "none");
  }
  crd++;
  $("#socialadded").val(crd);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="fullrow">
  <div class="leftcol">
    <div>Provider / Platform</div>
    <select name="platform_social" id="platform_social" onchange="otherps();">
     <option value="" selected="selected"> </option>
  <option value="ASKfm">ASKfm</option>
  <option value="Facebook">Facebook</option>
  <option value="Flickr">Flickr</option>
  <option value="GitHub">GitHub</option>
  <option value="Google">Google+</option>
  <option value="Instagram">Instagram</option>
  <option value="JustPaste">JustPaste.it</option>
  <option value="LinkedIn">LinkedIn</option>
  <option value="Tumblr">Tumblr</option>
  <option value="Twitter">Twitter</option>
  <option value="Vine">Vine</option>
  <option value="VKontakte">VKontakte (VK)</option>
  <option value="YouTube">YouTube</option>
  <option value="Other">Other</option>
    </select>
    <div id="othersocial" style="display:none;">
      <br>
      <div>Other Platform </div>
      <input type="text" name="otherplatform" id="otherplatform" /><br>
    </div>
  </div>

  <div class="rightcol">
    <div>Social Media Identifier</div>
    <input type="text" id="social_user" name="social_user" disabled />
  </div>
</div>

<div id="socialextra"></div>

<input type="hidden" name="socialadded" id="socialadded" value="0" />
<br>
<div class="fullrow">
  <div class="leftcol">
    <span class="addtravel">Add Another  </span>
  </div>
</div></code>```

Everything works perfectly until I tried to add the condition for the extra social network.

Thanks a lot

答:
Check the snippet

function otherps(val) {
  if ($("#platform_social"+ val ).val() !== '') {
    $("#social_user"+ val).prop('disabled', false);
    $("#social_user"+ val).prop('required', true);
  } else {
    $("#social_user" + val).prop('disabled', true);
    $("#social_user" + val).prop('required', false);
  }
  if ($("#platform_social" + val).val() == "Other") {
    $("#othersocial" + val).css("display", "block");
    $("#otherplatform" + val).prop('required', true);
    //$("input").prop('required',true);
  } else {
    $("#otherplatform" + val).val("");
    $("#otherplatform" + val).prop('required', false);
    $("#othersocial" + val).css("display", "none");
  }
}

//more social
function add_social() {
  var crd = $("#socialadded").val();
  var newblock = '

Other Social Media
';
  newblock += '
';
  newblock += '
';
  newblock += 'Provider / Platform:';
  newblock += '<select name="platform_social' + crd + '" id="platform_social' + crd + '" onchange="otherps("+crd+")>';
  newblock += '<option value="" selected="selected"> </option>';
  newblock += '<option value="ASKfm">ASKfm</option>';
  newblock += '<option value="Facebook">Facebook</option>';
  newblock += '<option value="Flickr">Flickr</option>';
  newblock += '<option value="GitHub">GitHub</option>';
  newblock += '<option value="Google">Google+</option>';
  newblock += '<option value="Instagram">Instagram</option>';
  newblock += '<option value="JustPaste">JustPaste.it</option>';
  newblock += '<option value="LinkedIn">LinkedIn</option>';
  newblock += '<option value="Tumblr">Tumblr</option>';
  newblock += '<option value="Twitter">Twitter</option>';
  newblock += '<option value="Vine">Vine</option>';
  newblock += '<option value="VKontakte">VKontakte (VK)</option>';
  newblock += '<option value="YouTube">YouTube</option>';
  newblock += '<option value="Other">Other</option>';
  newblock += '</select>';
  newblock += '
';
  newblock += '
';
  newblock += '
Other Platform / Provider *
';
  newblock += '<input type="text" name="otherplatform' + crd + '" id="otherplatform' + crd + '" />
';
  newblock += '
';
  newblock += '
';
  newblock += '
';
  newblock += '
';
  newblock += 'Social Media Identifier:';
  newblock += '<input type="text" name="social_user' + crd + '" id="social_user' + crd + '" disabled />';
  newblock += '
';
  newblock += '
';

  $("#socialextra").append(newblock);
  var whichplatform_social = "#platform_social" + crd;
  var whichsocial_usere = "#social_user" + crd;
  var whichotherplatform = "#otherplatform" + crd;
  var whichothersocial = "#othersocial" + crd;
  $(whichplatform_social).prop('required', true);
  $(whichsocial_user).prop('required', true);
  $(whichotherplatform).prop('required', true);
  $(whichothersocial).css('display', 'block');
  if ($whichotherplatform !== '') {
    $whichsocial_usere.prop('disabled', false);
    $whichsocial_usere.prop('required', true);
  } else {
    $whichsocial_usere.prop('disabled', true);
    $whichsocial_usere.prop('required', false);
  }
  if (whichotherplatform == "Other") {
    $whichothersocial.css("display", "block");
    $whichotherplatform.prop('required', true);
    //$("input").prop('required',true);
  } else {
    $whichotherplatform.val("");
    $whichotherplatform.prop('required', false);
    $whichothersocial.css("display", "none");
  }
  crd++;
  $("#socialadded").val(crd);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>

  <head>
    <script data-require="jquery@*" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>

    <div class="fullrow">
  <div class="leftcol">
    <div>Provider / Platform</div>
    <select name="platform_social" id="platform_social" onchange="otherps('');">
     <option value="" selected="selected"> </option>
  <option value="ASKfm">ASKfm</option>
  <option value="Facebook">Facebook</option>
  <option value="Flickr">Flickr</option>
  <option value="GitHub">GitHub</option>
  <option value="Google">Google+</option>
  <option value="Instagram">Instagram</option>
  <option value="JustPaste">JustPaste.it</option>
  <option value="LinkedIn">LinkedIn</option>
  <option value="Tumblr">Tumblr</option>
  <option value="Twitter">Twitter</option>
  <option value="Vine">Vine</option>
  <option value="VKontakte">VKontakte (VK)</option>
  <option value="YouTube">YouTube</option>
  <option value="Other">Other</option>
    </select>
    <div id="othersocial" style="display:none;">
      <br>
      <div>Other Platform </div>
      <input type="text" name="otherplatform" id="otherplatform" /><br>
    </div>
  </div>

  <div class="rightcol">
    <div>Social Media Identifier</div>
    <input type="text" id="social_user" name="social_user" disabled />
  </div>
</div>

<div id="socialextra"></div>

<input type="hidden" name="socialadded" id="socialadded" value="0" />
<br>
<div class="fullrow">
  <div class="leftcol">
    <span class="addtravel">Add Another  </span>
  </div>
</div>

  </body>

</html></code>```

and also here is the working plunker. Plunker

Solution
I added a parameter to the "otherps" function and then parse the crd to the function when the dynamic HTML generate.

Body:
I have 2 fields (select social network and type usersocial network) conditioned with js so when people select "other" a new field show up and I have a button to add other extra fields to select another social network, everything works perfectly but I can't make work the second conditions for the option "other"
I appreciate your help.

function otherps() {
  if ($("#platform_social").val() !== '') {
    $("#social_user").prop('disabled', false);
    $("#social_user").prop('required', true);
  } else {
    $("#social_user").prop('disabled', true);
    $("#social_user").prop('required', false);
  }
  if ($("#platform_social").val() == "Other") {
    $("#othersocial").css("display", "block");
    $("#otherplatform").prop('required', true);
    //$("input").prop('required',true);
  } else {
    $("#otherplatform").val("");
    $("#otherplatform").prop('required', false);
    $("#othersocial").css("display", "none");
  }
}

//more social
function add_social() {
  var crd = $("#socialadded").val();
  var newblock = '

Other Social Media
';
  newblock += '
';
  newblock += '
';
  newblock += 'Provider / Platform:';
  newblock += '<select name="platform_social' + crd + '" id="platform_social' + crd + '">';
  newblock += '<option value="" selected="selected"> </option>';
  newblock += '<option value="ASKfm">ASKfm</option>';
  newblock += '<option value="Facebook">Facebook</option>';
  newblock += '<option value="Flickr">Flickr</option>';
  newblock += '<option value="GitHub">GitHub</option>';
  newblock += '<option value="Google">Google+</option>';
  newblock += '<option value="Instagram">Instagram</option>';
  newblock += '<option value="JustPaste">JustPaste.it</option>';
  newblock += '<option value="LinkedIn">LinkedIn</option>';
  newblock += '<option value="Tumblr">Tumblr</option>';
  newblock += '<option value="Twitter">Twitter</option>';
  newblock += '<option value="Vine">Vine</option>';
  newblock += '<option value="VKontakte">VKontakte (VK)</option>';
  newblock += '<option value="YouTube">YouTube</option>';
  newblock += '<option value="Other">Other</option>';
  newblock += '</select>';
  newblock += '
';
  newblock += '
';
  newblock += '
Other Platform / Provider *
';
  newblock += '<input type="text" name="otherplatform' + crd + '" id="otherplatform' + crd + '" />
';
  newblock += '
';
  newblock += '
';
  newblock += '
';
  newblock += '
';
  newblock += 'Social Media Identifier:';
  newblock += '<input type="text" name="social_user' + crd + '" id="social_user' + crd + '" disabled />';
  newblock += '
';
  newblock += '
';

  $("#socialextra").append(newblock);
  var whichplatform_social = "#platform_social" + crd;
  var whichsocial_usere = "#social_user" + crd;
  var whichotherplatform = "#otherplatform" + crd;
  var whichothersocial = "#othersocial" + crd;
  $(whichplatform_social).prop('required', true);
  $(whichsocial_user).prop('required', true);
  $(whichotherplatform).prop('required', true);
  $(whichothersocial).css('display', 'block');
  if ($whichotherplatform !== '') {
    $whichsocial_usere.prop('disabled', false);
    $whichsocial_usere.prop('required', true);
  } else {
    $whichsocial_usere.prop('disabled', true);
    $whichsocial_usere.prop('required', false);
  }
  if (whichotherplatform == "Other") {
    $whichothersocial.css("display", "block");
    $whichotherplatform.prop('required', true);
    //$("input").prop('required',true);
  } else {
    $whichotherplatform.val("");
    $whichotherplatform.prop('required', false);
    $whichothersocial.css("display", "none");
  }
  crd++;
  $("#socialadded").val(crd);
}

Provider / Platform

    <select name="platform_social" id="platform_social" onchange="otherps();">
     <option value="" selected="selected"> </option>
  <option value="ASKfm">ASKfm</option>
  <option value="Facebook">Facebook</option>
  <option value="Flickr">Flickr</option>
  <option value="GitHub">GitHub</option>
  <option value="Google">Google+</option>
  <option value="Instagram">Instagram</option>
  <option value="JustPaste">JustPaste.it</option>
  <option value="LinkedIn">LinkedIn</option>
  <option value="Tumblr">Tumblr</option>
  <option value="Twitter">Twitter</option>
  <option value="Vine">Vine</option>
  <option value="VKontakte">VKontakte (VK)</option>
  <option value="YouTube">YouTube</option>
  <option value="Other">Other</option>
    </select>

Other Platform

      <input type="text" name="otherplatform" id="otherplatform" />

Social Media Identifier

    <input type="text" id="social_user" name="social_user" disabled />

<input type="hidden" name="socialadded" id="socialadded" value="0" />

    Add Another

Everything works perfectly until I tried to add the condition for the extra social network.

Thanks a lot

Body:
Check the snippet

function otherps(val) {
  if ($("#platform_social"+ val ).val() !== '') {
    $("#social_user"+ val).prop('disabled', false);
    $("#social_user"+ val).prop('required', true);
  } else {
    $("#social_user" + val).prop('disabled', true);
    $("#social_user" + val).prop('required', false);
  }
  if ($("#platform_social" + val).val() == "Other") {
    $("#othersocial" + val).css("display", "block");
    $("#otherplatform" + val).prop('required', true);
    //$("input").prop('required',true);
  } else {
    $("#otherplatform" + val).val("");
    $("#otherplatform" + val).prop('required', false);
    $("#othersocial" + val).css("display", "none");
  }
}

//more social
function add_social() {
  var crd = $("#socialadded").val();
  var newblock = '<br><div class="headline">Other Social Media </div>';
  newblock += '<div class="fullrow" id="alremove' + crd + '">';
  newblock += '<div class="leftcol">';
  newblock += 'Provider / Platform:';
  newblock += '<select name="platform_social' + crd + '" id="platform_social' + crd + '" onchange="otherps("+crd+")>';
  newblock += '<option value="" selected="selected">&nbsp;</option>';
  newblock += '<option value="ASKfm">ASKfm</option>';
  newblock += '<option value="Facebook">Facebook</option>';
  newblock += '<option value="Flickr">Flickr</option>';
  newblock += '<option value="GitHub">GitHub</option>';
  newblock += '<option value="Google">Google+</option>';
  newblock += '<option value="Instagram">Instagram</option>';
  newblock += '<option value="JustPaste">JustPaste.it</option>';
  newblock += '<option value="LinkedIn">LinkedIn</option>';
  newblock += '<option value="Tumblr">Tumblr</option>';
  newblock += '<option value="Twitter">Twitter</option>';
  newblock += '<option value="Vine">Vine</option>';
  newblock += '<option value="VKontakte">VKontakte (VK)</option>';
  newblock += '<option value="YouTube">YouTube</option>';
  newblock += '<option value="Other">Other</option>';
  newblock += '</select>';
  newblock += '<div id="othersocial' + crd + '" style="display:none;">';
  newblock += '<br>';
  newblock += '<div>Other Platform / Provider *</div>';
  newblock += '<input type="text" name="otherplatform' + crd + '" id="otherplatform' + crd + '" /><br>';
  newblock += '</div>';
  newblock += '</div>';
  newblock += '<br>';
  newblock += '<div class="rightcol">';
  newblock += 'Social Media Identifier:';
  newblock += '<input type="text" name="social_user' + crd + '" id="social_user' + crd + '" disabled />';
  newblock += '</div>';
  newblock += '</div>';

  $("#socialextra").append(newblock);
  var whichplatform_social = "#platform_social" + crd;
  var whichsocial_usere = "#social_user" + crd;
  var whichotherplatform = "#otherplatform" + crd;
  var whichothersocial = "#othersocial" + crd;
  $(whichplatform_social).prop('required', true);
  $(whichsocial_user).prop('required', true);
  $(whichotherplatform).prop('required', true);
  $(whichothersocial).css('display', 'block');
  if ($whichotherplatform !== '') {
    $whichsocial_usere.prop('disabled', false);
    $whichsocial_usere.prop('required', true);
  } else {
    $whichsocial_usere.prop('disabled', true);
    $whichsocial_usere.prop('required', false);
  }
  if (whichotherplatform == "Other") {
    $whichothersocial.css("display", "block");
    $whichotherplatform.prop('required', true);
    //$("input").prop('required',true);
  } else {
    $whichotherplatform.val("");
    $whichotherplatform.prop('required', false);
    $whichothersocial.css("display", "none");
  }
  crd++;
  $("#socialadded").val(crd);
}

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

  <head>
    <script data-require="jquery@*" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>

    <div class="fullrow">
  <div class="leftcol">
    <div>Provider / Platform</div>
    <select name="platform_social" id="platform_social" onchange="otherps('');">
     <option value="" selected="selected">&nbsp;</option>
  <option value="ASKfm">ASKfm</option>
  <option value="Facebook">Facebook</option>
  <option value="Flickr">Flickr</option>
  <option value="GitHub">GitHub</option>
  <option value="Google">Google+</option>
  <option value="Instagram">Instagram</option>
  <option value="JustPaste">JustPaste.it</option>
  <option value="LinkedIn">LinkedIn</option>
  <option value="Tumblr">Tumblr</option>
  <option value="Twitter">Twitter</option>
  <option value="Vine">Vine</option>
  <option value="VKontakte">VKontakte (VK)</option>
  <option value="YouTube">YouTube</option>
  <option value="Other">Other</option>
    </select>
    <div id="othersocial" style="display:none;">
      <br>
      <div>Other Platform </div>
      <input type="text" name="otherplatform" id="otherplatform" /><br>
    </div>
  </div>

  <div class="rightcol">
    <div>Social Media Identifier</div>
    <input type="text" id="social_user" name="social_user" disabled />
  </div>
</div>

<div id="socialextra"></div>

<input type="hidden" name="socialadded" id="socialadded" value="0" />
<br>
<div class="fullrow">
  <div class="leftcol">
    <span class="addtravel"><a onclick="add_social()"
    class="button medium dark">Add Another</a>&nbsp;&nbsp;</span>
  </div>
</div>

  </body>

</html>

and also here is the working plunker. Plunker

Solution
I added a parameter to the "otherps" function and then parse the crd to the function when the dynamic HTML generate.


问:
Configure Angular-cli proxy for custom headers in request to backend?
the topic, as I understand it is quite fresh and relevant.
Tell me where is my mistake?

So, I did everything as in the documentation:

https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md

Angular-cli version:

```<code>....
  "devDependencies": {
    "@angular/cli": "1.2.0",
....
</code>```

Created the file: proxy.conf.json

```<code>{
  "/profile/*": {
    "target": "http://localhost:8888",
    "secure": false,
    "pathRewrite": {
      "^/profile": ""
    },
    "changeOrigin": true,
    "logLevel": "debug"
  }
}
</code>```

I registered it in package.json

```<code>....
  "scripts": {
    "ng": "ng",
    "start": "ng serve --proxy-config proxy.conf.json",
....
</code>```

Starting application as follows: npm start

Here ist the start log:

```<code>> ng serve --proxy-config proxy.conf.json

** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200 **
 10% building modules 3/3 modules 0 active[HPM] Proxy created: /profile  ->  http://localhost:8888
[HPM] Proxy rewrite rule created: "^/profile" ~> ""
[HPM] Subscribed to http-proxy events:  [ 'error', 'close' ]
Hash: 2f1f9b69df46574b900e
Time: 12544ms
chunk    {0} polyfills.bundle.js, polyfills.bundle.js.map (polyfills) 160 kB {4} [initial] [rendered]
chunk    {1} main.bundle.js, main.bundle.js.map (main) 131 kB {3} [initial] [rendered]
chunk    {2} styles.bundle.js, styles.bundle.js.map (styles) 255 kB {4} [initial] [rendered]
chunk    {3} vendor.bundle.js, vendor.bundle.js.map (vendor) 3.79 MB [initial] [rendered]
chunk    {4} inline.bundle.js, inline.bundle.js.map (inline) 0 bytes [entry] [rendered]
webpack: Compiled successfully.
</code>```

And the problem is definitely not in the backend, because the cors is configured there. I monitor my request with Fiddler.

Here's how it looks now:

```<code>OPTIONS http://localhost:8888/profile/data/personal HTTP/1.1
Host: localhost:8888
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36
x-ijt: c2q0qqq02it9p2jrk3m6ihbs5u
Access-Control-Request-Headers: content-type,x-auth-token
Accept: */*
Referer: http://localhost:4200/
Accept-Encoding: gzip, deflate, br
Accept-Language: de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4
</code>```

We are talking about this header: x-auth-token

I also read this topic.

angular-cli server - how to proxy API requests to another server?

Any Ideas? Thanks.

答:
Reposting the answer I posted in that other question.

I had to make a small adjustment based on the above answers, although it seems a bit odd looking at the config now.

This is my proxy.conf.json shown below:

```<code>{
  "/api/*": {
    "target": "https://url.com",
    "secure": false,
    "changeOrigin": true,
    "logLevel": "debug",
    "pathRewrite": {"^/api" : "http://url.com/api"}
  }
}
</code>```

Basically, I rewrote the path completely. And it works now.

Body:
the topic, as I understand it is quite fresh and relevant.
Tell me where is my mistake?

So, I did everything as in the documentation:

https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md

Angular-cli version:

....
  "devDependencies": {
    "@angular/cli": "1.2.0",
....

Created the file: proxy.conf.json

{
  "/profile/*": {
    "target": "http://localhost:8888",
    "secure": false,
    "pathRewrite": {
      "^/profile": ""
    },
    "changeOrigin": true,
    "logLevel": "debug"
  }
}

I registered it in package.json

....
  "scripts": {
    "ng": "ng",
    "start": "ng serve --proxy-config proxy.conf.json",
....

Starting application as follows: npm start

Here ist the start log:

> ng serve --proxy-config proxy.conf.json

** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200 **
 10% building modules 3/3 modules 0 active[HPM] Proxy created: /profile  ->  http://localhost:8888
[HPM] Proxy rewrite rule created: "^/profile" ~> ""
[HPM] Subscribed to http-proxy events:  [ 'error', 'close' ]
Hash: 2f1f9b69df46574b900e
Time: 12544ms
chunk    {0} polyfills.bundle.js, polyfills.bundle.js.map (polyfills) 160 kB {4} [initial] [rendered]
chunk    {1} main.bundle.js, main.bundle.js.map (main) 131 kB {3} [initial] [rendered]
chunk    {2} styles.bundle.js, styles.bundle.js.map (styles) 255 kB {4} [initial] [rendered]
chunk    {3} vendor.bundle.js, vendor.bundle.js.map (vendor) 3.79 MB [initial] [rendered]
chunk    {4} inline.bundle.js, inline.bundle.js.map (inline) 0 bytes [entry] [rendered]
webpack: Compiled successfully.

And the problem is definitely not in the backend, because the cors is configured there. I monitor my request with Fiddler.

Here's how it looks now:

OPTIONS http://localhost:8888/profile/data/personal HTTP/1.1
Host: localhost:8888
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36
x-ijt: c2q0qqq02it9p2jrk3m6ihbs5u
Access-Control-Request-Headers: content-type,x-auth-token
Accept: */*
Referer: http://localhost:4200/
Accept-Encoding: gzip, deflate, br
Accept-Language: de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4

We are talking about this header: x-auth-token

I also read this topic.

angular-cli server - how to proxy API requests to another server?

Any Ideas? Thanks.

Body:
Reposting the answer I posted in that other question.

I had to make a small adjustment based on the above answers, although it seems a bit odd looking at the config now.

This is my proxy.conf.json shown below:

{
  "/api/*": {
    "target": "https://url.com",
    "secure": false,
    "changeOrigin": true,
    "logLevel": "debug",
    "pathRewrite": {"^/api" : "http://url.com/api"}
  }
}

Basically, I rewrote the path completely. And it works now.


问:
About pandas datareader
When I try to import pandas datareader, it throws me an error.

I tried following pattern because some one said it should be underscore pandas_datareader when you import it.

Please help.

Package

```<code>PS C:\Users\cris\Anaconda3> conda list | Select-String "pandas-datareader"

pandas-datareader         0.4.0                    py36_0

PS C:\Users\cris\Anaconda3>
</code>```

Python

```<code>>>> import pandas_datareader.data as web
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'pandas_datareader'
>>>
>>> import pandas-datareader.data as web
  File "<stdin>", line 1
    import pandas-datareader.data as web
                 ^
SyntaxError: invalid syntax
>>>
>>> import pandas-datareader-0.4.0.data as web
  File "<stdin>", line 1
    import pandas-datareader-0.4.0.data as web
                 ^
SyntaxError: invalid syntax
>>>
</code>```

答:
See this:
https://pandas-datareader.readthedocs.io/en/latest/

The correct syntax is:

```<code>import pandas_datareader
</code>```

common convention is to import it as 'pdr' so a lot of code you read on the web will say this:

```<code>import pandas_datareader as pdr
</code>```

if you just want the web module, use this:

```<code>from pandas_datareader import wb
</code>```

Title: About pandas datareader

Body:
When I try to import pandas datareader, it throws me an error.

I tried following pattern because some one said it should be underscore pandas_datareader when you import it.

Please help.

Package

PS C:\Users\cris\Anaconda3> conda list | Select-String "pandas-datareader"

pandas-datareader         0.4.0                    py36_0

PS C:\Users\cris\Anaconda3>

Python

>>> import pandas_datareader.data as web
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'pandas_datareader'
>>>
>>> import pandas-datareader.data as web
  File "<stdin>", line 1
    import pandas-datareader.data as web
                 ^
SyntaxError: invalid syntax
>>>
>>> import pandas-datareader-0.4.0.data as web
  File "<stdin>", line 1
    import pandas-datareader-0.4.0.data as web
                 ^
SyntaxError: invalid syntax
>>>

Body:
See this:
https://pandas-datareader.readthedocs.io/en/latest/

The correct syntax is:

import pandas_datareader

common convention is to import it as 'pdr' so a lot of code you read on the web will say this:

import pandas_datareader as pdr

if you just want the web module, use this:

from pandas_datareader import wb


问:
Html table specify columns width in px does not work
I'm trying to make an ajax columns-resizable table, the interface works fine, but when I resize the columnns, the browser enlarges the table at max 100%, resizing eventually other columns.
I've tried with both this two solutions but no one works well:

1.

```<code>min-width: 100%;
table-layout: fixed;
width: 100%;
</code>```

with this solution, I need to resize any single column before going (if necessary) over 100%; if I enlarge only one column, for example, all the others columns are restricted, they does not maintain the original width (as I would)

2.

```<code>table-layout: fixed;
</code>```

Any ideas?

Edit:
This is the relevant html code:

```<code><table class="resizable" id="TabellaDati" ><thead>  <tr>
    <th id="MDT_ThID"><span>ID</span></th>
    <th id="MDT_ThText"  style="width: 146px;">Text</th>
    <th id="MDT_ThTitle"  style="width: 148px;">Title</th>
    <th id="MDT_ThCssClass"  style="width: 83px;">CssClass</th>
    <th id="MDT_ThUrl"  style="width: 92px;">Url</th>
    <th id="MDT_ThOrdine">Ordine</th>
    </tr>
</thead>
<tbody> <tr>
    <td headers="MDT_ThID">MenuAlbo</td>
    <td headers="MDT_ThText">Albo Pretorio</td>
    <td headers="MDT_ThTitle">Albo Pretorio</td>
    <td headers="MDT_ThCssClass"></td>
    <td headers="MDT_ThUrl">/AlboPretorio</td>
    <td headers="MDT_ThOrdine">2</td>
    </tr>
</tbody></table>
</code>```

And the Css:

```<code>#TabellaDati {
    min-width: 100%;
    table-layout: fixed;
    width: 100%;
}
table {
    border-collapse: collapse;
}
</code>```

答:
I answered a question on setting column width with css a couple of days ago. It may help to make sure that is set up correctly first.How to set table column width..  Basically I found I needed to set the table width as well as the th/td.  After that the table-layout: fixed should work alright.

EDIT:

SO, I missed that you had the cell width set inline. So I loaded your markup and css and that looks great.  (I'm using Chrome)

Then I was confused what the issue was and so I also realized that this is most likely an AJAX issue.  I'm not so hot with AJAX, but I'm still checking it out.

UPDATE:

Is there a reason why you must use Ajax?  That is, what benefit are you gaining by using AJAX instead of plain ol' Javascript like this:

```<code>var colText = document.getElementById('MDT_ThText');
function setWidth(w) {
 colText.style.width = w + "px";
}
</code>```

I feel like this would be a whole world easier, and it stays well formatted with the markup and styling you have.

If you are adamant in using AJAX, please provide what your code regarding AJAX.

Body:
I'm trying to make an ajax columns-resizable table, the interface works fine, but when I resize the columnns, the browser enlarges the table at max 100%, resizing eventually other columns.
I've tried with both this two solutions but no one works well:

1.

min-width: 100%;
table-layout: fixed;
width: 100%;

with this solution, I need to resize any single column before going (if necessary) over 100%; if I enlarge only one column, for example, all the others columns are restricted, they does not maintain the original width (as I would)

2.

table-layout: fixed;

Any ideas?

Edit:
This is the relevant html code:

    ID
    Text
    Title
    CssClass
    Url
    Ordine

    MenuAlbo
    Albo Pretorio
    Albo Pretorio

    /AlboPretorio
    2

And the Css:

#TabellaDati {
    min-width: 100%;
    table-layout: fixed;
    width: 100%;
}
table {
    border-collapse: collapse;
}

Body:
I answered a question on setting column width with css a couple of days ago. It may help to make sure that is set up correctly first.How to set table column width..  Basically I found I needed to set the table width as well as the th/td.  After that the table-layout: fixed should work alright.

EDIT:

SO, I missed that you had the cell width set inline. So I loaded your markup and css and that looks great.  (I'm using Chrome)

Then I was confused what the issue was and so I also realized that this is most likely an AJAX issue.  I'm not so hot with AJAX, but I'm still checking it out.

UPDATE:

Is there a reason why you must use Ajax?  That is, what benefit are you gaining by using AJAX instead of plain ol' Javascript like this:

var colText = document.getElementById('MDT_ThText');
function setWidth(w) {
 colText.style.width = w + "px";
}

I feel like this would be a whole world easier, and it stays well formatted with the markup and styling you have.

If you are adamant in using AJAX, please provide what your code regarding AJAX.

ContentLicense: CC BY-SA 2.5


问:
How do I get a latitude,longitude,state,and country using a zip code against the apache module maxmind mod geo ip
I'm able to get the following from the current client using the mod geoip:

```<code>$slat=apache_note("GEOIP_LATITUDE");$slon=apache_note("GEOIP_LONGITUDE");$scntry=apache_note("GEOIP_COUNTRY_CODE");
</code>```

However if I have a standalone zip code (possibly international) that I need to get the latitude and longitude and state and country for from this module how do I do that?

答: This is a geolocation module that translates IP address to other information. You cannot find information using ZIP code or postal codes.</p>

Body:
I'm able to get the following from the current client using the mod geoip:

$slat=apache_note("GEOIP_LATITUDE");$slon=apache_note("GEOIP_LONGITUDE");$scntry=apache_note("GEOIP_COUNTRY_CODE");

However if I have a standalone zip code (possibly international) that I need to get the latitude and longitude and state and country for from this module how do I do that?


问:
Ninject in WCF rest service hosted on Windows service
I created simple WCF Rest service:

```<code>[ServiceContract]
public interface IReadData
{
    [OperationContract]
    [WebInvoke(Method = "GET",
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Bare,
        UriTemplate = "GetHealthStatus")]
    string GetHealthStatus();
}
</code>```

And:

```<code>public class ReadData : IReadData
{
    private IFacadeToRepo repository;

    public ReadData(IFacadeToRepo connectorToRepo)
    {
        this.repository = connectorToRepo;
    }

    public string GetHealthStatus()
    {
        return "ok";
    }
}
</code>```

Next I created "mapper":

```<code>class NinjectBindings: NinjectModule
{
    public override void Load()
    {
        Bind<IReadData>().To<ReadData>();
        Bind<IFacadeToRepo>().To<RepositoryApi>();
    }
}
</code>```

And finally I created ServiceBase:

```<code>public partial class MyRestWCFRestWinSer : ServiceBase
{
    ServiceHost readDataServiceHost = null;
    private StandardKernel kernel;

    public MyRestWCFRestWinSer()
    {
        kernel = new StandardKernel();
        kernel.Load(Assembly.GetExecutingAssembly());

        InitializeComponent();
    }

    public void OnDebug()
    {
        OnStart(null);
    }

    protected override void OnStart(string[] args)
    {
        readDataServiceHost = new ServiceHost(kernel.Get<IReadData>());
        readDataServiceHost.Open();
    }

    protected override void OnStop()
    {
        if (readDataServiceHost != null)
        {
            readDataServiceHost.Close();
            readDataServiceHost = null;
        }
    }
}
</code>```

So I thought that now ninject should resolve IReadData and create new ReadData witch default IFacadeToRepo. But it doesn't work. After install windows service via installutil and running proces -> I receive "The  service is starting. The  service could not be started. The service did not report an error."

Could you help me with running these web services together with ninjects?

edit. It look like it have problem exclusive with:

```<code>kernel.Get<IReadData>()
</code>```

after replace it to:

typeof(ReadData)

and adding default, empty constructor to ReadData - it works

I made some testing by adding line after line.

答:
It appear to be very simple problem.

Firstly: When we are loading kernel into ninject, it should start method Load which was overwritten by

```<code>public override void Load().
</code>```

But it doesn't work.
Solution? Problem regarding to availability of this class:

```<code>class NinjectBindings: NinjectModule
</code>```

I changed it into:

```<code>public class NinjectBindings: NinjectModule
</code>```

In result it is work.

Second thing: I needed to change service behaviour by adding ServiceBehaviour:

```<code>[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple, UseSynchronizationContext = false)]
public class ReadData : IReadData
</code>```

That's it.

Body:
I created simple WCF Rest service:

[ServiceContract]
public interface IReadData
{
    [OperationContract]
    [WebInvoke(Method = "GET",
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Bare,
        UriTemplate = "GetHealthStatus")]
    string GetHealthStatus();
}

And:

public class ReadData : IReadData
{
    private IFacadeToRepo repository;

    public ReadData(IFacadeToRepo connectorToRepo)
    {
        this.repository = connectorToRepo;
    }

    public string GetHealthStatus()
    {
        return "ok";
    }
}

Next I created "mapper":

class NinjectBindings: NinjectModule
{
    public override void Load()
    {
        Bind<IReadData>().To<ReadData>();
        Bind<IFacadeToRepo>().To<RepositoryApi>();
    }
}

And finally I created ServiceBase:

public partial class MyRestWCFRestWinSer : ServiceBase
{
    ServiceHost readDataServiceHost = null;
    private StandardKernel kernel;

    public MyRestWCFRestWinSer()
    {
        kernel = new StandardKernel();
        kernel.Load(Assembly.GetExecutingAssembly());

        InitializeComponent();
    }

    public void OnDebug()
    {
        OnStart(null);
    }

    protected override void OnStart(string[] args)
    {
        readDataServiceHost = new ServiceHost(kernel.Get<IReadData>());
        readDataServiceHost.Open();
    }

    protected override void OnStop()
    {
        if (readDataServiceHost != null)
        {
            readDataServiceHost.Close();
            readDataServiceHost = null;
        }
    }
}

So I thought that now ninject should resolve IReadData and create new ReadData witch default IFacadeToRepo. But it doesn't work. After install windows service via installutil and running proces -> I receive "The  service is starting. The  service could not be started. The service did not report an error."

Could you help me with running these web services together with ninjects?

edit. It look like it have problem exclusive with:

kernel.Get<IReadData>()

after replace it to:

typeof(ReadData)

and adding default, empty constructor to ReadData - it works

I made some testing by adding line after line.

Body:
It appear to be very simple problem.

Firstly: When we are loading kernel into ninject, it should start method Load which was overwritten by

public override void Load().

But it doesn't work.
Solution? Problem regarding to availability of this class:

class NinjectBindings: NinjectModule

I changed it into:

public class NinjectBindings: NinjectModule

In result it is work.

Second thing: I needed to change service behaviour by adding ServiceBehaviour:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple, UseSynchronizationContext = false)]
public class ReadData : IReadData

That's it.


问:
Preventing cheating for on-line arcade high score board
I'm going to be developing an online arcade for HTML5/Javascript games written in a to-be-released IDE.

The game will use Ajax requests to the server to record scores when people play these games.

I theoretically have complete control over the design of this, including the mechanics of the code that logs the high scores, game code, everything.

I know it's never impossible to hack client side games such as this or spoof high scores, but I want to make it difficult enough so that anyone competent enough wont be bothered enough to do it (wishful thinking).

I've read:

How can you prevent bogus high scores from appearing on a global high score list?

Which is a slightly different question as this is HTML/JS specific.

My initial idea is that the ajax request checks the source of the request is from the correct location, which is a simple and effective block for most hacking attempts.

答:
This doesn't work for all games but...

If you log all control input on every frame, and also log the RNG seed at the start of the level, it may be possible to re-run the level by replaying the controller input and get the exact same sequence of events.  This can be used to verify that the game was actually played and the score was not just made up.  It will be expensive to verify every game, but there are other options, e.g. only verify a game if the score would be in the top 100, or test random games and disable the accounts if verification fails.

Then sit back and watch as the cheaters start using robots to play for them instead, which is even harder to defend against.


问:
how to insert html, css and php in mail function in php
I am confused to use this function when my coding is too long and there is "php" function in email. Can you give me an example? I want to send an email according to this code that I created this from  to  * end     </p>

```<code>  <!doctype html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Wherco</title>

        <!-- Latest compiled and minified css -->
           <link rel="stylesheet" href="../view/css/bootstrap.min.css">
        <!-- optional theme-->
           <link rel="stylesheet" href="../view/css/bootstrap-theme.min.css">
        <!--my custom css-->
           <link rel="stylesheet" href="../view/css/style.css">
        <!--font-awesome-->
           <link rel="stylesheet" href="../view/font-awesome/css/font-awesome.min.css">

        <style>
        .invoice-box{
            max-width:800px;
            margin:auto;
            padding:30px;
            border:1px solid #eee;
            box-shadow:0 0 10px rgba(0, 0, 0, .15);
            font-size:16px;
            line-height:24px;
            font-family:'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif;
            color:#555;
        }

        .invoice-box table{
            width:100%;
            line-height:inherit;
            text-align:left;
        }

        .invoice-box table td{
            padding:5px;
            vertical-align:top;
        }

        .invoice-box table tr td:nth-child(2){
            text-align:right;
        }

        .invoice-box table tr.top table td{
            padding-bottom:20px;
        }

        .invoice-box table tr.top table td.title{
            font-size:45px;
            line-height:45px;
            color:#333;
        }

        .invoice-box table tr.information table td{
            padding-bottom:40px;
        }

        .invoice-box table tr.heading td{
            background:#eee;
            border-bottom:1px solid #ddd;
            font-weight:bold;
        }

        .invoice-box table tr.details td{
            padding-bottom:20px;
        }

        .invoice-box table tr.item td{
            border-bottom:1px solid #eee;
        }

        .invoice-box table tr.item.last td{
            border-bottom:none;
        }

        .invoice-box table tr.total td:nth-child(2){
            border-top:2px solid #eee;
            font-weight:bold;
        }

        @media only screen and (max-width: 600px) {
            .invoice-box table tr.top table td{
                width:100%;
                display:block;
                text-align:center;
            }

            .invoice-box table tr.information table td{
                width:100%;
                display:block;
                text-align:center;
            }
        }
        </style>
    </head>

    <?php $result = tampil_per_id_order($_GET['id']);
    while($row = mysqli_fetch_assoc($result)) { ?>

    <body>
        <div class="invoice-box">
            <table cellpadding="0" cellspacing="0">
                <tr class="top">
                    <td colspan="2">
                        <table>
                            <tr>
                                <td class="title">
                                    <h7> Wherco </h7>
                                </td>

                                <td>
                                    Invoice order #: <?php echo $row['id_order']?><br>
                                    Created: <?php echo date("Y-m-d"); ?><br>
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>

                <tr class="information">
                    <td colspan="2">
                        <table>
                            <tr>
                                <td>
                                    Wherco.<br>
                                    12345 Seminyak<br>
                                    -
                                </td>

                                <td>
                                    <?php echo $row['username']?><br>
                                      <?php echo $row['email']?><br>
                                      <?php echo $row['telp']?>
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>

                <tr class="heading">
                    <td>
                        Deskripsi Project
                    </td>

                    <td>
                        Tanggal Transfer
                    </td>
                </tr>

                <tr class="details">
                    <td>
                          <?php echo $row['deskripsi']?>
                    </td>

                    <td>
                      <?php echo $row['tanggal_konfirmasi']?>
                    </td>
                </tr>

                <tr class="heading">
                    <td>
                        Jenis Package
                    </td>

                    <td>
                        Biaya
                    </td>
                </tr>

                <tr class="item">
                    <td>
                      <?php echo $row['jenis_package']?>
                    </td>

                    <td>
                        Rp.<?php echo number_format($row['jumlah_transfer']); ?>
                    </td>
                </tr>

                <tr class="item last">
                    <td>

                    </td>

                    <td>

                    </td>
                </tr>

                <tr class="total">
                    <td>Total</td>

                    <td>
                      Rp.<?php echo number_format($row['jumlah_transfer']); ?> <br> <br>
                  <form class="" action="" method="post">
                      <div class="btn-group" role="group" aria-label="...">
                          <button type="submit" class="btn btn-success">Kirim Email</button>
                      </div>
                </form>
                    </td>
                </tr>
            </table>
        </div>
    </body>
      <?php }?>
    </html>
</code>```

答:
You are not writing code to be processed by a server and rendered by a browser - You are writing a self-contained webpage that takes the form of an email. You are severely restricted in what you can do.

You can't use PHP, JS, iframes, or any really anything that one would consider fancy. Email is stuck in the 90's in terms of technology (and for good reason), so write like your audience is running IE 5.5 on Windows 95.

You are only allowed a few things:

CSS contained in

Basic HTML (think HTML4 strict)

Images in  and are automatically blocked by most clients

Background images can be used, but with many restrictions. And are blocked like regular images.

Any PHP that needs to run must be done before you ever send the email.

See this answer on how to send emails with PHP: https://stackoverflow.com/a/5335311/618693

Body:
I am confused to use this function when my coding is too long and there is "php" function in email. Can you give me an example? I want to send an email according to this code that I created this from  to  * end

  <!doctype html>

        <meta charset="utf-8">
        <title>Wherco</title>

           <link rel="stylesheet" href="../view/css/bootstrap.min.css">

           <link rel="stylesheet" href="../view/css/bootstrap-theme.min.css">

           <link rel="stylesheet" href="../view/css/style.css">

           <link rel="stylesheet" href="../view/font-awesome/css/font-awesome.min.css">

    <?php $result = tampil_per_id_order($_GET['id']);
    while($row = mysqli_fetch_assoc($result)) { ?>

                                    <h7> Wherco </h7>

                                    Invoice order #: <?php echo $row['id_order']?>

                                    Created: <?php echo date("Y-m-d"); ?>

                                    Wherco.

                                    12345 Seminyak

                                    -

                                    <?php echo $row['username']?>

                                      <?php echo $row['email']?>

                                      <?php echo $row['telp']?>

                        Deskripsi Project

                        Tanggal Transfer

                          <?php echo $row['deskripsi']?>

                      <?php echo $row['tanggal_konfirmasi']?>

                        Jenis Package

                        Biaya

                      <?php echo $row['jenis_package']?>

                        Rp.<?php echo number_format($row['jumlah_transfer']); ?>

                    Total

                      Rp.<?php echo number_format($row['jumlah_transfer']); ?>

                  <form class="" action="" method="post">

                          <button type="submit" class="btn btn-success">Kirim Email</button>

                </form>

      <?php }?>

Body:
You are not writing code to be processed by a server and rendered by a browser - You are writing a self-contained webpage that takes the form of an email. You are severely restricted in what you can do.

You can't use PHP, JS, iframes, or any really anything that one would consider fancy. Email is stuck in the 90's in terms of technology (and for good reason), so write like your audience is running IE 5.5 on Windows 95.

You are only allowed a few things:

CSS contained in <style></style>

Basic HTML (think HTML4 strict)

Images in <img ..> and are automatically blocked by most clients

Background images can be used, but with many restrictions. And are blocked like regular images.

Any PHP that needs to run must be done before you ever send the email.

See this answer on how to send emails with PHP: https://stackoverflow.com/a/5335311/618693


问:
How to read column one by one in python pandas?
I have read file from URL as follows :

```<code>    url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"

    names = ['sepal length', 'sepal width', 'petal length', 'petal width',  'class']

    data = pd.read_csv(url, names=names)

    print(data.shape)

    print(data)
</code>```

Now, I want to read one column and do some processing (may be min, max, or std dev, r score etc) and then again read another column and do some processing.

Is there any way to do it in scikit learn/pandas/python?

答:
some dummy data

```<code>data = pd.DataFrame({'sepal length' : np.random.randn(3), 'sepal width' : np.random.randn(3)})
</code>```

if you want some customize calculations on all the columns one by one then you can apply for loop on the column names as

```<code>>>>for col in data.columns:
            print(col)
            print(np.mean(data[col]))
[out]: 'sepal length'
        -1.06206436799
       'sepal width'
       -0.586939385059
</code>```

If you are importing data in pandas dataframe then this would be the output.You can also include your customise operations on columns in the loop.

Body:
I have read file from URL as follows :

    url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"

    names = ['sepal length', 'sepal width', 'petal length', 'petal width',  'class']

    data = pd.read_csv(url, names=names)

    print(data.shape)

    print(data)

Now, I want to read one column and do some processing (may be min, max, or std dev, r score etc) and then again read another column and do some processing.

Is there any way to do it in scikit learn/pandas/python?

Body:
some dummy data

data = pd.DataFrame({'sepal length' : np.random.randn(3), 'sepal width' : np.random.randn(3)})

if you want some customize calculations on all the columns one by one then you can apply for loop on the column names as

>>>for col in data.columns:
            print(col)
            print(np.mean(data[col]))
[out]: 'sepal length'
        -1.06206436799
       'sepal width'
       -0.586939385059

If you are importing data in pandas dataframe then this would be the output.You can also include your customise operations on columns in the loop.


问:
Excel Vlookup Formula required from pivoted data
I have a simple data table from a pivot table in the following format:

```<code> A                          B           C            D
 Names                      Dog         Cat          Horse
 John Smith                 1           1            0
 Jane Smith                 0           0            0
 Jane Dow                   0           1            0
 John Dow                   1           1            1
</code>```

I want to use a formula to populate another table using the one above. The second table has a different ordering to it. For example Horse is in Column B instead of D and John Smith is on Row 5 instead of 1.

```<code> A                          B           C            D
 Names                      Horse       Cat          Dog
 John Dow                   ?
 Jane Smith
 Jane Dow
 John Smith
</code>```

What is the best formula to use given these circumstances, I do not think a Vlookup/hlookup will work because it is dependent on both horizontal and vertical variables.

答:
Try this formula in G2 cell (VLOOKUP with MATCH)

```<code>=VLOOKUP($F2,$A:$D,MATCH(TRIM(G$1),$A$1:$D$1,0),0)
</code>```

Body:
I have a simple data table from a pivot table in the following format:

 A                          B           C            D
 Names                      Dog         Cat          Horse
 John Smith                 1           1            0
 Jane Smith                 0           0            0
 Jane Dow                   0           1            0
 John Dow                   1           1            1

I want to use a formula to populate another table using the one above. The second table has a different ordering to it. For example Horse is in Column B instead of D and John Smith is on Row 5 instead of 1.

 A                          B           C            D
 Names                      Horse       Cat          Dog
 John Dow                   ?
 Jane Smith
 Jane Dow
 John Smith

What is the best formula to use given these circumstances, I do not think a Vlookup/hlookup will work because it is dependent on both horizontal and vertical variables.

Body:
Try this formula in G2 cell (VLOOKUP with MATCH)

=VLOOKUP($F2,$A:$D,MATCH(TRIM(G$1),$A$1:$D$1,0),0)


问:
Will async and await help increase the throughput when app makes short multiple db calls?
The application I am working on uses multiple short duration DB calls to read and update data. The output of one call is being used by the other.

In this scenario whether using await for each DB calls will result in an increase in throughput?

The application and DB are hosted separately.

Proof Of Concept built actually decreased the throughput and I speculate it is because of the overhead of context switching.

Sync version provided roughly 8 req/second, while the async provided only 2.5 req/second.

I have ensured httpTargetRuntime is set to 4.5.2, used aync and await all the way to the asmx service which uses APM style end point as documented https://learn.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/interop-with-other-asynchronous-patterns-and-types#ApmToTap

I am using ADO.NET async versions methods and have set Asynchronous Processing = True in connection string.

Should async await be considered good fit for short oltp transactions?

How to troubleshoot if the above is because of deadlock. We have done the review of code and did not observe any place where the .Result is used from task directly apart from the one mentioned in the link above.

答:
No, because you are not accessing them in parallel. Async and Await just return the context to the caller, thus making the main thread not have to wait. But the same amount of work needs to be done, with or without Async Await, and it's done waiting every call to pass the result to the next (plus the context switching).

I would recommend rewriting your logic to be able to call only one request to the database, creating a stored procedure if necessary, for example.


问:
parsing comma seperated values in MS-SQL (no csv or such)
I use a closed source commercial application that uses an MS-SQL database. I regularly have to query this database myself for various purposes. This means the table and database design is fixed, and I can't do anything about it at all. I just have to live with it. Now I have two tables with the following layouts (abstracted, not to discredit the software/database designer)

```<code>t1: ID (int), att1(varchar), att2(varchar), .... attx(varchar)

t2: ID (int), t1_ids(varchar)
</code>```

Now the contents of this t1_ids is (shudder) a comma separated list of t1 id's. (for example 12, 456, 43, 675, 54). What I want to do is (you guessed it) join those two tables.

Fortunately for me, these are very small tables, and I don't care about performance in terms of complexity at all (could be O(n^m) as far as I care).

Ideally I would like to make a view that joins these two tables. I don't have any requirements for inserting or updating, just for select statements. What would be the easiest and clearest (in terms of maintainability) way to do this?

答:
EDIT: I realised after posting this answer the PARSENAME function can only return one part of the parsed string, so it's not a useful as I thought it would be in your situation.

Searching SO for alternative solutions I came across an interesting answer to this question: Split String in SQL

If you can add triggers to your database then you could call the split string on INSERT, UPDATE and DELETE to maintain another table with the id's separated as rows. Then you can create your view using that table.

I know you said you don't mind about the speed of the query but at least that way you are not parsing all the strings every time you query the data.

Body:
I use a closed source commercial application that uses an MS-SQL database. I regularly have to query this database myself for various purposes. This means the table and database design is fixed, and I can't do anything about it at all. I just have to live with it. Now I have two tables with the following layouts (abstracted, not to discredit the software/database designer)

t1: ID (int), att1(varchar), att2(varchar), .... attx(varchar)

t2: ID (int), t1_ids(varchar)

Now the contents of this t1_ids is (shudder) a comma separated list of t1 id's. (for example 12, 456, 43, 675, 54). What I want to do is (you guessed it) join those two tables.

Fortunately for me, these are very small tables, and I don't care about performance in terms of complexity at all (could be O(n^m) as far as I care).

Ideally I would like to make a view that joins these two tables. I don't have any requirements for inserting or updating, just for select statements. What would be the easiest and clearest (in terms of maintainability) way to do this?


问:
query sql join and where clause
First table employee

```<code>id   empName     empEmail           empSal   active
====================================================
13   sadf        asdf@sdf.com       233       1
12   checkout    cherckout@g.com    3         1
11   safg        asdf@asdf.com      123       1
10   sdf         sadf@sdf           4         1
9    sdaf        asdf@sdf.com       3         1
8    asdf        asdf@sdf.com       8         1
7    asdf        asdf@sdf.com       8         1
6    asdf        asdf@sdf.com       8         1
</code>```

Second Table emp_status

```<code>id  emp_id  EmpSalary  active
=============================
5   4       156        1
4   2       156        1
3   2       555        1
2   1       200        0
1   1       1500       1

SELECT o.*
FROM employees as o
LEFT JOIN emp_status as emp ON emp.emp_id = o.id
WHERE (emp.active IS NULL OR (emp.active != 0))
GROUP BY o.id
ORDER BY o.id DESC
</code>```

If emp_status has two rows one having status 1 and other having status 0 what we want it should not count to 1 if I have zero it should help out the execution. how could it be possible?

答:
Don't pass join table condition on where clause and I suggest you active column datatype =ENUM And set value 0,1,2,3,4,5,6</p>

```<code>SELECT o.* FROM employees as o
LEFT JOIN emp_status as emp ON emp.emp_id = o.id and emp.active IN (1,2,3,5,6) GROUP BY o.id ORDER BY o.id DESC
</code>```

Title: query sql join and where clause

Body:
First table employee

id   empName     empEmail           empSal   active
====================================================
13   sadf        asdf@sdf.com       233       1
12   checkout    cherckout@g.com    3         1
11   safg        asdf@asdf.com      123       1
10   sdf         sadf@sdf           4         1
9    sdaf        asdf@sdf.com       3         1
8    asdf        asdf@sdf.com       8         1
7    asdf        asdf@sdf.com       8         1
6    asdf        asdf@sdf.com       8         1

Second Table emp_status

id  emp_id  EmpSalary  active
=============================
5   4       156        1
4   2       156        1
3   2       555        1
2   1       200        0
1   1       1500       1

SELECT o.*
FROM employees as o
LEFT JOIN emp_status as emp ON emp.emp_id = o.id
WHERE (emp.active IS NULL OR (emp.active != 0))
GROUP BY o.id
ORDER BY o.id DESC

If emp_status has two rows one having status 1 and other having status 0 what we want it should not count to 1 if I have zero it should help out the execution. how could it be possible?

Body:
Don't pass join table condition on where clause and I suggest you active column datatype =ENUM And set value 0,1,2,3,4,5,6

SELECT o.* FROM employees as o
LEFT JOIN emp_status as emp ON emp.emp_id = o.id and emp.active IN (1,2,3,5,6) GROUP BY o.id ORDER BY o.id DESC


问:
Search mysql database by phrase or seperate key words
Ok so when a user types their search phrase in the search input, I would like it to match the exact phrase or the key words entered.
I.e
So the title of a post is "Search the Database"

```<code>$searchVal = "Search database";
WHERE post_title LIKE '%" . $searchVal . "%'
</code>```

The above code doesn't find a match as the title has "the" between Search Database.

How could I get it to match.
I thought maybe using explode but Im getting an error:

```<code>$sVals = explode(" ", $searchVal);
foreach ($sVals as $s) {
    $querySearchVals .= "OR post_title LIKE '%" . $s . "%'";
}
</code>```

Hope that makes sense.
Cheers

答:
You may want to insert the % in between the words and execute with 1 where clause. some thing like below should work.

```<code>$searchVal = "Search database";
$querySearchVals = "post_title LIKE '%";
$sVals = explode(" ", $searchVal);
foreach ($sVals as $s) {
    $querySearchVals .= $s."%";
}
$querySearchVals .= "'";
echo $querySearchVals;
</code>```

Hope it helps!

Body:
Ok so when a user types their search phrase in the search input, I would like it to match the exact phrase or the key words entered.
I.e
So the title of a post is "Search the Database"

$searchVal = "Search database";
WHERE post_title LIKE '%" . $searchVal . "%'

The above code doesn't find a match as the title has "the" between Search Database.

How could I get it to match.
I thought maybe using explode but Im getting an error:

$sVals = explode(" ", $searchVal);
foreach ($sVals as $s) {
    $querySearchVals .= "OR post_title LIKE '%" . $s . "%'";
}

Hope that makes sense.
Cheers

Body:
You may want to insert the % in between the words and execute with 1 where clause. some thing like below should work.

$searchVal = "Search database";
$querySearchVals = "post_title LIKE '%";
$sVals = explode(" ", $searchVal);
foreach ($sVals as $s) {
    $querySearchVals .= $s."%";
}
$querySearchVals .= "'";
echo $querySearchVals;

Hope it helps!


问:
Insert error while inserting data to PostgreSQL with python psycopg2
```<code> try:
            for i in (0, nCount):
                query = "INSERT INTO students (Name, ID, Birth) VALUES (%s %d %d);"
                data = ('Y', 2, 9)
                cur.execute(query, data)
                conn.commit()

 except:
            print("I can't INSERT into students")
</code>```

Connect to database and select operation are work but insert operation is not.

I use PostgreSQL and pgAdmin4

And create database use pgAdmin4

The DB structure is Name(text), Id(integer), Birth(integer)

-------------------------------------------------------------------------

Solve

* Change type of all columns to text (not text[]).

 * Change column name in DB to small letter.

答: From my best knowledge you missed , in values clause. I think you need write smthng like values (%s,%d,%d)

Body:
 try:
            for i in (0, nCount):
                query = "INSERT INTO students (Name, ID, Birth) VALUES (%s %d %d);"
                data = ('Y', 2, 9)
                cur.execute(query, data)
                conn.commit()

 except:
            print("I can't INSERT into students")

Connect to database and select operation are work but insert operation is not.

I use PostgreSQL and pgAdmin4

And create database use pgAdmin4

The DB structure is Name(text), Id(integer), Birth(integer)

-------------------------------------------------------------------------

Solve

* Change type of all columns to text (not text[]).

 * Change column name in DB to small letter.


问:
What is the difference between the GNU Makefile variable assignments =, ?=, := and +=?
Can anybody give a clear explanation of how variable assignment really works in Makefiles.

What is the difference between :

```<code> VARIABLE = value
 VARIABLE ?= value
 VARIABLE := value
 VARIABLE += value
</code>```

I have read the section in GNU Make's manual, but it still doesn't make sense to me.

答:
Using = causes the variable to be assigned a value.  If the variable already had a value, it is replaced.  This value will be expanded when it is used.  For example:

```<code>HELLO = world
HELLO_WORLD = $(HELLO) world!

# This echoes "world world!"
echo $(HELLO_WORLD)

HELLO = hello

# This echoes "hello world!"
echo $(HELLO_WORLD)
</code>```

Using := is similar to using =.  However, instead of the value being expanded when it is used, it is expanded during the assignment.  For example:

```<code>HELLO = world
HELLO_WORLD := $(HELLO) world!

# This echoes "world world!"
echo $(HELLO_WORLD)

HELLO = hello

# Still echoes "world world!"
echo $(HELLO_WORLD)

HELLO_WORLD := $(HELLO) world!

# This echoes "hello world!"
echo $(HELLO_WORLD)
</code>```

Using ?= assigns the variable a value iff the variable was not previously assigned.  If the variable was previously assigned a blank value (VAR=), it is still considered set I think.  Otherwise, functions exactly like =.

Using += is like using =, but instead of replacing the value, the value is appended to the current one, with a space in between.  If the variable was previously set with :=, it is expanded I think.  The resulting value is expanded when it is used I think.  For example:

```<code>HELLO_WORLD = hello
HELLO_WORLD += world!

# This echoes "hello world!"
echo $(HELLO_WORLD)
</code>```

If something like HELLO_WORLD = $(HELLO_WORLD) world! were used, recursion would result, which would most likely end the execution of your Makefile.  If A := $(A) $(B) were used, the result would not be the exact same as using += because B is expanded with := whereas += would not cause B to be expanded.

OwnerDisplayName: mmoris

Body:
Can anybody give a clear explanation of how variable assignment really works in Makefiles.

What is the difference between :

 VARIABLE = value
 VARIABLE ?= value
 VARIABLE := value
 VARIABLE += value

I have read the section in GNU Make's manual, but it still doesn't make sense to me.

Body:
Using = causes the variable to be assigned a value.  If the variable already had a value, it is replaced.  This value will be expanded when it is used.  For example:

HELLO = world
HELLO_WORLD = $(HELLO) world!

# This echoes "world world!"
echo $(HELLO_WORLD)

HELLO = hello

# This echoes "hello world!"
echo $(HELLO_WORLD)

Using := is similar to using =.  However, instead of the value being expanded when it is used, it is expanded during the assignment.  For example:

HELLO = world
HELLO_WORLD := $(HELLO) world!

# This echoes "world world!"
echo $(HELLO_WORLD)

HELLO = hello

# Still echoes "world world!"
echo $(HELLO_WORLD)

HELLO_WORLD := $(HELLO) world!

# This echoes "hello world!"
echo $(HELLO_WORLD)

Using ?= assigns the variable a value iff the variable was not previously assigned.  If the variable was previously assigned a blank value (VAR=), it is still considered set I think.  Otherwise, functions exactly like =.

Using += is like using =, but instead of replacing the value, the value is appended to the current one, with a space in between.  If the variable was previously set with :=, it is expanded I think.  The resulting value is expanded when it is used I think.  For example:

HELLO_WORLD = hello
HELLO_WORLD += world!

# This echoes "hello world!"
echo $(HELLO_WORLD)

If something like HELLO_WORLD = $(HELLO_WORLD) world! were used, recursion would result, which would most likely end the execution of your Makefile.  If A := $(A) $(B) were used, the result would not be the exact same as using += because B is expanded with := whereas += would not cause B to be expanded.

OwnerDisplayName: strager

LastEditorDisplayName: strager


问:
Ruby/RoR - Count occurrence of an element in an array
I'v a hash

{1=>true, 7=>false, 6=>true, 4=>false}

or an array like

[1, true], [7, false], [6, true], [4, false]]

or

[true, false, true, false].

How can I find the number of trues in the array?

答:
Simpler:

```<code>hash.values.count(true)

array.flatten.count(true)
</code>```

This works with all the above cases.

Body:
Simpler:

hash.values.count(true)

array.flatten.count(true)

This works with all the above cases.


问:
Payu payement error "Some error occurred, Try again!"
I have integrated payu into my android app through official docs at
https://www.payumoney.com/dev-guide/mobilecheckout/android.html#prereq .

The problem i'm facing is that my code works perfectly with test credentials, and fails when i use credentials of my live account that i want to integrate in the app.

```<code>   public void makePayment(View view) {
    String phone = "8882434664";
    String productName = "product_name";
    String firstName = "piyush";
    String txnId = "0nf7" + System.currentTimeMillis();
    String email = "piyush.jain@payu.in";
    String sUrl = "https://test.payumoney.com/mobileapp/payumoney/success.php";
    String fUrl = "https://test.payumoney.com/mobileapp/payumoney/failure.php";
    String udf1 = "";
    String udf2 = "";
    String udf3 = "";
    String udf4 = "";
    String udf5 = "";
    boolean isDebug = true;

    String key = "2fcU3pmI";
    String merchantId = "4947182";// These credentials are from https://test.payumoney.com/
    String salt = "BxA24L2F7Z";   //  THIS WORKS

  /*  String key = "yX8OvWy1";     //These credentials are from https://www.payumoney.com/
    String merchantId = "5826688"; //THIS DOESN'T WORK
    String salt = "0vciMJBbaa";    //ERROR: "some error occurred, Try again"
  */

    PayUmoneySdkInitilizer.PaymentParam.Builder builder = new PayUmoneySdkInitilizer.PaymentParam.Builder();

    builder.setAmount(getAmount())
            .setTnxId(txnId)
            .setPhone(phone)
            .setProductName(productName)
            .setFirstName(firstName)
            .setEmail(email)
            .setsUrl(sUrl)
            .setfUrl(fUrl)
            .setUdf1(udf1)
            .setUdf2(udf2)
            .setUdf3(udf3)
            .setUdf4(udf4)
            .setUdf5(udf5)
            .setIsDebug(isDebug) //Also can someone clarify if this should be true/false for live mode
            .setKey(key)
            .setMerchantId(merchantId);

    PayUmoneySdkInitilizer.PaymentParam paymentParam = builder.build();

    String hash = hashCal(key + "|" + txnId + "|" + getAmount() + "|" + productName + "|"
            + firstName + "|" + email + "|" + udf1 + "|" + udf2 + "|" + udf3 + "|" + udf4 + "|" + udf5 + "|" + salt);
    Log.d("app_activity123", hash);
    paymentParam.setMerchantHash(hash);

    PayUmoneySdkInitilizer.startPaymentActivityForResult(MyActivity.this, paymentParam);

}
</code>```

Extra Info: Test credentials weren't working initially. I had to contact the payu support team to activate the account after which the code was working fine. My employer said he has activated the live account so i don't know what is the issue here.

There are no other issues like mine here, the closest one is here PayuMoney Integration in Android : Some error occured! Try again and it is unanswered.

答:
setIsDebug(boolean) you need to pass false as parameter in this method to use live payment and true when testing in live mode.
I've set it to false and used Real Merchant id,salt and key and it worked, no errors.
Hope this helps someone.

Body:
I have integrated payu into my android app through official docs at
https://www.payumoney.com/dev-guide/mobilecheckout/android.html#prereq .

The problem i'm facing is that my code works perfectly with test credentials, and fails when i use credentials of my live account that i want to integrate in the app.

   public void makePayment(View view) {
    String phone = "8882434664";
    String productName = "product_name";
    String firstName = "piyush";
    String txnId = "0nf7" + System.currentTimeMillis();
    String email = "piyush.jain@payu.in";
    String sUrl = "https://test.payumoney.com/mobileapp/payumoney/success.php";
    String fUrl = "https://test.payumoney.com/mobileapp/payumoney/failure.php";
    String udf1 = "";
    String udf2 = "";
    String udf3 = "";
    String udf4 = "";
    String udf5 = "";
    boolean isDebug = true;

    String key = "2fcU3pmI";
    String merchantId = "4947182";// These credentials are from https://test.payumoney.com/
    String salt = "BxA24L2F7Z";   //  THIS WORKS

  /*  String key = "yX8OvWy1";     //These credentials are from https://www.payumoney.com/
    String merchantId = "5826688"; //THIS DOESN'T WORK
    String salt = "0vciMJBbaa";    //ERROR: "some error occurred, Try again"
  */

    PayUmoneySdkInitilizer.PaymentParam.Builder builder = new PayUmoneySdkInitilizer.PaymentParam.Builder();

    builder.setAmount(getAmount())
            .setTnxId(txnId)
            .setPhone(phone)
            .setProductName(productName)
            .setFirstName(firstName)
            .setEmail(email)
            .setsUrl(sUrl)
            .setfUrl(fUrl)
            .setUdf1(udf1)
            .setUdf2(udf2)
            .setUdf3(udf3)
            .setUdf4(udf4)
            .setUdf5(udf5)
            .setIsDebug(isDebug) //Also can someone clarify if this should be true/false for live mode
            .setKey(key)
            .setMerchantId(merchantId);

    PayUmoneySdkInitilizer.PaymentParam paymentParam = builder.build();

    String hash = hashCal(key + "|" + txnId + "|" + getAmount() + "|" + productName + "|"
            + firstName + "|" + email + "|" + udf1 + "|" + udf2 + "|" + udf3 + "|" + udf4 + "|" + udf5 + "|" + salt);
    Log.d("app_activity123", hash);
    paymentParam.setMerchantHash(hash);

    PayUmoneySdkInitilizer.startPaymentActivityForResult(MyActivity.this, paymentParam);

}

Extra Info: Test credentials weren't working initially. I had to contact the payu support team to activate the account after which the code was working fine. My employer said he has activated the live account so i don't know what is the issue here.

There are no other issues like mine here, the closest one is here PayuMoney Integration in Android : Some error occured! Try again and it is unanswered.


问:
Element type is invalid: expected a string (for built-in components) or a class/function
```<code>import React from 'react';
import ReactDOM from 'react-dom';
import Map from './components/map/container/map';
import App from './App';
import './index.css';
import shell from './shared/utility/shell';
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore, applyMiddleware, compose } from 'redux'
import { routerMiddleware, ConnectedRouter } from 'react-router-redux'
import thunk from 'redux-thunk'
import createHistory from 'history/createBrowserHistory'
import rootReducer from './reducers'
import registerServiceWorker from './registerServiceWorker';
import { Routes } from './config';

const history = createHistory();
const target = document.querySelector('#root')
const initialState = {};
const enhancers = [];
const middleware = [
thunk,
routerMiddleware(history)
 ];

if (process.env.NODE_ENV === 'development') {
const devToolsExtension = window.devToolsExtension;

if (typeof devToolsExtension === 'function') {
enhancers.push(devToolsExtension());
 }
}
const composedEnhancers = compose(
applyMiddleware(...middleware),
  ...enhancers
);
const store = createStore(
 rootReducer,
 initialState,
 composedEnhancers
);
render(
  <Provider store={store}>
   <ConnectedRouter history={history}>
    <div>
     <Routes />
    </div>
   </ConnectedRouter>
  </Provider>,
  target
   )
 registerServiceWorker();
 ReactDOM.render(<App />, document.getElementById('root'));
 registerServiceWorker();
</code>```

I am trying to call an API from with the help of redux and display its data in a table. I am getting this error. Above is my index.js file.

1.
  Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.

2.
  React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.

I have referred to many answers I am not able to recognize the error.

答:
Problem is in the import statements. You have not used curly braces while importing some components like createHistory.

If a component uses a default export like:

```<code>export default X
</code>```

Then you can simply import it like:

```<code>import X from './X';
</code>```

But if you are using a named export like:

```<code>export const X=1;
</code>```

Then you need to import it in curly braces like:

```<code>import {X} from './X';
</code>```

So have a look at your imports. This will resolve your issue.

Body:
import React from 'react';
import ReactDOM from 'react-dom';
import Map from './components/map/container/map';
import App from './App';
import './index.css';
import shell from './shared/utility/shell';
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore, applyMiddleware, compose } from 'redux'
import { routerMiddleware, ConnectedRouter } from 'react-router-redux'
import thunk from 'redux-thunk'
import createHistory from 'history/createBrowserHistory'
import rootReducer from './reducers'
import registerServiceWorker from './registerServiceWorker';
import { Routes } from './config';

const history = createHistory();
const target = document.querySelector('#root')
const initialState = {};
const enhancers = [];
const middleware = [
thunk,
routerMiddleware(history)
 ];

if (process.env.NODE_ENV === 'development') {
const devToolsExtension = window.devToolsExtension;

if (typeof devToolsExtension === 'function') {
enhancers.push(devToolsExtension());
 }
}
const composedEnhancers = compose(
applyMiddleware(...middleware),
  ...enhancers
);
const store = createStore(
 rootReducer,
 initialState,
 composedEnhancers
);
render(
  <Provider store={store}>
   <ConnectedRouter history={history}>

     <Routes />

   </ConnectedRouter>
  </Provider>,
  target
   )
 registerServiceWorker();
 ReactDOM.render(<App />, document.getElementById('root'));
 registerServiceWorker();

I am trying to call an API from with the help of redux and display its data in a table. I am getting this error. Above is my index.js file.

1.
  Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.

2.
  React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.

I have referred to many answers I am not able to recognize the error.

Body:
Problem is in the import statements. You have not used curly braces while importing some components like createHistory.

If a component uses a default export like:

export default X

Then you can simply import it like:

import X from './X';

But if you are using a named export like:

export const X=1;

Then you need to import it in curly braces like:

import {X} from './X';

So have a look at your imports. This will resolve your issue.


问:
Trouble adding a variable as a table name SQL/PHP
I am having some issues with my code. It has worked previously, but now it seems to not want to work at all.

The PHP line is as follows: (all sensitive data has been altered for protective purposes)

```<code><?php
$servername = "*****";
$server_username = "*****";
$server_password = "*****";
$dbName = "*****";

$tableName = $_POST["tableNamePost"];
$variable1 = $_POST["variable1Post"];
$variable2 = $_POST["variable2Post"];
$variable3 = $_POST["variable3Post"];
$variable4 = $_POST["variable4Post"];
$variable5 = $_POST["variable5Post"];

$conn = new mysqli($servername, $server_username, $server_password, $dbName);

if(!$conn)
{
    die("Connection Failed" .mysqli_connect_error());
}
$sql = "INSERT INTO ".$tableName." VALUES ('".$variable1."', '".$variable2."', '".$variable3."', '".$variable4."', '".$variable5."', '0', '0', '0', '0')";
$result = mysqli_query($conn, $sql);
?>
</code>```

All variables for tableName(s) are matching as they are static variables in the program itself. The C# code segment is as follows: (again, all sensitive data has been altered for protective purposes)

```<code>public string tableName;
public int var1;
public string var2;
public string var3;
public string var4;
public int var5;
public float var6;
public float var7;
string AddToTableURL = "http://urlofthe.php"; //The actual link has been tested and works fine.

public void FunctionInQuestion()
{
    float i = (var7 / 60.0f * var6);
    var5 = Mathf.FloorToInt(i);
    WWWForm form = new WWWForm();
    form.AddField("tableNamePost", tableName);
    form.AddField("dayNumberPost", var1.ToString());
    form.AddField("dueDayPost", var2);
    form.AddField("timeOfTheDayPost", var3);
    form.AddField("choreNamePost", var4);
    form.AddField("pointsOnOfferPost", var5.ToString());
    WWW www = new WWW(AddToTableURL, form);
    NextFunction();
}
</code>```

The problem I am having is that my C# that defines the variables is running through correctly, but I cannot determine as to whether the PHP is receiving the variables or not. Every time I run the scripts, nothing is added to the databases.

Has something been missed or is incorrectly written? I have been over the code for a few days now and cannot find the issue.

答:
You'll have to make debug-purpose PHP code to check what's going on, or to read PHP error and database server error logs if enabled on the server.

As far as I see from this code we have: tableName (C#) as null.

Also, depending on version of MySQL server you're running it might be issue of not putting the table name in the right quote symbol - try qouting `$tableName` like this on PHP side.

Also, check the character-set you're using for database connection - if $tableName has some Unicode characters or something?

And just in case make full database.tablename path in INSERT INTO call - maybe you're selecting another database in other places on the PHP side.

The last thing I would double check: are you sure you want to insert these zeros as varchar/text value and not as integer? Remove the quotes around them.

Update 1:
Are you sure you are using HTTP POST method with the form (C#)?
I can't see in your code your're setting POST as method of the WWW form object.

Update 2:
Put mysqli debug code to see if there were also errors in the SQL execution/syntax.

Check this example from PHP documentation (http://php.net/manual/en/mysqli.quickstart.statements.php):

```<code><?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT)") ||
    !$mysqli->query("INSERT INTO test(id) VALUES (1)")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
?>
</code>```

Try this form of the INSERT INTO command.

Body:
I am having some issues with my code. It has worked previously, but now it seems to not want to work at all.

The PHP line is as follows: (all sensitive data has been altered for protective purposes)

<?php
$servername = "*****";
$server_username = "*****";
$server_password = "*****";
$dbName = "*****";

$tableName = $_POST["tableNamePost"];
$variable1 = $_POST["variable1Post"];
$variable2 = $_POST["variable2Post"];
$variable3 = $_POST["variable3Post"];
$variable4 = $_POST["variable4Post"];
$variable5 = $_POST["variable5Post"];

$conn = new mysqli($servername, $server_username, $server_password, $dbName);

if(!$conn)
{
    die("Connection Failed" .mysqli_connect_error());
}
$sql = "INSERT INTO ".$tableName." VALUES ('".$variable1."', '".$variable2."', '".$variable3."', '".$variable4."', '".$variable5."', '0', '0', '0', '0')";
$result = mysqli_query($conn, $sql);
?>

All variables for tableName(s) are matching as they are static variables in the program itself. The C# code segment is as follows: (again, all sensitive data has been altered for protective purposes)

public string tableName;
public int var1;
public string var2;
public string var3;
public string var4;
public int var5;
public float var6;
public float var7;
string AddToTableURL = "http://urlofthe.php"; //The actual link has been tested and works fine.

public void FunctionInQuestion()
{
    float i = (var7 / 60.0f * var6);
    var5 = Mathf.FloorToInt(i);
    WWWForm form = new WWWForm();
    form.AddField("tableNamePost", tableName);
    form.AddField("dayNumberPost", var1.ToString());
    form.AddField("dueDayPost", var2);
    form.AddField("timeOfTheDayPost", var3);
    form.AddField("choreNamePost", var4);
    form.AddField("pointsOnOfferPost", var5.ToString());
    WWW www = new WWW(AddToTableURL, form);
    NextFunction();
}

The problem I am having is that my C# that defines the variables is running through correctly, but I cannot determine as to whether the PHP is receiving the variables or not. Every time I run the scripts, nothing is added to the databases.

Has something been missed or is incorrectly written? I have been over the code for a few days now and cannot find the issue.

Body:
You'll have to make debug-purpose PHP code to check what's going on, or to read PHP error and database server error logs if enabled on the server.

As far as I see from this code we have: tableName (C#) as null.

Also, depending on version of MySQL server you're running it might be issue of not putting the table name in the right quote symbol - try qouting `$tableName` like this on PHP side.

Also, check the character-set you're using for database connection - if $tableName has some Unicode characters or something?

And just in case make full database.tablename path in INSERT INTO call - maybe you're selecting another database in other places on the PHP side.

The last thing I would double check: are you sure you want to insert these zeros as varchar/text value and not as integer? Remove the quotes around them.

Update 1:
Are you sure you are using HTTP POST method with the form (C#)?
I can't see in your code your're setting POST as method of the WWW form object.

Update 2:
Put mysqli debug code to see if there were also errors in the SQL execution/syntax.

Check this example from PHP documentation (http://php.net/manual/en/mysqli.quickstart.statements.php):

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT)") ||
    !$mysqli->query("INSERT INTO test(id) VALUES (1)")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
?>

Try this form of the INSERT INTO command.