问:
Columns don't act responsive even though @media is set?
I've created these to text boxes and want to add responsiveness to them, however, adding the @media doesn't work for some reason. I want the the right box move under the left box when the screen size is under x pixels.

/* CSS Document */

* {
  box-sizing: border-box;
}

#fullbodybg {
  margin-top: 20%;
}

/* Create two unequal columns that floats next to each other */

.column {
  float: left;
  padding: 10px;
  height: auto;
  /* Should be removed. Only for demonstration */
}

@media screen and (max-width: 1000px) {
  .column {
    width: 100%;
  }
}

.left {
  margin-left: 10%;
  width: 25%;
}

.right {
  margin-right: 10%;
  width: 55%;
}

/* Clear floats after the columns */

.row:after {
  content: "";
  display: table;
  clear: both;
}

.row {
  font-family: lato;
  font-style: normal;
  font-weight: 100;
  font-size: 15px;
  text-align: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div class="column left">
    <h2>Angaben gemäß § 5 TMG</h2>
    <p>Max Muster<br>Musterweg<br>12345 Musterstadt<br><br>Vertreten durch:<br>Max Muster<br><br>Kontakt:<br>Telefon: 01234-789456<br>Fax: 1234-56789<br>E-Mail: max@muster.de<br><br>Umsatzsteuer-ID:<br>Umsatzsteuer-Identifikationsnummer gemäß
      §27a Umsatzsteuergesetz: Musterustid.<br><br>Wirtschafts-ID:<br>Musterwirtschaftsid<br><br>Aufsichtsbehörde:<br>Musteraufsicht Musterstadt</p>
  </div>
  <div class="column right">
    <h2>Haftungsausschluss:</h2>
    <p>Zweck einverstanden.</p>
  </div>
</div></code>```

答:
Your main issue is actually the order of your styles. What happens is that your style in .left and .right overrides your @media style. This should be a quick fix:

```<code>/* CSS Document */

* {
    box-sizing: border-box;
}
#fullbodybg {
    margin-top: 20%;
}

/* Create two unequal columns that floats next to each other */
.column {
    float: left;
    padding: 10px;
    height: auto; /* Should be removed. Only for demonstration */
}

.left {
    margin-left: 10%;
    width: 25%;
}

.right {
    margin-right: 10%;
    width: 55%;
}

/* Clear floats after the columns */
.row:after {
    content: "";
    display: table;
    clear: both;
}

.row {
    font-family: lato;
    font-style: normal;
    font-weight: 100;
    font-size: 15px;
    text-align: left;
}

@media screen and (max-width: 1000px) {
    .column {
        width: 100%;
    }
}
</code>```

I simply moved @media at the end to make sure it overrides all other styles when it meets the requirements you've set.

Body:
I've created these to text boxes and want to add responsiveness to them, however, adding the @media doesn't work for some reason. I want the the right box move under the left box when the screen size is under x pixels.

/* CSS Document */

* {
  box-sizing: border-box;
}

#fullbodybg {
  margin-top: 20%;
}

/* Create two unequal columns that floats next to each other */

.column {
  float: left;
  padding: 10px;
  height: auto;
  /* Should be removed. Only for demonstration */
}

@media screen and (max-width: 1000px) {
  .column {
    width: 100%;
  }
}

.left {
  margin-left: 10%;
  width: 25%;
}

.right {
  margin-right: 10%;
  width: 55%;
}

/* Clear floats after the columns */

.row:after {
  content: "";
  display: table;
  clear: both;
}

.row {
  font-family: lato;
  font-style: normal;
  font-weight: 100;
  font-size: 15px;
  text-align: left;
}

Angaben gemäß § 5 TMG

Max Muster
Musterweg
12345 Musterstadt

Vertreten durch:
Max Muster

Kontakt:
Telefon: 01234-789456
Fax: 1234-56789
E-Mail: max@muster.de

Umsatzsteuer-ID:
Umsatzsteuer-Identifikationsnummer gemäß
      §27a Umsatzsteuergesetz: Musterustid.

Wirtschafts-ID:
Musterwirtschaftsid

Aufsichtsbehörde:
Musteraufsicht Musterstadt

Haftungsausschluss:

Zweck einverstanden.

Body:
Your main issue is actually the order of your styles. What happens is that your style in .left and .right overrides your @media style. This should be a quick fix:

/* CSS Document */

* {
    box-sizing: border-box;
}
#fullbodybg {
    margin-top: 20%;
}

/* Create two unequal columns that floats next to each other */
.column {
    float: left;
    padding: 10px;
    height: auto; /* Should be removed. Only for demonstration */
}

.left {
    margin-left: 10%;
    width: 25%;
}

.right {
    margin-right: 10%;
    width: 55%;
}

/* Clear floats after the columns */
.row:after {
    content: "";
    display: table;
    clear: both;
}

.row {
    font-family: lato;
    font-style: normal;
    font-weight: 100;
    font-size: 15px;
    text-align: left;
}

@media screen and (max-width: 1000px) {
    .column {
        width: 100%;
    }
}

I simply moved @media at the end to make sure it overrides all other styles when it meets the requirements you've set.


来源: stackexchange

问:
How do you display code snippets in MS Word preserving format and syntax highlighting?
Does anyone know a way to display code in Microsoft Word documents that preserves coloring and formatting? Preferably, the method would also be unobtrusive and easy to update.

I have tried to include code as regular text which looks awful and gets in the way when editing regular text.  I have also tried inserting objects, a WordPad document and Text Box, into the document then putting the code inside those objects.  The code looks much better and is easier to avoid while editing the rest of the text.  However, these objects can only span one page which makes editing a nightmare when several pages of code need to be added.

Lastly, I know that there are much better editors/formats that have no problem handling this but I am stuck working with MS word.

答:
A web site for coloration with lots of languages.
http://hilite.me/

You can host one yourself since it is open source. The code is on github.

ContentLicense: CC BY-SA 3.0

LastEditorDisplayName: Rob

ContentLicense: CC BY-SA 4.0


问:
How to set a button for changing color?
I am new to js and here I have a function changeColor() that I want to change the color of an image when a button is clicked, but it seems the function is not defined. Someone help?

Here is just a simple button in html, and I want to change img's color by clicking button:

  <button name="color" value="#33FFBD" type="button" onclick="changeColor();">
    Change
  </button>

```

<p>My js file, I want to get the value of the button and change to specified color for the img:</p>

```var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var originalPixels = null;
var currentPixels = null;

function getPixels(img) {
    canvas.width = img.width;
    canvas.height = img.height;

    ctx.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight, 0, 0, img.width, img.height);
    originalPixels = ctx.getImageData(0, 0, img.width, img.height);
    currentPixels = ctx.getImageData(0, 0, img.width, img.height);

    img.onload = null;
}
function hexToRGB(hex)
{
var long = parseInt(hex.replace(/^#/, ""), 16);
return {
    R: (long >>> 16) & 0xff,
    G: (long >>> 8) & 0xff,
    B: long & 0xff
 };
}
Object.onclick = function changeColor()
{
    var mug = document.getElementById("mug");
    if(!originalPixels) return; // Check if image has loaded
    var newColor = hexToRGB(document.getElementByName("color").value);

    for(var I = 0, L = originalPixels.data.length; I < L; I += 4)
    {
        if(currentPixels.data[I + 3] > 0) // If it's not a transparent pixel
        {
            currentPixels.data[I] = originalPixels.data[I] / 255 * newColor.R;
            currentPixels.data[I + 1] = originalPixels.data[I + 1] / 255 * newColor.G;
            currentPixels.data[I + 2] = originalPixels.data[I + 2] / 255 * newColor.B;
        }
    }

    ctx.putImageData(currentPixels, 0, 0);
    mug.src = canvas.toDataURL("image/png");
}
```

答:
Your function changeColor() can't be found because it was not declared.

You have this:

Object.onclick = function changeColor() {...}
```

<p>Change that to a function declaration that can be found globally:</p>

<pre class="lang-js prettyprint-override"><code>function changeColor() {...}
</code>```

Title: How to set a button for changing color?

Body:
I am new to js and here I have a function changeColor() that I want to change the color of an image when a button is clicked, but it seems the function is not defined. Someone help?

Here is just a simple button in html, and I want to change img's color by clicking button:

  <button name="color" value="#33FFBD" type="button" onclick="changeColor();">
    Change
  </button>

My js file, I want to get the value of the button and change to specified color for the img:

var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var originalPixels = null;
var currentPixels = null;

