问:
Java WebServices with Spring and OAS/OC4J
I'm having problems deploying a simple WebServices app (like "Hello World" simple) to OC4J. The same code works fine under Jetty, but breaks in OC4J, and I'm wondering if anyone else has faced the same issue. I'm using Enterprise Manager to deploy the app, but the deployment fails with this message:

```<code>    [Jan 23, 2009 8:46:20 AM] Binding TestWs web-module for application TestWs to site default-web-site under context root /TestWs
    [Jan 23, 2009 8:46:22 AM] Operation failed with error: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://cxf.apache.org/jaxws]
Offending resource: ServletContext resource [/WEB-INF/beans.xml]
</code>```

Looking at the beans.xml, the offending code seems to be the XML namespace declarations:

```<code><beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jaxws="http://cxf.apache.org/jaxws"
    xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">

    <import resource="classpath:META-INF/cxf/cxf.xml" />
    <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
    <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

    <jaxws:endpoint
        id="helloService"
        implementor="com.test.endpoint.HelloImpl"
        address="/HelloWorld" />
</beans>
</code>```

The stack trace is not terribly illuminating:

```<code>    09/01/23 08:57:28 oracle.oc4j.admin.internal.DeployerException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://cxf.apache.org/jaxws]
    Offending resource: ServletContext resource [/WEB-INF/beans.xml]

    09/01/23 08:57:28   at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68)
    09/01/23 08:57:28   at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85)
    09/01/23 08:57:28   at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:80)
    09/01/23 08:57:28   at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.error(BeanDefinitionParserDelegate.java:261)
    09/01/23 08:57:28   at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1120)
...
</code>```

Has anyone else run into similar problems? And if so, what's the best way to go about fixing it? My XML skills are middling, and I'm a complete noob with WebServices. But this may be an OC4J issue.

Thanks in advance for your help!

EDIT: This is not, as far as I can tell, a classpath issue, unless OC4J is odd about what jars it want to see where (as I know Tomcat can be). My WEB-INF/lib folder has the CXF jar, the Spring jars (beans, context, core, and web), xml-resolver-1.2.jar, and XmlSchema-1.4.2.jar. If I need to list everything in the WEB-INF/lib folder, I will. But again, the program works in Jetty.

Another Edit: Based on what I'm reading here, this appears to be an issue between Spring and the CXF jar -- there's a NamespaceHandler class in the CXF jar (in org.apache.cxf.frontend.spring to be precise), but there seems to be a configuration issue preventing Spring from seeing it.

Last Edit: Thank you everyone for your help. I never ended up getting CXF working in OC4J, because my client is on version 10.1.3.3.0. It's not J2EE 5 compliant, and I'm pretty sure they're not going to go for unpacking their oc4j.jar in order to change the boot.xml. But without the document Daniel pointed me to, I never would have known that.

So I switched to XFire version 1.2.6, and got my test app working after a few hiccups. Along the way I learned some interesting things about OC4J:

When deploying in Enterprise Manager, make sure you choose to load the local classpath first.

OC4J uses non-standard XML files, so make sure your app is not using any of OC4J's native XML files (in the Deployment Settings, uncheck all the currently selected imports -- that way, you can ensure that the app is using only files you provide in WEB-INF/lib)

If you can, use another app server. :P

Thank you all again!

答:
I hate to ask the obvious, but have you looked at all the stuff for configuring OS4J and CXF together from the CXF web site?
http://cwiki.apache.org/CXF20DOC/appserverguide.html#AppServerGuide-OC4J</p>

OwnerDisplayName: rtperson

Body:
I'm having problems deploying a simple WebServices app (like "Hello World" simple) to OC4J. The same code works fine under Jetty, but breaks in OC4J, and I'm wondering if anyone else has faced the same issue. I'm using Enterprise Manager to deploy the app, but the deployment fails with this message:

    [Jan 23, 2009 8:46:20 AM] Binding TestWs web-module for application TestWs to site default-web-site under context root /TestWs
    [Jan 23, 2009 8:46:22 AM] Operation failed with error: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://cxf.apache.org/jaxws]
Offending resource: ServletContext resource [/WEB-INF/beans.xml]

Looking at the beans.xml, the offending code seems to be the XML namespace declarations:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jaxws="http://cxf.apache.org/jaxws"
    xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">

    <import resource="classpath:META-INF/cxf/cxf.xml" />
    <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
    <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

    <jaxws:endpoint
        id="helloService"
        implementor="com.test.endpoint.HelloImpl"
        address="/HelloWorld" />
</beans>

The stack trace is not terribly illuminating:

    09/01/23 08:57:28 oracle.oc4j.admin.internal.DeployerException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://cxf.apache.org/jaxws]
    Offending resource: ServletContext resource [/WEB-INF/beans.xml]

    09/01/23 08:57:28   at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68)
    09/01/23 08:57:28   at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85)
    09/01/23 08:57:28   at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:80)
    09/01/23 08:57:28   at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.error(BeanDefinitionParserDelegate.java:261)
    09/01/23 08:57:28   at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1120)
...

Has anyone else run into similar problems? And if so, what's the best way to go about fixing it? My XML skills are middling, and I'm a complete noob with WebServices. But this may be an OC4J issue.

Thanks in advance for your help!

EDIT: This is not, as far as I can tell, a classpath issue, unless OC4J is odd about what jars it want to see where (as I know Tomcat can be). My WEB-INF/lib folder has the CXF jar, the Spring jars (beans, context, core, and web), xml-resolver-1.2.jar, and XmlSchema-1.4.2.jar. If I need to list everything in the WEB-INF/lib folder, I will. But again, the program works in Jetty.

Another Edit: Based on what I'm reading here, this appears to be an issue between Spring and the CXF jar -- there's a NamespaceHandler class in the CXF jar (in org.apache.cxf.frontend.spring to be precise), but there seems to be a configuration issue preventing Spring from seeing it.

Last Edit: Thank you everyone for your help. I never ended up getting CXF working in OC4J, because my client is on version 10.1.3.3.0. It's not J2EE 5 compliant, and I'm pretty sure they're not going to go for unpacking their oc4j.jar in order to change the boot.xml. But without the document Daniel pointed me to, I never would have known that.

So I switched to XFire version 1.2.6, and got my test app working after a few hiccups. Along the way I learned some interesting things about OC4J:

When deploying in Enterprise Manager, make sure you choose to load the local classpath first.

OC4J uses non-standard XML files, so make sure your app is not using any of OC4J's native XML files (in the Deployment Settings, uncheck all the currently selected imports -- that way, you can ensure that the app is using only files you provide in WEB-INF/lib)

If you can, use another app server. :P

Thank you all again!

LastEditorDisplayName: rtperson

OwnerDisplayName: Daniel Kulp


来源: stackexchange

问:
send mouse position data from QGraphicsItem to label on mainwindow
I created a custom QGraphicsItem and I am able to find the mouse position over the image by overriding the hoverMoveEvent.

How can I send that position data to a QLabel that is in my main window, that has my GraphicsView so that the label is always showing the pixel coordinates over the main label? Do I have to use a timer or something?

答:
I would use the signal/slot mechanism of Qt to do this.

Declare a custom signal in your QGraphicsItem.

Connect your signal with the setNum or setText slot of the QLabel.

emit the signal after you read the mouse position.

ContentLicense: CC BY-SA 2.5


问:
Rolling sum windowed for every ID individually
In the following dataframe, I need rolling sum of X for the last two 'Time' periods for every ID.

```<code>df = pd.DataFrame({'ID':[1000, 1000, 1000, 2000, 2000, 2000, 3000,3000,3000],
              'Time':[1,2,3,1,2,3,1,2,3],
              'X':[101, 201, 123, 234, 222, 333, 444, 0, 0 ]})
</code>```

I tried the following code, but it resulted rolling sum carried over from customer ID '1000' to '2000' and so on.

```<code>df[['X']].rolling(2).sum()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In the following dataframe, I need rolling sum of X for the last two 'Time' periods for every ID.

df = pd.DataFrame({'ID':[1000, 1000, 1000, 2000, 2000, 2000, 3000,3000,3000],
              'Time':[1,2,3,1,2,3,1,2,3],
              'X':[101, 201, 123, 234, 222, 333, 444, 0, 0 ]})

I tried the following code, but it resulted rolling sum carried over from customer ID '1000' to '2000' and so on.

df[['X']].rolling(2).sum()

Body:
IIUC:

In [190]: df['new'] = df.groupby('ID', as_index=False)['X'].rolling(2).sum().reset_index(level=0, drop=True)

In [191]: df
Out[191]:
     ID  Time    X    new
0  1000     1  101    NaN
1  1000     2  201  302.0
2  1000     3  123  324.0
3  2000     1  234    NaN
4  2000     2  222  456.0
5  2000     3  333  555.0
6  3000     1  444    NaN
7  3000     2    0  444.0
8  3000     3    0    0.0


问:
enabling/ disabling combobox when selected index is selected
I'm trying to enable comboxbox when specific country is selected, otherwise should be disabled. </p>

```<code>Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    cboCountry.Items.AddRange(File.ReadAllLines("..\..\TextFiles\countries.txt"))
    cboCounty.Items.AddRange(File.ReadAllLines("..\..\TextFiles\county.txt"))

End Sub

Private Sub cboCountry_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboCountry.SelectedIndexChanged
    If cboCountry.SelectedIndex = cboCountry.Items.IndexOf("Ireland") Then

        cboCounty.Enabled = True

    Else
        cboCounty.Enabled = False

    End If
End Sub
</code>```

<p>When I select any country including "Ireland" combobox is disabled </p>

答:
```<code>If cboCountry.Text = "Ireland" Then
   cboCounty.Enabled = True
Else
   cboCounty.Enabled = False
