问:
LINQ Group by and count concatenated output
With this query:

```<code>foreach(var y in items)
{
        <div>@y.fieldA => @y.FieldB</div>
}
</code>```

I get this output:

```<code>3 => 2
3 => 1
2 => 2
3 => 2
</code>```

I know in LINQ we can easily count and group by with this:

```<code>foreach(var y in items.GroupBy(g => g.Field)
                      .Select(group => new {Field = group.Key, count = group.Count()}))
{
    <div>@y.Field : @y.count</div>
}
</code>```

But how can I adapt this to the concatenated output so that I can get this result:

```<code>3 => 2 : 2
3 => 1 : 1
2 => 2 : 1
</code>```

答:
Use Select to project the desired string instead of projecting an anonymous object:

```<code>foreach(var item in items.GroupBy(g => $"{g.FieldA} => {g.FieldB}")
                         .Select(g => $"{g.Key} : {g.Count()}"))
{
    <div>@item</div>
}
</code>```

For a pre C# 6.0 version:

```<code>foreach(var item in items.GroupBy(g => g.FieldA + " => " + g.FieldB)
                         .Select(g => g.Key + " : " + g.Count()))
{
    <div>@item</div>
}
</code>```

Body:
With this query:

foreach(var y in items)
{

@y.fieldA => @y.FieldB

}

I get this output:

3 => 2
3 => 1
2 => 2
3 => 2

I know in LINQ we can easily count and group by with this:

foreach(var y in items.GroupBy(g => g.Field)
                      .Select(group => new {Field = group.Key, count = group.Count()}))
{

@y.Field : @y.count

}

But how can I adapt this to the concatenated output so that I can get this result:

3 => 2 : 2
3 => 1 : 1
2 => 2 : 1

Body:
Use Select to project the desired string instead of projecting an anonymous object:

foreach(var item in items.GroupBy(g => $"{g.FieldA} => {g.FieldB}")
                         .Select(g => $"{g.Key} : {g.Count()}"))
{
    <div>@item</div>
}

For a pre C# 6.0 version:

foreach(var item in items.GroupBy(g => g.FieldA + " => " + g.FieldB)
                         .Select(g => g.Key + " : " + g.Count()))
{
    <div>@item</div>
}


来源: stackexchange

问:
XPath trying to get the third position
I want to get the authors on the third position. I am using //authors[3]. Is there any reason this way does not work? When i type //authors[1] i get the whole row.

```<code><publications>

    <publication>

    <publication_name> Group agency: The possibility, design, and status of corporate agents </publication_name>
    <authors> C List,P Pettit  </authors>
    <publisher> Oxford University Press </publisher>
    <year> 2011 </year>
    <citation> 598 </citation>

</publication>

<publication>

    <publication_name> Aggregating sets of judgments: An impossibility result</publication_name>
    <authors> C List, P Pettit  </authors>
    <publisher> Economics and Philosophy </publisher>
    <volume> 18 </volume>
    <number> 1 </number>
    <pages> 89- 110 </pages>
    <citation> 558 </citation>
    <year> 2002 </year>e

</publication>

<publication>

    <publication_name> Epistemic democracy: generalizing the Condorcet jury theorem</publication_name>
    <authors> C List, RE Goodin  </authors>
    <publisher> Journal of Political Philosophy </publisher>
    <volume> 9 </volume>
    <number> 3 </number>
    <pages> 277-306 </pages>
    <citation> 409 </citation>
    <year> 2001 </year>

</publication>

<publication>

    <publication_name> Arrow’s theorem in judgment aggregation </publication_name>
    <authors> F Dietrich, C List  </authors>
    <publisher> Social Choice and Welfare </publisher>
    <volume> 29 </volume>
    <number> 1 </number>
    <pages> 19 - 33 </pages>
    <citation> 220 </citation>
    <year> 2007 </year>

</publication>

<publication>

    <publication_name> Deliberation, single-peakedness, and the possibility of meaningful democracy: evidence from deliberative polls </publication_name>
    <authors> C List, RC Luskin, JS Fishkin, I McLean  </authors>
    <publisher> Journal of Politics </publisher>
    <volume> 75 </volume>
    <number> 01 </number>
    <pages> 80-95 </pages>
    <citation> 143 </citation>
    <year> 2013 </year>

</publication>

<publication>

    <publication_name> Swarm intelligence: When uncertainty meets conflict </publication_name>
    <authors> L Conradt, C List, TJ Roper </authors>
    <publisher> The American Naturalist </publisher>
    <volume> 182 </volume>
    <number> 5 </number>
    <pages> 592-610 </pages>
    <citation> 10 </citation>
    <year> 2013 </year>

</publication>

<publication>

    <publication_name> Intradimensional Single-peakedness and the Multidimensional Arrow Problem </publication_name>
    <authors> C List </authors>
    <publisher> Theory and Decision </publisher>
    <citation> 10 </citation>
    <year> 2004 </year>

</publication>

<publication>

    <publication_name> The methodology of political theory </publication_name>
    <authors> C List, L Valentini  </authors>
    <publisher> The Oxford Handbook of Philosophical Methodology </publisher>
    <citation> 8 </citation>
    <year> 2016 </year>

</publication>

<publication>

    <publication_name> Social choice theory and deliberative democracy: a response to Aldred </publication_name>
    <authors> JS Dryzek, C List </authors>
    <publisher> British Journal of Political Science </publisher>
    <volume> 34 </volume>
    <number> 4 </number>
    <pages> 752-758 </pages>
    <citation> 8 </citation>
    <year> 2004 </year>

</publication>

<publication>

    <publication_name> Episteme symposium on group agency: Replies to Gaus, Cariani, Sylvan, and Briggs </publication_name>
    <authors> C List, P Pettit </authors>
    <publisher> Episteme </publisher>
    <volume> 9 </volume>
    <number> 3 </number>
    <pages> 293 </pages>
    <citation> 5 </citation>
    <year> 2012 </year>

</publication>

<publication>

    <publication_name> Two intuitions about free will: Alternative possibilities and intentional endorsement </publication_name>
    <authors> C List, W Rabinowicz  </authors>
    <publication> Philosophical Perspectives </publication>
    <volume> 28 </volume>
    <number> 1 </number>
    <pages> 155-172 </pages>
    <citation> 4 </citation>
    <year> 2014 </year>

</publication>

<publication>

    <publication_name> Reasons for (prior) belief in Bayesian epistemology </publication_name>
    <authors> F Dietrich, C List  </authors>
    <publisher> Synthese </publisher>
    <volume> 190 </volume>
    <number> 5 </number>
    <pages> 787-808 </pages>
    <citation> 4 </citation>
    <year> 2013 </year>

</publication>

<publication>

    <publication_name> Freedom as independence </publication_name>
    <authors> C List, L Valentini  </authors>
    <publisher> Ethics </publisher>
    <volume> 126 </volume>
    <number> 4 </number>
    <pages> 1043-1074 </pages>
    <citation> 3 </citation>
    <year> 2016 </year>

</publication>

<publication>

    <publication_name> Belief revision generalized: A joint characterization of Bayes' and Jeffrey's rules </publication_name>
    <authors> F Dietrich, C List, R Bradley </authors>
    <publisher> Journal of Economic Theory </publisher>
    <volume> 162</volume>
    <pages> 352–371 </pages>
    <citation> 3 </citation>
    <year> 2016 </year>

</publication>

    <publication>

        <publication_name>Which worlds are possible? A judgment aggregation problem</publication_name>
        <authors>C List</authors>
        <publisher>Journal of Philosophical Logic</publisher>
        <volume>37</volume>
        <number>1</number>
        <pages>57-65</pages>
        <citation>12</citation>
        <year>2008</year>

    </publication>

</publications>
</code>```

I only want to get the author on the third position.

There is no result and i get an error saying: The XPath query returned no results. XPath scope:current file.

答:
This XPath 2.0 expression,

```<code>//authors[count(tokenize(.,',')) > 2]/tokenize(.,',')[3]
</code>```

will select the third author listed for each publication,

```<code>JS Fishkin
TJ Roper
R Bradley
</code>```

for those author elements that have 3 or more authors (as identified via comma separation).

XPath 1.0 solution is left as an exercise for the reader.

ContentLicense: CC BY-SA 3.0

Title: XPath trying to get the third position

Body:
I want to get the authors on the third position. I am using //authors[3]. Is there any reason this way does not work? When i type //authors[1] i get the whole row.

<publications>

    <publication>

    <publication_name> Group agency: The possibility, design, and status of corporate agents </publication_name>
    <authors> C List,P Pettit  </authors>
    <publisher> Oxford University Press </publisher>
    <year> 2011 </year>
    <citation> 598 </citation>

</publication>

<publication>

    <publication_name> Aggregating sets of judgments: An impossibility result</publication_name>
    <authors> C List, P Pettit  </authors>
    <publisher> Economics and Philosophy </publisher>
    <volume> 18 </volume>
    <number> 1 </number>
    <pages> 89- 110 </pages>
    <citation> 558 </citation>
    <year> 2002 </year>e

</publication>

<publication>

    <publication_name> Epistemic democracy: generalizing the Condorcet jury theorem</publication_name>
    <authors> C List, RE Goodin  </authors>
    <publisher> Journal of Political Philosophy </publisher>
    <volume> 9 </volume>
    <number> 3 </number>
    <pages> 277-306 </pages>
    <citation> 409 </citation>
    <year> 2001 </year>

</publication>

<publication>

    <publication_name> Arrow’s theorem in judgment aggregation </publication_name>
    <authors> F Dietrich, C List  </authors>
    <publisher> Social Choice and Welfare </publisher>
    <volume> 29 </volume>
    <number> 1 </number>
    <pages> 19 - 33 </pages>
    <citation> 220 </citation>
    <year> 2007 </year>

</publication>

<publication>

    <publication_name> Deliberation, single-peakedness, and the possibility of meaningful democracy: evidence from deliberative polls </publication_name>
    <authors> C List, RC Luskin, JS Fishkin, I McLean  </authors>
    <publisher> Journal of Politics </publisher>
    <volume> 75 </volume>
    <number> 01 </number>
    <pages> 80-95 </pages>
    <citation> 143 </citation>
    <year> 2013 </year>

</publication>

<publication>

    <publication_name> Swarm intelligence: When uncertainty meets conflict </publication_name>
    <authors> L Conradt, C List, TJ Roper </authors>
    <publisher> The American Naturalist </publisher>
    <volume> 182 </volume>
    <number> 5 </number>
    <pages> 592-610 </pages>
    <citation> 10 </citation>
    <year> 2013 </year>

</publication>

<publication>

    <publication_name> Intradimensional Single-peakedness and the Multidimensional Arrow Problem </publication_name>
    <authors> C List </authors>
    <publisher> Theory and Decision </publisher>
    <citation> 10 </citation>
    <year> 2004 </year>

</publication>

<publication>

    <publication_name> The methodology of political theory </publication_name>
    <authors> C List, L Valentini  </authors>
    <publisher> The Oxford Handbook of Philosophical Methodology </publisher>
    <citation> 8 </citation>
    <year> 2016 </year>

</publication>