function getPixels(img) {
    canvas.width = img.width;
    canvas.height = img.height;

    ctx.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight, 0, 0, img.width, img.height);
    originalPixels = ctx.getImageData(0, 0, img.width, img.height);
    currentPixels = ctx.getImageData(0, 0, img.width, img.height);

    img.onload = null;
}
function hexToRGB(hex)
{
var long = parseInt(hex.replace(/^#/, ""), 16);
return {
    R: (long >>> 16) & 0xff,
    G: (long >>> 8) & 0xff,
    B: long & 0xff
 };
}
Object.onclick = function changeColor()
{
    var mug = document.getElementById("mug");
    if(!originalPixels) return; // Check if image has loaded
    var newColor = hexToRGB(document.getElementByName("color").value);

    for(var I = 0, L = originalPixels.data.length; I < L; I += 4)
    {
        if(currentPixels.data[I + 3] > 0) // If it's not a transparent pixel
        {
            currentPixels.data[I] = originalPixels.data[I] / 255 * newColor.R;
            currentPixels.data[I + 1] = originalPixels.data[I + 1] / 255 * newColor.G;
            currentPixels.data[I + 2] = originalPixels.data[I + 2] / 255 * newColor.B;
        }
    }

    ctx.putImageData(currentPixels, 0, 0);
    mug.src = canvas.toDataURL("image/png");
}

Body:
Your function changeColor() can't be found because it was not declared.

You have this:

Object.onclick = function changeColor() {...}

Change that to a function declaration that can be found globally:

function changeColor() {...}


问:
Jetty: How to solve redirection wtih ssl certificate to other jetty instance?
I have two jetty instances.
The first Jetty instance has an external port.
All requests come through the first Jetty instance.
Some requests need to be redirected to the second Jetty instance.
The certificate will be validated on the second jetty.

What is the best way to do this with jetty (9)?

Thank you in advance.

答:
In a proxy scenario, the first server will negotiate all of the SSL/TLS layer before issuing the request to the proxy server.

Once the SSL/TLS layer is successfully negotiated, there's no option to THEN perform the Client certificate validation, as that only occurs during the SSL/TLS layer.

In short, once your User-Agent (client/browser) can start making requests, then it's too late for the Client Certificate validation.

As for accessing the javax.servlet.request.X509Certificate that will require whatever proxy you are using to include the appropriate forwarding headers to the second server.

If the second server is Jetty, then that server will requires the ForwardedRequestCustomerizer to pull the Forwarding headers out from the request to then insert into the Request attributes.


问:
Feign ErrorDecoder : retrieve the original message
I use a ErrorDecoder to return the right exception rather than a 500 status code.

Is there a way to retrieve the original message inside the decoder. I can see that it is inside the FeignException, but not in the decode method. All I have is the 'status code' and a empty 'reason'.

```<code>public class CustomErrorDecoder implements ErrorDecoder {

    private final ErrorDecoder errorDecoder = new Default();

    @Override
    public Exception decode(String s, Response response) {

        switch (response.status()) {

            case 404:
                return new FileNotFoundException("File no found");
            case 403:
                return new ForbiddenAccessException("Forbidden access");
        }

        return errorDecoder.decode(s, response);
    }
}
</code>```

Here the original message : "message":"Access to the file forbidden"

```<code>feign.FeignException: status 403 reading ProxyMicroserviceFiles#getUserRoot(); content:
{"timestamp":"2018-11-28T17:34:05.235+0000","status":403,"error":"Forbidden","message":"Access to the file forbidden","path":"/root"}
</code>```

Also I use my FeignClient interface like a RestController so I don't use any other Controler populated with the proxy that could encapsulate the methods calls.

```<code>   @RestController
   @FeignClient(name = "zuul-server")
   @RibbonClient(name = "microservice-files")

   public interface ProxyMicroserviceFiles {

                @GetMapping(value = "microservice-files/root")
                Object getUserRoot();

                @GetMapping(value = "microservice-files/file/{id}")
                Object getFileById(@PathVariable("id") int id);

    }
</code>```

答:
If you're like me and really just want the content out of a failed Feign call without all these custom decoders and boilerplate, there is a hacky way do this.

If we look at FeignException when it is being created and a response body exists, it assembles the exception message like so:

```<code>if (response.body() != null) {
    String body = Util.toString(response.body().asReader());
    message += "; content:\n" + body;
}
</code>```

Therefore if you're after the response body, you can just pull it out by parsing the Exception message since it is delimited by a newline.

```<code>String[] feignExceptionMessageParts = e.getMessage().split("\n");
String responseContent = feignExceptionMessageParts[1];
</code>```

And if you want the object, you can use something like Jackson:

```<code>MyResponseBodyPojo errorBody = objectMapper.readValue(responseContent, MyResponseBodyPojo.class);
</code>```

I do not claim this is a smart approach or a best practice.

Body:
I use a ErrorDecoder to return the right exception rather than a 500 status code.

Is there a way to retrieve the original message inside the decoder. I can see that it is inside the FeignException, but not in the decode method. All I have is the 'status code' and a empty 'reason'.

public class CustomErrorDecoder implements ErrorDecoder {

    private final ErrorDecoder errorDecoder = new Default();

    @Override
    public Exception decode(String s, Response response) {

        switch (response.status()) {

            case 404:
                return new FileNotFoundException("File no found");
            case 403:
                return new ForbiddenAccessException("Forbidden access");
        }

        return errorDecoder.decode(s, response);
    }
}

Here the original message : "message":"Access to the file forbidden"

feign.FeignException: status 403 reading ProxyMicroserviceFiles#getUserRoot(); content:
{"timestamp":"2018-11-28T17:34:05.235+0000","status":403,"error":"Forbidden","message":"Access to the file forbidden","path":"/root"}

Also I use my FeignClient interface like a RestController so I don't use any other Controler populated with the proxy that could encapsulate the methods calls.

   @RestController
   @FeignClient(name = "zuul-server")
   @RibbonClient(name = "microservice-files")

   public interface ProxyMicroserviceFiles {

                @GetMapping(value = "microservice-files/root")
                Object getUserRoot();

                @GetMapping(value = "microservice-files/file/{id}")
                Object getFileById(@PathVariable("id") int id);

    }

Body:
If you're like me and really just want the content out of a failed Feign call without all these custom decoders and boilerplate, there is a hacky way do this.

If we look at FeignException when it is being created and a response body exists, it assembles the exception message like so:

if (response.body() != null) {
    String body = Util.toString(response.body().asReader());
    message += "; content:\n" + body;
}

Therefore if you're after the response body, you can just pull it out by parsing the Exception message since it is delimited by a newline.

String[] feignExceptionMessageParts = e.getMessage().split("\n");
String responseContent = feignExceptionMessageParts[1];

And if you want the object, you can use something like Jackson:

MyResponseBodyPojo errorBody = objectMapper.readValue(responseContent, MyResponseBodyPojo.class);

I do not claim this is a smart approach or a best practice.


问:
CORS with client https certificates
I have a site with two https servers.  One (frontend) serves up a UI made of static pages.  The other (backend) serves up a microservice.  Both of them happen to be using the same (test) X509 certificate to identify themselves.  Individually, I can connect to them both over https requiring the client certificate "tester".

We were hiding CORS issues until now by going through an nginx setup that makes the frontend and backend appear that they are same Origin.  I have implemented the headers 'Access-Control-Allow-Origin', 'Access-Control-Allow-Credentials' for all requests; with methods, headers for preflight check requests (OPTIONS).

In Chrome, cross-site like this works just fine.  I can see that front-end URLs and backend URLs are different sites.  I see the OPTIONS requests being made before backend requests are made.

Even though Chrome doesn't seem to need it, I did find the xmlhttprequest object that will be used to perform the request and did a xhr.withCredentials = true on it, because that seems to be what fetch.js does under the hood when it gets "credentials":"include".  I noticed that there is an xhr.setRequestHeader function available that I might need to use to make Firefox happy.

Firefox behaves identically for the UI calls.  But for all backend calls, I get a 405.  When it does this, there is no network connection being made to the server.  The browser just decided that this is a 405 without executing any https request.  Even though this is different behavior from Chrome, it kind of makes sense.  Both the front-end UI and backend service need a client certificate to be chosen.  I chose the certificate "tester" when I connected to the UI.  When it goes to make a backend request, it could assume that the same client certificate should be used to reach the back-end.  But maybe it assumes that it could be different, and there is something else I need to tell Firefox.

Is anybody here using CORS in combination with 2 way SSL certificates like this, and had this Firefox problem and fixed it somewhere.  I suspect that it's not a server-side fix, but something that the client needs to do.

Edit: see the answer here: https://stackoverflow.com/a/74744206/537554

答:
When using CORS with credentials (basic auth, cookies, client certificate, etc.):

Access-Control-Allow-Credentials must be true

Access-Control-Allow-Origin must not be *

Access-Control-Allow-Origin must not be multi-value (neither duplicated nor comma-delimited)

Access-Control-Allow-Origin must be set to exactly the value from the request's Origin header in order for the request to work (either hard-coded that way or if it passes a whitelist of allowed values)

The preflight OPTIONS request must not require credentials (including the client certificate). Part of the purpose of the preflight is to ask what is allowed in a CORS request, and therefore sending credentials before knowing if they are allowed is incorrect.

The preflight OPTIONS request must return a 200-level response, generally 204

Note: For Access-Control-Allow-Origin, you may want to consider allowing the value null since redirect chains (like the ones typically used for OAuth) can cause that Origin value in a request from a browser.

Title: CORS with client https certificates


问:
how to filter properties with values in Neptune + nodejs
with Neptune + nodejs

g.V().hasLabel('A').properties()

returns:

```<code>id, label, value
1, 'p1','v1'
2, 'p1','b2'
3, 'p1','b3'
4, 'p1','d4'
</code>```

how can I do a filter so it only returns:

```<code>id, label, value
2, 'p1','b2'
3, 'p1','b3'

</code>```

I tried

g.V().hasLabel('Device').properties().value().is(containing('b'))

but it throws error UnsupportedOperationException

I also tried
g.V().hasLabel('Device').where(properties().value().is(containing('b')))

same error, but i think it is because i have different data type in multiple properties, the containing method failed when it come across number type.....

答:
You can use filter :

```<code>g.V().hasLabel('Device').filter({ it.getProperty("value").startsWith("b") })
</code>```

or

```<code>g.V().hasLabel('Device').filter({ it.getProperty("value").contains("b") })
</code>```

EDIT:
This query works in pure Gremlin not Neptune version.

Body:
with Neptune + nodejs

g.V().hasLabel('A').properties()

returns:

id, label, value
1, 'p1','v1'
2, 'p1','b2'
3, 'p1','b3'
4, 'p1','d4'

how can I do a filter so it only returns:

id, label, value
2, 'p1','b2'
3, 'p1','b3'

I tried

g.V().hasLabel('Device').properties().value().is(containing('b'))

but it throws error UnsupportedOperationException

I also tried
g.V().hasLabel('Device').where(properties().value().is(containing('b')))

same error, but i think it is because i have different data type in multiple properties, the containing method failed when it come across number type.....

Body:
You can use filter :

g.V().hasLabel('Device').filter({ it.getProperty("value").startsWith("b") })

or

g.V().hasLabel('Device').filter({ it.getProperty("value").contains("b") })

EDIT:
This query works in pure Gremlin not Neptune version.


问:
How to change color of a Like button on react native with galio
I want to implement a like button that changes it's icon color when it's liked and that can be disliked reverting the color change and like stored in my app. I am using react Native with expo and the galio frameworks This is my attempt:

```<code>function like_quote(_this) {
    _this.setState( {iconColor: theme.COLORS.THEME })
    //_this.iconColor= theme.COLORS.THEME //I also tried this
    Alert.alert('Like!') //this is supposed to be where I store the like for my app
}
</code>```

this inside the render()

```<code>...
            <Button
              onlyIcon
              icon="heart"
          key="like"
              iconFamily="font-awesome"
              iconSize={theme.SIZES.BASE}
              iconColor={'#ffbbbb'}//theme.COLORS.THEME
              color="transparent"
              style={{ marginRight: theme.SIZES.BASE }}
              onPress={() => like_quote(this)}
            />,
    ...
</code>```

Though it does nothing to the button. The Alert works fine but the icon color doesn't change.

答:
You have to change the color of the icon according to your state either it's liked or unliked.

```<code>    like_quote = () => {
    this.setState({iconColor: theme.COLORS.THEME })
    Alert.alert('Like!') //this is supposed to be where I store the
    like for my app
    }

      <Button
          onlyIcon
          icon="heart"
          key="like"
          iconFamily="font-awesome"
          iconSize={theme.SIZES.BASE}
          iconColor={this.state.iconColor}  //theme.COLORS.THEME
          color="transparent"
          style={{ marginRight: theme.SIZES.BASE }}
          onPress={() => like_quote()}
        />
</code>```

Here is I have created a snack where you can see an example, On every button press color, is been change of icon

https://snack.expo.io/@waheed25/smiling-carrot

Body:
I want to implement a like button that changes it's icon color when it's liked and that can be disliked reverting the color change and like stored in my app. I am using react Native with expo and the galio frameworks This is my attempt:

function like_quote(_this) {
    _this.setState( {iconColor: theme.COLORS.THEME })
    //_this.iconColor= theme.COLORS.THEME //I also tried this
    Alert.alert('Like!') //this is supposed to be where I store the like for my app
}

this inside the render()

...
            <Button
              onlyIcon
              icon="heart"
          key="like"
              iconFamily="font-awesome"
              iconSize={theme.SIZES.BASE}
              iconColor={'#ffbbbb'}//theme.COLORS.THEME
              color="transparent"
              style={{ marginRight: theme.SIZES.BASE }}
              onPress={() => like_quote(this)}
            />,
    ...

Though it does nothing to the button. The Alert works fine but the icon color doesn't change.

Body:
You have to change the color of the icon according to your state either it's liked or unliked.

    like_quote = () => {
    this.setState({iconColor: theme.COLORS.THEME })
    Alert.alert('Like!') //this is supposed to be where I store the
    like for my app
    }

      <Button
          onlyIcon
          icon="heart"
          key="like"
          iconFamily="font-awesome"
          iconSize={theme.SIZES.BASE}
          iconColor={this.state.iconColor}  //theme.COLORS.THEME
          color="transparent"
          style={{ marginRight: theme.SIZES.BASE }}
          onPress={() => like_quote()}
        />

Here is I have created a snack where you can see an example, On every button press color, is been change of icon

https://snack.expo.io/@waheed25/smiling-carrot


问:
TD works center and left align but not right align
My code add one row of a table dinamicaly. The alignment wrks for the firs row that is static but not for the other rows. Intead of this I have tested the dinamic content with center align attribute and it works.

Here is the part of the code that I am refering, and below the complete function.

```<code>colsfila=document.createElement('td');
textonodo=document.createTextNode(qTrib);
idnodo='qTrib'+NUM_FILAS;
colsfila.setAttribute('id', idnodo);
colsfila.setAttribute('onclick','addInputdetCompra(this)');
colsfila.setAttribute('style', 'text-align: center;');
colsfila.appendChild(textonodo);
novafila.appendChild(colsfila);

colsfila=document.createElement('td');
textonodo=document.createTextNode(vUnTrib);
idnodo='vUnTrib'+NUM_FILAS;
var align='rigth';
colsfila.setAttribute('id', idnodo);
colsfila.setAttribute('onclick','addInputdetCompra(this)');
colsfila.appendChild(textonodo);
colsfila.setAttribute('style','text-align :rigth;');
novafila.appendChild(colsfila);

function importxmlcompra(){
    var novostring= new String(document.getElementById('file').value);

    if (novostring!=''){
        oPed.open("GET",novostring, false);
        oPed.send();
        var result = oPed.responseXML;
        if (!result.documentElement && oPed.responseStream) {
        result.load(oPed.responseStream);
        }
    }else{
            alert ("Por favor seleccione un arquivo XML");
    }
    if (!result||result.getElementsByTagName('emit').length==0){
        return};
    var emit=result.getElementsByTagName("emit")[0];
    var dEmi=result.getElementsByTagName('dEmi')[0].childNodes[0].nodeValue;
    dEmi=dataNF(dEmi);
    document.getElementById('dEmi').value=dEmi;
    var CNPJ=emit.getElementsByTagName('CNPJ')[0].childNodes[0].nodeValue;
    document.getElementById('cnpj').value=CNPJ;
    var razaosocialimportada=emit.getElementsByTagName("xNome")[0].childNodes[0].nodeValue;
    document.getElementById("xNome").value=razaosocialimportada;
    var ide=result.getElementsByTagName("ide")[0];
    var nNF=ide.getElementsByTagName("nNF")[0].childNodes[0].nodeValue;
    document.getElementById("nNF").value=nNF;
    var vNF='R$'+number_format(result.getElementsByTagName("vNF")[0].childNodes[0].nodeValue,2,',','.');
    document.getElementById("vNF").value=vNF;

    var detlength=result.getElementsByTagName("det").length;
    var j=0, cProd, xProd, vUnTrib, qTrib, vProd;
    var tabledet=document.getElementsByTagName('table')[0];
    var tablerows=document.getElementsByTagName('table')[0].rows.length;
    var novafila, colsfila, idnodo, textonodo, imgnodo, attid, ant;

    while(j<detlength){
        det=result.getElementsByTagName('det')[j];
        cProd=det.getElementsByTagName('cProd')[0].childNodes[0].nodeValue;
        xProd=det.getElementsByTagName('xProd')[0].childNodes[0].nodeValue;
        vUnTrib=number_format(det.getElementsByTagName('vUnTrib')[0].childNodes[0].nodeValue,2,',','.');
        qTrib=number_format(det.getElementsByTagName('qTrib')[0].childNodes[0].nodeValue,0,'','.');
        vProd=number_format(det.getElementsByTagName('vProd')[0].childNodes[0].nodeValue,2,',','.');

        if(validacProd(cProd)==true){

            if (tablerows==2&& document.getElementById('cProd0').innerHTML=='0'){
              document.getElementById('cProd0').innerHTML=cProd;
              document.getElementById('xProd0').innerHTML=xProd;
              document.getElementById('vUnTrib0').innerHTML=vUnTrib;
              document.getElementById('qTrib0').innerHTML=qTrib;
              document.getElementById('vProd0').innerHTML=vProd;
            }else{
                novafila=document.createElement('tr');
                textonodo=document.createTextNode(cProd);
                attid=document.createAttribute('id');
                colsfila=document.createElement('td');
                idnodo='cProd'+NUM_FILAS;
                colsfila.setAttribute('id', idnodo);
                colsfila.setAttribute('onclick','addInputdetCompra(this)');
                colsfila.appendChild(textonodo);
                novafila.appendChild(colsfila);
                tabledet.appendChild(novafila)

                colsfila=document.createElement('td');
                textonodo=document.createTextNode(xProd);
                idnodo='xProd'+NUM_FILAS;
                colsfila.setAttribute('id', idnodo);
                colsfila.setAttribute('onclick','addInputdetCompra(this)');
                colsfila.appendChild(textonodo);
                novafila.appendChild(colsfila);

                colsfila=document.createElement('td');
                idnodo='codproduto'+NUM_FILAS;
                colsfila.setAttribute('id', idnodo);
                colsfila.setAttribute('style','display:none');
                novafila.appendChild(colsfila);

                colsfila=document.createElement('td');
                idnodo='descproduto'+NUM_FILAS;
                colsfila.setAttribute('id', idnodo);
                colsfila.setAttribute('onclick','addInputdetCompra(this)');
                novafila.appendChild(colsfila);

                colsfila=document.createElement('td');
                textonodo=document.createTextNode(qTrib);
                idnodo='qTrib'+NUM_FILAS;
                colsfila.setAttribute('id', idnodo);
                colsfila.setAttribute('onclick','addInputdetCompra(this)');
                colsfila.setAttribute('style', 'text-align: center;');
                colsfila.appendChild(textonodo);
                novafila.appendChild(colsfila);

                colsfila=document.createElement('td');
                textonodo=document.createTextNode(vUnTrib);
                idnodo='vUnTrib'+NUM_FILAS;
                var align='rigth';
                colsfila.setAttribute('id', idnodo);
                colsfila.setAttribute('onclick','addInputdetCompra(this)');
                colsfila.appendChild(textonodo);
                colsfila.setAttribute('style','text-align :rigth;');
                novafila.appendChild(colsfila);

                colsfila=document.createElement('td');
                textonodo=document.createTextNode(vProd);
                idnodo='vProd'+NUM_FILAS;
                colsfila.setAttribute('id', idnodo);
                colsfila.setAttribute('align', 'rigth');
                colsfila.appendChild(textonodo);
                novafila.appendChild(colsfila);

                colsfila=document.createElement('td');
                imgnodo=document.createElement('img');
                idnodo='addrow'+NUM_FILAS;
                colsfila.setAttribute('id', idnodo);
                colsfila.setAttribute('onclick','addRowdetCompra(this)');
                imgnodo.setAttribute('src','../../../imagens/addrow/addrow.png');
                colsfila.appendChild(imgnodo);
                novafila.appendChild(colsfila);
                document.getElementsByTagName('table')[0].appendChild(novafila);
            }
        }
        tablerows=document.getElementsByTagName('table')[0].rows.length;
        NUM_FILAS++;
        j++;
    }
    comandosfilas();
}
</code>```

答:
Typo:

```<code>colsfila.setAttribute('style','text-align :rigth;');
                                           ^^^^^ - should be 'right'
</code>```

If you'd pop up your browser's error console (e.g. shift-ctrl-J in Firefox) you'd see an error flash by for this.

Body:
My code add one row of a table dinamicaly. The alignment wrks for the firs row that is static but not for the other rows. Intead of this I have tested the dinamic content with center align attribute and it works.

Here is the part of the code that I am refering, and below the complete function.

colsfila=document.createElement('td');
textonodo=document.createTextNode(qTrib);
idnodo='qTrib'+NUM_FILAS;
colsfila.setAttribute('id', idnodo);
colsfila.setAttribute('onclick','addInputdetCompra(this)');
colsfila.setAttribute('style', 'text-align: center;');
colsfila.appendChild(textonodo);
novafila.appendChild(colsfila);

colsfila=document.createElement('td');
textonodo=document.createTextNode(vUnTrib);
idnodo='vUnTrib'+NUM_FILAS;
var align='rigth';
colsfila.setAttribute('id', idnodo);
colsfila.setAttribute('onclick','addInputdetCompra(this)');
colsfila.appendChild(textonodo);
colsfila.setAttribute('style','text-align :rigth;');
novafila.appendChild(colsfila);

function importxmlcompra(){
    var novostring= new String(document.getElementById('file').value);

    if (novostring!=''){
        oPed.open("GET",novostring, false);
        oPed.send();
        var result = oPed.responseXML;
        if (!result.documentElement && oPed.responseStream) {
        result.load(oPed.responseStream);
        }
    }else{
            alert ("Por favor seleccione un arquivo XML");
    }
    if (!result||result.getElementsByTagName('emit').length==0){
        return};
    var emit=result.getElementsByTagName("emit")[0];
    var dEmi=result.getElementsByTagName('dEmi')[0].childNodes[0].nodeValue;
    dEmi=dataNF(dEmi);
    document.getElementById('dEmi').value=dEmi;
    var CNPJ=emit.getElementsByTagName('CNPJ')[0].childNodes[0].nodeValue;
    document.getElementById('cnpj').value=CNPJ;
    var razaosocialimportada=emit.getElementsByTagName("xNome")[0].childNodes[0].nodeValue;
    document.getElementById("xNome").value=razaosocialimportada;
    var ide=result.getElementsByTagName("ide")[0];
    var nNF=ide.getElementsByTagName("nNF")[0].childNodes[0].nodeValue;
    document.getElementById("nNF").value=nNF;
    var vNF='R$'+number_format(result.getElementsByTagName("vNF")[0].childNodes[0].nodeValue,2,',','.');
    document.getElementById("vNF").value=vNF;

    var detlength=result.getElementsByTagName("det").length;
    var j=0, cProd, xProd, vUnTrib, qTrib, vProd;
    var tabledet=document.getElementsByTagName('table')[0];
    var tablerows=document.getElementsByTagName('table')[0].rows.length;
    var novafila, colsfila, idnodo, textonodo, imgnodo, attid, ant;

    while(j<detlength){
        det=result.getElementsByTagName('det')[j];
        cProd=det.getElementsByTagName('cProd')[0].childNodes[0].nodeValue;
        xProd=det.getElementsByTagName('xProd')[0].childNodes[0].nodeValue;
        vUnTrib=number_format(det.getElementsByTagName('vUnTrib')[0].childNodes[0].nodeValue,2,',','.');
        qTrib=number_format(det.getElementsByTagName('qTrib')[0].childNodes[0].nodeValue,0,'','.');
        vProd=number_format(det.getElementsByTagName('vProd')[0].childNodes[0].nodeValue,2,',','.');

        if(validacProd(cProd)==true){

            if (tablerows==2&& document.getElementById('cProd0').innerHTML=='0'){
              document.getElementById('cProd0').innerHTML=cProd;
              document.getElementById('xProd0').innerHTML=xProd;
              document.getElementById('vUnTrib0').innerHTML=vUnTrib;
              document.getElementById('qTrib0').innerHTML=qTrib;
              document.getElementById('vProd0').innerHTML=vProd;
            }else{
                novafila=document.createElement('tr');
                textonodo=document.createTextNode(cProd);
                attid=document.createAttribute('id');
                colsfila=document.createElement('td');
                idnodo='cProd'+NUM_FILAS;
                colsfila.setAttribute('id', idnodo);
                colsfila.setAttribute('onclick','addInputdetCompra(this)');
                colsfila.appendChild(textonodo);
                novafila.appendChild(colsfila);
                tabledet.appendChild(novafila)

                colsfila=document.createElement('td');
                textonodo=document.createTextNode(xProd);
                idnodo='xProd'+NUM_FILAS;
                colsfila.setAttribute('id', idnodo);
                colsfila.setAttribute('onclick','addInputdetCompra(this)');
                colsfila.appendChild(textonodo);
                novafila.appendChild(colsfila);

                colsfila=document.createElement('td');
                idnodo='codproduto'+NUM_FILAS;
                colsfila.setAttribute('id', idnodo);
                colsfila.setAttribute('style','display:none');
                novafila.appendChild(colsfila);

                colsfila=document.createElement('td');
                idnodo='descproduto'+NUM_FILAS;
                colsfila.setAttribute('id', idnodo);
                colsfila.setAttribute('onclick','addInputdetCompra(this)');
                novafila.appendChild(colsfila);

                colsfila=document.createElement('td');
                textonodo=document.createTextNode(qTrib);
                idnodo='qTrib'+NUM_FILAS;
                colsfila.setAttribute('id', idnodo);
                colsfila.setAttribute('onclick','addInputdetCompra(this)');
                colsfila.setAttribute('style', 'text-align: center;');
                colsfila.appendChild(textonodo);
                novafila.appendChild(colsfila);

                colsfila=document.createElement('td');
                textonodo=document.createTextNode(vUnTrib);
                idnodo='vUnTrib'+NUM_FILAS;
                var align='rigth';
                colsfila.setAttribute('id', idnodo);
                colsfila.setAttribute('onclick','addInputdetCompra(this)');
                colsfila.appendChild(textonodo);
                colsfila.setAttribute('style','text-align :rigth;');
                novafila.appendChild(colsfila);

                colsfila=document.createElement('td');
                textonodo=document.createTextNode(vProd);
                idnodo='vProd'+NUM_FILAS;
                colsfila.setAttribute('id', idnodo);
                colsfila.setAttribute('align', 'rigth');
                colsfila.appendChild(textonodo);
                novafila.appendChild(colsfila);

                colsfila=document.createElement('td');
                imgnodo=document.createElement('img');
                idnodo='addrow'+NUM_FILAS;
                colsfila.setAttribute('id', idnodo);
                colsfila.setAttribute('onclick','addRowdetCompra(this)');
                imgnodo.setAttribute('src','../../../imagens/addrow/addrow.png');
                colsfila.appendChild(imgnodo);
                novafila.appendChild(colsfila);
                document.getElementsByTagName('table')[0].appendChild(novafila);
            }
        }
        tablerows=document.getElementsByTagName('table')[0].rows.length;
        NUM_FILAS++;
        j++;
    }
    comandosfilas();
}

Body:
Typo:

colsfila.setAttribute('style','text-align :rigth;');
                                           ^^^^^ - should be 'right'

If you'd pop up your browser's error console (e.g. shift-ctrl-J in Firefox) you'd see an error flash by for this.


问:
How can I make two components communicate in React?
I have just started using React and I am struggling to figure out how to make 2 components communicate between each other to exchange data. For example, I am trying to build a calculator which has component buttons with their values and component input field which is supposed to display the value of the buttons. I think I can figure out how to write the code, but I am strugging to understand, how to make them know about each other?
Thank you!</p>

答:
Coming from OOP, I tend to prefer the simple createRef() approach as a way to expose the methods of a component to another in a simple way.

Here's below a very simple example:

class MyComponent extends Component {
   constructor(props) {
      this.compRef = React.createRef()
   }

   onSomething = (val) => {
      this.compRef.current.setState({key: val})
   }

   render() {
      return (
         <SomeComponent ref={this.compRef} />
         <SomeOtherComponent onChange={this.onSomething} />
      )
   }

}
```


问:
How to minimize the size of a flutter app
I was creating a flutter app without adding any thing to it and try launching it.
The problem is, size of the flutter app that was created is 65.88MB

Are these the flaws of flutter or not?

答:
Flutter apps may be larger in file size than native apps, but not that much according to my experience. I've built a fully-featured app with firebase and some in-app-database like SQLite with most of the apps under the file size of 6 or 7MB. If I would not split per ABI, then the app would probably around 12 or 13MB. But for most of the apps that you're actually launching, you would want to split per ABI.

According to your question, you might be checking the application's file size of the debugging build. The debug application's file size would normally be large because it has lots and lots of components to make your development smooth and faster, for example, the ability to hot-reload during debugging.

What you would want to do is to build a release version of the app by doing,

flutter build apk --split-per-abi
```

which should yield a release version of the app, with the file size around 5MB which normally is the file size of a hello world application in Flutter. You can learn more about building the release application here.

Body:
Flutter apps may be larger in file size than native apps, but not that much according to my experience. I've built a fully-featured app with firebase and some in-app-database like SQLite with most of the apps under the file size of 6 or 7MB. If I would not split per ABI, then the app would probably around 12 or 13MB. But for most of the apps that you're actually launching, you would want to split per ABI.

According to your question, you might be checking the application's file size of the debugging build. The debug application's file size would normally be large because it has lots and lots of components to make your development smooth and faster, for example, the ability to hot-reload during debugging.

What you would want to do is to build a release version of the app by doing,

flutter build apk --split-per-abi

which should yield a release version of the app, with the file size around 5MB which normally is the file size of a hello world application in Flutter. You can learn more about building the release application here.


问:
Flask error: werkzeug.routing.BuildError when connecting to web service
For educational purposes, we're building a very simple Flask app. While it runs smoothly locally, it no longer does when I copy the code to my virtual private server.

The route is defined as follows:

from flask import Flask, request, render_template
app = Flask(__name__)
@app.route("/", methods=["GET", "POST"])
def sign_up():
...
```

<p>This is the function that uses autocomplete:</p>

<pre class="lang-py prettyprint-override"><code>    with connection.cursor() as cursor:
        sql = f"SELECT * FROM movies WHERE title"
        query = cursor.execute(sql)
        data = cursor.fetchall()
        # from flask import jsonify
        results = [data[i]['title'] for i in range(len(data))]

    return render_template("autocomplete.html", results=results)
</code>```

autocomplete.html is located in the templates folder, which sits next to the Python program file.

And the web service is started like this:

if __name__ == '__main__':
    app.run(host='0.0.0.0')
```

<p>I can start the web service successfully, but when I connect using the URL, it returns a 500 error, and the server console shows:</p>

```[2020-05-28 16:19:47,099] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
  File "/root/miniconda3/lib/python3.7/site-packages/flask/app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "/root/miniconda3/lib/python3.7/site-packages/flask/app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/root/miniconda3/lib/python3.7/site-packages/flask/app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/root/miniconda3/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/root/miniconda3/lib/python3.7/site-packages/flask/app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "/root/miniconda3/lib/python3.7/site-packages/flask/app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "app.py", line 94, in sign_up
    return render_template("autocomplete.html", results=results)
  File "/root/miniconda3/lib/python3.7/site-packages/flask/templating.py", line 140, in render_template
    ctx.app,
  File "/root/miniconda3/lib/python3.7/site-packages/flask/templating.py", line 120, in _render
    rv = template.render(context)
  File "/root/miniconda3/lib/python3.7/site-packages/jinja2/environment.py", line 1090, in render
    self.environment.handle_exception()
  File "/root/miniconda3/lib/python3.7/site-packages/jinja2/environment.py", line 832, in handle_exception
    reraise(*rewrite_traceback_stack(source=source))
  File "/root/miniconda3/lib/python3.7/site-packages/jinja2/_compat.py", line 28, in reraise
    raise value.with_traceback(tb)
  File "/root/recommender/app-flask/templates/autocomplete.html", line 10, in top-level template code
    $.getJSON("{{url_for('autocomplete')}}",{
  File "/root/miniconda3/lib/python3.7/site-packages/flask/helpers.py", line 370, in url_for
    return appctx.app.handle_url_build_error(error, endpoint, values)
  File "/root/miniconda3/lib/python3.7/site-packages/flask/app.py", line 2216, in handle_url_build_error
    reraise(exc_type, exc_value, tb)
  File "/root/miniconda3/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/root/miniconda3/lib/python3.7/site-packages/flask/helpers.py", line 358, in url_for
    endpoint, values, method=method, force_external=external
  File "/root/miniconda3/lib/python3.7/site-packages/werkzeug/routing.py", line 2179, in build
    raise BuildError(endpoint, values, method, self)
werkzeug.routing.BuildError: Could not build url for endpoint 'autocomplete'. Did you mean 'static' instead?
```

I assume this is because of a change in the URL, but I don't know how to solve this.

Can anyone help?

答:
$.getJSON("{{url_for('autocomplete')}}",{
=> your code wrong at this line, read more about url_for in flask.

It's need to render route like: <blueprint_name>.<function_name> If use app as route use can skip blueprint_name => Ex: .sign_up
sample

Body:
For educational purposes, we're building a very simple Flask app. While it runs smoothly locally, it no longer does when I copy the code to my virtual private server.

The route is defined as follows:

from flask import Flask, request, render_template
app = Flask(__name__)
@app.route("/", methods=["GET", "POST"])
def sign_up():
...

This is the function that uses autocomplete:

    with connection.cursor() as cursor:
        sql = f"SELECT * FROM movies WHERE title"
        query = cursor.execute(sql)
        data = cursor.fetchall()
        # from flask import jsonify
        results = [data[i]['title'] for i in range(len(data))]

    return render_template("autocomplete.html", results=results)

autocomplete.html is located in the templates folder, which sits next to the Python program file.

And the web service is started like this:

if __name__ == '__main__':
    app.run(host='0.0.0.0')

I can start the web service successfully, but when I connect using the URL, it returns a 500 error, and the server console shows:

[2020-05-28 16:19:47,099] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
  File "/root/miniconda3/lib/python3.7/site-packages/flask/app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "/root/miniconda3/lib/python3.7/site-packages/flask/app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/root/miniconda3/lib/python3.7/site-packages/flask/app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/root/miniconda3/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/root/miniconda3/lib/python3.7/site-packages/flask/app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "/root/miniconda3/lib/python3.7/site-packages/flask/app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "app.py", line 94, in sign_up
    return render_template("autocomplete.html", results=results)
  File "/root/miniconda3/lib/python3.7/site-packages/flask/templating.py", line 140, in render_template
    ctx.app,
  File "/root/miniconda3/lib/python3.7/site-packages/flask/templating.py", line 120, in _render
    rv = template.render(context)
  File "/root/miniconda3/lib/python3.7/site-packages/jinja2/environment.py", line 1090, in render
    self.environment.handle_exception()
  File "/root/miniconda3/lib/python3.7/site-packages/jinja2/environment.py", line 832, in handle_exception
    reraise(*rewrite_traceback_stack(source=source))
  File "/root/miniconda3/lib/python3.7/site-packages/jinja2/_compat.py", line 28, in reraise
    raise value.with_traceback(tb)
  File "/root/recommender/app-flask/templates/autocomplete.html", line 10, in top-level template code
    $.getJSON("{{url_for('autocomplete')}}",{
  File "/root/miniconda3/lib/python3.7/site-packages/flask/helpers.py", line 370, in url_for
    return appctx.app.handle_url_build_error(error, endpoint, values)
  File "/root/miniconda3/lib/python3.7/site-packages/flask/app.py", line 2216, in handle_url_build_error
    reraise(exc_type, exc_value, tb)
  File "/root/miniconda3/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/root/miniconda3/lib/python3.7/site-packages/flask/helpers.py", line 358, in url_for
    endpoint, values, method=method, force_external=external
  File "/root/miniconda3/lib/python3.7/site-packages/werkzeug/routing.py", line 2179, in build
    raise BuildError(endpoint, values, method, self)
werkzeug.routing.BuildError: Could not build url for endpoint 'autocomplete'. Did you mean 'static' instead?

I assume this is because of a change in the URL, but I don't know how to solve this.

Can anyone help?


问:
Android webview load data error eglChooseConfig failed with error EGL_BAD_ATTRIBUTE
I am trying to use a web view to make an HTML to bitmap. Everything was running ok until I try to had my app in the background. I make the app came to the foreground like this

```<code>Intent it = new Intent("intent.my.action");
it.setComponent(new ComponentName(getApplicationContext().getPackageName(),
MainActivity.class.getName()));
it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().getApplicationContext().startActivity(it);
Thread.sleep(2000);
</code>```

After that, I load data to my web view and wait for the onPageCommitVisible to run but never run!!!

webView.loadData(html, "text/html","UTF-8");

答: I have just add the load data part and the new webclient to a fuction called in the onResume and it is working</p>

Body:
I am trying to use a web view to make an HTML to bitmap. Everything was running ok until I try to had my app in the background. I make the app came to the foreground like this

Intent it = new Intent("intent.my.action");
it.setComponent(new ComponentName(getApplicationContext().getPackageName(),
MainActivity.class.getName()));
it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().getApplicationContext().startActivity(it);
Thread.sleep(2000);

After that, I load data to my web view and wait for the onPageCommitVisible to run but never run!!!

webView.loadData(html, "text/html","UTF-8");


问:
A generic Intent to launch Calendar app on Android?
For stock Android ROMs, we can launch the Google Calendar app by:

Intent intent = new Intent(Intent.ACTION_EDIT);

intent.setType("vnd.android.cursor.item/event");

intent.putExtra("title", "Some title");

intent.putExtra("description", "Some description");

startActivity(intent);
```

However, it looks like manufacturers w/ custom UIs implemented their own Calendar, such as HTC Sense UI.

I'm not sure about MotoBlur and Samsung TouchWiz, but I assume they are doing the same.

So, the question is: is there a generic Intent we can use to launch the Calendar app on Android phones (regardless it's stock android or custom UI)? Or we kind of need to write a wrapper class to check and launch the appropriate calendars?

答: There is currently no supported API for the calendar.  What you are doing is relying on private implementation details (the need to hand-write a string literal for the MIME type indicates this), so you are going to get different behavior on different devices depending their implementation.</p>

Body:
For stock Android ROMs, we can launch the Google Calendar app by:

Intent intent = new Intent(Intent.ACTION_EDIT);

intent.setType("vnd.android.cursor.item/event");

intent.putExtra("title", "Some title");

intent.putExtra("description", "Some description");

startActivity(intent);

However, it looks like manufacturers w/ custom UIs implemented their own Calendar, such as HTC Sense UI.

I'm not sure about MotoBlur and Samsung TouchWiz, but I assume they are doing the same.

So, the question is: is there a generic Intent we can use to launch the Calendar app on Android phones (regardless it's stock android or custom UI)? Or we kind of need to write a wrapper class to check and launch the appropriate calendars?


问:
Prettier removes escape characters in Angular
I am using Prettier in my Angular project, and I'm trying to include a regex pattern for a form validator.  When I run Prettier, the string is fundamentally altered to make the pattern validation dysfunctional, as shown here:

Before:

```<code>export const EmailVal: ScaffoldValidator = PatternVal(
  "/^[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z_+])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9}$/"
);
</code>```

After:

```<code>export const EmailVal: ScaffoldValidator = PatternVal(
  "/^[0-9a-zA-Z]([-.w]*[0-9a-zA-Z_+])*@([0-9a-zA-Z][-w]*[0-9a-zA-Z].)+[a-zA-Z]{2,9}$/"
);
</code>```

I've gone through the Prettier Docs, which speaks to changing escapes within the context of single vs double quotes, yet asserts that other escapes will be untouched.  I've also gone through my tsLint.json, and nothing stands out to me as the source.  It does denote "Codelyzer" as the ruleset. Is there a setting somewhere I can disable to prevent this behavior?

答:
You can directly use a regex (note: no quotes - just the slashes):

```<code>/^[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z_+])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9}$/;
</code>```

or correct the string escapes (note the double backslashes):

```<code>"/^[0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z_+])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9}$/";
                  ^^                                 ^^              ^^
</code>```

Consider using EsLint - it can warn you about these cases (see no-useless-escape rule):

Body:
I am using Prettier in my Angular project, and I'm trying to include a regex pattern for a form validator.  When I run Prettier, the string is fundamentally altered to make the pattern validation dysfunctional, as shown here:

Before:

export const EmailVal: ScaffoldValidator = PatternVal(
  "/^[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z_+])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9}$/"
);

After:

export const EmailVal: ScaffoldValidator = PatternVal(
  "/^[0-9a-zA-Z]([-.w]*[0-9a-zA-Z_+])*@([0-9a-zA-Z][-w]*[0-9a-zA-Z].)+[a-zA-Z]{2,9}$/"
);

I've gone through the Prettier Docs, which speaks to changing escapes within the context of single vs double quotes, yet asserts that other escapes will be untouched.  I've also gone through my tsLint.json, and nothing stands out to me as the source.  It does denote "Codelyzer" as the ruleset. Is there a setting somewhere I can disable to prevent this behavior?

Body:
You can directly use a regex (note: no quotes - just the slashes):

/^[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z_+])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9}$/;

or correct the string escapes (note the double backslashes):

"/^[0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z_+])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9}$/";
                  ^^                                 ^^              ^^

Consider using EsLint - it can warn you about these cases (see no-useless-escape rule):


问:
Cannot start docker after installation on Windows
I am a new to Docker. After the installation of Docker Toolbox (OS: Windows 10) I run Docker Quickstart Terminal and in the console I see this:

```<code>Running pre-create checks...
Error wirh pre-create check: "Hyper-V is installed. VirtualBox won't boot a 64bits VM when Hyper-V is activated. It it's installed but deactivated, you can use --virtualbox-no-vtx-check to try anyways"
Look like something went wrong in step 'Checking if machine default exists'...
Press any key to continue...
</code>```

What did I do wrong? All checking of system and install steps are taken from here.

Thank you very much for your help!

答:
You need to disable Hypervisor to check new application that use VT-x before the virtual machine launch:

Open the command prompt as Administrator

Run bcdedit to check hypervisor status:

Check hypervisor launch type.

If is set to auto then disable it:

```<code>bcdedit /set hypervisorlaunchtype off
</code>```

Reboot host machine and launch VirtualBox again

After performing above steps I opened again Docker Quickstart terminal and it is working fine.

Body:
I am a new to Docker. After the installation of Docker Toolbox (OS: Windows 10) I run Docker Quickstart Terminal and in the console I see this:

Running pre-create checks...
Error wirh pre-create check: "Hyper-V is installed. VirtualBox won't boot a 64bits VM when Hyper-V is activated. It it's installed but deactivated, you can use --virtualbox-no-vtx-check to try anyways"
Look like something went wrong in step 'Checking if machine default exists'...
Press any key to continue...

What did I do wrong? All checking of system and install steps are taken from here.

Thank you very much for your help!

Body:
You need to disable Hypervisor to check new application that use VT-x before the virtual machine launch:

Open the command prompt as Administrator

Run bcdedit to check hypervisor status:

Check hypervisor launch type.

If is set to auto then disable it:

bcdedit /set hypervisorlaunchtype off

Reboot host machine and launch VirtualBox again

After performing above steps I opened again Docker Quickstart terminal and it is working fine.


问:
CNN model not working well on 4 species but works well with 2 species
I tried CNN model on two classes and got 80% but when i tried the same model with 4 classes i got very bad result. What is the reason pls help.
The model of CNN i used is:

```<code>model= Sequential()

model.add(Conv2D(64,(3,3),input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64,(3,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64,(3,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten())

model.add(Dense(64))
model.add(Activation('relu'))

model.add(Dropout(0.5))

model.add(Dense(1))
model.add(Activation('sigmoid'))

#opt = SGD( lr=0.01)

model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

history = model.fit_generator(
    train_generator,
    steps_per_epoch=nb_train_samples//batch_size,
    epochs=epochs,
    validation_data = validation_generator,
    validation_steps = validation_generator.samples // batch_size,
)
</code>```

The result of 2 classes something like this i lost the actual result of it:

```<code>Epoch 29/35
46/46 [==============================] - 188s 4s/step - loss: 0.6511 - accuracy: 0.5880 - val_loss: 0.7534 - val_accuracy: 0.5175

</code>```

The result with 4 classes is:

```<code>46/46 [==============================] - 367s 8s/step - loss: -10550614391401.7266 - accuracy: 0.2541 - val_loss: -15023441182720.0000 - val_accuracy: 0.2354
</code>```

答:
The output layer is using sigmoid activation function which can be used only for binary classification problems.

For more than two classes, use softmax activation function and the dense layer before it should have num_of_classes nodes.

```<code>model.add(Dense(numclasses)) # numclasses = 4 in your case
model.add(Activation('softmax'))
</code>```

Also the loss should be changed from binary_crossentropy to categorical_crossentropy (this is the main reason for weird loss displayed in your case).

```<code>model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])
</code>```

Note : categorical_crossentropy expects one-hot vectors. If the labels you have is just a 1D array rather than an one-hot vector, use sparse_categorical_crossentropy

Body:
I tried CNN model on two classes and got 80% but when i tried the same model with 4 classes i got very bad result. What is the reason pls help.
The model of CNN i used is:

model= Sequential()

model.add(Conv2D(64,(3,3),input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64,(3,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64,(3,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten())

model.add(Dense(64))
model.add(Activation('relu'))

model.add(Dropout(0.5))

model.add(Dense(1))
model.add(Activation('sigmoid'))

#opt = SGD( lr=0.01)

model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

history = model.fit_generator(
    train_generator,
    steps_per_epoch=nb_train_samples//batch_size,
    epochs=epochs,
    validation_data = validation_generator,
    validation_steps = validation_generator.samples // batch_size,
)

The result of 2 classes something like this i lost the actual result of it:

Epoch 29/35
46/46 [==============================] - 188s 4s/step - loss: 0.6511 - accuracy: 0.5880 - val_loss: 0.7534 - val_accuracy: 0.5175

The result with 4 classes is:

46/46 [==============================] - 367s 8s/step - loss: -10550614391401.7266 - accuracy: 0.2541 - val_loss: -15023441182720.0000 - val_accuracy: 0.2354

Body:
The output layer is using sigmoid activation function which can be used only for binary classification problems.

For more than two classes, use softmax activation function and the dense layer before it should have num_of_classes nodes.

model.add(Dense(numclasses)) # numclasses = 4 in your case
model.add(Activation('softmax'))

Also the loss should be changed from binary_crossentropy to categorical_crossentropy (this is the main reason for weird loss displayed in your case).

model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

Note : categorical_crossentropy expects one-hot vectors. If the labels you have is just a 1D array rather than an one-hot vector, use sparse_categorical_crossentropy


问:
Regex string does not start or end (or both) with forward slash
I have this regular expression for javascript that should return a match when the string does not start or end with a forward slash (or both). The problem is that it does not return a match if I just type a single character (i.e. 'g').

https://regex101.com/r/9Bi3uc/1

The expression: (^[^/].*)(.*[^/]$)

Any idea what I am doing wrong?

答:
I believe the reason it won't match single characters, is that you have two instances of [^/] in your regex. This means that it needs at least two characters that are not slashes for it to properly match. A quick solution to this is to use a regex OR operator to handle this case. Here's a modified version of your regex that matches all of your examples:

((^[^/].*[^/]$)|^[^/]$)

This can be broken into two segments

(^[^/].*[^/]$)

this first part is a shortened version of yours and will capture any strings with a length of 2 or more that don't start or end with a slash.

The second part on the other side of the OR operator (|) is this
^[^/]$

This will match a single character lines that are not a slash.


问:
Does the night mode need sqlite?
I just want to know if the night mode in Android needs sqlite?
or there's another way to save the mode in it
when the user close the app and reopen it again it will save the mode
pls help

If there's another way please share it with me
Thanks

答:
Write this code on the first page that runs

```<code> SharedPreferences pref = getApplicationContext().getSharedPreferences("nightMode", 0);
    if(pref.getBoolean("mode",false)){
        // code change ui to night
    }
</code>```

and Write this code on the night mode switch

```<code>    SharedPreferences pref = getApplicationContext().getSharedPreferences("nightMode", 0);

    pref.edit().putBoolean("mode",true).apply();
</code>```

Just as easily

Title: Does the night mode need sqlite?

Body:
Write this code on the first page that runs

 SharedPreferences pref = getApplicationContext().getSharedPreferences("nightMode", 0);
    if(pref.getBoolean("mode",false)){
        // code change ui to night
    }

and Write this code on the night mode switch

    SharedPreferences pref = getApplicationContext().getSharedPreferences("nightMode", 0);

    pref.edit().putBoolean("mode",true).apply();

Just as easily


问:
Spring Data JPA + JpaSpecificationExecutor + NamedEntityGraph
I have two Entities. Parent and Child.

```<code>@Entity
public class Parent {

    @Id
    @Column(name = "PARENT_ID")
    private BigInteger id;

    @Column(name = "FIRST_NAME")
    private String firstName;

    @Column(name = "LAST_NAME")
    private String lastName;
}

@Entity
@NamedEntityGraph(name = "Child.parentObj", attributeNodes = @NamedAttributeNodes("parentObj"))
public class Child{
//blah blah blah

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name="PARENT_ID")
Parent parentObj;

@OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name="CHILD_ID")
Set<Address> address
//blah blah blah
}
</code>```

ChildRepository.java

```<code>public interface ChildRepository extends JpaRepository<T, ID>, JpaSpecificationExecutor<T>{

     @EntityGraph(value="Child.parentObj")
     public List<Child> findAll(Specification<Child> spec);
}
</code>```

I am trying to find child entities by criteria and it should always have parent.

I am getting exception that it is trying to find parentObj in Address table.

```<code>Caused by: org.hibernate.QueryException: could not resolve property: parentObj of: com.xxx.Address [..]
</code>```

I found this link and tried solution given by Joep but same error.

Spring Data JPA + JpaSpecificationExecutor + EntityGraph

what am I missing. I am not able to understand why/how i limit to look for parentObj in just Child Object as Address has no reference to Parent.

I am doing search by Address.street.

I have tried ad-hoc entity graph too. exception:

```<code>org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.QueryException: could not resolve property: parentObj of: com.xxx.Address

Caused by: org.hibernate.QueryException: could not resolve property: parentObj of: com.xxx.Address
    at org.hibernate.persister.entity.AbstractPropertyMapping.propertyException(AbstractPropertyMapping.java:83)
    at org.hibernate.persister.entity.AbstractPropertyMapping.toType(AbstractPropertyMapping.java:77)
    at org.hibernate.persister.entity.AbstractEntityPersister.toType(AbstractEntityPersister.java:1978)
    at org.hibernate.hql.internal.ast.tree.FromElementType.getPropertyType(FromElementType.java:367)
    at org.hibernate.hql.internal.ast.tree.FromElement.getPropertyType(FromElement.java:500)
    at org.hibernate.engine.query.spi.EntityGraphQueryHint.getFromElements(EntityGraphQueryHint.java:95)
    at org.hibernate.engine.query.spi.EntityGraphQueryHint.toFromElements(EntityGraphQueryHint.java:68)
    at org.hibernate.hql.internal.ast.HqlSqlWalker.processQuery(HqlSqlWalker.java:676)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:665)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.collectionFunctionOrSubselect(HqlSqlBaseWalker.java:4905)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.comparisonExpr(HqlSqlBaseWalker.java:4606)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:2104)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:2029)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:2029)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.whereClause(HqlSqlBaseWalker.java:796)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:597)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:301)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:249)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:278)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:206)
    ... 60 more
</code>```

答:
I wanted to  find Child entries by criteria search and get ParentObj for each child. I wanted to do join and not individual select for Parent. I was trying to solve that by using EntityGraph but it didn't work. As @EKlavya pointed out Specification and EntityGraph don't work togather.

The way I solved was:

```<code>root.fetch("parentObj", JOIN.LEFT);
</code>```

in my toPredicate method. this will get Child entity with Parent in 1 query.

Body:
I have two Entities. Parent and Child.

@Entity
public class Parent {

    @Id
    @Column(name = "PARENT_ID")
    private BigInteger id;

    @Column(name = "FIRST_NAME")
    private String firstName;

    @Column(name = "LAST_NAME")
    private String lastName;
}

@Entity
@NamedEntityGraph(name = "Child.parentObj", attributeNodes = @NamedAttributeNodes("parentObj"))
public class Child{
//blah blah blah

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name="PARENT_ID")
Parent parentObj;

@OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name="CHILD_ID")
Set<Address> address
//blah blah blah
}

ChildRepository.java

public interface ChildRepository extends JpaRepository<T, ID>, JpaSpecificationExecutor<T>{

     @EntityGraph(value="Child.parentObj")
     public List<Child> findAll(Specification<Child> spec);
}

I am trying to find child entities by criteria and it should always have parent.

I am getting exception that it is trying to find parentObj in Address table.

Caused by: org.hibernate.QueryException: could not resolve property: parentObj of: com.xxx.Address [..]

I found this link and tried solution given by Joep but same error.

Spring Data JPA + JpaSpecificationExecutor + EntityGraph

what am I missing. I am not able to understand why/how i limit to look for parentObj in just Child Object as Address has no reference to Parent.

I am doing search by Address.street.

I have tried ad-hoc entity graph too. exception:

org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.QueryException: could not resolve property: parentObj of: com.xxx.Address

Caused by: org.hibernate.QueryException: could not resolve property: parentObj of: com.xxx.Address
    at org.hibernate.persister.entity.AbstractPropertyMapping.propertyException(AbstractPropertyMapping.java:83)
    at org.hibernate.persister.entity.AbstractPropertyMapping.toType(AbstractPropertyMapping.java:77)
    at org.hibernate.persister.entity.AbstractEntityPersister.toType(AbstractEntityPersister.java:1978)
    at org.hibernate.hql.internal.ast.tree.FromElementType.getPropertyType(FromElementType.java:367)
    at org.hibernate.hql.internal.ast.tree.FromElement.getPropertyType(FromElement.java:500)
    at org.hibernate.engine.query.spi.EntityGraphQueryHint.getFromElements(EntityGraphQueryHint.java:95)
    at org.hibernate.engine.query.spi.EntityGraphQueryHint.toFromElements(EntityGraphQueryHint.java:68)
    at org.hibernate.hql.internal.ast.HqlSqlWalker.processQuery(HqlSqlWalker.java:676)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:665)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.collectionFunctionOrSubselect(HqlSqlBaseWalker.java:4905)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.comparisonExpr(HqlSqlBaseWalker.java:4606)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:2104)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:2029)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:2029)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.whereClause(HqlSqlBaseWalker.java:796)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:597)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:301)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:249)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:278)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:206)
    ... 60 more