End If
</code>```

since you're wanting this to happen when Ireland is selected, you should be able to just check that the text is set to Ireland

Case sensitivity applies here so makes sure Ireland is indeed displayed just as you're checking or force case for comparison.

Body:
I'm trying to enable comboxbox when specific country is selected, otherwise should be disabled.

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    cboCountry.Items.AddRange(File.ReadAllLines("..\..\TextFiles\countries.txt"))
    cboCounty.Items.AddRange(File.ReadAllLines("..\..\TextFiles\county.txt"))

End Sub

Private Sub cboCountry_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboCountry.SelectedIndexChanged
    If cboCountry.SelectedIndex = cboCountry.Items.IndexOf("Ireland") Then

        cboCounty.Enabled = True

    Else
        cboCounty.Enabled = False

    End If
End Sub

When I select any country including "Ireland" combobox is disabled

Body:
If cboCountry.Text = "Ireland" Then
   cboCounty.Enabled = True
Else
   cboCounty.Enabled = False
End If

since you're wanting this to happen when Ireland is selected, you should be able to just check that the text is set to Ireland

Case sensitivity applies here so makes sure Ireland is indeed displayed just as you're checking or force case for comparison.


问:
google geocoding api services with zip code 12593
I am having an issue with google geo-loaction services. essentially we are using it for a zip code validator and there is an issue with zip code '12593'. This zip code is showing as being in Spain. (see screenshot here = http://prntscr.com/hkkafh.

See xml here
    https://maps.googleapis.com/maps/api/geocode/xml?&address=12593)

This zip code though is a USA based zip code as can be seen here = https://www.google.com/search?num=100&q=us+zip+code+12593&oq=us+zip+code+12593 (google search results.)

I understand that google is not the othority on zip codes however I would expect google to understand that this zip code may have two seperate locations.

any idea How I can get the api to understand I am looking for zip codes specifically in the USA?

答:
The zip code you're trying to find isn't reachable by the geocoding api. This near one is reachable:

https://maps.googleapis.com/maps/api/geocode/json?&components=country:US|postal_code:12516

To search by zip code and restrict by country (i.e. US), you must use the subparameters of the components query parameter like in the URL above

...&components=country:US|postal_code:[YOUR PARAMETER]

(got this parameter info on https://developers.google.com/maps/documentation/geocoding/intro#ComponentFiltering)


问:
chrome and safari render css columns differently when number of items equals number of columns
I've got a directory listing that uses CSS columns but behaves differently in Chrome and Safari. Each section of the directory has a wrapper that arranges the listings into two columns.

I've got the CSS so Chrome renders it the way I want:

In Safari, the first item in the second column sometimes has an apparent margin above it.

I can fix this in Safari by adding display: inline-block; to the list elements. This breaks the layout in Chrome, as sections which have only two items list both items in the first column.

Snippet:

ul {
 moz-column-count:2;
 -webkit-column-count:2;
 column-count:2;
  column-gap: 2em;
}

li {
   -webkit-column-break-inside: avoid;
  page-break-inside: avoid;
  break-inside: avoid;
  width:100%;
 list-style-type:none;
 padding:10px;
  box-sizing:border-box;
  background-color: #90cdc0;
  margin-bottom: 2em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h3>
A
</h3>
<ul>
  <li>Anna<p>Sometimes there is additional content</p></li>
    <li>Anya</li>
</ul>
<h3>
B
</h3>
<ul>
    <li>Bartolo <p>Sometimes there is additional content. The boxes are of variable size.</p></li>
    <li>Beatriz</li>
    <li>Benedicto</li>
  <li>Boggins</li>
</ul></code>```

Is it possible to style this two-column directory in such away that it displays correctly in all browsers?

答:
I sorted this out, at least for Safari vs. Chrome.

Since this only applies when the number of items is equal to the number of columns, and since that number is known, I can apply display: inline-block; to li and then override that when the 2nd listing is also the last listing.

In my case, the solution is to add to the CSS:

```<code>li {
  display: inline-block;
}

li:last-child:nth-child(2) {
  display: block;
}
</code>```

Full CSS:

```<code>ul {
  moz-column-count:2;
  -webkit-column-count:2;
  column-count:2;
  column-gap: 2em;
}

li {
  display: inline-block;
  -webkit-margin-before: 0;
  -webkit-margin-after: 0;
  -webkit-column-break-inside: avoid;
  page-break-inside: avoid;
  break-inside: avoid;
  width:100%;
  list-style-type:none;
  padding: 1em;
  box-sizing:border-box;
  background-color: #90cdc0;
  margin-bottom: 2em;
}

li:last-child:nth-child(2) {
  display: block;
}
</code>```

Body:
I've got a directory listing that uses CSS columns but behaves differently in Chrome and Safari. Each section of the directory has a wrapper that arranges the listings into two columns.

I've got the CSS so Chrome renders it the way I want:

In Safari, the first item in the second column sometimes has an apparent margin above it.

I can fix this in Safari by adding display: inline-block; to the list elements. This breaks the layout in Chrome, as sections which have only two items list both items in the first column.

Snippet:

ul {
 moz-column-count:2;
 -webkit-column-count:2;
 column-count:2;
  column-gap: 2em;
}

li {
   -webkit-column-break-inside: avoid;
  page-break-inside: avoid;
  break-inside: avoid;
  width:100%;
 list-style-type:none;
 padding:10px;
  box-sizing:border-box;
  background-color: #90cdc0;
  margin-bottom: 2em;
}

A

Anna
Sometimes there is additional content

Anya

B

Bartolo
Sometimes there is additional content. The boxes are of variable size.

Beatriz

Benedicto

Boggins

Is it possible to style this two-column directory in such away that it displays correctly in all browsers?

Body:
I sorted this out, at least for Safari vs. Chrome.

Since this only applies when the number of items is equal to the number of columns, and since that number is known, I can apply display: inline-block; to li and then override that when the 2nd listing is also the last listing.

In my case, the solution is to add to the CSS:

li {
  display: inline-block;
}

li:last-child:nth-child(2) {
  display: block;
}

Full CSS:

ul {
  moz-column-count:2;
  -webkit-column-count:2;
  column-count:2;
  column-gap: 2em;
}

li {
  display: inline-block;
  -webkit-margin-before: 0;
  -webkit-margin-after: 0;
  -webkit-column-break-inside: avoid;
  page-break-inside: avoid;
  break-inside: avoid;
  width:100%;
  list-style-type:none;
  padding: 1em;
  box-sizing:border-box;
  background-color: #90cdc0;
  margin-bottom: 2em;
}

li:last-child:nth-child(2) {
  display: block;
}


问:
Is it Meaningful to Add 'x-frame-options' in an Restful API
We are developing a restful API that fulfills some various events. We have done a Nessus vulnerability scan to see security leaks. It turned out that we have some leaks leads to clickjacking and we have found the solution. I have added x-frame-options as SAMEORIGINin order to handle problems.

My question here is that, since I am an API, do I need to handle clickjacking? I guess 3rd party user should be able to reach my API over an iframe and I don't need to handle this.

Do I miss something? Could you please share your ideas?

答:
OWASP recommends that not only do you send an X-Frame-Options header but that it is set to DENY.

These are recommendations not for a web site but for a REST service.

The scenario where it makes sense to do this is exactly the one the OP mentioned - running a vulnerability scan.

If you do not return a correct X-Frame-Options header the scan will fail. This matters when proving to customers that your endpoint is safe.

It is much easier to provide your customer a passing report than have to argue why a missing header does not matter.

Adding a X-Frame-Options header should not affect the endpoint consumer as it is not a browser with an iframe.


问:
Java/Scala multi-threading issue for a web service
In a web service environment, I want to make a few independent http calls per each request that my application receives. As these calls are independent, it doesn't make sense to make them serially so I need a sort of concurrency.

To my understanding, it doesn't make sense to carelessly create new threads for each http call. And also, recreating all these threads brings a lot of overhead.

So I think my best option would be to create a FixedThreadPool in a singleton for all http calls and use that across the application.

Is this the best choice?

答: You may want to consider using the AsyncHttpClient AsyncHttpClient library for very easy asynchronous http calls. A good series of blog posts that describes how to use this library is Going Asynchronous using AsyncHttpClient </p>


答:
You can look at the index of the error using findIndex:

```<code>var errIndex = data.findIndex(el => el[0] == "err");
assert(errIndex != -1);
return data.map(([date, val], i) => {
  if (i < errIndex)
    return [date, val, 0];
  if (i > errIndex)
    return [date, 0, val];
  return ["err", NaN] // or whatever
);
</code>```

Alternatively you might want to do

```<code>var it = data.values();
for (const el of it) {
  if (el[0] == "err") break;
  el.push(0);
}
for (const el of it) {
  el.splice(1, 0, 0);
}
</code>```

Title: transform array of arrays inserting nulls, Javascript

Body:
I am receiving data in this way:

  [Sun Jan 01 2006 00:00:00 GMT-0600 (CST), 8.605613643557573]
  [Mon Jan 01 2007 00:00:00 GMT-0600 (CST), 4.639263458390814]
  [Tue Jan 01 2008 00:00:00 GMT-0600 (CST), 3.690424190442011]
  [Thu Jan 01 2009 00:00:00 GMT-0600 (CST), -6.068362055704255]
  [Fri Jan 01 2010 00:00:00 GMT-0600 (CST), 0.011317380895792274]
  [Sat Jan 01 2011 00:00:00 GMT-0600 (CST), 3.9984661908088825]
  [Sun Jan 01 2012 00:00:00 GMT-0600 (CST), 2.4211622308876173]
  [Tue Jan 01 2013 00:00:00 GMT-0600 (CST), -1.5740599423273804]
  [Wed Jan 01 2014 00:00:00 GMT-0600 (CST), 2.6624793033769967]
  [Thu Jan 01 2015 00:00:00 GMT-0600 (CST), 1744.9379869455643]
  ["err", NaN]
  [Wed Jan 01 2020 00:00:00 GMT-0600 (CST), 3417.1886283181875]
  [Wed Jan 01 2025 00:00:00 GMT-0600 (CST), 3331.7059850696196]
  [Tue Jan 01 2030 00:00:00 GMT-0600 (CST), 3237.940431993671]

And I'm trying to make a dataset to look like this:

  [Sun Jan 01 2006 00:00:00 GMT-0600 (CST), 8.605613643557573, 0]
  [Mon Jan 01 2007 00:00:00 GMT-0600 (CST), 4.639263458390814, 0]
  [Tue Jan 01 2008 00:00:00 GMT-0600 (CST), 3.690424190442011, 0]
  [Thu Jan 01 2009 00:00:00 GMT-0600 (CST), -6.068362055704255, 0]
  [Fri Jan 01 2010 00:00:00 GMT-0600 (CST), 0.011317380895792274, 0]
  [Sat Jan 01 2011 00:00:00 GMT-0600 (CST), 3.9984661908088825, 0]
  [Sun Jan 01 2012 00:00:00 GMT-0600 (CST), 2.4211622308876173, 0]
  [Tue Jan 01 2013 00:00:00 GMT-0600 (CST), -1.5740599423273804, 0]
  [Wed Jan 01 2014 00:00:00 GMT-0600 (CST), 2.6624793033769967, 0]
  [Thu Jan 01 2015 00:00:00 GMT-0600 (CST), 1744.9379869455643, 0]
  ["err", NaN]
  [Wed Jan 01 2020 00:00:00 GMT-0600 (CST),0 , 3417.1886283181875]
  [Wed Jan 01 2025 00:00:00 GMT-0600 (CST),0 , 3331.7059850696196]
  [Tue Jan 01 2030 00:00:00 GMT-0600 (CST),0 , 3237.940431993671]

Is there a way to do this by looking at the index of "err" ?

Body:
You can look at the index of the error using findIndex:

var errIndex = data.findIndex(el => el[0] == "err");
assert(errIndex != -1);
return data.map(([date, val], i) => {
  if (i < errIndex)
    return [date, val, 0];
  if (i > errIndex)
    return [date, 0, val];
  return ["err", NaN] // or whatever
);

Alternatively you might want to do

var it = data.values();
for (const el of it) {
  if (el[0] == "err") break;
  el.push(0);
}
for (const el of it) {
  el.splice(1, 0, 0);
}


问:
Batch File Programming with Findstr and Regex
First off, I am not a batch file and/or regex programmer.  ;)

Using batch file programming to parse filenames beginning with "T" that may be immediately followed by "2" AND "2" may be immediately followed by any of the integers 0-9.  All the files in the folder will be named the same beginning with "T" and followed by integers 1-29.  For example:
T1_... or T12_... or T2_... or T22_....

In this particular case ...

a) Filenames with T2 should fail the regex.  Errorlevel should be 1.

b) Filenames with T12 should fail the regex.  Errorlevel should be 1.

c) Filenames with T20 - T29 should pass the regex.  Errorlevel should be 0.