<publication>

    <publication_name> Social choice theory and deliberative democracy: a response to Aldred </publication_name>
    <authors> JS Dryzek, C List </authors>
    <publisher> British Journal of Political Science </publisher>
    <volume> 34 </volume>
    <number> 4 </number>
    <pages> 752-758 </pages>
    <citation> 8 </citation>
    <year> 2004 </year>

</publication>

<publication>

    <publication_name> Episteme symposium on group agency: Replies to Gaus, Cariani, Sylvan, and Briggs </publication_name>
    <authors> C List, P Pettit </authors>
    <publisher> Episteme </publisher>
    <volume> 9 </volume>
    <number> 3 </number>
    <pages> 293 </pages>
    <citation> 5 </citation>
    <year> 2012 </year>

</publication>

<publication>

    <publication_name> Two intuitions about free will: Alternative possibilities and intentional endorsement </publication_name>
    <authors> C List, W Rabinowicz  </authors>
    <publication> Philosophical Perspectives </publication>
    <volume> 28 </volume>
    <number> 1 </number>
    <pages> 155-172 </pages>
    <citation> 4 </citation>
    <year> 2014 </year>

</publication>

<publication>

    <publication_name> Reasons for (prior) belief in Bayesian epistemology </publication_name>
    <authors> F Dietrich, C List  </authors>
    <publisher> Synthese </publisher>
    <volume> 190 </volume>
    <number> 5 </number>
    <pages> 787-808 </pages>
    <citation> 4 </citation>
    <year> 2013 </year>

</publication>

<publication>

    <publication_name> Freedom as independence </publication_name>
    <authors> C List, L Valentini  </authors>
    <publisher> Ethics </publisher>
    <volume> 126 </volume>
    <number> 4 </number>
    <pages> 1043-1074 </pages>
    <citation> 3 </citation>
    <year> 2016 </year>

</publication>

<publication>

    <publication_name> Belief revision generalized: A joint characterization of Bayes' and Jeffrey's rules </publication_name>
    <authors> F Dietrich, C List, R Bradley </authors>
    <publisher> Journal of Economic Theory </publisher>
    <volume> 162</volume>
    <pages> 352–371 </pages>
    <citation> 3 </citation>
    <year> 2016 </year>

</publication>

    <publication>

        <publication_name>Which worlds are possible? A judgment aggregation problem</publication_name>
        <authors>C List</authors>
        <publisher>Journal of Philosophical Logic</publisher>
        <volume>37</volume>
        <number>1</number>
        <pages>57-65</pages>
        <citation>12</citation>
        <year>2008</year>

    </publication>

</publications>

I only want to get the author on the third position.

There is no result and i get an error saying: The XPath query returned no results. XPath scope:current file.

Body:
This XPath 2.0 expression,

//authors[count(tokenize(.,',')) > 2]/tokenize(.,',')[3]

will select the third author listed for each publication,

JS Fishkin
TJ Roper
R Bradley

for those author elements that have 3 or more authors (as identified via comma separation).

XPath 1.0 solution is left as an exercise for the reader.


问:
Android: How many times can I send a high priority GCM to my app in Android 7.0?
I have an android app and I am using GCM. I will upgrade it to FCM. But for now, How many times can I send high priority GCM, or for the sake of it FCM so that it can do some network requests in an hour.</p>

答:
If you are referring to Downstream messages, there is no limit on how many messages you could send regardless of it's priority.

I noticed that you added the android-doze tag in your question. For some devices, it is possible that some requests will be postponed or dropped until such time that the app exits doze mode, similarly to what happens when the app is in background and/or killed state (see here).


问:
only first paragraph appending javascript
I am attempting to add multiple "p" elements with different inner texts but for some reason only one paragraph element in total is appending, which always seems to be the final one in the code.

My code is shown below. Thanks for the help.

HTML:

```<code><select>
<option>Movie Title</option>
  <option>Movie Actor</option>
  <option>Genre</option>
  <option>Release Year</option>
</select>
  <input type="text" id="search">

<button id="submitSearch">SUBMIT</button>

<div id="searchresult">

</div>
</code>```

JAVASCRIPT:

```<code>var searchBtn = document.getElementById("submitSearch");
var userSearch = document.getElementById("search");
var resultDiv = document.getElementById("searchresult");

searchBtn.addEventListener("click",function(){
  var userMovie = userSearch.value.toLowerCase();
  //removing all white space from title
  var arraySearch = userMovie.split(" ");
  var convertedSearch = arraySearch.join("");
  if (!movies[convertedSearch]){
    console.log("Sorry, this does not match any DVD's you own");
  } else {
    var para = document.createElement("p");
    resultDiv.appendChild(para);
    para.innerText = "Title: " + movies[convertedSearch].title;
    resultDiv.appendChild(para);
    para.innerText = "Cast: " + movies[convertedSearch].cast;
  }
})
</code>```

答:
The problem is that you're not asking the browser to append two paragraphs: you're asking it to append the same one (para) twice. No DOM element can be in two places at once, so it is failing.

You need to repeat para = document.createElement("p"); after appending it the first time. That will ask the browser to create two paragraphs and append them both.

Body:
I am attempting to add multiple "p" elements with different inner texts but for some reason only one paragraph element in total is appending, which always seems to be the final one in the code.

My code is shown below. Thanks for the help.

HTML:

<select>
<option>Movie Title</option>
  <option>Movie Actor</option>
  <option>Genre</option>
  <option>Release Year</option>
</select>
  <input type="text" id="search">

<button id="submitSearch">SUBMIT</button>

JAVASCRIPT:

var searchBtn = document.getElementById("submitSearch");
var userSearch = document.getElementById("search");
var resultDiv = document.getElementById("searchresult");

searchBtn.addEventListener("click",function(){
  var userMovie = userSearch.value.toLowerCase();
  //removing all white space from title
  var arraySearch = userMovie.split(" ");
  var convertedSearch = arraySearch.join("");
  if (!movies[convertedSearch]){
    console.log("Sorry, this does not match any DVD's you own");
  } else {
    var para = document.createElement("p");
    resultDiv.appendChild(para);
    para.innerText = "Title: " + movies[convertedSearch].title;
    resultDiv.appendChild(para);
    para.innerText = "Cast: " + movies[convertedSearch].cast;
  }
})


问:
How to join two JDBC tables and avoid Exchange?
I've got ETL-like scenario, in which I read data from multiple JDBC tables and files and perform some aggregations and join between sources.

In one step I must join two JDBC tables. I've tried to do something like:

val df1 = spark.read.format("jdbc")
            .option("url", Database.DB_URL)
            .option("user", Database.DB_USER)
            .option("password", Database.DB_PASSWORD)
            .option("dbtable", tableName)
            .option("driver", Database.DB_DRIVER)
            .option("upperBound", data.upperBound)
            .option("lowerBound", data.lowerBound)
            .option("numPartitions", data.numPartitions)
            .option("partitionColumn", data.partitionColumn)
            .load();

val df2 = spark.read.format("jdbc")
            .option("url", Database.DB_URL)
            .option("user", Database.DB_USER)
            .option("password", Database.DB_PASSWORD)
            .option("dbtable", tableName)
            .option("driver", Database.DB_DRIVER)
            .option("upperBound", data2.upperBound)
            .option("lowerBound", data2.lowerBound)
            .option("numPartitions", data2.numPartitions)
            .option("partitionColumn", data2.partitionColumn)
            .load();

df1.join(df2, Seq("partition_key", "id")).show();
```

<p>Note that <code>partitionColumn</code> in both cases is the same - "partition_key".</p>

<p>However, when I run such query, I can see unnecessary exchange (plan cleared for readability):</p>

<pre class="lang-scala prettyprint-override"><code>df1.join(df2, Seq("partition_key", "id")).explain(extended = true);
</code>```