Body:
I wanted to  find Child entries by criteria search and get ParentObj for each child. I wanted to do join and not individual select for Parent. I was trying to solve that by using EntityGraph but it didn't work. As @EKlavya pointed out Specification and EntityGraph don't work togather.

The way I solved was:

root.fetch("parentObj", JOIN.LEFT);

in my toPredicate method. this will get Child entity with Parent in 1 query.


问:
Creating a button in Java, causes getLayoutParams to return null
I need to create a button in Java. Below is my code:

```<code> Button b = new Button(MyClass.this);
 b.requestLayout();
 LayoutParams lp = b.getLayoutParams();
 lp.height = LayoutParams.WRAP_CONTENT;
 lp.width = LayoutParams.WRAP_CONTENT;
 b.setLayoutParams(lp);
 b.setText("bla");
 b.setTextSize(16);
 b.setOnClickListener(myListener);
</code>```

I then add this button to the bottom of a ListView:

```<code> getListView().addFooterView(b);
</code>```

However this crashes, because getLayoutParams returns null.

Even if I create new  LayoutParams instead of getLayoutParams, i.e.:

```<code> Button b = new Button(MyClass.this);
 LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
 b.setLayoutParams(lp);
 b.setText("bla");
 b.setTextSize(16);
 b.setOnClickListener(myListener);
</code>```