Problem: These results are not seen.  Errorlevel appears to be 0, always.

```<code>echo on

dir *.bin /b | findstr /r /c:"^[T][2][?=0123456789]*"
if errorlevel 0 goto :regular

:special
   echo special
   pause
   exit /B 0

:regular
   echo regular
   pause
   exit /B 0
</code>```

Two web based regex evaluators say my regex is valid as written when tested against all combinations, pass and fail.

What is going on with the "findstr" regex that it does not produce the outlined behavior (a-c)?  Or, am I not using errorlevel correctly?

Thanks for any insight.

答:
findstr supports limited regular expression, but, for your application, you could use `findstr /r "^T2[0-9]".

For full Javascript compatible regular expressions, how about using cscript instead?

@echo off

dir *.txt /b | cscript //nologo match.js "^T2[0-9]"
if %errorlevel% == 0 goto :regular

:special
   echo special
   pause
   exit /B 0

:regular
   echo regular
   pause
   exit /B 0
```

<p>Where <code>match.js</code> is defined as:</p>

<pre class="lang-js prettyprint-override"><code>if (WScript.Arguments.Count() !== 1) {
  WScript.Echo("Syntax: match.js regex");
  WScript.Quit(1);
}
var rx = new RegExp(WScript.Arguments(0), "i");
var matched = false;
while (!WScript.StdIn.AtEndOfStream) {
  var str = WScript.StdIn.ReadLine();
  if (str.match(rx)) {
    WScript.Echo(str);
    matched = true;
  }
}
if (!matched) {
  WScript.Quit(1);
}
</code>```

Body:
First off, I am not a batch file and/or regex programmer.  ;)

Using batch file programming to parse filenames beginning with "T" that may be immediately followed by "2" AND "2" may be immediately followed by any of the integers 0-9.  All the files in the folder will be named the same beginning with "T" and followed by integers 1-29.  For example:
T1_... or T12_... or T2_... or T22_....

In this particular case ...

a) Filenames with T2 should fail the regex.  Errorlevel should be 1.

b) Filenames with T12 should fail the regex.  Errorlevel should be 1.

c) Filenames with T20 - T29 should pass the regex.  Errorlevel should be 0.

Problem: These results are not seen.  Errorlevel appears to be 0, always.

echo on

dir *.bin /b | findstr /r /c:"^[T][2][?=0123456789]*"
if errorlevel 0 goto :regular

:special
   echo special
   pause
   exit /B 0

:regular
   echo regular
   pause
   exit /B 0

Two web based regex evaluators say my regex is valid as written when tested against all combinations, pass and fail.

What is going on with the "findstr" regex that it does not produce the outlined behavior (a-c)?  Or, am I not using errorlevel correctly?

Thanks for any insight.

Body:
findstr supports limited regular expression, but, for your application, you could use `findstr /r "^T2[0-9]".

For full Javascript compatible regular expressions, how about using cscript instead?

@echo off

dir *.txt /b | cscript //nologo match.js "^T2[0-9]"
if %errorlevel% == 0 goto :regular

:special
   echo special
   pause
   exit /B 0

:regular
   echo regular
   pause
   exit /B 0

Where match.js is defined as:

if (WScript.Arguments.Count() !== 1) {
  WScript.Echo("Syntax: match.js regex");
  WScript.Quit(1);
}
var rx = new RegExp(WScript.Arguments(0), "i");
var matched = false;
while (!WScript.StdIn.AtEndOfStream) {
  var str = WScript.StdIn.ReadLine();
  if (str.match(rx)) {
    WScript.Echo(str);
    matched = true;
  }
}
if (!matched) {
  WScript.Quit(1);
}


问:
Decal shader not working on Device
I'm really novice and this is first time I wrote a shader for unity mobile game.
Here is the shader, working well on Editor but not on my android device :

```<code>                Shader "Decal" {
            Properties {
             _Skin("Skin (RGB)", 2D) = "white" {}
             _Dirt("Dirt (RGBA)", 2D) = "black" {}
             _Outfit("Outfit (RGBA)", 2D) = "black" {}
             _Painting("Painting (RGBA)", 2D) = "black" {}
             _Cheek("Cheek (RGBA)", 2D) = "black" {}
             _LipStick("LipStick (RGBA)", 2D) = "black" {}
             _Eye("Eye (RGBA)", 2D) = "black" {}
             _EyeLid("EyeLid (RGBA)", 2D) = "black" {}
             _ShadowHat("ShadowHat (RGBA)", 2D) = "black" {}
            }
            SubShader {
            Tags { "RenderType"="Opaque" }
            LOD 150

            CGPROGRAM
            #pragma surface surf Lambert noforwardadd

            sampler2D _Skin;
            sampler2D _Dirt;
            sampler2D _Outfit;
            sampler2D _Painting;
            sampler2D _Cheek;
            sampler2D _LipStick;
            sampler2D _Eye;
            sampler2D _EyeLid;
            sampler2D _ShadowHat;

            struct Input {
            float2 uv_Skin;
            };

            void surf (Input IN, inout SurfaceOutput o) {
            fixed4 c = tex2D(_Skin, IN.uv_Skin);
            fixed4 dirt = tex2D(_Dirt, IN.uv_Skin);
            fixed4 outfit = tex2D(_Outfit, IN.uv_Skin);
            fixed4 painting = tex2D(_Painting, IN.uv_Skin);
            fixed4 cheek = tex2D(_Cheek, IN.uv_Skin);
            fixed4 lipstick = tex2D(_LipStick, IN.uv_Skin);
            fixed4 eye = tex2D(_Eye, IN.uv_Skin);
            fixed4 eyelid = tex2D(_EyeLid, IN.uv_Skin);
            fixed4 shadowHat = tex2D(_ShadowHat, IN.uv_Skin);

            c.rgb = lerp (c.rgb, dirt.rgb, dirt.a);
            c.rgb = lerp (c.rgb, outfit.rgb, outfit.a);
            c.rgb = lerp (c.rgb, painting.rgb, painting.a);
            c.rgb = lerp (c.rgb, cheek.rgb, cheek.a);
            c.rgb = lerp (c.rgb, lipstick.rgb, lipstick.a);
            c.rgb = lerp (c.rgb, eye.rgb, eye.a);
            c.rgb = lerp (c.rgb, eyelid.rgb, eyelid.a);
            c.rgb = lerp (c.rgb, shadowHat.rgb, shadowHat.a);

            o.Albedo = c.rgb;
            o.Alpha = c.a;
            }
            ENDCG
            }

            Fallback "Mobile/VertexLit"
            }
</code>```

So any help would be very welcome :),and also one thing to clarify, I'm not sure the performance of this shader is good enough for mobile ?

Thanks you very much !

答:
According to this Unity Manual, OpenGL ES 2.0 only supports the maximum of 8 textures in a single shader.
Also, if you go to the Edit > Graphics Emulation menu and choose OpenGL ES 2.0, you can see the shader warnings for it.

I'm not sure the performance of this shader is good enough for mobile ?

You're using too many sampler2D's in a single shader. Also you should avoid expensive math functions in shader code. Your shader is expensive for mobile.

You can read more about mobile optimization here and here.

Title: Decal shader not working on Device

Body:
I'm really novice and this is first time I wrote a shader for unity mobile game.
Here is the shader, working well on Editor but not on my android device :

                Shader "Decal" {
            Properties {
             _Skin("Skin (RGB)", 2D) = "white" {}
             _Dirt("Dirt (RGBA)", 2D) = "black" {}
             _Outfit("Outfit (RGBA)", 2D) = "black" {}
             _Painting("Painting (RGBA)", 2D) = "black" {}
             _Cheek("Cheek (RGBA)", 2D) = "black" {}
             _LipStick("LipStick (RGBA)", 2D) = "black" {}
             _Eye("Eye (RGBA)", 2D) = "black" {}
             _EyeLid("EyeLid (RGBA)", 2D) = "black" {}
             _ShadowHat("ShadowHat (RGBA)", 2D) = "black" {}
            }
            SubShader {
            Tags { "RenderType"="Opaque" }
            LOD 150

            CGPROGRAM
            #pragma surface surf Lambert noforwardadd

            sampler2D _Skin;
            sampler2D _Dirt;
            sampler2D _Outfit;
            sampler2D _Painting;
            sampler2D _Cheek;
            sampler2D _LipStick;
            sampler2D _Eye;
            sampler2D _EyeLid;
            sampler2D _ShadowHat;

            struct Input {
            float2 uv_Skin;
            };

            void surf (Input IN, inout SurfaceOutput o) {
            fixed4 c = tex2D(_Skin, IN.uv_Skin);
            fixed4 dirt = tex2D(_Dirt, IN.uv_Skin);
            fixed4 outfit = tex2D(_Outfit, IN.uv_Skin);
            fixed4 painting = tex2D(_Painting, IN.uv_Skin);
            fixed4 cheek = tex2D(_Cheek, IN.uv_Skin);
            fixed4 lipstick = tex2D(_LipStick, IN.uv_Skin);
            fixed4 eye = tex2D(_Eye, IN.uv_Skin);
            fixed4 eyelid = tex2D(_EyeLid, IN.uv_Skin);
            fixed4 shadowHat = tex2D(_ShadowHat, IN.uv_Skin);

            c.rgb = lerp (c.rgb, dirt.rgb, dirt.a);
            c.rgb = lerp (c.rgb, outfit.rgb, outfit.a);
            c.rgb = lerp (c.rgb, painting.rgb, painting.a);
            c.rgb = lerp (c.rgb, cheek.rgb, cheek.a);
            c.rgb = lerp (c.rgb, lipstick.rgb, lipstick.a);
            c.rgb = lerp (c.rgb, eye.rgb, eye.a);
            c.rgb = lerp (c.rgb, eyelid.rgb, eyelid.a);
            c.rgb = lerp (c.rgb, shadowHat.rgb, shadowHat.a);

            o.Albedo = c.rgb;
            o.Alpha = c.a;
            }
            ENDCG
            }

            Fallback "Mobile/VertexLit"
            }

So any help would be very welcome :),and also one thing to clarify, I'm not sure the performance of this shader is good enough for mobile ?

Thanks you very much !


问:
How to change one character for another on a keyboard layout in KDE/Ubuntu
I would like to enter @ sign when I type № on my Russian keyboard layout.

I'm using KDE 4.13 on Ubuntu system.

I understand that I need to modify the layout somehow. What is the best way to do it?

答: I'd probably start by using xev to figure out the keycode sent by your keyboard for №, then use xmodmap to remap that key.


问:
Insert text before and after the selected text in javascript
I want to put some specified text (where possible/any editable field) before and after any selected text in an HTML document.
document.getSelection() or document.selection.createRange().text returns only the text itself not the position.
Is there anyway to replace the selected text? Anyway to insert specific text before and after selcted text anywhere in the document?

答:
Here's a cross-browser function to do this, which works in all major browsers and caters for the vastly different way IE does this compared  to other browsers.

Live example: http://jsfiddle.net/timdown/UWExN/64/