Project [many many fields]
+- Project [partition_key#10090L, iv_id#10091L, last_update_timestamp#10114,  ... more fields]
    +- SortMergeJoin [partition_key#10090L, id#10091L], [partition_key#10172L, id#10179L], Inner
       :- *Sort [partition_key#10090L ASC NULLS FIRST, iv_id#10091L ASC NULLS FIRST], false, 0
       :  +- Exchange hashpartitioning(partition_key#10090L, iv_id#10091L, 4)
       :     +- *Scan JDBCRelation((select mod(s.id, 23) as partition_key, s.* from tab2 s)) [numPartitions=23] [partition_key#10090L,id#10091L,last_update_timestamp#10114] PushedFilters: [*IsNotNull(PARTITION_KEY)], ReadSchema: struct<partition_key:bigint,id:bigint,last_update_timestamp:timestamp>
       +- *Sort [partition_key#10172L ASC NULLS FIRST, id#10179L ASC NULLS FIRST], false, 0
          +- Exchange hashpartitioning(partition_key#10172L, iv_id#10179L, 4)
             +- *Project [partition_key#10172L, id#10179L ... 75 more fields]
               +- *Scan JDBCRelation((select mod(s.id, 23) as partition_key, s.* from tab1 s)) [numPartitions=23] [fields] PushedFilters: [*IsNotNull(ID), *IsNotNull(PARTITION_KEY)], ReadSchema: struct<partition_key:bigint,id:bigint...
```

If we have already partitioned reading with numPartitions and other options, partition count is the same, why there is a need for another Exchange? Can we somehow avoid this unnecessary shuffle? On the test data I see Sparks sends more than 150M of data during this Exchange, where production Datasets are much bigger, so it can be serious bottleneck.

答:
With current implementation of the Date Source API there is no partitioning information passed upstream so even if data could be joined without a shuffle, Spark cannot use this information. Therefore your assumption that:

JdbcRelation uses RangePartitioning on reading

is just incorrect. Furthermore it looks like Spark uses the same internal code to handle range-based JDBC partitions and predicate-based JDBC partitions. While the former one could be translated to SortOrder, the latter one might be incompatible with Spark SQL in general.

When in doubt, it is possible to retrieve Partitioner information using QueryExecution and internal RDD:

```<code>df.queryExecution.toRdd.partitioner
</code>```

This might change in the future (SPIP:  Data  Source  API  V2, SPARK-15689 - Data source API v2 and
Spark Data Frame. PreSorded partitions ).

Body:
I've got ETL-like scenario, in which I read data from multiple JDBC tables and files and perform some aggregations and join between sources.

In one step I must join two JDBC tables. I've tried to do something like:

val df1 = spark.read.format("jdbc")
            .option("url", Database.DB_URL)
            .option("user", Database.DB_USER)
            .option("password", Database.DB_PASSWORD)
            .option("dbtable", tableName)
            .option("driver", Database.DB_DRIVER)
            .option("upperBound", data.upperBound)
            .option("lowerBound", data.lowerBound)
            .option("numPartitions", data.numPartitions)
            .option("partitionColumn", data.partitionColumn)
            .load();

val df2 = spark.read.format("jdbc")
            .option("url", Database.DB_URL)
            .option("user", Database.DB_USER)
            .option("password", Database.DB_PASSWORD)
            .option("dbtable", tableName)
            .option("driver", Database.DB_DRIVER)
            .option("upperBound", data2.upperBound)
            .option("lowerBound", data2.lowerBound)
            .option("numPartitions", data2.numPartitions)
            .option("partitionColumn", data2.partitionColumn)
            .load();

df1.join(df2, Seq("partition_key", "id")).show();

Note that partitionColumn in both cases is the same - "partition_key".

However, when I run such query, I can see unnecessary exchange (plan cleared for readability):

df1.join(df2, Seq("partition_key", "id")).explain(extended = true);

Project [many many fields]
+- Project [partition_key#10090L, iv_id#10091L, last_update_timestamp#10114,  ... more fields]
    +- SortMergeJoin [partition_key#10090L, id#10091L], [partition_key#10172L, id#10179L], Inner
       :- *Sort [partition_key#10090L ASC NULLS FIRST, iv_id#10091L ASC NULLS FIRST], false, 0
       :  +- Exchange hashpartitioning(partition_key#10090L, iv_id#10091L, 4)
       :     +- *Scan JDBCRelation((select mod(s.id, 23) as partition_key, s.* from tab2 s)) [numPartitions=23] [partition_key#10090L,id#10091L,last_update_timestamp#10114] PushedFilters: [*IsNotNull(PARTITION_KEY)], ReadSchema: struct<partition_key:bigint,id:bigint,last_update_timestamp:timestamp>
       +- *Sort [partition_key#10172L ASC NULLS FIRST, id#10179L ASC NULLS FIRST], false, 0
          +- Exchange hashpartitioning(partition_key#10172L, iv_id#10179L, 4)
             +- *Project [partition_key#10172L, id#10179L ... 75 more fields]
               +- *Scan JDBCRelation((select mod(s.id, 23) as partition_key, s.* from tab1 s)) [numPartitions=23] [fields] PushedFilters: [*IsNotNull(ID), *IsNotNull(PARTITION_KEY)], ReadSchema: struct<partition_key:bigint,id:bigint...

If we have already partitioned reading with numPartitions and other options, partition count is the same, why there is a need for another Exchange? Can we somehow avoid this unnecessary shuffle? On the test data I see Sparks sends more than 150M of data during this Exchange, where production Datasets are much bigger, so it can be serious bottleneck.

Body:
With current implementation of the Date Source API there is no partitioning information passed upstream so even if data could be joined without a shuffle, Spark cannot use this information. Therefore your assumption that:

JdbcRelation uses RangePartitioning on reading

is just incorrect. Furthermore it looks like Spark uses the same internal code to handle range-based JDBC partitions and predicate-based JDBC partitions. While the former one could be translated to SortOrder, the latter one might be incompatible with Spark SQL in general.

When in doubt, it is possible to retrieve Partitioner information using QueryExecution and internal RDD:

df.queryExecution.toRdd.partitioner

This might change in the future (SPIP:  Data  Source  API  V2, SPARK-15689 - Data source API v2 and
Spark Data Frame. PreSorded partitions ).


问:
if element class = element class or data-attr do something
Hi have two different megamenus, which cannot be displayed by css based on the html markup. Therefore I want to use Javascript/jQuery.

```<code>HTML of links:
<li id="menu-item-154" class="tg-submenu__link .tg-submenu__tg menu-item menu-item-type-post_type menu-item-object-page menu-item-154">
<a href="#">MEGAMENU-LINK1</a></li>

<li id="menu-item-155" class="tg-submenu__link .tg-submenu__abteilungen menu-item menu-item-type-post_type menu-item-object-page menu-item-155">
<a href="#">MEGA MENU LINK2</a></li>

HTML of the mega menu containers
<div class="tg-submenu tg-submenu__tg" data-trigger="tg-submenu__tg">
</div>

<div class="tg-submenu tg-submenu__abteilungen" data-trigger="tg-submenu__abteilungen">
</div>
</code>```

So I'd like to run a function, which checks if the links has the same classes (.tg-submenu__tg and .tg-submenu__abteilungen) or the same data-trigger attribute and if so add a class to the particular mega menu container by hovering the corresponding link. I could easily write two separate functions which test this isolated but I need an universal function, cause the links may change or more links may be added in the future.

答:
Ok, this is what I came up by using .hasClass, which was adviced by @Darshit Hedpara:

```<code>jQuery(document).ready (function ($) {
var $tg_body = $('body'),
    $tg_top_menu = $('ul.nav'),
    $tg_submenu_link = $('.tg-submenu__link');

    $tg_submenu_link.hover(function() {
    if (! $(this).closest('li.tg-submenu__link').length || $(this).hasClass('tg-submenu__link') && $(this).hasClass('tg-submenu__link--tgkonz')) {
        $tg_body.addClass('tg-submenu__tg--active tg-showDropdown');
        $tg_body.removeClass('tg-hover').addClass('tg-hover');
        tg_menu_hover_triggered = true;
    }
    else {
        $tg_body.addClass('tg-submenu__abteilungen--active tg-showDropdown');
        $tg_body.removeClass('tg-hover').addClass('tg-hover');
    }
}, function () {
    $tg_body.removeClass('tg-submenu__tg--active tg-submenu__abteilungen--active tg-showDropdown');
    $tg_body.addClass('tg-submenu__removing');

    tg_menu_hover_triggered = false;

    setTimeout(function () {
        if (! $tg_body.hasClass('tg-showDropdown')) {
            $tg_body.removeClass('tg-hover').removeClass('tg-submenu__removing');
        }
    }, 200);
});
});
</code>```

This is not for universal purpose. For example, if I decide to include a third megamenu, I would to rewrite the code. If someone has an idea to make this universal with a callback function or has some ideas to make this a way more performant/best practice, feel free to repost. I'll keep an eye on this topic!

Body:
Hi have two different megamenus, which cannot be displayed by css based on the html markup. Therefore I want to use Javascript/jQuery.

HTML of links:

MEGAMENU-LINK1

MEGA MENU LINK2

HTML of the mega menu containers

So I'd like to run a function, which checks if the links has the same classes (.tg-submenu__tg and .tg-submenu__abteilungen) or the same data-trigger attribute and if so add a class to the particular mega menu container by hovering the corresponding link. I could easily write two separate functions which test this isolated but I need an universal function, cause the links may change or more links may be added in the future.

Body:
Ok, this is what I came up by using .hasClass, which was adviced by @Darshit Hedpara:

jQuery(document).ready (function ($) {
var $tg_body = $('body'),
    $tg_top_menu = $('ul.nav'),
    $tg_submenu_link = $('.tg-submenu__link');

    $tg_submenu_link.hover(function() {
    if (! $(this).closest('li.tg-submenu__link').length || $(this).hasClass('tg-submenu__link') && $(this).hasClass('tg-submenu__link--tgkonz')) {
        $tg_body.addClass('tg-submenu__tg--active tg-showDropdown');
        $tg_body.removeClass('tg-hover').addClass('tg-hover');
        tg_menu_hover_triggered = true;
    }
    else {
        $tg_body.addClass('tg-submenu__abteilungen--active tg-showDropdown');
        $tg_body.removeClass('tg-hover').addClass('tg-hover');
    }
}, function () {
    $tg_body.removeClass('tg-submenu__tg--active tg-submenu__abteilungen--active tg-showDropdown');
    $tg_body.addClass('tg-submenu__removing');

    tg_menu_hover_triggered = false;

    setTimeout(function () {
        if (! $tg_body.hasClass('tg-showDropdown')) {
            $tg_body.removeClass('tg-hover').removeClass('tg-submenu__removing');
        }
    }, 200);
});
});

This is not for universal purpose. For example, if I decide to include a third megamenu, I would to rewrite the code. If someone has an idea to make this universal with a callback function or has some ideas to make this a way more performant/best practice, feel free to repost. I'll keep an eye on this topic!


问:
How can I connect two segment controls to each other?

I'm trying to disable the bottom segment control if the user clicks Diesel. The problem is I can't connect two IBActions to each other. Such as:

```<code>@IBAction func didSelect(_ control: UISegmentedControl) {
    switch control.selectedSegmentIndex
    {
    case 0:
        isPetrol = true
        isDiesel = false

    case 1:
        isPetrol = false
        isDiesel = true

    default:
        print  ("break")
    }
}

@IBACtion func didSecondSelect (_ control: UISegmentedControl) {
    //something here that when case1 is clicked disables it
    }
}
</code>```

How can I disable it if the top case 1 is clicked?

答:
You are mixing up IBActions and IBOutlets.

You should create an IBOutlet that points to the second segmented control and change that from the first one's code.

```<code>@IBOutlet weak var secondSegmentedControl: UISegmentedControl!

@IBAction func didSelect(_ control: UISegmentedControl) {
    [...]

    secondSegmentedControl.isEnabled = control.selectedSegmentIndex == 0
}
</code>```

For more information about working with IBOutlets, check out this question.

Body:
I'm trying to disable the bottom segment control if the user clicks Diesel. The problem is I can't connect two IBActions to each other. Such as:

@IBAction func didSelect(_ control: UISegmentedControl) {
    switch control.selectedSegmentIndex
    {
    case 0:
        isPetrol = true
        isDiesel = false

    case 1:
        isPetrol = false
        isDiesel = true

    default:
        print  ("break")
    }
}

@IBACtion func didSecondSelect (_ control: UISegmentedControl) {
    //something here that when case1 is clicked disables it
    }
}

How can I disable it if the top case 1 is clicked?

Body:
You are mixing up IBActions and IBOutlets.

You should create an IBOutlet that points to the second segmented control and change that from the first one's code.

@IBOutlet weak var secondSegmentedControl: UISegmentedControl!

@IBAction func didSelect(_ control: UISegmentedControl) {
    [...]

    secondSegmentedControl.isEnabled = control.selectedSegmentIndex == 0
}

For more information about working with IBOutlets, check out this question.


问:
How to reset a date in Firefox input[type=date]?
Firefox v57.0.1 supports the attribute "date" for the HTML input tag.
I would like in jQuery to reset the date value when the user click on a radio button like this:

In order to get this result:

My jQuery code:

```<code>$("input[name=f_foo_duration]").click(function() {

   if ($("#f_foo_duration_until").is(':checked')) {
       $("#f_foo_duration_date").attr("readonly", false);
   }else{
      $("#f_foo_duration_date").attr("readonly", true);
      $("#f_foo_duration_date").attr( "value", new Date() ); <-- here
   }
});
</code>```

I tested:

val("")

val(null)

val("0000-00-00")

val( new Date() )

without any success... is there a solution?

答:
To set an input element's value use the jQuery function elem.val("..."):

$(function() {
  $('[name="contact"]:radio').on("change", function() {
    if ($("#f_foo_duration_until").is(":checked")) {
      let now = new Date().toISOString().slice(0,10);
      $("#f_foo_duration_date").val(now);
      $("#f_foo_duration_date").attr("readonly", false);
    } else {
      $("#f_foo_duration_date").val("YYYY-MM-DD");
      $("#f_foo_duration_date").attr("readonly", true);
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#my-form > * {
  vertical-align: middle;
}</code>```

<form id="my-form">

  <input type="radio" id="f_foo_duration_until" name="contact" value="email">
  Valid until

  <input id="f_foo_duration_date" name="f_foo_duration" type="date" value="2017-06-01">
  </input>

  <input type="radio" id="f_foo_duration_unlimited" name="contact" value="unlimited">
  Unlimited

</form>```

ContentLicense: CC BY-SA 4.0

Body:
Firefox v57.0.1 supports the attribute "date" for the HTML input tag.
I would like in jQuery to reset the date value when the user click on a radio button like this:

In order to get this result:

My jQuery code:

$("input[name=f_foo_duration]").click(function() {

   if ($("#f_foo_duration_until").is(':checked')) {
       $("#f_foo_duration_date").attr("readonly", false);
   }else{
      $("#f_foo_duration_date").attr("readonly", true);
      $("#f_foo_duration_date").attr( "value", new Date() ); <-- here
   }
});

I tested:

val("")

val(null)

val("0000-00-00")

val( new Date() )

without any success... is there a solution?

Body:
To set an input element's value use the jQuery function elem.val("..."):

$(function() {
  $('[name="contact"]:radio').on("change", function() {
    if ($("#f_foo_duration_until").is(":checked")) {
      let now = new Date().toISOString().slice(0,10);
      $("#f_foo_duration_date").val(now);
      $("#f_foo_duration_date").attr("readonly", false);
    } else {
      $("#f_foo_duration_date").val("YYYY-MM-DD");
      $("#f_foo_duration_date").attr("readonly", true);
    }
  });
});

#my-form > * {
  vertical-align: middle;
}

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

  <input type="radio" id="f_foo_duration_until" name="contact" value="email">
  <label for="f_foo_duration_until">Valid until</label>

  <input id="f_foo_duration_date" name="f_foo_duration" type="date" value="2017-06-01">
  </input>

  <input type="radio" id="f_foo_duration_unlimited" name="contact" value="unlimited">
  <label for="f_foo_duration_unlimited">Unlimited</label>

</form>


问:
What image gallery? [iPhone]

Hey guys,
checkout this. How can I do something similar? I mean a scrollview with 9x9 images.
Also, how can I put a custom loading image??

Ty.

答: Use some pre-existing code. AQGridView is a solid piece of grid code.</p>

ContentLicense: CC BY-SA 2.5

Title: What image gallery? [iPhone]


问:
In React ES6, why does the input field lose focus after typing a character?
In my component below, the input field loses focus after typing a character. While using Chrome's Inspector, it looks like the whole form is being re-rendered instead of just the value attribute of the input field when typing.

I get no errors from either eslint nor Chrome Inspector.

Submitting the form itself works as does the actual input field when it is located either in the render's return or while being imported as a separate component but not in how I have it coded below.

Why is this so?

Main Page Component

```<code>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as actionPost from '../redux/action/actionPost';
import InputText from './form/InputText';
import InputSubmit from './form/InputSubmit';

class _PostSingle extends Component {
    constructor(props, context) {
        super(props, context);
        this.state = {
            post: {
                title: '',
            },
        };
        this.onChange = this.onChange.bind(this);
        this.onSubmit = this.onSubmit.bind(this);
    }
    onChange(event) {
        this.setState({
            post: {
                title: event.target.value,
            },
        });
    }
    onSubmit(event) {
        event.preventDefault();
        this.props.actions.postCreate(this.state.post);
        this.setState({
            post: {
                title: '',
            },
        });
    }
    render() {
        const onChange = this.onChange;
        const onSubmit = this.onSubmit;
        const valueTitle = this.state.post.title;
        const FormPostSingle = () => (
            <form onSubmit={onSubmit}>
                <InputText name="title" label="Title" placeholder="Enter a title" onChange={onChange} value={valueTitle} />
                <InputSubmit name="Save" />
            </form>
        );
        return (
            <main id="main" role="main">
                <div className="container-fluid">
                    <FormPostSingle />
                </div>
            </main>
        );
    }
}

_PostSingle.propTypes = {
    actions: PropTypes.objectOf(PropTypes.func).isRequired,
};

function mapStateToProps(state) {
    return {
        posts: state.posts,
    };
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators(actionPost, dispatch),
    };
}

export default connect(mapStateToProps, mapDispatchToProps)(_PostSingle);
</code>```

Text Input Component

```<code>import React, { PropTypes } from 'react';

const InputText = ({ name, label, placeholder, onChange, value, error }) => {
    const fieldClass = 'form-control input-lg';
    let wrapperClass = 'form-group';
    if (error && error.length > 0) {
        wrapperClass += ' has-error';
    }
    return (
        <div className={wrapperClass}>
            <label htmlFor={name} className="sr-only">{label}</label>
            <input type="text" id={name} name={name} placeholder={placeholder} onChange={onChange} value={value} className={fieldClass} />
            {error &&
                <div className="alert alert-danger">{error}</div>
            }
        </div>
    );
};

InputText.propTypes = {
    name: PropTypes.string.isRequired,
    label: PropTypes.string.isRequired,
    placeholder: PropTypes.string.isRequired,
    onChange: PropTypes.func.isRequired,
    value: PropTypes.string,
    error: PropTypes.string,
};

InputText.defaultProps = {
    value: null,
    error: null,
};

export default InputText;
</code>```

Submit Button Component

```<code>import React, { PropTypes } from 'react';

const InputSubmit = ({ name }) => {
    const fieldClass = 'btn btn-primary btn-lg';
    return (
        <input type="submit" value={name} className={fieldClass} />
    );
};

InputSubmit.propTypes = {
    name: PropTypes.string,
};

InputSubmit.defaultProps = {
    name: 'Submit',
};

export default InputSubmit;
</code>```

答:
it is because you are rendering the form in a function inside render().

Every time your state/prop change, the function returns a new form. it caused you to lose focus.

Try putting what's inside the function into your render directly.

```<code><main id="main" role="main">
    <div className="container-fluid">
        <FormPostSingle />
    </div>
</main>
</code>```

===>

```<code><main id="main" role="main">
    <div className="container-fluid">
        <form onSubmit={onSubmit}>
            <InputText name="title" label="Title" placeholder="Enter a title" onChange={onChange} value={valueTitle} />
            <InputSubmit name="Save" />
        </form>
    </div>
</main>
</code>```

Body:
In my component below, the input field loses focus after typing a character. While using Chrome's Inspector, it looks like the whole form is being re-rendered instead of just the value attribute of the input field when typing.

I get no errors from either eslint nor Chrome Inspector.

Submitting the form itself works as does the actual input field when it is located either in the render's return or while being imported as a separate component but not in how I have it coded below.

Why is this so?

Main Page Component

import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as actionPost from '../redux/action/actionPost';
import InputText from './form/InputText';
import InputSubmit from './form/InputSubmit';

class _PostSingle extends Component {
    constructor(props, context) {
        super(props, context);
        this.state = {
            post: {
                title: '',
            },
        };
        this.onChange = this.onChange.bind(this);
        this.onSubmit = this.onSubmit.bind(this);
    }
    onChange(event) {
        this.setState({
            post: {
                title: event.target.value,
            },
        });
    }
    onSubmit(event) {
        event.preventDefault();
        this.props.actions.postCreate(this.state.post);
        this.setState({
            post: {
                title: '',
            },
        });
    }
    render() {
        const onChange = this.onChange;
        const onSubmit = this.onSubmit;
        const valueTitle = this.state.post.title;
        const FormPostSingle = () => (
            <form onSubmit={onSubmit}>
                <InputText name="title" label="Title" placeholder="Enter a title" onChange={onChange} value={valueTitle} />
                <InputSubmit name="Save" />
            </form>
        );
        return (

                    <FormPostSingle />

        );
    }
}

_PostSingle.propTypes = {
    actions: PropTypes.objectOf(PropTypes.func).isRequired,
};

function mapStateToProps(state) {
    return {
        posts: state.posts,
    };
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators(actionPost, dispatch),
    };
}

export default connect(mapStateToProps, mapDispatchToProps)(_PostSingle);

Text Input Component

import React, { PropTypes } from 'react';

const InputText = ({ name, label, placeholder, onChange, value, error }) => {
    const fieldClass = 'form-control input-lg';
    let wrapperClass = 'form-group';
    if (error && error.length > 0) {
        wrapperClass += ' has-error';
    }
    return (

            {label}
            <input type="text" id={name} name={name} placeholder={placeholder} onChange={onChange} value={value} className={fieldClass} />
            {error &&

{error}

            }

    );
};

InputText.propTypes = {
    name: PropTypes.string.isRequired,
    label: PropTypes.string.isRequired,
    placeholder: PropTypes.string.isRequired,
    onChange: PropTypes.func.isRequired,
    value: PropTypes.string,
    error: PropTypes.string,
};

InputText.defaultProps = {
    value: null,
    error: null,
};

export default InputText;

Submit Button Component

import React, { PropTypes } from 'react';

const InputSubmit = ({ name }) => {
    const fieldClass = 'btn btn-primary btn-lg';
    return (
        <input type="submit" value={name} className={fieldClass} />
    );
};

InputSubmit.propTypes = {
    name: PropTypes.string,
};

InputSubmit.defaultProps = {
    name: 'Submit',
};

export default InputSubmit;

Body:
it is because you are rendering the form in a function inside render().

Every time your state/prop change, the function returns a new form. it caused you to lose focus.

Try putting what's inside the function into your render directly.

<main id="main" role="main">
    <div className="container-fluid">
        <FormPostSingle />
    </div>
</main>

===>

<main id="main" role="main">
    <div className="container-fluid">
        <form onSubmit={onSubmit}>
            <InputText name="title" label="Title" placeholder="Enter a title" onChange={onChange} value={valueTitle} />
            <InputSubmit name="Save" />
        </form>
    </div>
</main>


问:
Git - deleted some files locally, how do I get them from a remote repository
I've deleted some files on my PC, how do I download them again?

Pull says: "Already up-to-date".

答:
Also, I add to do the following steps so that the git repo would be correctly linked with the IDE:

```<code> $ git reset <commit #>

 $ git checkout <file/path>
</code>```

I hope this was helpful!!

Body:
Also, I add to do the following steps so that the git repo would be correctly linked with the IDE:

 $ git reset <commit #>

 $ git checkout <file/path>

I hope this was helpful!!


问:
Java Data Structure Benchmark
So I'm still fairly new to programming and I'm just wondering if I'm doing these benchmarks correctly. For queue I'm basically giving it a list filled with integers, and I would time how long it would take for it to find a number on the list. As for the HashMap it's basically the same idea, I would time how long it would take to get a number from the list. Also for both of them I would also time how long it would take for them to remove the contents of the list. Any help on this would be appreciated. Thank you!</p>

```<code>// Create a queue, and test its performance
PriorityQueue<Integer> queue = new PriorityQueue <> (list);
System.out.println("Member test time for Priority Queue is " +
        getTestTime(queue) + " milliseconds");
      System.out.println("Remove element time for Priority Queue is " +
        getRemoveTime(queue) + " milliseconds");

// Create a hash map, and test its performance
HashMap<Integer, Integer> newmap = new HashMap<Integer, Integer>();
 for (int i = 0; i <N;i++) {
  newmap.put(i, i);
}
System.out.println("Member test time for hash map is " +
        getTestTime1(newmap) + " milliseconds");
 System.out.println("Remove element time for hash map is " +
        getRemoveTime1(newmap) + " milliseconds");
}

public static long getTestTime(Collection<Integer> c) {
  long startTime = System.currentTimeMillis();

 // Test if a number is in the collection
 for (int i = 0; i < N; i++)
   c.contains((int)(Math.random() * 2 * N));

return System.currentTimeMillis() - startTime;
}

 public static long getTestTime1(HashMap<Integer,Integer> newmap) {
   long startTime = System.currentTimeMillis();

     // Test if a number is in the collection
     for (int i = 0; i < N; i++)
      newmap.containsKey((int)(Math.random() * 2 * N));

   return System.currentTimeMillis() - startTime;
 }

public static long getRemoveTime(Collection<Integer> c) {
 long startTime = System.currentTimeMillis();

  for (int i = 0; i < N; i++)
   c.remove(i);

 return System.currentTimeMillis() - startTime;
}
public static long getRemoveTime1(HashMap<Integer,Integer> newmap) {
    long startTime = System.currentTimeMillis();

     for (int i = 0; i < N; i++)
       newmap.remove(i);

      return System.currentTimeMillis() - startTime;
   }
}
</code>```

答:
I have two suggestion. First, when doing benchmarking, do the bare minimum work immediately before and after the code you are evaluating. You don't want your benchmark activity to affect the result.

Second, System.currentTimeMillis() can, depending on the OS, only be accurate within 10 milliseconds. Better to use System.nanoTime(), which is accurate to perhaps 200 nanoseconds. Divide by 1_000_000 to get milliseconds.

Practically,

```<code>final long startNanos, endNanos;
startNanos = System.nanoTime();
// your code goes here
endNanos = System.nanoTime();
// display the results of the benchmark
</code>```

Title: Java Data Structure Benchmark

Body:
So I'm still fairly new to programming and I'm just wondering if I'm doing these benchmarks correctly. For queue I'm basically giving it a list filled with integers, and I would time how long it would take for it to find a number on the list. As for the HashMap it's basically the same idea, I would time how long it would take to get a number from the list. Also for both of them I would also time how long it would take for them to remove the contents of the list. Any help on this would be appreciated. Thank you!

// Create a queue, and test its performance
PriorityQueue<Integer> queue = new PriorityQueue <> (list);
System.out.println("Member test time for Priority Queue is " +
        getTestTime(queue) + " milliseconds");
      System.out.println("Remove element time for Priority Queue is " +
        getRemoveTime(queue) + " milliseconds");

// Create a hash map, and test its performance
HashMap<Integer, Integer> newmap = new HashMap<Integer, Integer>();
 for (int i = 0; i <N;i++) {
  newmap.put(i, i);
}
System.out.println("Member test time for hash map is " +
        getTestTime1(newmap) + " milliseconds");
 System.out.println("Remove element time for hash map is " +
        getRemoveTime1(newmap) + " milliseconds");
}

public static long getTestTime(Collection<Integer> c) {
  long startTime = System.currentTimeMillis();

 // Test if a number is in the collection
 for (int i = 0; i < N; i++)
   c.contains((int)(Math.random() * 2 * N));

return System.currentTimeMillis() - startTime;
}

 public static long getTestTime1(HashMap<Integer,Integer> newmap) {
   long startTime = System.currentTimeMillis();

     // Test if a number is in the collection
     for (int i = 0; i < N; i++)
      newmap.containsKey((int)(Math.random() * 2 * N));

   return System.currentTimeMillis() - startTime;
 }

public static long getRemoveTime(Collection<Integer> c) {
 long startTime = System.currentTimeMillis();

  for (int i = 0; i < N; i++)
   c.remove(i);

 return System.currentTimeMillis() - startTime;
}
public static long getRemoveTime1(HashMap<Integer,Integer> newmap) {
    long startTime = System.currentTimeMillis();

     for (int i = 0; i < N; i++)
       newmap.remove(i);

      return System.currentTimeMillis() - startTime;
   }
}

Body:
I have two suggestion. First, when doing benchmarking, do the bare minimum work immediately before and after the code you are evaluating. You don't want your benchmark activity to affect the result.

Second, System.currentTimeMillis() can, depending on the OS, only be accurate within 10 milliseconds. Better to use System.nanoTime(), which is accurate to perhaps 200 nanoseconds. Divide by 1_000_000 to get milliseconds.

Practically,

final long startNanos, endNanos;
startNanos = System.nanoTime();
// your code goes here
endNanos = System.nanoTime();
// display the results of the benchmark


问:
Is it safe to cast from List<Optional> to List<Optional<?>>?
If you have a raw type in Java, you can safely assign/cast this to the same type with an unbounded wildcard. For example a List can be safely cast to a List<?>, which removes its raw nature and allows you to use it in a safe (type-checked) manner1.

On the other hand, Java doesn't let you cast from a List itself parameterized with a raw type, like List<Optional> to a list of the same type parameter with an unbounded wildcard, like List<Optional<?>>.

You can still do it by dropping all the way down a raw List and back up again (implicitly via the assignment):

```<code>List<Optional> rawOptionalList = null;
List<Optional<?>> wildcardOptionalList = (List)rawOptionalList;
</code>```

Of course, this triggers warning about unchecked conversion (from List to List<Optional<?>>).

It seems to me though that this conversion is guaranteed safe: isn't List<Optional<?>> just as safe as List<Optional> in the same way that casting a raw Optional to an Optional<?> is safe?

1 ... but you'll never be able to add anything to this list, since nothing will match the capture of ? for the add(?) method. That's the price you pay for safety.

答: Yes, it's safe.  The generic check is just at compile time.</p>

Body:
If you have a raw type in Java, you can safely assign/cast this to the same type with an unbounded wildcard. For example a List can be safely cast to a List<?>, which removes its raw nature and allows you to use it in a safe (type-checked) manner1.

On the other hand, Java doesn't let you cast from a List itself parameterized with a raw type, like List<Optional> to a list of the same type parameter with an unbounded wildcard, like List<Optional<?>>.

You can still do it by dropping all the way down a raw List and back up again (implicitly via the assignment):

List<Optional> rawOptionalList = null;
List<Optional<?>> wildcardOptionalList = (List)rawOptionalList;

Of course, this triggers warning about unchecked conversion (from List to List<Optional<?>>).

It seems to me though that this conversion is guaranteed safe: isn't List<Optional<?>> just as safe as List<Optional> in the same way that casting a raw Optional to an Optional<?> is safe?

1 ... but you'll never be able to add anything to this list, since nothing will match the capture of ? for the add(?) method. That's the price you pay for safety.


问:
Convert encoded application/x-www-form-urlencoded post data to json object
A client wants to be able to make xmlhttp ajax requests with the default content type of content-type:"application/x-www-form-urlencoded; charset=UTF-8" but sending the data in the form the API expects application/json. So the request comes across as this:

```<code>  var settings = {
  "async": true,
  "crossDomain": true,
  "url": "http://localhost:80/api/metadata/taxonomy",
  "method": "POST",
  "headers": {
    "cache-control": "no-cache",
    "postman-token": "62a245ad-a0a2-4dd3-bf84-37f622f00b7d"
  },
  "processData": false,
  "data": "{\n\t\"practice\": [\"Learning\"]\n}"
}

$.ajax(settings).done(function (response) {
  console.log(response);
});
</code>```

But the API expects to be able to get req.body as a JSON object it can immediately use:

```<code>"{"practice":["Learning"]}"
</code>```

Can I transform this "{\n\t\"practice\": [\"Learning\"]\n}" to this "{"practice":["Learning"]}" in some safe/suggested manner? (without some home grown parsing function or regex)

答:
Yes, the JSON.parse function can be used for this:

```<code>try{JSON.stringify(JSON.parse(data))}
</code>```

will convert strange json with newlines to standard one line string json.

JSON.parse
Parses the json into an object

JSON.stringify
Turns an object into a one line formatted JSON object

try
JSON.parse will fail if an invalid json string is passed. (\ns are valid in json.parse)

If this you meant converting "{\n\"your\":\n \"object\"}" to a javascript object like {"your": "object"}, you can just use try{JSON.parse(variablename)}

According to these answers, for older browsers you may need JSON-js

Body:
A client wants to be able to make xmlhttp ajax requests with the default content type of content-type:"application/x-www-form-urlencoded; charset=UTF-8" but sending the data in the form the API expects application/json. So the request comes across as this:

  var settings = {
  "async": true,
  "crossDomain": true,
  "url": "http://localhost:80/api/metadata/taxonomy",
  "method": "POST",
  "headers": {
    "cache-control": "no-cache",
    "postman-token": "62a245ad-a0a2-4dd3-bf84-37f622f00b7d"
  },
  "processData": false,
  "data": "{\n\t\"practice\": [\"Learning\"]\n}"
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

But the API expects to be able to get req.body as a JSON object it can immediately use:

"{"practice":["Learning"]}"

Can I transform this "{\n\t\"practice\": [\"Learning\"]\n}" to this "{"practice":["Learning"]}" in some safe/suggested manner? (without some home grown parsing function or regex)

Body:
Yes, the JSON.parse function can be used for this:

try{JSON.stringify(JSON.parse(data))}

will convert strange json with newlines to standard one line string json.

JSON.parse
Parses the json into an object

JSON.stringify
Turns an object into a one line formatted JSON object

try
JSON.parse will fail if an invalid json string is passed. (\ns are valid in json.parse)

If this you meant converting "{\n\"your\":\n \"object\"}" to a javascript object like {"your": "object"}, you can just use try{JSON.parse(variablename)}

According to these answers, for older browsers you may need JSON-js


问:
Visual Studio not updating the build
Just started learning coding(c) and this is a simple code that I'm working on:

```<code>#include <stdio.h>
int main()
{
        int A;
        int B;
        int C;
        printf("Enter A: ");
        scanf_s("%d", &A);
        printf("Enter B: ");
        scanf_s("%d", &B);
        printf("Enter C: ");
        scanf_s("%d", &C);
        if (A > B)
        {
                if (A > C)
                {
                        printf("A is largest. \n");
                }
                else
                {
                        printf("C is largest. \n");
                }
        }
        else
        {
                if (B > C)
                {
                        printf("B is largest. \n");
                }
                else
                {
                        printf("C is largest. \n");
                }
        }
return 0;
}
</code>```

Before this, I just tested a simple program that just used 'printf' to printed out 'Testing'.

However, I had overwritten that with the above program but it is still printing out 'Testing' as the output.

P.S. if you can simplify your answer then that would be really appreciated since I'm a complete beginner at coding.

答:
Try to store the variable using scanf(); also u can declare variables as follows: if u did not mention int before main(),than by default it returns as int type.. </p>

```<code>#include <stdio.h>
main()
{
        int A,B,C;
        printf("Enter A: ");
        scanf("%d", &A);
        printf("Enter B: ");
        scanf("%d", &B);
        printf("Enter C: ");
        scanf_s("%d", &C);
        if (A > B)
        {
                if (A > C)
                {
                        printf("A is largest. \n");
                }
                else
                {
                        printf("C is largest. \n");
                }
        }
        else
        {
                if (B > C)
                {
                        printf("B is largest. \n");
                }
                else
                {
                        printf("C is largest. \n");
                }
        }
return 0;
}
</code>```

Title: Visual Studio not updating the build

Body:
Just started learning coding(c) and this is a simple code that I'm working on:

#include <stdio.h>
int main()
{
        int A;
        int B;
        int C;
        printf("Enter A: ");
        scanf_s("%d", &A);
        printf("Enter B: ");
        scanf_s("%d", &B);
        printf("Enter C: ");
        scanf_s("%d", &C);
        if (A > B)
        {
                if (A > C)
                {
                        printf("A is largest. \n");
                }
                else
                {
                        printf("C is largest. \n");
                }
        }
        else
        {
                if (B > C)
                {
                        printf("B is largest. \n");
                }
                else
                {
                        printf("C is largest. \n");
                }
        }
return 0;
}

Before this, I just tested a simple program that just used 'printf' to printed out 'Testing'.

However, I had overwritten that with the above program but it is still printing out 'Testing' as the output.

P.S. if you can simplify your answer then that would be really appreciated since I'm a complete beginner at coding.

Body:
Try to store the variable using scanf(); also u can declare variables as follows: if u did not mention int before main(),than by default it returns as int type..

#include <stdio.h>
main()
{
        int A,B,C;
        printf("Enter A: ");
        scanf("%d", &A);
        printf("Enter B: ");
        scanf("%d", &B);
        printf("Enter C: ");
        scanf_s("%d", &C);
        if (A > B)
        {
                if (A > C)
                {
                        printf("A is largest. \n");
                }
                else
                {
                        printf("C is largest. \n");
                }
        }
        else
        {
                if (B > C)
                {
                        printf("B is largest. \n");
                }
                else
                {
                        printf("C is largest. \n");
                }
        }
return 0;
}


问:
Device Location on Actions on Google
Currently, I have an application setup to prompt the user for their location upon first use of the application.  If the user gives permission, then I get the location and store it.  However, if the user is on the phone and moves, I don't get the location in the second "conversation".

Do I have to request the location for each "conversation", or is requesting permission one time enough, and I am just not doing something else properly.

答:
Unfortunately, yes, you will need to request it every time.

(This is a frequent complaint, and the team is aware of our desire to handle this better, but this is how it is right now.)

Title: Device Location on Actions on Google


问:
Qt and UI Skinning
I wanted to consult with the sages here regarding Qt and skinning, get your opinion and chart a path for my development. My requirements are as follows:

My Qt/C++ application (cross platform with Mac, Windows and Linux versions) needs to have modular skins.

A skin is defined as a set of one or more elements: - Window background texture - Look/feel of UI controls such as edit boxes, drop down, radio buttons, buttons etc. - Look/feel of window "caption", resize grips etc.

Skins will be installed with the application installer, allowing the user to choose which one he/she wants to use. Users should be able to change skins on the fly.

Can I go the QML route? should this be custom and based on simple resources which are built into the application? Any design advice will be appreciated.

Thanks.

答:
If I understood you correctly then stylesheet is the best way forward. You can create stylesheets similar to CSS and then pass them as command line option to your application or load on invocation to style your application at runtime. That way you can create multiple stylesheets each having a different look and feel and allow user to load them at will. Since its CSS it doesn't need any new learning and you can keep all your styling outside your source code.

Here are a list of resources that can get you up and running quickly:

http://blog.qt.io/blog/2007/11/27/theming-qt-for-fun-and-profit/

http://doc.qt.io/qt-5/stylesheet.html

Title: Qt and UI Skinning


问:
Call to pdflatex in R/knitr constantly brings up new errors
I'm trying to print the results of a data frame as a table in a PDF using knitr, and more specifically kable. When I pass the data frame using kable(df, format = 'latex') it produces a basic, unformatted table. As soon as I try to add any styling (e.g. booktab = T or kable_styling), I receive a series of errors once R tries to call:

/Applications/RStudio.app/Contents/MacOS/pandoc/pandoc +RTS -K512m -RTS Payments.utf8.md --to latex --from markdown+autolink_bare_uris+ascii_identifiers+tex_math_single_backslash --output pandoc2b922cfdb1c9.pdf --template /Library/Frameworks/R.framework/Versions/3.3/Resources/library/rmarkdown/rmd/latex/default-1.17.0.2.tex --highlight-style tango --latex-engine pdflatex --variable graphics=yes --variable 'geometry:margin=1in'

When I Google the resulting error, the suggestion is usually to include a -/usepackage{} statement with a certain package. However, every time I do that, a new error appears at the same step next time I run my script.

Here are the errors I've received so far, and the packages I used to resolve them:

1)

```<code>! LaTeX Error: Unknown float option `H'.
l.87 \begin{table}[H]

  - \usepackage{float}
</code>```

2)

```<code>! Undefined control sequence.
l.89 \centering\rowcolors

- \usepackage[table]{xcolor}
</code>```

3)

```<code><argument> ...r}{lllllll} \hiderowcolors \toprule
l.100 \end{tabular}}

- \usepackage[table]{\centering}
</code>```

At this point I got tired of whack-a-mole, and I feel like there's a bigger underlying issue. I also regularly receive:

```<code>pandoc: Error producing PDF
Error: pandoc document conversion failed with error 43
</code>```

Anyone have any insight as to why such a basic function that appears to be relatively stable is causing me so many errors? Is there a way to force the program to try to run everything so I can see how many errors there are?

答:
You could try to narrow down the issue by producing an intermediate tex file

```<code>---
output:
  pdf_document:
    keep_tex: yes
---
</code>```

And then try to run this file in your tex application (e.g. texworks).

Note that I've also provided an answer to your question (how to add a link to the bookstab package) there

Body:
I'm trying to print the results of a data frame as a table in a PDF using knitr, and more specifically kable. When I pass the data frame using kable(df, format = 'latex') it produces a basic, unformatted table. As soon as I try to add any styling (e.g. booktab = T or kable_styling), I receive a series of errors once R tries to call:

/Applications/RStudio.app/Contents/MacOS/pandoc/pandoc +RTS -K512m -RTS Payments.utf8.md --to latex --from markdown+autolink_bare_uris+ascii_identifiers+tex_math_single_backslash --output pandoc2b922cfdb1c9.pdf --template /Library/Frameworks/R.framework/Versions/3.3/Resources/library/rmarkdown/rmd/latex/default-1.17.0.2.tex --highlight-style tango --latex-engine pdflatex --variable graphics=yes --variable 'geometry:margin=1in'

When I Google the resulting error, the suggestion is usually to include a -/usepackage{} statement with a certain package. However, every time I do that, a new error appears at the same step next time I run my script.

Here are the errors I've received so far, and the packages I used to resolve them:

1)

! LaTeX Error: Unknown float option `H'.
l.87 \begin{table}[H]

  - \usepackage{float}

2)

! Undefined control sequence.
l.89 \centering\rowcolors

- \usepackage[table]{xcolor}

3)

<argument> ...r}{lllllll} \hiderowcolors \toprule
l.100 \end{tabular}}

- \usepackage[table]{\centering}

At this point I got tired of whack-a-mole, and I feel like there's a bigger underlying issue. I also regularly receive:

pandoc: Error producing PDF
Error: pandoc document conversion failed with error 43

Anyone have any insight as to why such a basic function that appears to be relatively stable is causing me so many errors? Is there a way to force the program to try to run everything so I can see how many errors there are?

Body:
You could try to narrow down the issue by producing an intermediate tex file

---
output:
  pdf_document:
    keep_tex: yes
---

And then try to run this file in your tex application (e.g. texworks).

Note that I've also provided an answer to your question (how to add a link to the bookstab package) there


问:
Robots.txt disallow path with regular expression
Does robots.txt accept regular expression ?
I have many URLs with this format:

```<code>https://example.com/view/99/title-sample-text
ID ----------------------^
Title -----------------------------^
</code>```

I used this:

```<code>Disallow: /view
</code>```

But look like this not working because google indexed more pages. so i want to do this with regex, something like this:

```<code>Disallow: /view/([0-9]+)/([^/]*)
</code>```

But is this correct format or valid in robots.txt ?

答:
You can use a wildcard ...

```<code>User-agent: *
disallow: /view/*
</code>```

See https://webmasters.stackexchange.com/questions/72722/can-we-use-regex-in-robots-txt-file-to-block-urls

Hope this helps.

Body:
Does robots.txt accept regular expression ?
I have many URLs with this format:

https://example.com/view/99/title-sample-text
ID ----------------------^
Title -----------------------------^

I used this:

Disallow: /view

But look like this not working because google indexed more pages. so i want to do this with regex, something like this:

Disallow: /view/([0-9]+)/([^/]*)

But is this correct format or valid in robots.txt ?

Body:
You can use a wildcard ...

User-agent: *
disallow: /view/*

See https://webmasters.stackexchange.com/questions/72722/can-we-use-regex-in-robots-txt-file-to-block-urls

Hope this helps.


问:
Python-Generic method to find child of a webelement
I trying to create a generic method in python to find the child element of a webelement using any locator strategy. Currently I have the below code, please help in completing the method getchildobject in below code. This method should be capable of find the child of the webelement with any locator like xpath, css or id etc</p>

```<code>getelement="xpath=//div[@id='test']"
def get_webelement_Cus(locator):

    strategy=locator.split("=")[0]
    locator=locator.replace(locator.split("=")[0]+"=","")
    if strategy.uppercase()=='XPATH':
        return driver.find_elements_by_xpath(locator)
    elif strategy.uppercase()=='CSS':
        return  driver.find_element_by_css_selector(locator)
    else:
        return None

def getchildobject(webelement,locator):
    webelement.????????
</code>```

答:
I guess you're searching for find_element()/find_elements() method which is already created and available via built-ins. You can use it as below:

```<code>getelement = "xpath", "//div[@id='test']"
element = driver.find_elements(*getelement)
</code>```

You can also do from selenium.webdriver.common.by import By and use attributes of By class:

```<code>getelement = By.XPATH, "//div[@id='test']"
getelement = By.TAG_NAME, "div"
getelement = By.CSS_SELECTOR, "div#test"
...
</code>```

In the same way you can find child elements:

```<code>getelement = "xpath", "//div[@id='test']"
childelement = "xpath", ".//div[@id='child id']"
element = driver.find_elements(*getelement)
child = element.find_elements(*childelemen)
</code>```

P.S. note that to locate child/descendant element by XPath you need to add dot at the beggining of expression to point on current context (".//tag_name")

Body:
I trying to create a generic method in python to find the child element of a webelement using any locator strategy. Currently I have the below code, please help in completing the method getchildobject in below code. This method should be capable of find the child of the webelement with any locator like xpath, css or id etc

getelement="xpath=//div[@id='test']"
def get_webelement_Cus(locator):

    strategy=locator.split("=")[0]
    locator=locator.replace(locator.split("=")[0]+"=","")
    if strategy.uppercase()=='XPATH':
        return driver.find_elements_by_xpath(locator)
    elif strategy.uppercase()=='CSS':
        return  driver.find_element_by_css_selector(locator)
    else:
        return None

def getchildobject(webelement,locator):
    webelement.????????

Body:
I guess you're searching for find_element()/find_elements() method which is already created and available via built-ins. You can use it as below:

getelement = "xpath", "//div[@id='test']"
element = driver.find_elements(*getelement)

You can also do from selenium.webdriver.common.by import By and use attributes of By class:

getelement = By.XPATH, "//div[@id='test']"
getelement = By.TAG_NAME, "div"
getelement = By.CSS_SELECTOR, "div#test"
...

In the same way you can find child elements:

getelement = "xpath", "//div[@id='test']"
childelement = "xpath", ".//div[@id='child id']"
element = driver.find_elements(*getelement)
child = element.find_elements(*childelemen)

P.S. note that to locate child/descendant element by XPath you need to add dot at the beggining of expression to point on current context (".//tag_name")


问:
Substring of a line from a file is not working for one specific line in Java
Before I start I know this isnt the only way of getting the information from the file I need, since I can use a scanner. However when i've been trying to read it this way the substring seems to be causing problems with this line from the Contract.txt file:07-Jun-2016 1   3   1   N   JB847N  900 S Trotter

Which thorws a NormatFormatException "00    " because it is trying to then parse a tab. This is the only line that does this.

```<code>public String averageCostOflarge() {
    int numberOfBundles = 0;
    int total = 0;
    try {
        BufferedReader reader = new BufferedReader(new FileReader("Contract.txt"));

        String line;
        while ((line = reader.readLine()) != null) {
            if (line.charAt(14) == '3') {
                numberOfBundles++;
                if(line.charAt(32)=='\t'){
                    total+=Integer.parseInt(line.substring(28, 32));
                }else{
                    total+=Integer.parseInt(line.substring(28, 31));
                }
            }

        }
        reader.close();
        return Integer.toString(numberOfBundles);
    } catch (FileNotFoundException e) {
        return "Error";
    } catch (IOException ex) {
        Logger.getLogger(ContractSummary.class.getName()).log(Level.SEVERE, null, ex);
        return "Error";
    }
}
</code>```

However the it seems to mainly be this part: 1  3   1   N   JB847N  900 as this part comes up multiple times in the file.

Contract file: https://pastebin.com/GFG1Um4g

I have removed all the lines that have been causing this problem and the code works just fine.

The section of code needs to check if the third row is set as 3 and then get the cost in the seventh row. The pieces of information are seperated by tabs not spaces and I have tried manually typing the line that is causing the problem to see if it was a formatting error in the file.

Any explanation as to why my code is doing this would be greatly appreciated.

答:
This has nothing to do with a tab; your substring is either "00 " or "00 S", depending on whether the letter following the S is a tab.  But parseInt("00 ") throws an exception because of the trailing space.

If you are trying to extract the "900", then your index is off; the first index should be 27 instead of 28.  And if you only want to get the part of "900" after the 9, then only ask for 2characters, substring(28,30).

However, depending on the exact character-index seems rather brittle -- sure the date will be a predictable number of characters long, but are the following "1 3 1" each guaranteed to be a single digit, and never longer?  Similarly, the "N" and "JB847N" aren't ever longer/shorter?
My first inclination would be to use String.split("\s") to divide your long line into the meaningful chunks.

(Btw, you are looking for the 3rd and 7th "columns" (or, "fields"), not "rows".)

Body:
Before I start I know this isnt the only way of getting the information from the file I need, since I can use a scanner. However when i've been trying to read it this way the substring seems to be causing problems with this line from the Contract.txt file:07-Jun-2016 1   3   1   N   JB847N  900 S Trotter

Which thorws a NormatFormatException "00    " because it is trying to then parse a tab. This is the only line that does this.

public String averageCostOflarge() {
    int numberOfBundles = 0;
    int total = 0;
    try {
        BufferedReader reader = new BufferedReader(new FileReader("Contract.txt"));

        String line;
        while ((line = reader.readLine()) != null) {
            if (line.charAt(14) == '3') {
                numberOfBundles++;
                if(line.charAt(32)=='\t'){
                    total+=Integer.parseInt(line.substring(28, 32));
                }else{
                    total+=Integer.parseInt(line.substring(28, 31));
                }
            }

        }
        reader.close();
        return Integer.toString(numberOfBundles);
    } catch (FileNotFoundException e) {
        return "Error";
    } catch (IOException ex) {
        Logger.getLogger(ContractSummary.class.getName()).log(Level.SEVERE, null, ex);
        return "Error";
    }
}

However the it seems to mainly be this part: 1  3   1   N   JB847N  900 as this part comes up multiple times in the file.

Contract file: https://pastebin.com/GFG1Um4g

I have removed all the lines that have been causing this problem and the code works just fine.

The section of code needs to check if the third row is set as 3 and then get the cost in the seventh row. The pieces of information are seperated by tabs not spaces and I have tried manually typing the line that is causing the problem to see if it was a formatting error in the file.

Any explanation as to why my code is doing this would be greatly appreciated.


问:
how to get cookie php/wordpress
Users come to my site thorough a referral link.

I can successfully set the cookie using either of the following code snippets:
(I know it is successful because I can see the cookie file saved on my computer)

```<code>function set_my_cookie() {
if (empty($_COOKIE['OREF2']))
{
wp_set_auth_cookie('OREF2', $_SERVER['QUERY_STRING'], time()+5200, "/", ".website.com");
}
}
add_action( 'init', 'set_my_cookie');
</code>```

or

```<code>function set_newuser_cookie() {
    if (!isset($_COOKIE['OREF2'])) {
        setcookie('OREF2', $_SERVER['QUERY_STRING'], time()+5200, "/", ".website.com");
}
}
add_action( 'init', 'set_newuser_cookie');
</code>```

Now the user clicks to a different page in my site. They click a form which should pass the cookie info when they click submit.

I am using the following code snippets:

```<code>function get_my_cookie() {
//$_COOKIE['OREF2'];
//var_dump($_COOKIE);
echo $_COOKIE['OREF2'];
}
add_shortcode('cookies', 'get_my_cookie');
</code>```

This first bit of code has commented lines where I have attempted different ways to get my cookie. None of the 3 ways worked. I then moved on to trying to read if my cookie is set with the following code:

```<code>function get_my_cookie() {
if(!isset($_COOKIE['OREF2'])) {
    echo "Cookie named '" . OREF2 . "' is not set!";
} else {
    echo "Cookie '" . OREF2 . "' is set!<br>";
    echo "Value is: " . $_COOKIE['OREF2'];
}}
add_shortcode('cookies', 'get_my_cookie');
</code>```

When using this code I am ALWAYS met with "cookie is NOT set" Even though I can clearly see the cookie file on my computer. If the cookie is not set my shortcode can't be used to display anything...

All I want is a shortcode to display my cookie. What am I doing wrong?
Any help would be greatly appreciated!

答:
User comes to site through referral source-cookie is created from query string.

```<code>function set_my_cookie() {
if (empty($_COOKIE['OREF2']))
{
wp_set_auth_cookie('OREF2', $_SERVER['QUERY_STRING'], time()+5200);
}
}
add_action( 'init', 'set_my_cookie');
</code>```

Now the user clicks to a different page in site. They click a form which should pass the cookie info through a shortcode when they click submit.

```<code>function get_my_cookie() {
return $_COOKIE['OREF2'];
}
add_shortcode('cookies', 'get_my_cookie');
</code>```

This now sets the cookie, and allows the shortcode "cookies" to retrieve the stored cookie value at any time.

Thanks to twisty for helping me with the reduced set cookie code and explaining the domain path.

This works on localhost no problem!

:)

Title: how to get cookie php/wordpress

Body:
Users come to my site thorough a referral link.

I can successfully set the cookie using either of the following code snippets:
(I know it is successful because I can see the cookie file saved on my computer)

function set_my_cookie() {
if (empty($_COOKIE['OREF2']))
{
wp_set_auth_cookie('OREF2', $_SERVER['QUERY_STRING'], time()+5200, "/", ".website.com");
}
}
add_action( 'init', 'set_my_cookie');

or

function set_newuser_cookie() {
    if (!isset($_COOKIE['OREF2'])) {
        setcookie('OREF2', $_SERVER['QUERY_STRING'], time()+5200, "/", ".website.com");
}
}
add_action( 'init', 'set_newuser_cookie');

Now the user clicks to a different page in my site. They click a form which should pass the cookie info when they click submit.

I am using the following code snippets:

function get_my_cookie() {
//$_COOKIE['OREF2'];
//var_dump($_COOKIE);
echo $_COOKIE['OREF2'];
}
add_shortcode('cookies', 'get_my_cookie');

This first bit of code has commented lines where I have attempted different ways to get my cookie. None of the 3 ways worked. I then moved on to trying to read if my cookie is set with the following code:

function get_my_cookie() {
if(!isset($_COOKIE['OREF2'])) {
    echo "Cookie named '" . OREF2 . "' is not set!";
} else {
    echo "Cookie '" . OREF2 . "' is set!
";
    echo "Value is: " . $_COOKIE['OREF2'];
}}
add_shortcode('cookies', 'get_my_cookie');

When using this code I am ALWAYS met with "cookie is NOT set" Even though I can clearly see the cookie file on my computer. If the cookie is not set my shortcode can't be used to display anything...

All I want is a shortcode to display my cookie. What am I doing wrong?
Any help would be greatly appreciated!

Body:
User comes to site through referral source-cookie is created from query string.

function set_my_cookie() {
if (empty($_COOKIE['OREF2']))
{
wp_set_auth_cookie('OREF2', $_SERVER['QUERY_STRING'], time()+5200);
}
}
add_action( 'init', 'set_my_cookie');

Now the user clicks to a different page in site. They click a form which should pass the cookie info through a shortcode when they click submit.

function get_my_cookie() {
return $_COOKIE['OREF2'];
}
add_shortcode('cookies', 'get_my_cookie');

This now sets the cookie, and allows the shortcode "cookies" to retrieve the stored cookie value at any time.

Thanks to twisty for helping me with the reduced set cookie code and explaining the domain path.

This works on localhost no problem!

:)


问:
JsonMappingException when serializing avro generated object to json
I used avro-tools to generate java classes from avsc files, using:

```<code>java.exe -jar avro-tools-1.7.7.jar compile -string schema myfile.avsc
</code>```

Then I tried to serialize such objects to json by ObjectMapper,
but always got a JsonMappingException saying "not an enum" or "not a union".
In my test I create the generated object using it's builder or constructor.
I got such exceptions for objects of different classes...

Sample Code:

```<code>ObjectMapper serializer = new ObjectMapper(); // com.fasterxml.jackson.databind
serializer.register(new JtsModule()); // com.bedatadriven.jackson.datatype.jts
...
return serializer.writeValueAsBytes(avroConvertedObject); // => JsonMappingException
</code>```

I also tried many configurations using: serializer.configure(...) but still failed.
Versions: Java 1.8, jackson-datatype-jts 2.3,
jackson-core 2.6.5, jackson-databind 2.6.5, jackson-annotations 2.6.5

Any suggestions?
Thanks!

答:
If the SCHEMA member is really the case (we don't see the full error message), then you can switch it off. I use a mixin to do it, like this:

```<code>import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.apache.avro.Schema;
import org.junit.Test;

import java.io.File;
import java.io.IOException;

public class AvroGenerTests
{
  abstract class IgnoreSchemaProperty
  {
    // You have to use the correct package for JsonIgnore,
    // fasterxml or codehaus
    @JsonIgnore abstract void getSchema();
  }

  @Test
  public void writeJson() throws IOException {
    BookAvro b = BookAvro.newBuilder()
      .setTitle("Wilk stepowy")
      .setAuthor("Herman Hesse")
      .build();
    ObjectMapper om = new ObjectMapper();
    om.enable(SerializationFeature.INDENT_OUTPUT);
    om.addMixIn(BookAvro.class, IgnoreSchemaProperty.class);
    om.writeValue(new File("plik_z_gen.json"), b);
  }
}
</code>```

Body:
I used avro-tools to generate java classes from avsc files, using:

java.exe -jar avro-tools-1.7.7.jar compile -string schema myfile.avsc

Then I tried to serialize such objects to json by ObjectMapper,
but always got a JsonMappingException saying "not an enum" or "not a union".
In my test I create the generated object using it's builder or constructor.
I got such exceptions for objects of different classes...

Sample Code:

ObjectMapper serializer = new ObjectMapper(); // com.fasterxml.jackson.databind
serializer.register(new JtsModule()); // com.bedatadriven.jackson.datatype.jts
...
return serializer.writeValueAsBytes(avroConvertedObject); // => JsonMappingException

I also tried many configurations using: serializer.configure(...) but still failed.
Versions: Java 1.8, jackson-datatype-jts 2.3,
jackson-core 2.6.5, jackson-databind 2.6.5, jackson-annotations 2.6.5

Any suggestions?
Thanks!

Body:
If the SCHEMA member is really the case (we don't see the full error message), then you can switch it off. I use a mixin to do it, like this:

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.apache.avro.Schema;
import org.junit.Test;

import java.io.File;
import java.io.IOException;

public class AvroGenerTests
{
  abstract class IgnoreSchemaProperty
  {
    // You have to use the correct package for JsonIgnore,
    // fasterxml or codehaus
    @JsonIgnore abstract void getSchema();
  }

  @Test
  public void writeJson() throws IOException {
    BookAvro b = BookAvro.newBuilder()
      .setTitle("Wilk stepowy")
      .setAuthor("Herman Hesse")
      .build();
    ObjectMapper om = new ObjectMapper();
    om.enable(SerializationFeature.INDENT_OUTPUT);
    om.addMixIn(BookAvro.class, IgnoreSchemaProperty.class);
    om.writeValue(new File("plik_z_gen.json"), b);
  }
}


问:
How to limit file size when writing one?
I am using the output streams from the io module and writing to files. I want to be able to detect when I have written 1G of data to a file and then start writing to a second file. I can't seem to figure out how to determine how much data I have written to the file.

Is there something easy built in to io? Or might I have to count the bytes before each write manually?

答:
I noticed an ambiguity in your question. Do you want the file to be (a) over (b) under (c) exactly 1GiB large, before switching?

It's easy to tell if you've gone over. tell() is sufficient for that kind of thing; just check if tell() > 1024*1024*1024: and you'll know.

Checking if you're under 1GiB, but will go over 1GiB on your next write, is a similar technique. if len(data_to_write) + tell > 1024*1024*1024: will suffice.

The trickiest thing to do is to get the file to exactly 1GiB. You will need to tell() the length of the file, and then partition your data appropriately in order to hit the mark precisely.

Regardless of exactly which semantics you want, tell() is always going to be at least as slow as doing the counting yourself, and possibly slower. This doesn't mean that it's the wrong thing to do; if you're writing the file from a thread, then you almost certainly will want to tell() rather than hope that you've correctly preempted other threads writing to the same file. (And do your locks, etc., but that's another question.)

By the way, I noticed a definite direction in your last couple questions. Are you aware of #twisted and #python IRC channels on Freenode (irc.freenode.net)? You will get timelier, more useful answers.

~ C.


问:
clang fails with pip install on macos
I am running pip install scrypt==0.8.0.

I get the following error: error: command '/usr/bin/clang' failed with exit status 1.
I have xcode-select, gcc etc. installed. when i try to cd into that folder it doesn't exist and running clang --version it gives me:

```<code>Apple LLVM version 9.0.0 (clang-900.0.38)
Target: x86_64-apple-darwin17.2.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
</code>```

full error: https://pastebin.com/JZW1jRCy

答:
Well... It seems that the problem lies on Apple's side. I was able to reproduce the issue on my Macbook with High Sierra. I found this discussion on github regarding other cryptographic library for python and the solution they used worked for me.

```<code>$  env LDFLAGS="-L$(brew --prefix openssl)/lib" CFLAGS="-I$(brew --prefix openssl)/include" pip install scrypt==0.8.0
</code>```

Scrypt installed without any problems and I was able to import it in my interpreter:

```<code>$  python
Python 3.6.3 (default, Oct  4 2017, 06:09:15)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.37)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import scrypt
>>> dir(scrypt)
['ERROR_MESSAGES', 'IS_PY2', 'MAXMEMFRAC_DEFAULT', 'MAXMEM_DEFAULT', 'MAXTIME_DEFAULT', 'MAXTIME_DEFAULT_ENC', 'POINTER', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '__warningregistry__', '_crypto_scrypt', '_ensure_bytes', '_scrypt', '_scryptdec_buf', '_scryptenc_buf', 'c_char_p', 'c_double', 'c_int', 'c_size_t', 'c_uint32', 'c_uint64', 'cdll', 'create_string_buffer', 'decrypt', 'encrypt', 'error', 'hash', 'imp', 'os', 'pointer', 'sys']
>>>
</code>```

I see, however, that cryptography library describes alternative solution here. Unfortunatelly, I was unable to reproduce the issue locally after using mentioned solution so I can't say if it solves the problem. I'd suggest going through it first since it seems less intrusive.

Title: clang fails with pip install on macos

Body:
I am running pip install scrypt==0.8.0.

I get the following error: error: command '/usr/bin/clang' failed with exit status 1.
I have xcode-select, gcc etc. installed. when i try to cd into that folder it doesn't exist and running clang --version it gives me:

Apple LLVM version 9.0.0 (clang-900.0.38)
Target: x86_64-apple-darwin17.2.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

full error: https://pastebin.com/JZW1jRCy

Body:
Well... It seems that the problem lies on Apple's side. I was able to reproduce the issue on my Macbook with High Sierra. I found this discussion on github regarding other cryptographic library for python and the solution they used worked for me.

$  env LDFLAGS="-L$(brew --prefix openssl)/lib" CFLAGS="-I$(brew --prefix openssl)/include" pip install scrypt==0.8.0

Scrypt installed without any problems and I was able to import it in my interpreter:

$  python
Python 3.6.3 (default, Oct  4 2017, 06:09:15)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.37)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import scrypt
>>> dir(scrypt)
['ERROR_MESSAGES', 'IS_PY2', 'MAXMEMFRAC_DEFAULT', 'MAXMEM_DEFAULT', 'MAXTIME_DEFAULT', 'MAXTIME_DEFAULT_ENC', 'POINTER', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '__warningregistry__', '_crypto_scrypt', '_ensure_bytes', '_scrypt', '_scryptdec_buf', '_scryptenc_buf', 'c_char_p', 'c_double', 'c_int', 'c_size_t', 'c_uint32', 'c_uint64', 'cdll', 'create_string_buffer', 'decrypt', 'encrypt', 'error', 'hash', 'imp', 'os', 'pointer', 'sys']
>>>

I see, however, that cryptography library describes alternative solution here. Unfortunatelly, I was unable to reproduce the issue locally after using mentioned solution so I can't say if it solves the problem. I'd suggest going through it first since it seems less intrusive.


问:
How to process video files in batch using Emotion SDK for Javascript
I am using Affectiva's Emotion SDK for Javascript to play and analyze a video file. Currently, I am playing the video as a stream and capturing emotion features following their "Analyze a video frame stream" tutorial. However, I want to process the video file in batch rather than taking the whole duration of the video to analyze.

Increasing the playback rate of the video helped speed up this processes. I have also tried to skip frames by seeking ahead in the video but the performance was disappointing. Does anyone know of a way to process the video file that isn't bottlenecked by the playback rate of the video?

答:
I was able to solve this problem (albeit probably not very efficient) by using seeking with a lower fps. Essentially in the detector's "onImageResultsSuccess" function, I call the function nextFrame which skips ahead in the video by an amount I set with the variable fps. Which calls the "seeked" event on the video element which can then call the captureImage function that triggers the detector creating a loop that runs until the whole video is analyzed. Below is a portion of the code as well as jsfiddle implementation.

```<code>  var nextFrame = function() {
    // when frame is captured, increase
    vidTimeStamp = vidTimeStamp + (1 / fps);
    // if we are not passed end, seek to next interval
    if (vidTimeStamp <= video.duration) {
      // this will trigger another seeked event
      message_text.innerHTML = ((vidTimeStamp / video.duration) * 100).toFixed(2) + "% completed";
      video.currentTime = vidTimeStamp;
    } else {
      // DONE!, next action
      message_text.innerHTML = "100% Completed";
      alert("Video Processed");

      download_btn.click();
    }
  };

  video.addEventListener("seeked", function(e) {
    // now video has seeked and current frames will show
    // at the time as we expect
    captureImage(vidTimeStamp);
  });
</code>```

https://jsfiddle.net/kkawabat/zvt9rbve/

Body:
I was able to solve this problem (albeit probably not very efficient) by using seeking with a lower fps. Essentially in the detector's "onImageResultsSuccess" function, I call the function nextFrame which skips ahead in the video by an amount I set with the variable fps. Which calls the "seeked" event on the video element which can then call the captureImage function that triggers the detector creating a loop that runs until the whole video is analyzed. Below is a portion of the code as well as jsfiddle implementation.

  var nextFrame = function() {
    // when frame is captured, increase
    vidTimeStamp = vidTimeStamp + (1 / fps);
    // if we are not passed end, seek to next interval
    if (vidTimeStamp <= video.duration) {
      // this will trigger another seeked event
      message_text.innerHTML = ((vidTimeStamp / video.duration) * 100).toFixed(2) + "% completed";
      video.currentTime = vidTimeStamp;
    } else {
      // DONE!, next action
      message_text.innerHTML = "100% Completed";
      alert("Video Processed");

      download_btn.click();
    }
  };

  video.addEventListener("seeked", function(e) {
    // now video has seeked and current frames will show
    // at the time as we expect
    captureImage(vidTimeStamp);
  });

https://jsfiddle.net/kkawabat/zvt9rbve/


问:
Unexpected token / in JSON. How to include a regex in an array in a JSON?
I want to include a regex in an array in JSON, like this:

```<code>"routes:before": {
    "./middleware/foo": {
        "enabled": false,
        "paths": [/^\/(?!css|js|img).+$/ig] // <== doesn't work, throws
    }
},
</code>```

But it throws:

SyntaxError: \middleware.json: Unexpected token / in JSON at position 884

Although they say it is possible:

In addition to a literal string, route can be a path matching pattern, a regular expression, or an array including all these types.

What do I miss? How to pass a regex in an array in JSON?

答:
You would need to store it as a string, i.e. "paths": "[/^\/(?!css|js|img).+$/ig]"

Then, you can reconstruct: var re = new RegExp(paths, 'i');

JSON allows strings, booleans, numbers, objects, arrays, and null. You cannot store/transfer a regular expression unless it is as a string.

Body:
I want to include a regex in an array in JSON, like this:

"routes:before": {
    "./middleware/foo": {
        "enabled": false,
        "paths": [/^\/(?!css|js|img).+$/ig] // <== doesn't work, throws
    }
},

But it throws:

SyntaxError: \middleware.json: Unexpected token / in JSON at position 884

Although they say it is possible:

In addition to a literal string, route can be a path matching pattern, a regular expression, or an array including all these types.

What do I miss? How to pass a regex in an array in JSON?