then the application crashes. Without setLayoutParams, it runs fine, but my button is not sized properly.

How can I size my button?

答: You have to add this button to a view if you want to get LayoutParams from button. Or just create new LayoutParams and set it.

Body:
I need to create a button in Java. Below is my code:

 Button b = new Button(MyClass.this);
 b.requestLayout();
 LayoutParams lp = b.getLayoutParams();
 lp.height = LayoutParams.WRAP_CONTENT;
 lp.width = LayoutParams.WRAP_CONTENT;
 b.setLayoutParams(lp);
 b.setText("bla");
 b.setTextSize(16);
 b.setOnClickListener(myListener);

I then add this button to the bottom of a ListView:

 getListView().addFooterView(b);

However this crashes, because getLayoutParams returns null.

Even if I create new  LayoutParams instead of getLayoutParams, i.e.:

 Button b = new Button(MyClass.this);
 LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
 b.setLayoutParams(lp);
 b.setText("bla");
 b.setTextSize(16);
 b.setOnClickListener(myListener);

then the application crashes. Without setLayoutParams, it runs fine, but my button is not sized properly.

How can I size my button?


问:
How do I draw text onto the screen in pygame?
I'm trying to just draw any text on to the screen in pygame but when I run the program it just runs normally but no text appears on the screen. Is there something I'm doing wrong?</p>