```<code>function insertHtmlAtSelectionEnd(html, isBefore) {
    var sel, range, node;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = window.getSelection().getRangeAt(0);
            range.collapse(isBefore);

            // Range.createContextualFragment() would be useful here but was
            // until recently non-standard and not supported in all browsers
            // (IE9, for one)
            var el = document.createElement("div");
            el.innerHTML = html;
            var frag = document.createDocumentFragment(), node, lastNode;
            while ( (node = el.firstChild) ) {
                lastNode = frag.appendChild(node);
            }
            range.insertNode(frag);
        }
    } else if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        range.collapse(isBefore);
        range.pasteHTML(html);
    }
}
</code>```

Body:
Here's a cross-browser function to do this, which works in all major browsers and caters for the vastly different way IE does this compared  to other browsers.

Live example: http://jsfiddle.net/timdown/UWExN/64/

function insertHtmlAtSelectionEnd(html, isBefore) {
    var sel, range, node;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = window.getSelection().getRangeAt(0);
            range.collapse(isBefore);

            // Range.createContextualFragment() would be useful here but was
            // until recently non-standard and not supported in all browsers
            // (IE9, for one)
            var el = document.createElement("div");
            el.innerHTML = html;
            var frag = document.createDocumentFragment(), node, lastNode;
            while ( (node = el.firstChild) ) {
                lastNode = frag.appendChild(node);
            }
            range.insertNode(frag);
        }
    } else if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        range.collapse(isBefore);
        range.pasteHTML(html);
    }
}


问:
If I have a URL String but one part is dynamic should I break it in two or can I insert a variable in the middle?
I'm trying to build a URL that I'll use in a POST request. The completed URL will look something like this:

```<code>http://somesite.com/post/member/{AccountNumber}/verify/etc
</code>```

The AccountNumber will be dynamic.

That can be done easily enough by having something like this:

```<code>String PATH1 = "http://somesite.com/post/member/"
String PATH2 = "/verify/etc"
String accountNumber;     //set account Number somewhere in the code

public String buildURL(String path1, String path2, String accoundNumber) {
    String url = path1 + accountNumber + path2
    return url;
}
</code>```

I was wondering if I could do this more cleanly by having just one PATH. I'd like to read in the path from a yml or properties file and then dynamically insert the AccountNumber. Is it possible to do this?

So, my buildURL would look something like this:

```<code>String PATH = http://somesite.com/post/member/{AccountNumber}/verify/etc
String accountNumber;     //set account Number somewhere in the code

public String buildURL(String path, String accoundNumber) {
    String url = path{insert AccountNumber somehow}
    return url;
}
</code>```

Or should I just stick with breaking it in two (I am overthinking this?)? Thanks.

EDIT: I realize I may have misused some terms. Not 100$ sure if it should be called 'PATH1', 'PATH2' etc since after looking here: What is the name of this URL part?
it seems like I'm including the 'scheme' and 'authority' part of the URL as PATH1.

答:
You have two different mechanisms in Java to accomplish this:

java.text.MessageFormat

```<code>    String url = MessageFormat.format("http://somesite.com/post/member/{0}/verify/etc","1234567");
    System.out.println(url);
</code>```

java.util.Formatter:

```<code>    Formatter  f = new Formatter(new StringBuilder());
    f.format("http://somesite.com/post/member/%s/verify/etc", "1234546");
    System.out.println(f.toString());
</code>```

Body:
I'm trying to build a URL that I'll use in a POST request. The completed URL will look something like this:

http://somesite.com/post/member/{AccountNumber}/verify/etc

The AccountNumber will be dynamic.

That can be done easily enough by having something like this:

String PATH1 = "http://somesite.com/post/member/"
String PATH2 = "/verify/etc"
String accountNumber;     //set account Number somewhere in the code

public String buildURL(String path1, String path2, String accoundNumber) {
    String url = path1 + accountNumber + path2
    return url;
}

I was wondering if I could do this more cleanly by having just one PATH. I'd like to read in the path from a yml or properties file and then dynamically insert the AccountNumber. Is it possible to do this?

So, my buildURL would look something like this:

String PATH = http://somesite.com/post/member/{AccountNumber}/verify/etc
String accountNumber;     //set account Number somewhere in the code

public String buildURL(String path, String accoundNumber) {
    String url = path{insert AccountNumber somehow}
    return url;
}

Or should I just stick with breaking it in two (I am overthinking this?)? Thanks.

EDIT: I realize I may have misused some terms. Not 100$ sure if it should be called 'PATH1', 'PATH2' etc since after looking here: What is the name of this URL part?
it seems like I'm including the 'scheme' and 'authority' part of the URL as PATH1.

Body:
You have two different mechanisms in Java to accomplish this:

java.text.MessageFormat

    String url = MessageFormat.format("http://somesite.com/post/member/{0}/verify/etc","1234567");
    System.out.println(url);

java.util.Formatter:

    Formatter  f = new Formatter(new StringBuilder());
    f.format("http://somesite.com/post/member/%s/verify/etc", "1234546");
    System.out.println(f.toString());


问:
How to convert class to it's child in Python?
I have a class called class_A I do some work with it and store it with pickle.
I have another class class_B which is a child of class_A but has some additional methods and properties. I want to load data from my pickled file as class_B and work with it. How can I do it?

答:
You could override the unpickler's find_class function, like so:

```<code>import pickle

# Set up class_A and class_B as in the question
class class_A:
    def __init__(self):
        self.a = 1
    def method_a(self): pass
class class_B(class_A):
    def __init__(self):
        super().__init__()
        self.b = 1
    def method_b(self): pass

# Create an pickle a class_A object
a = class_A()
with open('pickle', 'wb') as f:
    pickle.dump(a, f)

# Create an unpickler that lies about class types
class MyUnpickler(pickle.Unpickler):
    def find_class(self, module, name):
        if (module, name) == ('__main__', 'class_A'):
            name = 'class_B'
        return pickle.Unpickler.find_class(self, module, name)

# Unpickle with the transmorgifying unpickler
with open('pickle', 'rb') as f:
    new_b = MyUnpickler(f).load()

# Verify that the returned object is a `class_B`
assert isinstance(new_b, class_B)
assert hasattr(new_b, 'method_a')
assert hasattr(new_b, 'method_b')
assert hasattr(new_b, 'a')

# Sadly, new_b.__init__ never ran, so no `new_b.b`
assert not hasattr(new_b, 'b')
</code>```

Reference: https://docs.python.org/3/library/pickle.html#pickle.Unpickler.find_class

ContentLicense: CC BY-SA 4.0

Body:
You could override the unpickler's find_class function, like so:

import pickle

# Set up class_A and class_B as in the question
class class_A:
    def __init__(self):
        self.a = 1
    def method_a(self): pass
class class_B(class_A):
    def __init__(self):
        super().__init__()
        self.b = 1
    def method_b(self): pass

# Create an pickle a class_A object
a = class_A()
with open('pickle', 'wb') as f:
    pickle.dump(a, f)

# Create an unpickler that lies about class types
class MyUnpickler(pickle.Unpickler):
    def find_class(self, module, name):
        if (module, name) == ('__main__', 'class_A'):
            name = 'class_B'
        return pickle.Unpickler.find_class(self, module, name)

# Unpickle with the transmorgifying unpickler
with open('pickle', 'rb') as f:
    new_b = MyUnpickler(f).load()

# Verify that the returned object is a `class_B`
assert isinstance(new_b, class_B)
assert hasattr(new_b, 'method_a')
assert hasattr(new_b, 'method_b')
assert hasattr(new_b, 'a')

# Sadly, new_b.__init__ never ran, so no `new_b.b`
assert not hasattr(new_b, 'b')

Reference: https://docs.python.org/3/library/pickle.html#pickle.Unpickler.find_class


问:
C# throws Unhandled exception error
I get Unhandled exception error when I try to execute this code:

```<code>class JsonData
{

    public static async Task RefreshDataAsync()
    {
        Console.WriteLine("Tes2t");
        var uri = new Uri("https://api.myjson.com/bins/****b");
        HttpClient myClient = new HttpClient();

        var response = await myClient.GetAsync(uri);
        if (response.IsSuccessStatusCode)
        {
            var content = await response.Content.ReadAsStringAsync();

            //This line throws the error
            var Items = JsonConvert.DeserializeObject<List<Rootobject>>(content);

            Console.WriteLine(content);
        }
    }
}
</code>```

RootObject:

```<code>public class Rootobject
{
    public int wantedDegree { get; set; }
    public int currentDegree { get; set; }
}
</code>```

My JSON array:

```<code>{
  "wantedDegree": 22,
  "currentDegree": 20
}
</code>```

I also used a JSON to C# converter as suggested but it gave me the same RootObject.

Error:

```<code>Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Smart_Thermometer.Rootobject]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
12-08 01:10:02.660 I/mono-stdout(11816):
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'wantedDegree', line 1, position 16.
</code>```

答:
As others have said in the comments, your JSON doesn't match up with the type you're trying to deserialize it to.

If your JSON is right, then you want to deserialize it to a single object:

var item = JsonConvert.DeserialiseObject<Rootobject>(content);
```

<p>Otherwise, if you're expecting a sequence of these, then your JSON should be something like:</p>

```[{
  "wantedDegree": 22,
  "currentDegree": 20
}, {
  "wantedDegree": 100,
  "currentDegree": 90
}, {
  "wantedDegree": 5,
  "currentDegree": 3
}]
```

Title: C# throws Unhandled exception error

Body:
I get Unhandled exception error when I try to execute this code:

class JsonData
{

    public static async Task RefreshDataAsync()
    {
        Console.WriteLine("Tes2t");
        var uri = new Uri("https://api.myjson.com/bins/****b");
        HttpClient myClient = new HttpClient();

        var response = await myClient.GetAsync(uri);
        if (response.IsSuccessStatusCode)
        {
            var content = await response.Content.ReadAsStringAsync();

            //This line throws the error
            var Items = JsonConvert.DeserializeObject<List<Rootobject>>(content);

            Console.WriteLine(content);
        }
    }
}

RootObject:

public class Rootobject
{
    public int wantedDegree { get; set; }
    public int currentDegree { get; set; }
}

My JSON array:

{
  "wantedDegree": 22,
  "currentDegree": 20
}

I also used a JSON to C# converter as suggested but it gave me the same RootObject.

Error:

Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Smart_Thermometer.Rootobject]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
12-08 01:10:02.660 I/mono-stdout(11816):
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'wantedDegree', line 1, position 16.

Body:
As others have said in the comments, your JSON doesn't match up with the type you're trying to deserialize it to.

If your JSON is right, then you want to deserialize it to a single object:

var item = JsonConvert.DeserialiseObject<Rootobject>(content);

Otherwise, if you're expecting a sequence of these, then your JSON should be something like:

[{
  "wantedDegree": 22,
  "currentDegree": 20
}, {
  "wantedDegree": 100,
  "currentDegree": 90
}, {
  "wantedDegree": 5,
  "currentDegree": 3
}]


问:
OnClick change tablerow background color
So I'm trying to find an easy way to get the background color or a table row to change when its clicked on. I've been trying to find a way to call what the background color is and check it but I haven't found a way to call the color. Here is what I have right now. </p>

```<code>    RowName = (TableRow) findViewById(R.id.RowName);
    RowName.setBackgroundColor(Color.TRANSPARENT);

    RowName.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            if (RowName.equals(Color.TRANSPARENT))
            RowName.setBackgroundColor(Color.YELLOW);

            else if (RowName.equals(Color.YELLOW))
            RowName.setBackgroundColor(Color.TRANSPARENT);
        }
    });