```<code>    import pygame, random, sys
    from pygame.locals import *
    pygame.init()
    #set constants
    WINDOWWIDTH = 600
    WINDOWHEIGHT = 600
    TEXTCOLOR = (255, 255, 255)
    BACKGROUNDCOLOR = (0, 0, 255)
    FPS = 40
    BLACK = (0,0,0)
    RED = (255, 0, 0)
    WHITE = (255, 255, 255)
    #set variables
    rectY1 = 200
    rectY2 = 200
    Y1change = 0
    Y2change = 0
    ballX = 320
    ballY = 240
    ballXvel = 0
    ballYvel = 0
    paddle1 = pygame.Rect(18,rectY1,10,100)
    paddle2 = pygame.Rect(620,rectY2,10,100)
    ball = pygame.Rect(ballX,ballY,30,30)
    font = pygame.font.SysFont(None, 48)
    #create shapes
    def drawshapes():
        pygame.draw.rect(DISPLAY, WHITE, paddle1)
        pygame.draw.rect(DISPLAY, WHITE, paddle2)
        pygame.draw.rect(DISPLAY, WHITE, ball)
    def drawText(text, font, surface, x, y):
        textobj = font.render(text, 1, TEXTCOLOR)
        textrect = textobj.get_rect()
        textrect.topleft = (x, y)
        surface.blit(textobj, textrect)

    #set up display

    DISPLAY = pygame.display.set_mode((640,480),0,32)
    pygame.display.set_caption('Pong')
    fpsClock = pygame.time.Clock()
    drawText('bruh', font, DISPLAY, (200), (200))
    pygame.display.update
</code>```