</code>```

<p>I know that its wrong. Hopefully you can see what I'm trying to accomplish. If not, what I want to do is have the table row start of transparent. When someone clicks on the table row I want it to change to yellow. Then, if they click it again, I want it to change back to transparent. Thanks. </p>

答:
So here is what wound up working. Make sure you have your TableRows named. Before my on create I have

private TableRow RowName;

I also have

int state = 0;

. I then add the code

```<code>public void RowName(View view) {
  switch (state) {
  case 0:
      RowName.setBackgroundColor(Color.YELLOW);
      state = 1;
      break;
  case 1:
      RowName.setBackgroundColor(Color.TRANSPARENT);
      state = 0;
      break;
  }
}
</code>```

To get it to work, go into your xml and in the OnClick property add RowName or the name of the public void that you are working with.
Enjoy.

Body:
So I'm trying to find an easy way to get the background color or a table row to change when its clicked on. I've been trying to find a way to call what the background color is and check it but I haven't found a way to call the color. Here is what I have right now.

    RowName = (TableRow) findViewById(R.id.RowName);
    RowName.setBackgroundColor(Color.TRANSPARENT);

    RowName.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            if (RowName.equals(Color.TRANSPARENT))
            RowName.setBackgroundColor(Color.YELLOW);

            else if (RowName.equals(Color.YELLOW))
            RowName.setBackgroundColor(Color.TRANSPARENT);
        }
    });

I know that its wrong. Hopefully you can see what I'm trying to accomplish. If not, what I want to do is have the table row start of transparent. When someone clicks on the table row I want it to change to yellow. Then, if they click it again, I want it to change back to transparent. Thanks.

Body:
So here is what wound up working. Make sure you have your TableRows named. Before my on create I have

private TableRow RowName;

I also have

int state = 0;

. I then add the code

public void RowName(View view) {
  switch (state) {
  case 0:
      RowName.setBackgroundColor(Color.YELLOW);
      state = 1;
      break;
  case 1:
      RowName.setBackgroundColor(Color.TRANSPARENT);
      state = 0;
      break;
  }
}

To get it to work, go into your xml and in the OnClick property add RowName or the name of the public void that you are working with.
Enjoy.


问:
How to join summary statistics as new variables for each statistics back to original dataframe
need help to create a function so that this function can produce summary statistics joined back to the original but named after the column (with a prefix (i.e. cyl_event_pct, cyl_distn_events for each variable with values to the corresponding variable in the data frame. The function will require input parameters both the dataframe, and the independent variable. in the example below, the independent variable will be mtcars$am

```<code>df <- mtcars %>%
  select(cyl,gear,vs,am)

df %>%
  gather(variable,value, -ncol(df)) %>%
  group_by(variable, value) %>%
  summarise (n = n(),
             n_events = sum(am),
             event_pct = round(mean(am),4)
  ) %>%
  mutate(distn_events = round(n_events/sum(n_events),4))
</code>```

Would like to add event_pct and distn_events as new variable to original df.

```<code>   # A tibble: 8 x 6
# Groups:   variable [3]
  variable value     n n_events event_pct distn_events
     <chr> <dbl> <int>    <dbl>     <dbl>        <dbl>
1      cyl     4    11        8    0.7273       0.6154
2      cyl     6     7        3    0.4286       0.2308
3      cyl     8    14        2    0.1429       0.1538
4     gear     3    15        0    0.0000       0.0000
5     gear     4    12        8    0.6667       0.6154
6     gear     5     5        5    1.0000       0.3846
7       vs     0    18        6    0.3333       0.4615
8       vs     1    14        7    0.5000       0.5385
</code>```

hope to see a dataframe after with additional columns added as cyl_event_pct, cyl_distn_events, gear_event_pct, gear_distn_events to the below table with values to the corresponding variable in the data frame(excluding the independent variable of am)

```<code>df
                    cyl gear vs am
Mazda RX4             6    4  0  1
Mazda RX4 Wag         6    4  0  1
Datsun 710            4    4  1  1
Hornet 4 Drive        6    3  1  0
Hornet Sportabout     8    3  0  0
Valiant               6    3  1  0
Duster 360            8    3  0  0
Merc 240D             4    4  1  0
Merc 230              4    4  1  0
Merc 280              6    4  1  0
Merc 280C             6    4  1  0
</code>```

Thank you in advanced you masters of the universe!
JT

答:
This is my attempt to writing a function using Prem's solution. If there is a more elegant way of doing this, please let me know.

```<code>library(dplyr)
library(tidyr)

cols <- c("cyl", "gear", "vs")
y <- 'am'

gen_stat_df <- function(df, char_col, y){

  my_df <- df %>%
    select(char_col,y)

  excl_y_cols <- setdiff(char_col,y)

  #create summary statistics
  df_stat <- my_df %>%
    gather(variable,value, excl_y_cols) %>%
    group_by(variable, value) %>%
    summarise (n = n(),
               n_events = sum(!! rlang::sym(y)),
               event_pct = round(mean(!! rlang::sym(y)),4)
    ) %>%
    mutate(distn_events = round(n_events/sum(n_events),4)) %>% data.frame()

  df[paste0(char_col,"_distn_events")] <- lapply(char_col, function(x) df_stat[df_stat$variable==x,"distn_events"][match(df[[x]], df_stat[df_stat$variable==x,"value"])])

  return(df)

}
gen_stat_df(mtcars,cols,y)
</code>```

and the output

```<code>> gen_stat_df(mtcars,cols,y)
                     mpg cyl  disp  hp drat    wt  qsec vs am gear carb cyl_distn_events gear_distn_events
Mazda RX4           21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4           0.2308            0.6154
Mazda RX4 Wag       21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4           0.2308            0.6154
Datsun 710          22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1           0.6154            0.6154
Hornet 4 Drive      21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1           0.2308            0.0000
Hornet Sportabout   18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2           0.1538            0.0000
Valiant             18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1           0.2308            0.0000
Duster 360          14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4           0.1538            0.0000
Merc 240D           24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2           0.6154            0.6154
Merc 230            22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2           0.6154            0.6154
Merc 280            19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4           0.2308            0.6154
Merc 280C           17.8   6 167.6 123 3.92 3.440 18.90  1  0    4    4           0.2308            0.6154
Merc 450SE          16.4   8 275.8 180 3.07 4.070 17.40  0  0    3    3           0.1538            0.0000
Merc 450SL          17.3   8 275.8 180 3.07 3.730 17.60  0  0    3    3           0.1538            0.0000
</code>```

Body:
need help to create a function so that this function can produce summary statistics joined back to the original but named after the column (with a prefix (i.e. cyl_event_pct, cyl_distn_events for each variable with values to the corresponding variable in the data frame. The function will require input parameters both the dataframe, and the independent variable. in the example below, the independent variable will be mtcars$am

df <- mtcars %>%
  select(cyl,gear,vs,am)

df %>%
  gather(variable,value, -ncol(df)) %>%
  group_by(variable, value) %>%
  summarise (n = n(),
             n_events = sum(am),
             event_pct = round(mean(am),4)
  ) %>%
  mutate(distn_events = round(n_events/sum(n_events),4))

Would like to add event_pct and distn_events as new variable to original df.

   # A tibble: 8 x 6
# Groups:   variable [3]
  variable value     n n_events event_pct distn_events
     <chr> <dbl> <int>    <dbl>     <dbl>        <dbl>
1      cyl     4    11        8    0.7273       0.6154
2      cyl     6     7        3    0.4286       0.2308
3      cyl     8    14        2    0.1429       0.1538
4     gear     3    15        0    0.0000       0.0000
5     gear     4    12        8    0.6667       0.6154
6     gear     5     5        5    1.0000       0.3846
7       vs     0    18        6    0.3333       0.4615
8       vs     1    14        7    0.5000       0.5385

hope to see a dataframe after with additional columns added as cyl_event_pct, cyl_distn_events, gear_event_pct, gear_distn_events to the below table with values to the corresponding variable in the data frame(excluding the independent variable of am)

df
                    cyl gear vs am
Mazda RX4             6    4  0  1
Mazda RX4 Wag         6    4  0  1
Datsun 710            4    4  1  1
Hornet 4 Drive        6    3  1  0
Hornet Sportabout     8    3  0  0
Valiant               6    3  1  0
Duster 360            8    3  0  0
Merc 240D             4    4  1  0
Merc 230              4    4  1  0
Merc 280              6    4  1  0
Merc 280C             6    4  1  0

Thank you in advanced you masters of the universe!
JT

Body:
This is my attempt to writing a function using Prem's solution. If there is a more elegant way of doing this, please let me know.

library(dplyr)
library(tidyr)

cols <- c("cyl", "gear", "vs")
y <- 'am'

gen_stat_df <- function(df, char_col, y){

  my_df <- df %>%
    select(char_col,y)

  excl_y_cols <- setdiff(char_col,y)

  #create summary statistics
  df_stat <- my_df %>%
    gather(variable,value, excl_y_cols) %>%
    group_by(variable, value) %>%
    summarise (n = n(),
               n_events = sum(!! rlang::sym(y)),
               event_pct = round(mean(!! rlang::sym(y)),4)
    ) %>%
    mutate(distn_events = round(n_events/sum(n_events),4)) %>% data.frame()

  df[paste0(char_col,"_distn_events")] <- lapply(char_col, function(x) df_stat[df_stat$variable==x,"distn_events"][match(df[[x]], df_stat[df_stat$variable==x,"value"])])

  return(df)

}
gen_stat_df(mtcars,cols,y)

and the output

> gen_stat_df(mtcars,cols,y)
                     mpg cyl  disp  hp drat    wt  qsec vs am gear carb cyl_distn_events gear_distn_events
Mazda RX4           21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4           0.2308            0.6154
Mazda RX4 Wag       21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4           0.2308            0.6154
Datsun 710          22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1           0.6154            0.6154
Hornet 4 Drive      21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1           0.2308            0.0000
Hornet Sportabout   18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2           0.1538            0.0000
Valiant             18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1           0.2308            0.0000
Duster 360          14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4           0.1538            0.0000
Merc 240D           24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2           0.6154            0.6154
Merc 230            22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2           0.6154            0.6154
Merc 280            19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4           0.2308            0.6154
Merc 280C           17.8   6 167.6 123 3.92 3.440 18.90  1  0    4    4           0.2308            0.6154
Merc 450SE          16.4   8 275.8 180 3.07 4.070 17.40  0  0    3    3           0.1538            0.0000
Merc 450SL          17.3   8 275.8 180 3.07 3.730 17.60  0  0    3    3           0.1538            0.0000


问:
basemap & contourf, Python
I have a set of satellite data file here, I created a grid for lat & lon and a 2D array for Ozone values.

I know that in order to plot the contourf of the data in a map I need the projection coordinates, but I can't get find a way around it as my grid is not square (144x24). I am covering the geographical area (0 to 360; -30 to 30) and I require square pixels.

The data is quite long to post it but this is my code so far,

```<code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from mpl_toolkits.basemap import Basemap, cm
%matplotlib inline

path = '/home/rafaella/month_files_CSV/O3_COLUMNS_MATCHED_fv0005_200306.csv'
df = pd.read_csv(path, skiprows=1)

df = pd.read_csv(path, delim_whitespace=True)
lat = np.array(df['AVG_LAT'])
lon = np.array(df['AVG_LON'])
toc = np.array(df['TROP_COL'])

#new grid for lon[0,360] lat[-30,30]

lomin = 0
lomax = 360
lamin = -30
lamax = 30
stp   = 2.5

loc_lon = np.zeros(int((lomax-lomin)/stp))
loc_lat = np.zeros(int((lamax-lamin)/stp))

for i in range(0,len(loc_lon)):
    loc_lon[i] = i*stp +lomin

for j in range(0,len(loc_lat)):
    loc_lat[j] = j*stp +lamin

mtoc_local = np.zeros((len(loc_lon),len(loc_lat)))
sdtoc_local = np.zeros((len(loc_lon),len(loc_lat)))
mtoc_local[:,:] = np.nan
sdtoc_local[:,:] = np.nan

for i in range (0, len(loc_lon)):
    for j in range (0,len(loc_lat)):
        ix = np.where((lon>=loc_lon[i])& (lat>=loc_lat[j]) & (lon<loc_lon[i]+stp) & (lat<loc_lat[j]+stp))[0]
        mtoc_local[i,j]=np.nanmean(toc[ix])
        sdtoc_local[i,j]=np.nanstd(toc[ix])

fig = plt.figure(figsize=(20, 5))
map = Basemap(llcrnrlon=0,llcrnrlat=-30, urcrnrlon=360.,urcrnrlat=30.,\
        rsphere=(6378137.00,6356752.3142),\
        resolution='l',projection='merc',\
        lat_0=0,lon_0=-30.,lat_ts=30.)

map.drawcoastlines()
# draw parallels
map.drawparallels(np.arange(-30,30,10),labels=[1,1,0,1])
# draw meridians
map.drawmeridians(np.arange(-180,180,20),labels=[1,1,0,1])

map = plt.contourf(loc_lon, loc_lat , mtoc_local.T, vmin=210, vmax=350,  cmap='RdPu')
plt.colorbar(orientation='horizontal', ticks=[200, 220, 240, 260, 280, 300, 320, 340] )
plt.title('Tropical TOC monthly mean 06,2009')

plt.show()
</code>```

It plots very well the map OR the data but not both. here an image of both separately
 map

real data

I am very new to python, I started a month ago, so it is still not familiar to me all the functions and libraries.

答:
Your code has two problems. First you have to apply the projection on your coordinates which is done using x,y = map(lon, lat). However, this will raise an error in your case since the dimensions of loc_lon and loc_lat are different. Instead of passing x and y vectors to the contourf function you can pass arrays with the same shape as z (mtoc_local.T). You can use np.meshgrid to create those. Long story short, replace the line with the contourf command with the following three lines

```<code>X, Y = np.meshgrid(loc_lon, loc_lat)
x,y = map(X,Y)
map = plt.contourf(x, y , mtoc_local.T, vmin=210, vmax=350,  cmap='RdPu')
</code>```

and the result looks like this

Title: basemap & contourf, Python

Body:
I have a set of satellite data file here, I created a grid for lat & lon and a 2D array for Ozone values.

I know that in order to plot the contourf of the data in a map I need the projection coordinates, but I can't get find a way around it as my grid is not square (144x24). I am covering the geographical area (0 to 360; -30 to 30) and I require square pixels.

The data is quite long to post it but this is my code so far,

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from mpl_toolkits.basemap import Basemap, cm
%matplotlib inline

path = '/home/rafaella/month_files_CSV/O3_COLUMNS_MATCHED_fv0005_200306.csv'
df = pd.read_csv(path, skiprows=1)

df = pd.read_csv(path, delim_whitespace=True)
lat = np.array(df['AVG_LAT'])
lon = np.array(df['AVG_LON'])
toc = np.array(df['TROP_COL'])

#new grid for lon[0,360] lat[-30,30]

lomin = 0
lomax = 360
lamin = -30
lamax = 30
stp   = 2.5

loc_lon = np.zeros(int((lomax-lomin)/stp))
loc_lat = np.zeros(int((lamax-lamin)/stp))

for i in range(0,len(loc_lon)):
    loc_lon[i] = i*stp +lomin

for j in range(0,len(loc_lat)):
    loc_lat[j] = j*stp +lamin

mtoc_local = np.zeros((len(loc_lon),len(loc_lat)))
sdtoc_local = np.zeros((len(loc_lon),len(loc_lat)))
mtoc_local[:,:] = np.nan
sdtoc_local[:,:] = np.nan

for i in range (0, len(loc_lon)):
    for j in range (0,len(loc_lat)):
        ix = np.where((lon>=loc_lon[i])& (lat>=loc_lat[j]) & (lon<loc_lon[i]+stp) & (lat<loc_lat[j]+stp))[0]
        mtoc_local[i,j]=np.nanmean(toc[ix])
        sdtoc_local[i,j]=np.nanstd(toc[ix])

fig = plt.figure(figsize=(20, 5))
map = Basemap(llcrnrlon=0,llcrnrlat=-30, urcrnrlon=360.,urcrnrlat=30.,\
        rsphere=(6378137.00,6356752.3142),\
        resolution='l',projection='merc',\
        lat_0=0,lon_0=-30.,lat_ts=30.)

map.drawcoastlines()
# draw parallels
map.drawparallels(np.arange(-30,30,10),labels=[1,1,0,1])
# draw meridians
map.drawmeridians(np.arange(-180,180,20),labels=[1,1,0,1])

map = plt.contourf(loc_lon, loc_lat , mtoc_local.T, vmin=210, vmax=350,  cmap='RdPu')
plt.colorbar(orientation='horizontal', ticks=[200, 220, 240, 260, 280, 300, 320, 340] )
plt.title('Tropical TOC monthly mean 06,2009')

plt.show()

It plots very well the map OR the data but not both. here an image of both separately
 map

real data

I am very new to python, I started a month ago, so it is still not familiar to me all the functions and libraries.

Body:
Your code has two problems. First you have to apply the projection on your coordinates which is done using x,y = map(lon, lat). However, this will raise an error in your case since the dimensions of loc_lon and loc_lat are different. Instead of passing x and y vectors to the contourf function you can pass arrays with the same shape as z (mtoc_local.T). You can use np.meshgrid to create those. Long story short, replace the line with the contourf command with the following three lines

X, Y = np.meshgrid(loc_lon, loc_lat)
x,y = map(X,Y)
map = plt.contourf(x, y , mtoc_local.T, vmin=210, vmax=350,  cmap='RdPu')

and the result looks like this


问:
Bug while checking for symbols inside of a string?
I'm creating a small calculator script and I've got stumbled on a strange bug. Everything seems to work but not when I input anything starting with (. When I do that if gives false and the code inside of else executes. I've tried a lot of ways rewriting how should "$input" =~ [-,+,*,/,\(,\)] look like but nothing worked. Do you have any idea why that's happening and how to solve this bug?

```<code>#!/bin/bash
read -p "Input: " input
if [[ ! "$input" =~ ^[A-Za-z_]+$ && "$input" =~ ^[0-9] && "$input" =~ [-,+,*,/,\(,\)] ]]; then
 (echo $input = $(($input))) 2>- || echo "Please, do not input ..."
else
 echo "Please, do not input letters or other special symbols and type in only expressions."
fi
</code>```

答:
If you need to make sure your input consists of just certain characters, use this much simpler regex:</p>

```<code>#!/bin/bash

read -r -p "Input: " input

if [[ $input =~ ^[0-9+*/()-]*$ ]]; then
   (echo "$input = $((input))") 2> /dev/null || echo "Please, do not input ..."
else
   echo "Please, do not input letters or other special symbols and type in only expressions."
fi
</code>```

Body:
I'm creating a small calculator script and I've got stumbled on a strange bug. Everything seems to work but not when I input anything starting with (. When I do that if gives false and the code inside of else executes. I've tried a lot of ways rewriting how should "$input" =~ [-,+,*,/,\(,\)] look like but nothing worked. Do you have any idea why that's happening and how to solve this bug?

#!/bin/bash
read -p "Input: " input
if [[ ! "$input" =~ ^[A-Za-z_]+$ && "$input" =~ ^[0-9] && "$input" =~ [-,+,*,/,\(,\)] ]]; then
 (echo $input = $(($input))) 2>- || echo "Please, do not input ..."
else
 echo "Please, do not input letters or other special symbols and type in only expressions."
fi

Body:
If you need to make sure your input consists of just certain characters, use this much simpler regex:

#!/bin/bash

read -r -p "Input: " input

if [[ $input =~ ^[0-9+*/()-]*$ ]]; then
   (echo "$input = $((input))") 2> /dev/null || echo "Please, do not input ..."
else
   echo "Please, do not input letters or other special symbols and type in only expressions."
fi


问:
Git for windows seems to automatically fall back to credential helper "manager" if everything else fails. How do I prevent this?
I'm trying to integrate a custom web page with git. In my PHP scripts, I use the option "-c credential.helper="store --file=..." so that the web page does not stop and wait for a password to be input. The User ID is specifically designated for automated tasks like this. As part of the web interface, I have some code that will update the credentials file when the password expires.

During development, when I issue the git commands at the windows command prompt (the "terminal" for you *NIX readers :) they all work fine. However, when I put the commands inside my PHP script and run it via the web server, they fail. I've managed to capture the output of the git task, and it's waiting for someone to type in a user ID.

It seems that git on windows will automatically drop back to the "manager" helper, if all other mechanisms fail. The following sequence of commands illustrates this:

```<code>C:\TFS\Train>git config --get --show-origin credential.helper

C:\TFS\Train>type .git\.git_web_credentials
http://Promote5:[.....]@tocgnxt1pv%3a8080

C:\TFS\Train>git -c credential.helper="store --file=C:\TFS\Train\.git\.git_credentials" tag -a -m "Testing tags from the command line" Who_created_this_tag2

C:\TFS\Train>git show Who_created_this_tag2
tag Who_created_this_tag2
Tagger: JimHyslop <jim.hyslop@xxx.xxx>
Date:   Wed Dec 6 18:13:27 2017 -0500

[... remainder of output elided ...]