答:
idk if this really is the loop you are talking about but here it is:</p>

```<code>running = True
while running:
    # RGB - Red, Green, Blue
    screen.fill((0, 0, 128 ))
    #background Image
    screen.blit(background, (0, 0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
</code>```

Body:
I'm trying to just draw any text on to the screen in pygame but when I run the program it just runs normally but no text appears on the screen. Is there something I'm doing wrong?

    import pygame, random, sys
    from pygame.locals import *
    pygame.init()
    #set constants
    WINDOWWIDTH = 600
    WINDOWHEIGHT = 600
    TEXTCOLOR = (255, 255, 255)
    BACKGROUNDCOLOR = (0, 0, 255)
    FPS = 40
    BLACK = (0,0,0)
    RED = (255, 0, 0)
    WHITE = (255, 255, 255)
    #set variables
    rectY1 = 200
    rectY2 = 200
    Y1change = 0
    Y2change = 0
    ballX = 320
    ballY = 240
    ballXvel = 0
    ballYvel = 0
    paddle1 = pygame.Rect(18,rectY1,10,100)
    paddle2 = pygame.Rect(620,rectY2,10,100)
    ball = pygame.Rect(ballX,ballY,30,30)
    font = pygame.font.SysFont(None, 48)
    #create shapes
    def drawshapes():
        pygame.draw.rect(DISPLAY, WHITE, paddle1)
        pygame.draw.rect(DISPLAY, WHITE, paddle2)
        pygame.draw.rect(DISPLAY, WHITE, ball)
    def drawText(text, font, surface, x, y):
        textobj = font.render(text, 1, TEXTCOLOR)
        textrect = textobj.get_rect()
        textrect.topleft = (x, y)
        surface.blit(textobj, textrect)

    #set up display

    DISPLAY = pygame.display.set_mode((640,480),0,32)
    pygame.display.set_caption('Pong')
    fpsClock = pygame.time.Clock()
    drawText('bruh', font, DISPLAY, (200), (200))
    pygame.display.update