C:\TFS\Train>git --version
git version 2.13.0.windows.1
</code>```

As you can see, the "tagger" line indicates that I'm the one who applied the tag.

I've even tried deleting the credentials file completely, but it still falls back to using my identity.

Is there any way to suppress this automatic fall back to using my Windows credentials? It's making it very difficult to debug my PHP script: I never know from the command prompt whether the command succeeded because it was able to use the credentials file, or because it fell back to using my own ID (which the web service cannot do).

Edit to add: The password is actually in the credentials file, I masked it out. The file was initially created by entering the ID and password from a Cygwin shell, which is running a slightly newer version of git: 2.15.0. I'm running a WAMP stack for my web service.

答: For the record, the solution I came up with was to write a custom credential manager, as outlined at git-scm.com</p>

Body:
I'm trying to integrate a custom web page with git. In my PHP scripts, I use the option "-c credential.helper="store --file=..." so that the web page does not stop and wait for a password to be input. The User ID is specifically designated for automated tasks like this. As part of the web interface, I have some code that will update the credentials file when the password expires.

During development, when I issue the git commands at the windows command prompt (the "terminal" for you *NIX readers :) they all work fine. However, when I put the commands inside my PHP script and run it via the web server, they fail. I've managed to capture the output of the git task, and it's waiting for someone to type in a user ID.

It seems that git on windows will automatically drop back to the "manager" helper, if all other mechanisms fail. The following sequence of commands illustrates this:

C:\TFS\Train>git config --get --show-origin credential.helper

C:\TFS\Train>type .git\.git_web_credentials
http://Promote5:[.....]@tocgnxt1pv%3a8080

C:\TFS\Train>git -c credential.helper="store --file=C:\TFS\Train\.git\.git_credentials" tag -a -m "Testing tags from the command line" Who_created_this_tag2

C:\TFS\Train>git show Who_created_this_tag2
tag Who_created_this_tag2
Tagger: JimHyslop <jim.hyslop@xxx.xxx>
Date:   Wed Dec 6 18:13:27 2017 -0500

[... remainder of output elided ...]

C:\TFS\Train>git --version
git version 2.13.0.windows.1

As you can see, the "tagger" line indicates that I'm the one who applied the tag.

I've even tried deleting the credentials file completely, but it still falls back to using my identity.

Is there any way to suppress this automatic fall back to using my Windows credentials? It's making it very difficult to debug my PHP script: I never know from the command prompt whether the command succeeded because it was able to use the credentials file, or because it fell back to using my own ID (which the web service cannot do).

Edit to add: The password is actually in the credentials file, I masked it out. The file was initially created by entering the ID and password from a Cygwin shell, which is running a slightly newer version of git: 2.15.0. I'm running a WAMP stack for my web service.


答:
Per the exception message:

To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type

If you want to deserialize an array, you have to provide an array, which would look like this:

```<code>[
  {
    "wantedDegree": 22,
    "currentDegree": 20
  }
]
</code>```

Or change the generic type argument to a simple .NET type and not a collection:

```<code>var Items = JsonConvert.DeserializeObject<Rootobject>(content);
</code>```

Title: C# throws Unhandled exception error

Body:
Per the exception message:

To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type

If you want to deserialize an array, you have to provide an array, which would look like this:

[
  {
    "wantedDegree": 22,
    "currentDegree": 20
  }
]

Or change the generic type argument to a simple .NET type and not a collection:

var Items = JsonConvert.DeserializeObject<Rootobject>(content);


问:
gradle: find to which project does a file belong
Let's consider this sample multi gradle project structure

```<code>build.gradle
|-- project-a
|   |-- build.gradle
|   +-- project-a-b
|       |--  src
|       |    |
|       |    +-- test.java
|       |
|       +-- build.gradle
+-- project-c
    |-- build.gradle
    +-- src
        +-- test2.java
</code>```

And let's say from git changelog I have changed files:

```<code>project-a/project-a-b/src/test.java
project-c/src/test2.java
</code>```

I need to find out to which project they belong

```<code>project-a/project-a-b/src/test.java -> project-a-b
project-c/src/test2.java -> project-c
</code>```

Is there something that gradle offers out of the box (e.g. give filename, get nearest project)? Googling did not help, but maybe the question was wrong.

I know I could just put filesystem in a tree structure and traverse it

答:
The following defines a findFile task for each project (using sourceSets), consolidated in the root build.gradle (full example here).

```<code>subprojects { project ->
    apply plugin: 'java'

    task findFile() {
        doLast {
            def targetFile = project.targetFile
            project.sourceSets.main.java.each { file ->
                if (file.absolutePath.contains(targetFile)) {
                    println "TRACER found ${targetFile} in project: ${project.name}"
                }
            }
        }
    }
}
</code>```

It currently only searches for one file, but that could easily be adopted for more. Example usage:

```<code>gradle findFile -PtargetFile=project-a/project-a-b/src/main/java/TestAB.java

TRACER found project-a/project-a-b/src/main/java/TestAB.java in project: project-a-b
</code>```

Body:
Let's consider this sample multi gradle project structure

build.gradle
|-- project-a
|   |-- build.gradle
|   +-- project-a-b
|       |--  src
|       |    |
|       |    +-- test.java
|       |
|       +-- build.gradle
+-- project-c
    |-- build.gradle
    +-- src
        +-- test2.java

And let's say from git changelog I have changed files:

project-a/project-a-b/src/test.java
project-c/src/test2.java

I need to find out to which project they belong

project-a/project-a-b/src/test.java -> project-a-b
project-c/src/test2.java -> project-c

Is there something that gradle offers out of the box (e.g. give filename, get nearest project)? Googling did not help, but maybe the question was wrong.

I know I could just put filesystem in a tree structure and traverse it

Body:
The following defines a findFile task for each project (using sourceSets), consolidated in the root build.gradle (full example here).

subprojects { project ->
    apply plugin: 'java'

    task findFile() {
        doLast {
            def targetFile = project.targetFile
            project.sourceSets.main.java.each { file ->
                if (file.absolutePath.contains(targetFile)) {
                    println "TRACER found ${targetFile} in project: ${project.name}"
                }
            }
        }
    }
}

It currently only searches for one file, but that could easily be adopted for more. Example usage:

gradle findFile -PtargetFile=project-a/project-a-b/src/main/java/TestAB.java

TRACER found project-a/project-a-b/src/main/java/TestAB.java in project: project-a-b


问:
Why does i += a[i]++ assign i before incrementing a[i] with Visual C++?
Problem

This example is a minimal reproduction of this issue encountered a code golf attempt. I am not advocating anyone use this style.

I am aware I may have hit undefined behaviour, my question is: why specifically, and does this go for C as well as C++?

I have this file:

```<code>#include <stdio.h>
int main() {
    int a[]={1, 0}, i=0;
    i += a[i]++;
    printf("i=%d a=[%d, %d]\n", i, a[0], a[1]);
    return 0;
}
</code>```

With GCC on Ubuntu on WSL I get the expected i=1 a=[2, 0] but with Visual C++ it is i=1 a=[1, 1]

The problem is fixed if I do this:

```<code>delta = a[i]++;
i += delta;
</code>```

Whilst order of evaluation of assignment is unspecified, I am surprised that it appears that a[i] is evaluated again for the increment, after the assignment of i. The disassembly below seems to confirm this.

Do either the C or C++ standards allow this?

Background

Build command line and output on Windows:

```<code>>cl test.c
Microsoft (R) C/C++ Optimizing Compiler Version 19.12.25830.2 for x64
Copyright (C) Microsoft Corporation.  All rights reserved.

test.c
Microsoft (R) Incremental Linker Version 14.12.25830.2
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:test.exe
test.obj
</code>```

Dissasembly of the statement (built with /Zi):

```<code>     4:     i += a[i]++;
00007FF6CBBA626C  movsxd      rax,dword ptr [i]
00007FF6CBBA6271  mov         eax,dword ptr a[rax*4]
00007FF6CBBA6275  mov         ecx,dword ptr [i]
00007FF6CBBA6279  add         ecx,eax
00007FF6CBBA627B  mov         eax,ecx
00007FF6CBBA627D  mov         dword ptr [i],eax
00007FF6CBBA6281  movsxd      rax,dword ptr [i]
00007FF6CBBA6286  mov         eax,dword ptr a[rax*4]
00007FF6CBBA628A  inc         eax
00007FF6CBBA628C  movsxd      rcx,dword ptr [i]
00007FF6CBBA6291  mov         dword ptr a[rcx*4],eax
</code>```

答:
The code is well-defined in all versions of C and C++. You are seeing a bug in MSVC.

The definition of the += operator is that x += y means x = x + y, except that x is only evaluated once.  (Note that "evaluate" is different to "lvalue conversion").

So we are looking at i = i + a[i]++.

Informally: the new value to store in i cannot be computed until both operands of + have been evaluated, and had lvalue conversion performed. Because we need the result of that lvalue conversion in order to know the value to store.

The term "evaluate" for an lvalue means to determine the memory location which the lvalue refers to. Evaluating a[i]++ when i is 0 beforehand means to determine that we are referring to a[0]. Then lvalue conversion retrieves the stored value of a[0], and the unsequenced side-effect is that the stored value of a[0] will be updated sooner or later.

Writing to a[0] has nothing to do with i, so there is no reason to believe there might be undefined behaviour.

More formally: prior to 2011, the C and C++ standards used a somewhat confusing sentence that expressed the logic in my "Informally:" paragraph. If the expression reads and writes i then it is well-defined only if the reads of i are all necessary to determine the new value to store in i, because that will guarantee that the reads have all happened before it is possible to store the new value.

In C11 and C++11 the language changed but not the implication. C11 6.5.16/3 (Assignment operators) says:

The side effect of updating the stored value of the left operand is
  sequenced after the value computations of the left and right operands.

which leaves no doubt that the write to i is sequenced after all reads of i on the right-hand side.

C++11 has similar language:

In all cases, the assignment is sequenced after the value computation of the right and left operands,

Body:
Problem

This example is a minimal reproduction of this issue encountered a code golf attempt. I am not advocating anyone use this style.

I am aware I may have hit undefined behaviour, my question is: why specifically, and does this go for C as well as C++?

I have this file:

#include <stdio.h>
int main() {
    int a[]={1, 0}, i=0;
    i += a[i]++;
    printf("i=%d a=[%d, %d]\n", i, a[0], a[1]);
    return 0;
}

With GCC on Ubuntu on WSL I get the expected i=1 a=[2, 0] but with Visual C++ it is i=1 a=[1, 1]

The problem is fixed if I do this:

delta = a[i]++;
i += delta;

Whilst order of evaluation of assignment is unspecified, I am surprised that it appears that a[i] is evaluated again for the increment, after the assignment of i. The disassembly below seems to confirm this.

Do either the C or C++ standards allow this?

Background

Build command line and output on Windows:

>cl test.c
Microsoft (R) C/C++ Optimizing Compiler Version 19.12.25830.2 for x64
Copyright (C) Microsoft Corporation.  All rights reserved.

test.c
Microsoft (R) Incremental Linker Version 14.12.25830.2
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:test.exe
test.obj

Dissasembly of the statement (built with /Zi):

     4:     i += a[i]++;
00007FF6CBBA626C  movsxd      rax,dword ptr [i]
00007FF6CBBA6271  mov         eax,dword ptr a[rax*4]
00007FF6CBBA6275  mov         ecx,dword ptr [i]
00007FF6CBBA6279  add         ecx,eax
00007FF6CBBA627B  mov         eax,ecx
00007FF6CBBA627D  mov         dword ptr [i],eax
00007FF6CBBA6281  movsxd      rax,dword ptr [i]
00007FF6CBBA6286  mov         eax,dword ptr a[rax*4]
00007FF6CBBA628A  inc         eax
00007FF6CBBA628C  movsxd      rcx,dword ptr [i]
00007FF6CBBA6291  mov         dword ptr a[rcx*4],eax


问:
Can I use BufferedReader and create an array inside actionListener class?
I've created an actionListener class. in the actionPerformed method, i would like run a code. This code involves importing data from multiple text files, and store them in a 2D array. Then it will print out a list of quotes in the frame. Then it will print out the 5 analysis and let the user choose which one. However, i am currently stuck with the IOException. Plus, some code states gives an error "unreachable code." What does that means? Below is the code for my actionListener class

```<code>import java.awt.event.*;
import java.io.*;
import java.util.*;

public class CrucibleButtonListener implements ActionListener
{
  private Swing g;

public CrucibleButtonListener (Swing g)
{
   this.g = g;
}

public void actionPerformed(ActionEvent e)
{
   this.g.updateTextField(getQuotes());
}

private String getQuotes() throws IOException
{
   BufferedReader inputQuote;
   BufferedReader inputTheme;
   BufferedReader inputCharacterAnalysis;
   BufferedReader inputSignificance;
   BufferedReader inputPlotEnhancement;
   BufferedReader inputSpeaker;

   Scanner in = new Scanner (System.in);
   int howMany=0;
   int quoteSelection;
   int analysisSelection;

   // Count how many lines in the text file
   FileReader fr = new FileReader ("CrucibleQuotations.txt");
   LineNumberReader ln = new LineNumberReader (fr);
   while (ln.readLine() != null)
   {
     howMany++;
   }

  //import information from the text file
  inputQuote = new BufferedReader (new FileReader ("CrucibleQuotations.txt"));
  inputTheme = new BufferedReader (new FileReader("CrucibleTheme.txt"));
  inputCharacterAnalysis = new BufferedReader (new FileReader("CrucibleCharacterAnalysis.txt"));
  inputSignificance = new BufferedReader (new FileReader("CrucibleSignificance.txt"));
  inputPlotEnhancement = new BufferedReader (new FileReader("CruciblePlotEnhancement.txt"));
  inputSpeaker = new BufferedReader (new FileReader("CrucibleSpeaker.txt"));

//Create array based on how many quotes available in the text file
String [][] quotes = new String [howMany][6];

//Store quote information in the array and display the list of quotations
for (int i=0; i<howMany; i++)
{
  quotes [i][0] = inputQuote.readLine();
  return (i+1 + ") " + quotes [i][0]);
  quotes [i][1] = inputTheme.readLine();
  quotes [i][2] = inputCharacterAnalysis.readLine();
  quotes [i][3] = inputSignificance.readLine();
  quotes [i][4] = inputPlotEnhancement.readLine();
  quotes [i][5] = inputSpeaker.readLine();
}

//Ask user to choose the quote they want to analyze
return ("Choose a quotation by inputting the number: ");
quoteSelection = in.nextInt ();

if (quoteSelection!=0)
{
  //Show user selections to analyze
  return ("1. Theme");
  return ("2. Character Analysis");
  return ("3. Significance");
  return ("4. Plot Enhancement");
  return ("5. Speaker");
  analysisSelection = in.nextInt ();

  //Display the analysis
  if (analysisSelection <= 5 || analysisSelection > 0)
  {
    return (quotes [quoteSelection-1][analysisSelection]);
  }
}
}
}
</code>```

Here is the swing class. It only contains a button, which i can't seem to make it work.

```<code>import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.util.*;

public class Swing
{
  private JLabel label;
  public Swing()
  {
    JFrame frame = new JFrame ("FRAME SAMPLE");
    frame.setSize(500, 500);
    frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

    JButton cButton = new JButton("The Crucible");//The JButton name.
    frame.add(cButton);//Add the button to the JFrame.
    cButton.addActionListener(new CrucibleButtonListener(this));
  }
}
</code>```

Main Class:

```<code>public class Main
{
  public static void main (String [] args)
  {
    new Swing();
  }
}
</code>```

答:
You are trying to directly convert a simplistic linear console program that is not based on objects or classes into an event-driven Swing GUI application, and to be blunt, this will never work; the logic of one cannot be shoehorned into the logic of the other. Your first task will be to change your code into a true OOPs program with one or more classes, and to separate all user interaction code from program logic code.  Once you've done that, you will much more easily be able to use your code in a GUI program.

addendum: calling getQuotes in try/catch block

```<code>  try {
     String quotes = getQuotes();
     g.updateTextField(quotes);
  } catch (IOException e1) {
     e1.printStackTrace();
     // or perhaps better would be to display a JOptionPane telling the user about the error.
  }
</code>```

Body:
I've created an actionListener class. in the actionPerformed method, i would like run a code. This code involves importing data from multiple text files, and store them in a 2D array. Then it will print out a list of quotes in the frame. Then it will print out the 5 analysis and let the user choose which one. However, i am currently stuck with the IOException. Plus, some code states gives an error "unreachable code." What does that means? Below is the code for my actionListener class

import java.awt.event.*;
import java.io.*;
import java.util.*;

public class CrucibleButtonListener implements ActionListener
{
  private Swing g;

public CrucibleButtonListener (Swing g)
{
   this.g = g;
}

public void actionPerformed(ActionEvent e)
{
   this.g.updateTextField(getQuotes());
}

private String getQuotes() throws IOException
{
   BufferedReader inputQuote;
   BufferedReader inputTheme;
   BufferedReader inputCharacterAnalysis;
   BufferedReader inputSignificance;
   BufferedReader inputPlotEnhancement;
   BufferedReader inputSpeaker;

   Scanner in = new Scanner (System.in);
   int howMany=0;
   int quoteSelection;
   int analysisSelection;

   // Count how many lines in the text file
   FileReader fr = new FileReader ("CrucibleQuotations.txt");
   LineNumberReader ln = new LineNumberReader (fr);
   while (ln.readLine() != null)
   {
     howMany++;
   }

  //import information from the text file
  inputQuote = new BufferedReader (new FileReader ("CrucibleQuotations.txt"));
  inputTheme = new BufferedReader (new FileReader("CrucibleTheme.txt"));
  inputCharacterAnalysis = new BufferedReader (new FileReader("CrucibleCharacterAnalysis.txt"));
  inputSignificance = new BufferedReader (new FileReader("CrucibleSignificance.txt"));
  inputPlotEnhancement = new BufferedReader (new FileReader("CruciblePlotEnhancement.txt"));
  inputSpeaker = new BufferedReader (new FileReader("CrucibleSpeaker.txt"));

//Create array based on how many quotes available in the text file
String [][] quotes = new String [howMany][6];

//Store quote information in the array and display the list of quotations
for (int i=0; i<howMany; i++)
{
  quotes [i][0] = inputQuote.readLine();
  return (i+1 + ") " + quotes [i][0]);
  quotes [i][1] = inputTheme.readLine();
  quotes [i][2] = inputCharacterAnalysis.readLine();
  quotes [i][3] = inputSignificance.readLine();
  quotes [i][4] = inputPlotEnhancement.readLine();
  quotes [i][5] = inputSpeaker.readLine();
}

//Ask user to choose the quote they want to analyze
return ("Choose a quotation by inputting the number: ");
quoteSelection = in.nextInt ();

if (quoteSelection!=0)
{
  //Show user selections to analyze
  return ("1. Theme");
  return ("2. Character Analysis");
  return ("3. Significance");
  return ("4. Plot Enhancement");
  return ("5. Speaker");
  analysisSelection = in.nextInt ();

  //Display the analysis
  if (analysisSelection <= 5 || analysisSelection > 0)
  {
    return (quotes [quoteSelection-1][analysisSelection]);
  }
}
}
}

Here is the swing class. It only contains a button, which i can't seem to make it work.

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.util.*;

public class Swing
{
  private JLabel label;
  public Swing()
  {
    JFrame frame = new JFrame ("FRAME SAMPLE");
    frame.setSize(500, 500);
    frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

    JButton cButton = new JButton("The Crucible");//The JButton name.
    frame.add(cButton);//Add the button to the JFrame.
    cButton.addActionListener(new CrucibleButtonListener(this));
  }
}

Main Class:

public class Main
{
  public static void main (String [] args)
  {
    new Swing();
  }
}

Body:
You are trying to directly convert a simplistic linear console program that is not based on objects or classes into an event-driven Swing GUI application, and to be blunt, this will never work; the logic of one cannot be shoehorned into the logic of the other. Your first task will be to change your code into a true OOPs program with one or more classes, and to separate all user interaction code from program logic code.  Once you've done that, you will much more easily be able to use your code in a GUI program.

addendum: calling getQuotes in try/catch block

  try {
     String quotes = getQuotes();
     g.updateTextField(quotes);
  } catch (IOException e1) {
     e1.printStackTrace();
     // or perhaps better would be to display a JOptionPane telling the user about the error.
  }


问:
Bind a set of animations to window load in jQuery?
I want to run some lines of code when my page finishes loading in jQuery. I want to specify the timings precisely, and I can't do that right now.

What I want:

```<code>load({
    //Load animations
});
</code>```

How can I do this?

答:
Quite simple, just some syntax:</p>

```<code>$(window).on('load', function() {
    //Load animations
});
</code>```

Body:
I want to run some lines of code when my page finishes loading in jQuery. I want to specify the timings precisely, and I can't do that right now.

What I want:

load({
    //Load animations
});

How can I do this?

Body:
Quite simple, just some syntax:

$(window).on('load', function() {
    //Load animations
});


问:
Adding emojis properly to a game
We are trying to add emojis our game using Emoji One and Unity with TextMeshPro. We have a window opening up which shows all the emojis and then the user can pick the one they want, we have run into problems with deleting them and typing text after them.

Here is the code we have have, the name of the sprite is this: 1f609, however the output when we run the code and add it to the input field is this: \ud83d\ude09

```<code>string name = _image.sprite.name;
int hexNumber = int.Parse(name, System.Globalization.NumberStyles.HexNumber);
string c = char.ConvertFromUtf32(hexNumber);
_inputField.text += c;
</code>```

The expected result is that we should see just a single unicode character (I think) so that we can properly delete emoji's with the backspace key and when you enter an emoji it does not create two characters to be deleted and it does not place the character between the two emoji spots so when we enter text it breaks.

Right now if we delete text it will leave us with empty square and if we add text afterwards through typing in the box it will split the characters in two breaking them.

答: Unicode in C# world means UTF-16, so there are these "surrogate pairs" that you have to deal with now. One solution would be to detect if you just removed one half of a surrogate pair and in that case remove the other half as well. First half of a surrogate pair is always in range [D800h, DBFFh] and second half is always in range [DC00h, DFFFh], so when you remove a char in one of those ranges you know that you should remove one more char, and you also know where that char is (before or after the one just removed).

Title: Adding emojis properly to a game

Body:
We are trying to add emojis our game using Emoji One and Unity with TextMeshPro. We have a window opening up which shows all the emojis and then the user can pick the one they want, we have run into problems with deleting them and typing text after them.

Here is the code we have have, the name of the sprite is this: 1f609, however the output when we run the code and add it to the input field is this: \ud83d\ude09

string name = _image.sprite.name;
int hexNumber = int.Parse(name, System.Globalization.NumberStyles.HexNumber);
string c = char.ConvertFromUtf32(hexNumber);
_inputField.text += c;

The expected result is that we should see just a single unicode character (I think) so that we can properly delete emoji's with the backspace key and when you enter an emoji it does not create two characters to be deleted and it does not place the character between the two emoji spots so when we enter text it breaks.

Right now if we delete text it will leave us with empty square and if we add text afterwards through typing in the box it will split the characters in two breaking them.


问:
"Add Documentation" is disabled in Xcode 9.1 (9B55)
For example:

Any ideas?

MacOS High Sierra 10.13.1

Xcode 9.1 9B55

答:
This happens to me once in awhile and deleting derived data and restarting Xcode doesn't work for me. I usually have to do the following:

Close Xcode

Execute command in terminal: sudo /usr/libexec/xpccachectl

Restart my computer.

Restarting the computer is a required step.

Source: Apple Forum