Body:
idk if this really is the loop you are talking about but here it is:

running = True
while running:
    # RGB - Red, Green, Blue
    screen.fill((0, 0, 128 ))
    #background Image
    screen.blit(background, (0, 0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False


问:
Do it only once for all MVC partial view: Is Context.Items (thread) safe?
I have a View which hold a list of items rendered through partials views.

I'd like to be able in the partial view to add a javascript script only once for the whole page.

I read I could use Context.Items to share data (like a boolean ScriptAlreadyIncluded) amongst all (partial) views.

But can I rely on this? Or should I use something else?

My current code (most relevant partial view being ITypedModel.cshtml and AFieldFormula_DirectFieldFormula.cshtm)

Index.cshtml

```<code>@model IEnumerable<MygLogWeb.Classes.MemberField>

@{
    Layout = "~/Views/Shared/_Layout.cshtml";

    var uid = Guid.NewGuid().ToString();
}

@using (Html.BeginForm("Index", "MemberField", FormMethod.Post, new { id = uid }))
{

    @Html.AntiForgeryToken()

    <table class="table none">
        <thead>
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.IsSystem)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.IsVirtual)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Name)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Formula)
                </th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            @Html.EditorFor(model => model)
        </tbody>
        <tfoot>
            <tr>
                <td colspan="5">
                    <input type="button" value="@Resources.Common.Buttons.add" />
                </td>
            </tr>
        </tfoot>
    </table>

    <input type="submit" value="@Resources.Common.Buttons.save"/>
}

<script type="text/javascript">
    new TableEdit("@uid");
</script>
</code>```

EditorTemplates/MemberField.cshtml

```<code>@model MygLogWeb.Classes.MemberField

<tr>
    <td>
        @Html.DisplayFor(model => model.IsSystem)
        @Html.HiddenFor(model => model.IsSystem)
    </td>
    <td>
        @Html.DisplayFor(model => model.IsVirtual)
        @Html.HiddenFor(model => model.IsVirtual)
    </td>
    <td>
        @if (Model.IsSystem)
        {
            @Html.DisplayFor(model => model.Name)
            @Html.HiddenFor(model => model.Name)
        }
        else
        {
            @Html.TextBoxFor(model => model.Name, new { data_focus = "true" })
            @Html.ValidationMessageFor(model => model.Name)
        }
    </td>
    <td>
        @Html.EditorFor(model => model.Formula, "ITypedModel")
    </td>
    <td>
        @if (!Model.IsSystem)
        {
            <input type="button" value="@Resources.Common.Buttons.delete" data-code="delete" />
        }
    </td>
</tr>
</code>```

EditorTemplates/ITypedModel.cshtml

```<code>...
@foreach (var item in items)
{
    <span data-refered-type="@item.Item.Value">
        @if (item.Type.IsSubclassOf(typeof(AFieldFormula)))
        {
            var newModel = item.Item.Selected ? Model : Activator.CreateInstance(item.Type);

            @Html.Partial("~/Views/MemberField/EditorTemplates/AFieldFormula_" + item.Type.Name + ".cshtml", newModel)
        }
    </span>
}
</code>```

EditorTemplates/AFieldFormula_ConstantFormula.cshtml

```<code>@model MygLogWeb.Classes.ConstantFormula

<b>ConstantFormula</b>
@Html.EditorFor(model => model.Constant)
@Html.ValidationMessageFor(model => model.Constant)
</code>```

EditorTemplates/AFieldFormula_DirectFieldFormula.cshtml

```<code>@model MygLogWeb.Classes.DirectFieldFormula

...Build a JSON dictionnary...

<b>DirectFieldFormula</b>
@Html.EditorFor(model => model.Field)
@Html.ValidationMessageFor(model => model.Field)

...Some controls using the JSON dictionnary...
</code>```

The dictionary would be the same for every AFieldFormula_DirectFieldFormula.cshtml view, so I'd like to compute and display it only once per web page.

答:
So, this is kind of an old question, but I found it while trying to solve a recent issue.

According to Microsoft, HttpContext is not thread safe.  The good news is there is a way to implement a reusable solution that would only use HttpContext in the thread controlled by ASP.NET, as recommended by Microsoft.  The main limitation is this method can only keep track of scripts which were added using it, but a script created specifically to add functionality to a partial view should only be used with the partial view, anyway.  See below.

Here is the original place where I left this answer.  It makes use of HttpContext.Current.Items to maintain a singleton-per-request static class containing a dictionary of scripts which have already been included (using this method).

Implement an Html helper extension function which will only load a script once.  (this can work for CSS and other included files, too).

Implement an extension for the HtmlHelper class and a private backing class as a singleton per HttpContext.

```<code>public static class YourHtmlHelperExtensionClass
{
    private class TagSrcAttrTracker
    {
        private TagSrcAttrTracker() { }

        public Dictionary<string, string> sources { get; } = new Dictionary<string, string>();

        public static TagSrcAttrTrackerInstance {
            get {
                IDictionary items = HttpContext.Current.Items;
                const string instanceName = "YourClassInstanceNameMakeSureItIsUniqueInThisDictionary";

                if(!items.Contains(instanceName))
                    items[instanceName] = new TagSrcAttrTracker();

                return items[instanceName] as TagSrcAttrTracker;
            }
        }
    }

    public static MvcHtmlString IncludeScriptOnlyOnce(this HtmlHelper helper, string urlOfScript)
    {
        if(TagSrcAttrTracker.Instance.sources.ContainsKey(urlOfScript))
            return null;

        TagSrcAttrTracker.Instance.sources[urlOfScript] = urlOfScript;

        TagBuilder script = new TagBuilder("script");
        scriptTag.MergeAttribute("src", urlOfScript);

        return MvcHtmlString.Create(script.ToString());
    }
}
</code>```

Then, separate the JavaScript and other code into separate files.

Example .js file contents

```<code>class MyClass{
    myFunction() {
        constructor(divId){
            this._divId = divId
        }

        doSomething() {
            // do something with a div with id == divId
        }
    }
}
</code>```

Example .cshtml file contents for partial view

```<code><link rel="stylesheet" type="text/css" href="~/Content/CustomCSS/MyPartialView.css"/>

<div id="@ViewBag.id">
    Some content!  Yay!
</div>

@Html.IncludeScriptOnlyOnce("/Scripts/CustomScripts/MyPartialView.js")
</code>```

Example .cshtml file that consumes the partial view

```<code>...
<body>
    <h1>Here is some content!</h1>
    @Html.Partial("/Views/MyPartial.cshtml", new ViewDataDictionary() { { "id", "id_1"} })
    @Html.Partial("/Views/MyPartial.cshtml", new ViewDataDictionary() { { "id", "id_2"} })
    @Html.Partial("/Views/MyPartial.cshtml", new ViewDataDictionary() { { "id", "id_3"} })
</body>
<script>
$().ready(
    const id1Functionality = new MyClass("id_1") // forgive the poor naming :-)
    const id2Functionality = new MyClass("id_3")
    const id3Functionality = new MyClass("id_2")

    id1Functionality.doSomething();
    id2Functionality.doSomething();
    id3Functionality.doSomething();
)
</script>
</code>```

The partial view may have been included more than once and the JavaScript is packaged with the partial view, but the .js file is only included in the page once, hence no complaining by the browser that MyClass was declared more than once.

Body:
I have a View which hold a list of items rendered through partials views.

I'd like to be able in the partial view to add a javascript script only once for the whole page.

I read I could use Context.Items to share data (like a boolean ScriptAlreadyIncluded) amongst all (partial) views.

But can I rely on this? Or should I use something else?

My current code (most relevant partial view being ITypedModel.cshtml and AFieldFormula_DirectFieldFormula.cshtm)

Index.cshtml

@model IEnumerable<MygLogWeb.Classes.MemberField>

@{
    Layout = "~/Views/Shared/_Layout.cshtml";

    var uid = Guid.NewGuid().ToString();
}

@using (Html.BeginForm("Index", "MemberField", FormMethod.Post, new { id = uid }))
{

    @Html.AntiForgeryToken()

                    @Html.DisplayNameFor(model => model.IsSystem)

                    @Html.DisplayNameFor(model => model.IsVirtual)

                    @Html.DisplayNameFor(model => model.Name)

                    @Html.DisplayNameFor(model => model.Formula)

            @Html.EditorFor(model => model)

                    <input type="button" value="@Resources.Common.Buttons.add" />

    <input type="submit" value="@Resources.Common.Buttons.save"/>
}

EditorTemplates/MemberField.cshtml

@model MygLogWeb.Classes.MemberField

        @Html.DisplayFor(model => model.IsSystem)
        @Html.HiddenFor(model => model.IsSystem)

        @Html.DisplayFor(model => model.IsVirtual)
        @Html.HiddenFor(model => model.IsVirtual)

        @if (Model.IsSystem)
        {
            @Html.DisplayFor(model => model.Name)
            @Html.HiddenFor(model => model.Name)
        }
        else
        {
            @Html.TextBoxFor(model => model.Name, new { data_focus = "true" })
            @Html.ValidationMessageFor(model => model.Name)
        }

        @Html.EditorFor(model => model.Formula, "ITypedModel")

        @if (!Model.IsSystem)
        {
            <input type="button" value="@Resources.Common.Buttons.delete" data-code="delete" />
        }

EditorTemplates/ITypedModel.cshtml

...
@foreach (var item in items)
{

        @if (item.Type.IsSubclassOf(typeof(AFieldFormula)))
        {
            var newModel = item.Item.Selected ? Model : Activator.CreateInstance(item.Type);

            @Html.Partial("~/Views/MemberField/EditorTemplates/AFieldFormula_" + item.Type.Name + ".cshtml", newModel)
        }

}

EditorTemplates/AFieldFormula_ConstantFormula.cshtml

@model MygLogWeb.Classes.ConstantFormula

ConstantFormula
@Html.EditorFor(model => model.Constant)
@Html.ValidationMessageFor(model => model.Constant)

EditorTemplates/AFieldFormula_DirectFieldFormula.cshtml

@model MygLogWeb.Classes.DirectFieldFormula

...Build a JSON dictionnary...

DirectFieldFormula
@Html.EditorFor(model => model.Field)
@Html.ValidationMessageFor(model => model.Field)

...Some controls using the JSON dictionnary...

The dictionary would be the same for every AFieldFormula_DirectFieldFormula.cshtml view, so I'd like to compute and display it only once per web page.

Body:
So, this is kind of an old question, but I found it while trying to solve a recent issue.

According to Microsoft, HttpContext is not thread safe.  The good news is there is a way to implement a reusable solution that would only use HttpContext in the thread controlled by ASP.NET, as recommended by Microsoft.  The main limitation is this method can only keep track of scripts which were added using it, but a script created specifically to add functionality to a partial view should only be used with the partial view, anyway.  See below.

Here is the original place where I left this answer.  It makes use of HttpContext.Current.Items to maintain a singleton-per-request static class containing a dictionary of scripts which have already been included (using this method).

Implement an Html helper extension function which will only load a script once.  (this can work for CSS and other included files, too).

Implement an extension for the HtmlHelper class and a private backing class as a singleton per HttpContext.

public static class YourHtmlHelperExtensionClass
{
    private class TagSrcAttrTracker
    {
        private TagSrcAttrTracker() { }

        public Dictionary<string, string> sources { get; } = new Dictionary<string, string>();

        public static TagSrcAttrTrackerInstance {
            get {
                IDictionary items = HttpContext.Current.Items;
                const string instanceName = "YourClassInstanceNameMakeSureItIsUniqueInThisDictionary";

                if(!items.Contains(instanceName))
                    items[instanceName] = new TagSrcAttrTracker();

                return items[instanceName] as TagSrcAttrTracker;
            }
        }
    }

    public static MvcHtmlString IncludeScriptOnlyOnce(this HtmlHelper helper, string urlOfScript)
    {
        if(TagSrcAttrTracker.Instance.sources.ContainsKey(urlOfScript))
            return null;

        TagSrcAttrTracker.Instance.sources[urlOfScript] = urlOfScript;

        TagBuilder script = new TagBuilder("script");
        scriptTag.MergeAttribute("src", urlOfScript);

        return MvcHtmlString.Create(script.ToString());
    }
}

Then, separate the JavaScript and other code into separate files.

Example .js file contents

class MyClass{
    myFunction() {
        constructor(divId){
            this._divId = divId
        }

        doSomething() {
            // do something with a div with id == divId
        }
    }
}

Example .cshtml file contents for partial view

<link rel="stylesheet" type="text/css" href="~/Content/CustomCSS/MyPartialView.css"/>

<div id="@ViewBag.id">
    Some content!  Yay!
</div>

@Html.IncludeScriptOnlyOnce("/Scripts/CustomScripts/MyPartialView.js")

Example .cshtml file that consumes the partial view

...
<body>
    <h1>Here is some content!</h1>
    @Html.Partial("/Views/MyPartial.cshtml", new ViewDataDictionary() { { "id", "id_1"} })
    @Html.Partial("/Views/MyPartial.cshtml", new ViewDataDictionary() { { "id", "id_2"} })
    @Html.Partial("/Views/MyPartial.cshtml", new ViewDataDictionary() { { "id", "id_3"} })
</body>
<script>
$().ready(
    const id1Functionality = new MyClass("id_1") // forgive the poor naming :-)
    const id2Functionality = new MyClass("id_3")
    const id3Functionality = new MyClass("id_2")

    id1Functionality.doSomething();
    id2Functionality.doSomething();
    id3Functionality.doSomething();
)
</script>

The partial view may have been included more than once and the JavaScript is packaged with the partial view, but the .js file is only included in the page once, hence no complaining by the browser that MyClass was declared more than once.


问:
Entered company name in Individual Account ( At the time for iphone APP Upload)
Recently I buy a new Individual developer account of $99 and now when I was trying to upload my first app. I got a message i.e.

What is the company or developer name that you want displayed on the App Store for all of your applications?

I have heard somewhere if you have Individual account you cannot enter any company name, you have to enter only profile name.

Is it really true ? Because I didn't enter my name. Instead of I have entered my company name and that is accepted when i clicked submit.

My question is: Will this create problem for me in my developer account ? Will be all my apps rejected ?

答:
If you have an Individual developer account, your real name is always displayed. The iPhone app store app shows only your real name, while iTunes on the computer will display your real name but use your company name to group your apps.

In any case, Apple has a simple and painless process in place to upgrade an Individual account to a Company account (they both cost the same) once you have done the paperwork to turn your company into a legal entity. All you need to do is call the Developer Relations customer service hotline to get the process started.


问:
How do I calculate the rest/modulo of two numbers without the "%" operator?
For example with the following input:

```<code>int num = -100
int divisor = 10
=>  -100 mod 10 = 0   (Edge-case: negative numbers as input)
</code>```

```<code>int num = 300
int divisor = -7
=>300 mod 7 = 6
</code>```

I used this method before but with negative numbers, it´s not working:

```<code>int method(int i, int div){
    return (num - divisor * (num / divisor));
}
</code>```

Expected result :

```<code>-1234, 512 ==> <302>
</code>```

Actual result :

```<code>-1234, 512 ==> <210>
</code>```

Body:
For example with the following input:

int num = -100
int divisor = 10
=>  -100 mod 10 = 0   (Edge-case: negative numbers as input)

int num = 300
int divisor = -7
=>300 mod 7 = 6

I used this method before but with negative numbers, it´s not working:

int method(int i, int div){
    return (num - divisor * (num / divisor));
}

Expected result :

-1234, 512 ==> <302>

Actual result :

-1234, 512 ==> <210>

Body:
The following test proves that your initial implementation provides the same results as original % operator:

static int mod(int n, int m) {
    return n - m * (n / m);
}
// test
int[][] data = {
    {100, 10}, {-100, 10}, {100, -10}, {-100, -10},
    {   5, 3}, {-  5,  3}, {  5, - 3}, {-  5, - 3}
};

Arrays.stream(data)
      .forEach(d -> System.out.printf("%s: %d %% %d = %d mod=%d%n",
               d[0]%d[1] == mod(d[0], d[1]) ? "OK" : "BAD",
               d[0], d[1], d[0]%d[1], mod(d[0], d[1])));

Output:

OK: 100 % 10 = 0 mod=0
OK: -100 % 10 = 0 mod=0
OK: 100 % -10 = 0 mod=0
OK: -100 % -10 = 0 mod=0
OK: 5 % 3 = 2 mod=2
OK: -5 % 3 = -2 mod=-2
OK: 5 % -3 = 2 mod=2
OK: -5 % -3 = -2 mod=-2