答:
Handling input2.json

Since some context-dependent information is required for the second set of requirements corresponding to input2.json, the context cannot be ignored, and so the following solution uses a "drill-down" approach.  The following will be a bit difficult to understand unless you understand foreach, so let me just mention that the approach essentially uses a state variable {counter, page, row} to keep track of the three counters.

```<code>["counter", "page", "row", "#text", "@data", "@fontName", "@fontSize", "@format", "@height", "@type", "@width", "@x", "@y"],
(foreach (.document.page[] | objects) as $page ({page: -1, counter: 0};
  .page += 1
  | foreach ($page | .row[]?) as $row (.row=-1;
    .row += 1
    | foreach ($row | (.column | (if type == "array" then .[] else . end )) | .text | objects) as $x (.;
      .counter += 1
      | .out = [.counter, .page, .row, $x["#text", "@data", "@fontName", "@fontSize", "@format", "@height", "@type", "@width", "@x", "@y"]]
      ; . )
      ; . )
      ; .out )
)
| @tsv
</code>```

This produces the desired TSV except for the very first line of data as that has no row. One way to include the first line is shown in my answer at Relate elements in table form from Json file with jq

Title: Parsing Json file with jq tool

Body:
I Have the following nested json file which I want to parse with jq tool and print in table form like I show at the end

The input.json structure is like this:

{
 "document":{
  "page":[
     {
        "@index":"0",
        "image":{
           "@data":"ABC",
           "@format":"png",
           "@height":"620.00",
           "@type":"base64encoded",
           "@width":"450.00",
           "@x":"85.00",
           "@y":"85.00"
        }
     },
     {
        "@index":"1",
        "row":[
           {
              "column":[
                 {
                    "text":""
                 },
                 {
                    "text":{
                       "#text":"Text1",
                       "@fontName":"Arial",
                       "@fontSize":"12.0",
                       "@height":"12.00",
                       "@width":"71.04",
                       "@x":"121.10",
                       "@y":"83.42"
                    }
                 }
              ]
           },
           {
              "column":[
                 {
                    "text":""
                 },
                 {
                    "text":{
                       "#text":"Text2",
                       "@fontName":"Arial",
                       "@fontSize":"12.0",
                       "@height":"12.00",
                       "@width":"101.07",
                       "@x":"121.10",
                       "@y":"124.82"
                    }
                 }
              ]
           }
        ]
     },
     {
        "@index":"2",
        "row":[
           {
              "column":{
                 "text":{
                    "#text":"Text3",
                    "@fontName":"Arial",
                    "@fontSize":"12.0",
                    "@height":"12.00",
                    "@width":"363.44",
                    "@x":"85.10",
                    "@y":"69.62"
                 }
              }
           },
           {
              "column":{
                 "text":{
                    "#text":"Text4",
                    "@fontName":"Arial",
                    "@fontSize":"12.0",
                    "@height":"12.00",
                    "@width":"382.36",
                    "@x":"85.10",
                    "@y":"83.42"
                 }
              }
           },
           {
              "column":{
                 "text":{
                    "#text":"Text5",
                    "@fontName":"Arial",
                    "@fontSize":"12.0",
                    "@height":"12.00",
                    "@width":"435.05",
                    "@x":"85.10",
                    "@y":"97.22"
                 }
              }
           }
        ]
     },
     {
        "@index":"3"
     }
  ]
 }
}

Following the answers of the following question (Parsing nested json with jq) I've tried this code but doesn't work

$ cat file.json | jq .document.page[].row | ["#text", "@x", "@y"] | @csv

The output I'm trying to get is:

#text @x     @y
Text1 121.10 83.42
Text2 121.10 124.82
Text3 65.10  69.62
Text4 85.10  83.42
Text5 85.10  97.22

How can achieve this?

Thanks

UPDATE

Thanks so much for the help. I've tried with a real file a bit longer.

I was able to adapt the first peak's solution like below:

["#text", "@data", "@fontName", "@fontSize", "@format", "@height", "@type", "@width", "@x", "@y"],
( ..
| objects
| select(has("#text","@data"))
| [.["#text", "@data", "@fontName", "@fontSize", "@format", "@height", "@type", "@width", "@x", "@y"]]
)
| @tsv

and with new input I get this table:

+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| #text         | @data | @fontName | @fontSize | @format | @height | @type         | @width | @x     | @y     |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
|               | ABC   |           |           | png     | 620     | base64encoded | 450    | 85     | 85     |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text ä 1      |       | Tahoma    | 12        |         | 12      |               | 427.79 | 85.1   | 69.62  |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text ¢76      |       | Tahoma    | 12        |         | 12      |               | 270.5  | 85.1   | 690.72 |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text % 5      |       | Tahoma    | 12        |         | 12      |               | 130.84 | 358.86 | 690.72 |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text 7Ç8      |       | Tahoma    | 12        |         | 12      |               | 115.95 | 85.1   | 704.52 |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text • 2 Wñ79 |       | Tahoma    | 8         |         | 8.04    |               | 398.16 | 121.1  | 68.06  |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text          |       | Tahoma    | 12        |         | 12      |               | 101.5  | 85.1   | 83.42  |
|   » 1 A\\\\CÓ |       |           |           |         |         |               |        |        |        |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text 12       |       | Tahoma    | 12        |         | 12      |               | 312.26 | 189.83 | 83.42  |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text 82       |       | Tahoma    | 12        |         | 12      |               | 44.99  | 85.1   | 97.22  |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text 31       |       | Tahoma    | 8         |         | 8.04    |               | 381.83 | 133.1  | 95.66  |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+

If possible, how to add the follwing 3 columns (counter, page and row) to know the corresponding page and row for each line?

The expected output would be like this:

+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| counter | page | row | #text             | @data | @fontName | @fontSize | @format | @height | @type         | @width | @x     | @y     |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 1     | 0    |     |                   | ABC   |           |           | png     | 620     | base64encoded | 450    | 85     | 85     |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 2     | 1    | 0   | Text ä 1          |       | Tahoma    | 12        |         | 12      |               | 427.79 | 85.1   | 69.62  |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 3     | 1    | 1   | Text ¢76          |       | Tahoma    | 12        |         | 12      |               | 270.5  | 85.1   | 690.72 |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 4     | 1    | 1   | Text % 5          |       | Tahoma    | 12        |         | 12      |               | 130.84 | 358.86 | 690.72 |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 5     | 2    | 2   | Text 7Ç8          |       | Tahoma    | 12        |         | 12      |               | 115.95 | 85.1   | 704.52 |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 6     | 2    | 0   | Text • 2 Wñ79     |       | Tahoma    | 8         |         | 8.04    |               | 398.16 | 121.1  | 68.06  |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 7     | 2    | 1   | Text  » 1 A\\\\CÓ |       | Tahoma    | 12        |         | 12      |               | 101.5  | 85.1   | 83.42  |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 8     | 2    | 1   | Text 12           |       | Tahoma    | 12        |         | 12      |               | 312.26 | 189.83 | 83.42  |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 9     | 2    | 2   | Text 82           |       | Tahoma    | 12        |         | 12      |               | 44.99  | 85.1   | 97.22  |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 10    | 2    | 2   | Text 31           |       | Tahoma    | 8         |         | 8.04    |               | 381.83 | 133.1  | 95.66  |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+

This is new more representative input file input2.json.

And seeing the Json structure in image below gives and idea about page number and row number present in json file and values within them.

Body:
Handling input2.json

Since some context-dependent information is required for the second set of requirements corresponding to input2.json, the context cannot be ignored, and so the following solution uses a "drill-down" approach.  The following will be a bit difficult to understand unless you understand foreach, so let me just mention that the approach essentially uses a state variable {counter, page, row} to keep track of the three counters.

["counter", "page", "row", "#text", "@data", "@fontName", "@fontSize", "@format", "@height", "@type", "@width", "@x", "@y"],
(foreach (.document.page[] | objects) as $page ({page: -1, counter: 0};
  .page += 1
  | foreach ($page | .row[]?) as $row (.row=-1;
    .row += 1
    | foreach ($row | (.column | (if type == "array" then .[] else . end )) | .text | objects) as $x (.;
      .counter += 1
      | .out = [.counter, .page, .row, $x["#text", "@data", "@fontName", "@fontSize", "@format", "@height", "@type", "@width", "@x", "@y"]]
      ; . )
      ; . )
      ; .out )
)
| @tsv

This produces the desired TSV except for the very first line of data as that has no row. One way to include the first line is shown in my answer at Relate elements in table form from Json file with jq


来源: stackexchange

问:
Javascript canvas drawing - shape is filled
I am trying to draw a series of circles orbiting a central point, a very, very basic version of this:
https://mgvez.github.io/jsorrery/

I have managed this so far, but the shape is filled, and I'm not sure why. It actually looks pretty cool, but not what I wanted ;)

var origin_x = 200;
var origin_y = 200;

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

class planet {
 constructor(orbital_velocity, orbital_radius, radius) {
  this.orbital_velocity = orbital_velocity;
  this.orbital_radius = orbital_radius;
  this.radius = radius;
  this.draw()
 }

 draw() {
   const theta = t*this.orbital_velocity
   const x  = origin_x + this.orbital_radius*Math.cos(theta)
   const y  = origin_y + this.orbital_radius*Math.sin(theta)
   ctx.arc(x, y, this.radius, 0, 2*Math.PI, 'anticlockwise')
   ctx.fill();
 }
}

let t = 0;
window.setInterval(function(){
 ctx.clearRect(0, 0, canvas.width, canvas.height);
 ctx.beginPath();
 const a = new planet(2*Math.PI, 30, 1 );
 const b = new planet(Math.PI, 50, 1 );
 const c = new planet(0.5*Math.PI, 70, 1 );
 const d = new planet(0.25*Math.PI, 90, 1 );
 t += 0.1;
}, 40);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
  <head>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
  </head>
  <body>
   <div class="container-fluid">
    <div class="row">
     <div class="col text-center">
      <canvas id="canvas" width="400" height="400" />
     </div>
    </div>
   </div>
  </body>
</html></code>```

I've read the docs, but I can't figure out why this is happening... I need the individual circles (arcs) to be filled, not the shape between them...

答:
You need to call ctx.beginPath() and ctx.closePath(), otherwise the canvas thinks you are drawing a complex element/polygon and tries to fill that.

var origin_x = 200;
var origin_y = 200;

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

class planet {
 constructor(orbital_velocity, orbital_radius, radius) {
  this.orbital_velocity = orbital_velocity;
  this.orbital_radius = orbital_radius;
  this.radius = radius;
  this.draw()
 }

 draw() {
   const theta = t*this.orbital_velocity
   const x  = origin_x + this.orbital_radius*Math.cos(theta)
   const y  = origin_y + this.orbital_radius*Math.sin(theta)
    ctx.beginPath();
    ctx.arc(x, y, this.radius, 0, 2*Math.PI, 'anticlockwise')
   ctx.fill();
    ctx.closePath();
 }
}

let t = 0;
window.setInterval(function(){
 ctx.clearRect(0, 0, canvas.width, canvas.height);
 ctx.beginPath();
 const a = new planet(2*Math.PI, 30, 1 );
 const b = new planet(Math.PI, 50, 1 );
 const c = new planet(0.5*Math.PI, 70, 1 );
 const d = new planet(0.25*Math.PI, 90, 1 );
 t += 0.1;
}, 40);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
  <head>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
  </head>
  <body>
   <div class="container-fluid">
    <div class="row">
     <div class="col text-center">
      <canvas id="canvas" width="400" height="400" />
     </div>
    </div>
   </div>
  </body>
</html></code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to draw a series of circles orbiting a central point, a very, very basic version of this:
https://mgvez.github.io/jsorrery/

I have managed this so far, but the shape is filled, and I'm not sure why. It actually looks pretty cool, but not what I wanted ;)

var origin_x = 200;
var origin_y = 200;

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

class planet {
 constructor(orbital_velocity, orbital_radius, radius) {
  this.orbital_velocity = orbital_velocity;
  this.orbital_radius = orbital_radius;
  this.radius = radius;
  this.draw()
 }

 draw() {
   const theta = t*this.orbital_velocity
   const x  = origin_x + this.orbital_radius*Math.cos(theta)
   const y  = origin_y + this.orbital_radius*Math.sin(theta)
   ctx.arc(x, y, this.radius, 0, 2*Math.PI, 'anticlockwise')
   ctx.fill();
 }
}

let t = 0;
window.setInterval(function(){
 ctx.clearRect(0, 0, canvas.width, canvas.height);
 ctx.beginPath();
 const a = new planet(2*Math.PI, 30, 1 );
 const b = new planet(Math.PI, 50, 1 );
 const c = new planet(0.5*Math.PI, 70, 1 );
 const d = new planet(0.25*Math.PI, 90, 1 );
 t += 0.1;
}, 40);

<!DOCTYPE html>

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

      <canvas id="canvas" width="400" height="400" />

I've read the docs, but I can't figure out why this is happening... I need the individual circles (arcs) to be filled, not the shape between them...

Body:
You need to call ctx.beginPath() and ctx.closePath(), otherwise the canvas thinks you are drawing a complex element/polygon and tries to fill that.

var origin_x = 200;
var origin_y = 200;

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

class planet {
 constructor(orbital_velocity, orbital_radius, radius) {
  this.orbital_velocity = orbital_velocity;
  this.orbital_radius = orbital_radius;
  this.radius = radius;
  this.draw()
 }

 draw() {
   const theta = t*this.orbital_velocity
   const x  = origin_x + this.orbital_radius*Math.cos(theta)
   const y  = origin_y + this.orbital_radius*Math.sin(theta)
    ctx.beginPath();
    ctx.arc(x, y, this.radius, 0, 2*Math.PI, 'anticlockwise')
   ctx.fill();
    ctx.closePath();
 }
}

let t = 0;
window.setInterval(function(){
 ctx.clearRect(0, 0, canvas.width, canvas.height);
 ctx.beginPath();
 const a = new planet(2*Math.PI, 30, 1 );
 const b = new planet(Math.PI, 50, 1 );
 const c = new planet(0.5*Math.PI, 70, 1 );
 const d = new planet(0.25*Math.PI, 90, 1 );
 t += 0.1;
}, 40);

<!DOCTYPE html>
<html lang="en">
  <head>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
  </head>
  <body>
   <div class="container-fluid">
    <div class="row">
     <div class="col text-center">
      <canvas id="canvas" width="400" height="400" />
     </div>
    </div>
   </div>
  </body>
</html>


问:
"ValueError: No gradients provided for any variable" when scale_diag of MultivariateNormalDiag() is a Constant
The following is a code snippet which, given a state, generates an action from a state-dependent distribution (prob_policy). Then the weights of the graph are updated according to a loss which is -1 times the probability of that action being selected. In the following example, both the mean (mu) and the covariance (sigma) of the MultivariateNormal are trainable/learned.

```<code>import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp

# make the graph
state = tf.placeholder(tf.float32, (1, 2), name="state")
mu = tf.contrib.layers.fully_connected(
    inputs=state,
    num_outputs=2,
    biases_initializer=tf.ones_initializer)
sigma = tf.contrib.layers.fully_connected(
    inputs=state,
    num_outputs=2,
    biases_initializer=tf.ones_initializer)
sigma = tf.squeeze(sigma)
mu = tf.squeeze(mu)
prob_policy = tfp.distributions.MultivariateNormalDiag(loc=mu, scale_diag=sigma)
action = prob_policy.sample()
picked_action_prob = prob_policy.prob(action)
loss = -tf.log(picked_action_prob)
optimizer = tf.train.AdamOptimizer(learning_rate=0.01)
train_op = optimizer.minimize(loss)

# run the optimizer
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    state_input = np.expand_dims([0.,0.],0)
    _, action_loss = sess.run([train_op, loss], { state: state_input })
    print(action_loss)
</code>```

However, when I replace this line

```<code>prob_policy = tfp.distributions.MultivariateNormalDiag(loc=mu, scale_diag=sigma)
</code>```

with the following line (and comment out the lines which generate the sigma layer and squeeze it)

```<code>prob_policy = tfp.distributions.MultivariateNormalDiag(loc=mu, scale_diag=[1.,1.])
</code>```

I get the following error

```<code>ValueError: No gradients provided for any variable, check your graph for ops that do not support gradients, between variables ["<tf.Variable 'fully_connected/weights:0' shape=(2, 2) dtype=float32_ref>", "<tf.Variable 'fully_connected/biases:0' shape=(2,) dtype=float32_ref>"] and loss Tensor("Neg:0", shape=(), dtype=float32).
</code>```

I don't understand why this is happening. Shouldn't it still be able to take the gradient with respect to the weights in the mu layer? Why does making the covariance of the distribution constant suddenly make it non-differentiable?

System Details:

Tensorflow 1.13.1

Tensorflow Probability 0.6.0

Python 3.6.8

MacOS 10.13.6

答:
I had to change this line

```<code>action = prob_policy.sample()
</code>```

to this line

```<code>action = tf.stop_gradient(prob_policy.sample())
</code>```

If anyone has an explanation for why learning the weights of the covariance makes the weights of the loc differentiable wrt the loss, but making the covariance a constant doesn't, and how this line change contrbutes to that, I would love an explanation! Thanks!

Body:
The following is a code snippet which, given a state, generates an action from a state-dependent distribution (prob_policy). Then the weights of the graph are updated according to a loss which is -1 times the probability of that action being selected. In the following example, both the mean (mu) and the covariance (sigma) of the MultivariateNormal are trainable/learned.

import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp

# make the graph
state = tf.placeholder(tf.float32, (1, 2), name="state")
mu = tf.contrib.layers.fully_connected(
    inputs=state,
    num_outputs=2,
    biases_initializer=tf.ones_initializer)
sigma = tf.contrib.layers.fully_connected(
    inputs=state,
    num_outputs=2,
    biases_initializer=tf.ones_initializer)
sigma = tf.squeeze(sigma)
mu = tf.squeeze(mu)
prob_policy = tfp.distributions.MultivariateNormalDiag(loc=mu, scale_diag=sigma)
action = prob_policy.sample()
picked_action_prob = prob_policy.prob(action)
loss = -tf.log(picked_action_prob)
optimizer = tf.train.AdamOptimizer(learning_rate=0.01)
train_op = optimizer.minimize(loss)

# run the optimizer
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    state_input = np.expand_dims([0.,0.],0)
    _, action_loss = sess.run([train_op, loss], { state: state_input })
    print(action_loss)

However, when I replace this line

prob_policy = tfp.distributions.MultivariateNormalDiag(loc=mu, scale_diag=sigma)

with the following line (and comment out the lines which generate the sigma layer and squeeze it)

prob_policy = tfp.distributions.MultivariateNormalDiag(loc=mu, scale_diag=[1.,1.])

I get the following error

ValueError: No gradients provided for any variable, check your graph for ops that do not support gradients, between variables ["<tf.Variable 'fully_connected/weights:0' shape=(2, 2) dtype=float32_ref>", "<tf.Variable 'fully_connected/biases:0' shape=(2,) dtype=float32_ref>"] and loss Tensor("Neg:0", shape=(), dtype=float32).

I don't understand why this is happening. Shouldn't it still be able to take the gradient with respect to the weights in the mu layer? Why does making the covariance of the distribution constant suddenly make it non-differentiable?

System Details:

Tensorflow 1.13.1

Tensorflow Probability 0.6.0

Python 3.6.8

MacOS 10.13.6

Body:
I had to change this line

action = prob_policy.sample()

to this line

action = tf.stop_gradient(prob_policy.sample())

If anyone has an explanation for why learning the weights of the covariance makes the weights of the loc differentiable wrt the loss, but making the covariance a constant doesn't, and how this line change contrbutes to that, I would love an explanation! Thanks!


问:
I get 'Error: '\U' used without hex digits in character string starting ""C:\U"' when starting R
I have the following problem when starting RStudio and when I try to compile a PDF from a .rnw format:

Error: '\U' used without hex digits in character string starting ""C:\U"
```
<p>When starting RStudio or just R, this is what is inside my console:</p>
<pre class="lang-none prettyprint-override"><code>R version 3.4.0 (2017-04-21) -- "You Stupid Darkness"
Copyright (C) 2017 The R Foundation for Statistical Computing
Platform: x86_64-w64-mingw32/x64 (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

Global .Rprofile loaded!

Error: '\U' used without hex digits in character string starting ""C:\U"

And this happens when I try to compile a PDF:

Global .Rprofile loaded!

Error: '\U' used without hex digits in character string starting ""C:\U"
Execution halted
</code>```

This kind of appeared from one day to another, and I am not sure what has changed. I tried updating RStudio and my R version, but it did not help. I am running R on Windows.

How can I fix this issue?

答:
Open the CSV file and save as the file to your "My Documents". Then use this:

```<code>[MyData <- read.csv("Data.csv",header = TRUE)]
</code>```

If it’s text, just change read.csv to read.text.

Body:
I have the following problem when starting RStudio and when I try to compile a PDF from a .rnw format:

Error: '\U' used without hex digits in character string starting ""C:\U"

When starting RStudio or just R, this is what is inside my console:

R version 3.4.0 (2017-04-21) -- "You Stupid Darkness"
Copyright (C) 2017 The R Foundation for Statistical Computing
Platform: x86_64-w64-mingw32/x64 (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

Global .Rprofile loaded!

Error: '\U' used without hex digits in character string starting ""C:\U"

And this happens when I try to compile a PDF:

Global .Rprofile loaded!

Error: '\U' used without hex digits in character string starting ""C:\U"
Execution halted

This kind of appeared from one day to another, and I am not sure what has changed. I tried updating RStudio and my R version, but it did not help. I am running R on Windows.

How can I fix this issue?

Body:
Open the CSV file and save as the file to your "My Documents". Then use this:

[MyData <- read.csv("Data.csv",header = TRUE)]

If it’s text, just change read.csv to read.text.


问:
Centering Buttons With Bootstrap 4
Hi I have this screen:

And it needs to be viewable on phones, tablets and desktops.  Uses BootStrap 4

What I want is a maximum width for each button AND for the buttons to be centered on the screen.

Here is my html/css:

```<code><!DOCTYPE html>
<html lang="en">

<head>
<title>Cacophonator Setup</title>
<meta charset="utf-8">
<meta name="viewport" content="max-width=device-max-width, initial-scale=1">
<link rel="stylesheet" href="/static/css/bootstrap.min.css">
<style> a { max-width: 400px; } </style>
</head>

<body>
{{template "navbar"}}

<div class="container">
        <div class="row">
            <div class="col-xs-12 w-100" >
                <a class="btn btn-primary btn-block mt-3" href="/camera" role="button">Camera</a>
            </div>
        </div>
        <div class="row">
            <div class="col-xs-12 w-100" >
                <a class="btn btn-primary btn-block mt-3" href="/disk-memory" role="button">Disk & Memory</a>
            </div>
        </div>
        <div class="row">
            <div class="col-xs-12 w-100" >
                <a class="btn btn-primary btn-block mt-3" href="/network" role="button">Network</a>
            </div>
        </div>
        <div class="row">
            <div class="col-xs-12 w-100" >
                <a class="btn btn-primary btn-block mt-3" href="/wifi-networks" role="button">WiFi Networks</a>
            </div>
        </div>
        <div class="row">
            <div class="col-xs-12 w-100" >
                <a class="btn btn-primary btn-block mt-3" href="/speaker" role="button">Speaker Test</a>
            </div>
        </div>
        <div class="row">
            <div class="col-xs-12 w-100" >
                <a class="btn btn-primary btn-block mt-3" href="/location" role="button">Location</a>
            </div>
        </div>

</div>

<script src="/static/js/jquery-3.3.1.slim.min.js"></script>
<script src="/static/js/bootstrap.min.js"></script>

<script>
    $(document).ready(function(){
        $("#btnBack").hide();
    });
</script>
</code>```

Any help would be much appreciated, thanks.

答:
Just add this styles:

```<code><style>
.row div{
    display: flex;
    justify-content: center;
}

.btn-block{
    max-width: 400px;
}
</style>
</code>```

Result:

<title>Cacophonator Setup</title>
<meta charset="utf-8">
<meta name="viewport" content="max-width=device-max-width, initial-scale=1">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

{{template "navbar"}}

                Camera

                Disk & Memory

                Network

                WiFi Networks

                Speaker Test

                Location

```

Title: Centering Buttons With Bootstrap 4

Body:
Hi I have this screen:

And it needs to be viewable on phones, tablets and desktops.  Uses BootStrap 4

What I want is a maximum width for each button AND for the buttons to be centered on the screen.

Here is my html/css:

<!DOCTYPE html>

<title>Cacophonator Setup</title>
<meta charset="utf-8">
<meta name="viewport" content="max-width=device-max-width, initial-scale=1">
<link rel="stylesheet" href="/static/css/bootstrap.min.css">

{{template "navbar"}}

                Camera

                Disk & Memory

                Network

                WiFi Networks

                Speaker Test

                Location

Any help would be much appreciated, thanks.

Body:
Just add this styles:

<style>
.row div{
    display: flex;
    justify-content: center;
}

.btn-block{
    max-width: 400px;
}
</style>

Result:

<head>
<title>Cacophonator Setup</title>
<meta charset="utf-8">
<meta name="viewport" content="max-width=device-max-width, initial-scale=1">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<style>
.row div{
  display: flex;
  justify-content: center;
}

.btn-block{
  max-width: 400px;
}
</style>
</head>

<body>
{{template "navbar"}}

<div class="container">
        <div class="row">
            <div class="col-xs-12 w-100" >
                <a class="btn btn-primary btn-block mt-3" href="/camera" role="button">Camera</a>
            </div>
        </div>
        <div class="row">
            <div class="col-xs-12 w-100" >
                <a class="btn btn-primary btn-block mt-3" href="/disk-memory" role="button">Disk &amp; Memory</a>
            </div>
        </div>
        <div class="row">
            <div class="col-xs-12 w-100" >
                <a class="btn btn-primary btn-block mt-3" href="/network" role="button">Network</a>
            </div>
        </div>
        <div class="row">
            <div class="col-xs-12 w-100" >
                <a class="btn btn-primary btn-block mt-3" href="/wifi-networks" role="button">WiFi Networks</a>
            </div>
        </div>
        <div class="row">
            <div class="col-xs-12 w-100" >
                <a class="btn btn-primary btn-block mt-3" href="/speaker" role="button">Speaker Test</a>
            </div>
        </div>
        <div class="row">
            <div class="col-xs-12 w-100" >
                <a class="btn btn-primary btn-block mt-3" href="/location" role="button">Location</a>
            </div>
        </div>

</div>

<script src="/static/js/jquery-3.3.1.slim.min.js"></script>
<script src="/static/js/bootstrap.min.js"></script>


问:
Can't understand why this simple recursion begins to work and then crashes
I was doing some trick questions about C++ and I run on similar code to this then I modified it to see what will happen.

I don't understand why at first place this recursion is working (it's printing values from 2 to 4764) and then suddenly it throws exception.

I don't understand also why I can say return in void function and actually return something other than "return;"

Can anyone explain this two problems?

```<code>#include<iostream>
using namespace std;

void function(int& a){
    a++;
    cout << a << endl;
    return function(a);
}

void main() {

    int b = 2;
    function(b);

    system("pause>0");
}
</code>```

答:
The comments have correctly identified that your infinite recursion is causing a stack overflow - each new call to the same function is taking up more RAM, until you use up the amount allocated for the program (the default C++ stack size varies greatly by environment, and anywhere from 10s kB on old systems to 10+ MB on the upper end).The comments have correctly identified that your infinite recursion is causing a stack overflow - the space amount allocated for this purpose (the default C++ stack size varies greatly by environment, and anywhere from 10s kB on old systems to 10+ MB on the upper end). While the function itself is doing very little in terms of memory, the stack frames (which keep track of which function called which other ongoing function with what parameters) can take up quite a lot.

While useful for certain data structures, recursive programs should not need to go several thousand layers deep and usually add a stop condition (in this case, even checking whether a > some_limit) to identify the point where they have gone to deep and need to stop adding more things to the stack (plain return;).

In this case, the exact same output can be achieved with a simple for loop, so I guess these trick questions are purely experimental.

Body:
I was doing some trick questions about C++ and I run on similar code to this then I modified it to see what will happen.

I don't understand why at first place this recursion is working (it's printing values from 2 to 4764) and then suddenly it throws exception.

I don't understand also why I can say return in void function and actually return something other than "return;"

Can anyone explain this two problems?

#include<iostream>
using namespace std;

void function(int& a){
    a++;
    cout << a << endl;
    return function(a);
}

void main() {

    int b = 2;
    function(b);

    system("pause>0");
}


问:
Why does this acquire and release memory fence not give a consistent value?
im just exploring the use of acquire and release memory fences and  dont understand why i get the value output to zero sometimes and not the value of 2 all the time

I ran the program a number of times , and assumed the atomic store before the release barrier and the atomic load after the acquire barrier would ensure the values always would synchronise

```<code>#include <iostream>
#include <thread>
#include <atomic>

std::atomic<int>x;

void write()
{

    x.store(2,std::memory_order_relaxed);

    std::atomic_thread_fence(std::memory_order_release);

}

void read()
{

    std::atomic_thread_fence(std::memory_order_acquire);

    // THIS DOES NOT GIVE THE EXPECTED VALUE OF 2 SOMETIMES
    std::cout<<x.load(std::memory_order_relaxed)<<std::endl;

}

int main()
{

std::thread t1(write);
std::thread t2(read);
t1.join();
t2.join();
return 0;
}
</code>```

the atomic varible x gives a value of 0 sometimes

答:
Looks like you misuse the fence. You are trying to use it as a mutex, right? If you expect the code to output 2 always, you just think that the load operation would never be executed before the save one. But that is not what memory fence does, that is what the synchronization primitives do.

The fences are much trickier and they just don't allow compiler/processor to reorder certain types of commands within one thread. At the end of the day the order of execution of two separate threads is undefined.

Body:
im just exploring the use of acquire and release memory fences and  dont understand why i get the value output to zero sometimes and not the value of 2 all the time

I ran the program a number of times , and assumed the atomic store before the release barrier and the atomic load after the acquire barrier would ensure the values always would synchronise

#include <iostream>
#include <thread>
#include <atomic>

std::atomic<int>x;

void write()
{

    x.store(2,std::memory_order_relaxed);

    std::atomic_thread_fence(std::memory_order_release);

}

void read()
{

    std::atomic_thread_fence(std::memory_order_acquire);

    // THIS DOES NOT GIVE THE EXPECTED VALUE OF 2 SOMETIMES
    std::cout<<x.load(std::memory_order_relaxed)<<std::endl;

}

int main()
{

std::thread t1(write);
std::thread t2(read);
t1.join();
t2.join();
return 0;
}

the atomic varible x gives a value of 0 sometimes


问:
variables in the flash scope don't stay alive in Google Chrome
When a user tries to access a page in the administration controllers (mostly CRUD stuff), he is being redirected to the login page. And, if the credentials is correct and he is indeed an administrator, he is begin redirected to the page he wanted to access in the previous request.

Whenever someone tries to access a forbidden page he is being redirected to the following controller:

```<code>    public static void login(String returnUrl) throws Throwable {
    Http.Cookie remember = request.cookies.get("rememberme");
    flash.put("url",returnUrl);
    if (remember != null && remember.value.indexOf("-") > 0) {
        String sign = remember.value.substring(0, remember.value.indexOf("-"));
        String username = remember.value.substring(remember.value.indexOf("-") + 1);
        if (Crypto.sign(username).equals(sign)) {
            session.put("username", username);
            redirectToOriginalURL(returnUrl);
        }
    }
    flash.keep();
    render();
}
</code>```

Which executes the authenticte(...) method:

```<code>public static void authenticate(@Required String username, String password, boolean remember, String returnUrl) throws Throwable {
    // Check tokens
    Boolean allowed = false;
    // This is the official method name
    allowed = (Boolean) Security.invoke("authenticate", username, password);
    if (validation.hasErrors() || !allowed) {
        flash.keep("url");
        flash.error("secure.error");
        params.flash();
        login(returnUrl);
    }
    // Mark user as connected
    session.put("username", username);
    // Remember if needed
    if (remember) {
        response.setCookie("rememberme", Crypto.sign(username) + "-" + username, "30d");
    }
    // Redirect to the original URL (or /)
    flash.keep("url");
    redirectToOriginalURL(returnUrl);
}
</code>```

Note the String returnUrl in the parameter list. This controller is always called in the view with the response.url value.

The redirectToOriginalURL() is a method that receives a returnUrl in the parameter or in the flash scope.

```<code>static void redirectToOriginalURL(String returnUrl) throws Throwable {
    if(returnUrl==null) returnUrl = flash.get("url");
    if (returnUrl == null) {
        returnUrl = "/";
    }
    redirect(returnUrl);
}
</code>```

This works fine in Firefox and Internet Explorer. But when I try to execute this in Google Chrome, the returnUrl is null. Is this a known issue, or am I doing something terribly wrong?

There are no special requests or anything. The url, when redirected from the unaccessible page (localhost:9000/admin) is http://localhost:9000/account?returnUrl=%2Fadmin. So nothing wrong there...

The error must therefore lie withing the authenticate controller, that seems to be unable to pass arguments to the redirectToOriginalURL method. But, then again, only in Google Chrome.

Suggestions?

答:
I got it working this way:

Make sure that checkAccess method calls login method with current url:

```<code>static void checkAccess() throws Throwable {
    // Authent
    if (!session.contains("username")) {
        login(request.method.equals("GET") ? request.url : "/");
    }
}
</code>```

Then in login.html view add the hidden field which is the param you already passed to login method:

```<code>#{form @authenticate()}
<input type="hidden" name="returnUrl" value="${params.returnUrl}">
...
#{/form}
</code>```

Or add returnUrl param directly to form.action:

```<code>#{form @authenticate().add("returnUrl", params.returnUrl)}
</code>```

That's it. And you don't need flash scope.

ContentLicense: CC BY-SA 3.0

Body:
When a user tries to access a page in the administration controllers (mostly CRUD stuff), he is being redirected to the login page. And, if the credentials is correct and he is indeed an administrator, he is begin redirected to the page he wanted to access in the previous request.

Whenever someone tries to access a forbidden page he is being redirected to the following controller:

    public static void login(String returnUrl) throws Throwable {
    Http.Cookie remember = request.cookies.get("rememberme");
    flash.put("url",returnUrl);
    if (remember != null && remember.value.indexOf("-") > 0) {
        String sign = remember.value.substring(0, remember.value.indexOf("-"));
        String username = remember.value.substring(remember.value.indexOf("-") + 1);
        if (Crypto.sign(username).equals(sign)) {
            session.put("username", username);
            redirectToOriginalURL(returnUrl);
        }
    }
    flash.keep();
    render();
}

Which executes the authenticte(...) method:

public static void authenticate(@Required String username, String password, boolean remember, String returnUrl) throws Throwable {
    // Check tokens
    Boolean allowed = false;
    // This is the official method name
    allowed = (Boolean) Security.invoke("authenticate", username, password);
    if (validation.hasErrors() || !allowed) {
        flash.keep("url");
        flash.error("secure.error");
        params.flash();
        login(returnUrl);
    }
    // Mark user as connected
    session.put("username", username);
    // Remember if needed
    if (remember) {
        response.setCookie("rememberme", Crypto.sign(username) + "-" + username, "30d");
    }
    // Redirect to the original URL (or /)
    flash.keep("url");
    redirectToOriginalURL(returnUrl);
}

Note the String returnUrl in the parameter list. This controller is always called in the view with the response.url value.

The redirectToOriginalURL() is a method that receives a returnUrl in the parameter or in the flash scope.

static void redirectToOriginalURL(String returnUrl) throws Throwable {
    if(returnUrl==null) returnUrl = flash.get("url");
    if (returnUrl == null) {
        returnUrl = "/";
    }
    redirect(returnUrl);
}

This works fine in Firefox and Internet Explorer. But when I try to execute this in Google Chrome, the returnUrl is null. Is this a known issue, or am I doing something terribly wrong?

There are no special requests or anything. The url, when redirected from the unaccessible page (localhost:9000/admin) is http://localhost:9000/account?returnUrl=%2Fadmin. So nothing wrong there...

The error must therefore lie withing the authenticate controller, that seems to be unable to pass arguments to the redirectToOriginalURL method. But, then again, only in Google Chrome.

Suggestions?

Body:
I got it working this way:

Make sure that checkAccess method calls login method with current url:

static void checkAccess() throws Throwable {
    // Authent
    if (!session.contains("username")) {
        login(request.method.equals("GET") ? request.url : "/");
    }
}

Then in login.html view add the hidden field which is the param you already passed to login method:

#{form @authenticate()}
<input type="hidden" name="returnUrl" value="${params.returnUrl}">
...
#{/form}

Or add returnUrl param directly to form.action:

#{form @authenticate().add("returnUrl", params.returnUrl)}

That's it. And you don't need flash scope.


问:
Python Sort Multidimensional Array
I need to sort an array of arrays by a specific element

This is an array:

```<code>arr=
[0, [71, 554, 258, 793]]
[1, [61, 415, 148, 593]]
[2, [91, 145, 658, 893]]
</code>```

I need to be able to sort it by arr[0][0] as well as by any element from the internal array like arr[0][1] or arr[0][2]

currently, I'm able to sort it by using key=itemgetter(1)
where: itemgetter(1) - is second element of array [0, [71, 554, 258, 793]]
in this cese = 71

```<code>from operator import itemgetter
array = sorted(array, key=itemgetter(1))
print(*array[:], sep="\n")
</code>```

how to sort this array by any element from the internal array [71, 554, 258, 793]?

so if I'm sorting by the second element from internal array output should be like this: (column 145,  415,  554)

```<code>arr=
[2, [91, 145, 658, 893]]
[1, [61, 415, 148, 593]]
[0, [71, 554, 258, 793]]
</code>```

if I'm sorting by the third element from internal array output should be like this: (column 148,  258,  658)

```<code>arr=
[1, [61, 415, 148, 593]]
[0, [71, 554, 258, 793]]
[2, [91, 145, 658, 893]]
</code>```

this is kinda similar to this question: Python Sort Multidimensional Array Based on 2nd Element of Subarray

答:
Just define a function that decides on the key to use.
You can use a partial function to create this function based on the key index</p>

```<code>from functools import partial

def sort_key(si, x):
    return x[1][si]

sort_index = 1  # or 1 or 2

partial_sort_key = partial(sort_key, sort_index)

print(sorted(arr, key=partial_sort_key))
</code>```

Title: Python Sort Multidimensional Array

Body:
I need to sort an array of arrays by a specific element

This is an array:

arr=
[0, [71, 554, 258, 793]]
[1, [61, 415, 148, 593]]
[2, [91, 145, 658, 893]]

I need to be able to sort it by arr[0][0] as well as by any element from the internal array like arr[0][1] or arr[0][2]

currently, I'm able to sort it by using key=itemgetter(1)
where: itemgetter(1) - is second element of array [0, [71, 554, 258, 793]]
in this cese = 71

from operator import itemgetter
array = sorted(array, key=itemgetter(1))
print(*array[:], sep="\n")

how to sort this array by any element from the internal array [71, 554, 258, 793]?

so if I'm sorting by the second element from internal array output should be like this: (column 145,  415,  554)

arr=
[2, [91, 145, 658, 893]]
[1, [61, 415, 148, 593]]
[0, [71, 554, 258, 793]]

if I'm sorting by the third element from internal array output should be like this: (column 148,  258,  658)

arr=
[1, [61, 415, 148, 593]]
[0, [71, 554, 258, 793]]
[2, [91, 145, 658, 893]]

this is kinda similar to this question: Python Sort Multidimensional Array Based on 2nd Element of Subarray

Body:
Just define a function that decides on the key to use.
You can use a partial function to create this function based on the key index

from functools import partial

def sort_key(si, x):
    return x[1][si]

sort_index = 1  # or 1 or 2

partial_sort_key = partial(sort_key, sort_index)

print(sorted(arr, key=partial_sort_key))


问:
Is it normal in scipy.optimise?
I want to optimise my portfolio using Markowitz theory (risk minimization by the Markowitz method for a given income = 15%) and Scipy.minimize

I have risk function

```<code>def objective(x):
    x1=x[0];x2=x[1];x3=x[2]; x4=x[3]
    return 1547.87020*x1**2 + 125.26258*x1*x2 + 1194.3433*x1*x3 + 63.6533*x1*x4  \
    + 27.3176649*x2**2 + 163.28848*x2*x3 + 4.829816*x2*x4 \
    + 392.11819*x3**2 + 56.50518*x3*x4 \
    + 34.484063*x4**2
</code>```

Sum of parts of stocks(in %) = 1

```<code>def constraint1(x):
    return (x[0]+x[1]+x[2]+x[3]-1.0)
</code>```

Income function with restriction

```<code>def constraint2(x):
    return (-1.37458*x[0] + 0.92042*x[1] + 5.06189*x[2] + 0.35974*x[3] - 15.0)
</code>```

And I test it using:

```<code>x0=[0,1,1,0] #Initial value
b=(0.0,1.0)
bnds=(b,b,b,b)
con1={'type':'ineq','fun':constraint1}
con2={'type':'eq','fun':constraint2}
cons=[con1,con2]
sol=minimize(objective,x0,method='SLSQP',\
             bounds=bnds,constraints=cons)
</code>```

And my result is:

```<code>     fun: 678.5433939
     jac: array([1383.25920868,  222.75363159, 1004.03005219,  130.30312347])
 message: 'Positive directional derivative for linesearch'
    nfev: 216
     nit: 20
    njev: 16
  status: 8
 success: False
       x: array([0., 1., 1., 1.])
</code>```

But how? Sum of parts of portfolio cant be more than 1(now parts of stock 2=stock3=stock4=100%). Its constraint1.  Where is problem?

答:
The output says "success: False"
So it is telling you that it failed to find a solution to the problem.

Also, why did you put
con1={'type':'ineq','fun':constraint1}

Don't you want
con1={'type':'eq','fun':constraint1}

I got success using method='BFGS'

Title: Is it normal in scipy.optimise?

Body:
I want to optimise my portfolio using Markowitz theory (risk minimization by the Markowitz method for a given income = 15%) and Scipy.minimize

I have risk function

def objective(x):
    x1=x[0];x2=x[1];x3=x[2]; x4=x[3]
    return 1547.87020*x1**2 + 125.26258*x1*x2 + 1194.3433*x1*x3 + 63.6533*x1*x4  \
    + 27.3176649*x2**2 + 163.28848*x2*x3 + 4.829816*x2*x4 \
    + 392.11819*x3**2 + 56.50518*x3*x4 \
    + 34.484063*x4**2

Sum of parts of stocks(in %) = 1

def constraint1(x):
    return (x[0]+x[1]+x[2]+x[3]-1.0)

Income function with restriction

def constraint2(x):
    return (-1.37458*x[0] + 0.92042*x[1] + 5.06189*x[2] + 0.35974*x[3] - 15.0)

And I test it using:

x0=[0,1,1,0] #Initial value
b=(0.0,1.0)
bnds=(b,b,b,b)
con1={'type':'ineq','fun':constraint1}
con2={'type':'eq','fun':constraint2}
cons=[con1,con2]
sol=minimize(objective,x0,method='SLSQP',\
             bounds=bnds,constraints=cons)

And my result is:

     fun: 678.5433939
     jac: array([1383.25920868,  222.75363159, 1004.03005219,  130.30312347])
 message: 'Positive directional derivative for linesearch'
    nfev: 216
     nit: 20
    njev: 16
  status: 8
 success: False
       x: array([0., 1., 1., 1.])

But how? Sum of parts of portfolio cant be more than 1(now parts of stock 2=stock3=stock4=100%). Its constraint1.  Where is problem?


问:
Hide a component when clicked outside
What would be the right way to handle a click outside of a single component that is supposed to hide this component?

Example of such component might be a dropdown menu, a datepicker and the like. We typically expect them to hide when we click outside. But to do so, it seems like we have to perform some "impure" hacks that I'm not sure how to avoid in FRP style.

I searched for relevant React examples for ideas and found this but they all seem to rely on attaching callbacks to global objects that then modify internal component's state.

答:
A bit late to the party here, but I was struggling with exactly the same problem and the elm community on slack suggested a nice way of detecting click outside an element (let's say, a dropdown).

The idea is that you can attach a global listener to mousedown via BrowserEvents.onMouseDown and pass it a custom decoder that would decode target DOM node from the event object. By "decoding DOM node" I mean decoding only the id and parentNode properties of the node. parentNode will allow recursively travers the DOM tree and for each node check whether its id is the same as the id of the dropdown.

The code for this (in elm 0.19) looks like this:

```<code>-- the result answers the question: is the node outside of the dropdown?
isOutsideDropdown : String -> Decode.Decoder Bool
isOutsideDropdown dropdownId =
    Decode.oneOf
        [ Decode.field "id" Decode.string
            |> Decode.andThen
                (\id ->
                    if dropdownId == id then
                        -- found match by id
                        Decode.succeed False

                    else
                        -- try next decoder
                        Decode.fail "continue"
                )
        , Decode.lazy
            (\_ -> isOutsideDropdown dropdownId |> Decode.field "parentNode")

        -- fallback if all previous decoders failed
        , Decode.succeed True
        ]

-- sends message Close if target is outside the dropdown
outsideTarget : String -> Decode.Decoder Msg
outsideTarget dropdownId =
    Decode.field "target" (isOutsideDropdown "dropdown")
        |> Decode.andThen
            (\isOutside ->
                if isOutside then
                    Decode.succeed Close

                else
                    Decode.fail "inside dropdown"
            )

-- subscribes to the global mousedown
subscriptions : Model -> Sub Msg
subscriptions _ =
   Browser.Events.onMouseDown (outsideTarget "dropdown")
</code>```

The code uses Json-Decode package that needs to be installed via elm install elm/json.

I also wrote an article explaining in details how this works, and have an example of a dropdown on github.

Title: Hide a component when clicked outside

Body:
A bit late to the party here, but I was struggling with exactly the same problem and the elm community on slack suggested a nice way of detecting click outside an element (let's say, a dropdown).

The idea is that you can attach a global listener to mousedown via BrowserEvents.onMouseDown and pass it a custom decoder that would decode target DOM node from the event object. By "decoding DOM node" I mean decoding only the id and parentNode properties of the node. parentNode will allow recursively travers the DOM tree and for each node check whether its id is the same as the id of the dropdown.

The code for this (in elm 0.19) looks like this:

-- the result answers the question: is the node outside of the dropdown?
isOutsideDropdown : String -> Decode.Decoder Bool
isOutsideDropdown dropdownId =
    Decode.oneOf
        [ Decode.field "id" Decode.string
            |> Decode.andThen
                (\id ->
                    if dropdownId == id then
                        -- found match by id
                        Decode.succeed False

                    else
                        -- try next decoder
                        Decode.fail "continue"
                )
        , Decode.lazy
            (\_ -> isOutsideDropdown dropdownId |> Decode.field "parentNode")

        -- fallback if all previous decoders failed
        , Decode.succeed True
        ]

-- sends message Close if target is outside the dropdown
outsideTarget : String -> Decode.Decoder Msg
outsideTarget dropdownId =
    Decode.field "target" (isOutsideDropdown "dropdown")
        |> Decode.andThen
            (\isOutside ->
                if isOutside then
                    Decode.succeed Close

                else
                    Decode.fail "inside dropdown"
            )

-- subscribes to the global mousedown
subscriptions : Model -> Sub Msg
subscriptions _ =
   Browser.Events.onMouseDown (outsideTarget "dropdown")

The code uses Json-Decode package that needs to be installed via elm install elm/json.

I also wrote an article explaining in details how this works, and have an example of a dropdown on github.


问:
How to search in ngFor results?
I have a JSON object and I need to iterate it and include a search functionality that displays the key and values searched in that key.

I achieved this Using a pipe and by looping over keys and its values.

COMPONENT.HTML:

```<code><input type="text" class="form-control" placeholder = "Search"[(ngModel)] = "query" id = "listSearch"  #search >

      <ul>
      <li * ngFor="let key of objectKey()" >
        <span>{{ key }}</span>
          < table >
          <tr * ngFor="let item of (testData[key] | LockFilter:'appName': search.value) as result" >
            <td>{{ item.appName }}</td>
              < /tr>
              < /table>
              < /li>
              < /ul>
</code>```

COMPONENT.TS:

```<code>testData = {
  "MyCat1": [
    {
      "appName": "Myapp1",
      "appCatName": "MyCat1"
    },
    {
      "appName": "Myapp2",
      "appCatName": "MyCat1"
    }
  ],
  "MyCat2": [
    {
      "appName": "Myapp3",
      "appCatName": "MyCat2"
    },
    {
      "appName": "Myapp4",
      "appCatName": "MyCat2"
    }
  ]
}
objectKey() {
  return Object.keys(this.testData);
}
</code>```

PIPE.TS:

```<code>transform(items: any[], field: string, value: string): any[] {

  if (!items) return [];
  if (!value) return items;

  return items.filter(str => {
    return str[field].toLowerCase().includes(value.toLowerCase());
  });

}
</code>```

Expected Results BEFORE SEARCH:
  MyCat1:
  Myapp1
  Myapp2

MyCat2:
  Myapp3
  Myapp4

AFTER SEARCH: (search string '1')
  MyCat1:
  Myapp1

Current Output Image

答:
Try this

```<code>  // check if exists and will return the keys
  objectKey(value) {
    return Object.entries(this.testData)
      .filter(data=> (data[1].filter(item=> item[value].includes(this.search)).length))
      .map([KEY, VAL] => KEY)
  }
</code>```

in HTML (the same code)

```<code>  <ul>
    <li *ngFor="let key of objectKey('appName')"  >
      <span   >{{ key }}</span>
        <table>
          <tr *ngFor="let  item of (testData[key] | LockFilter:'appName': search) as result" >
              <td >   {{ item.appName }}</td>
          </tr>
        </table>
    </li>
  </ul>
</code>```

Working Demo

Title: How to search in ngFor results?

Body:
I have a JSON object and I need to iterate it and include a search functionality that displays the key and values searched in that key.

I achieved this Using a pipe and by looping over keys and its values.

COMPONENT.HTML:

<input type="text" class="form-control" placeholder = "Search"[(ngModel)] = "query" id = "listSearch"  #search >

        {{ key }}

            {{ item.appName }}

COMPONENT.TS:

testData = {
  "MyCat1": [
    {
      "appName": "Myapp1",
      "appCatName": "MyCat1"
    },
    {
      "appName": "Myapp2",
      "appCatName": "MyCat1"
    }
  ],
  "MyCat2": [
    {
      "appName": "Myapp3",
      "appCatName": "MyCat2"
    },
    {
      "appName": "Myapp4",
      "appCatName": "MyCat2"
    }
  ]
}
objectKey() {
  return Object.keys(this.testData);
}

PIPE.TS:

transform(items: any[], field: string, value: string): any[] {

  if (!items) return [];
  if (!value) return items;

  return items.filter(str => {
    return str[field].toLowerCase().includes(value.toLowerCase());
  });

}

Expected Results BEFORE SEARCH:
  MyCat1:
  Myapp1
  Myapp2

MyCat2:
  Myapp3
  Myapp4

AFTER SEARCH: (search string '1')
  MyCat1:
  Myapp1

Current Output Image

Body:
Try this

  // check if exists and will return the keys
  objectKey(value) {
    return Object.entries(this.testData)
      .filter(data=> (data[1].filter(item=> item[value].includes(this.search)).length))
      .map([KEY, VAL] => KEY)
  }

in HTML (the same code)

  <ul>
    <li *ngFor="let key of objectKey('appName')"  >
      <span   >{{ key }}</span>
        <table>
          <tr *ngFor="let  item of (testData[key] | LockFilter:'appName': search) as result" >
              <td >   {{ item.appName }}</td>
          </tr>
        </table>
    </li>
  </ul>

Working Demo


问:
iOS ArcGIS.framework too large When making ipa File. How to reduce the size of iap file
I am maintaining an application with ArcGIS.framework for iOS.When am creating an .ipa files its file size is very large[92 mb] . i have to reduce the size of an .ipa file  to bellow 50 mb.</p>

答:
The Runtime will add about 70MB to your app. Note that this compresses down so the over-the-air download size may be much smaller (perhaps about 25-30MB).

Please see https://stackoverflow.com/a/50594322/1416253 for some more insight.

Can you explain why you specifically need to hit 50MB?


问:
Magento configuration - populating field when using frontend_model
I have specified a frontend_model in system.xml for an entry field. I did this because I wanted to make a field read-only. There may have been a more straightforward way to achieve that, but that's where I am at the moment. The thing is I cannot get the field to display the data it should.

I have a button that when pressed, populates the read-only field. That works fine. But when I hit 'Save Config', the data disappears from the field. The reason it disappears is because I can't find out what I should set the field's value to. Below tries using the getEscapedValue() method of Varien_Data_Form_Element_Abstract, but it returns nothing. And as usual with Magento, there is no documentation to speak of.

```<code>class Mypackage_MyModule_Block_Adminhtml_System_Config_DisabledText extends Mage_Adminhtml_Block_System_Config_Form_Field
{
    protected function _prepareLayout()
    {
        parent::_prepareLayout();
        if (!$this->getTemplate()) {
            $this->setTemplate('mypackage/system/config/disabled_text.phtml');
        }
        return $this;
    }

    public function render(Varien_Data_Form_Element_Abstract $element)
    {
        $element->unsScope()->unsCanUseWebsiteValue()->unsCanUseDefaultValue();
        return parent::render($element);
    }

    protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
    {
        $originalData = $element->getOriginalData();
        $this->addData(array(
            'my_value' => $element->getEscapedValue(),
            'html_id' => $element->getHtmlId(),
        ));
        return $this->_toHtml();
    }
}
</code>```

disabled_text.phtml contains the following:

```<code><input id="<?php echo $this->getHtmlId() ?>" value="<?php echo $this->getMyValue(); ?>" class=" input-text" type="text" disabled/>
</code>```

Thanks.

答:
This is one of those places where you  need to look at how Magento itself is doing something similar to what you want to do.  If you look at the Mage_Adminhtml_Block_System_Config_Form_Field class's _getElementHtml

```<code>protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
{
    return $element->getElementHtml();
}
</code>```

you can see that this method accepts a form element that's already been instantiated (based on what's in system.xml), and then this element renders itself with getElementHtml.  That means when Magento needs to render (and, in turn, get the value) it does so in from the element object.  Some crude debugging will let us know where getElementHtml can be located

```<code>protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
{
    var_dump(get_class($element));
    return $element->getElementHtml();
}
</code>```

Something like Varien_Data_Form_Element_Text will be dumped to the screen.  In turn, this class inherits form Varien_Data_Form_Element_Abstract, which contains the following definition

```<code>public function getElementHtml()
{
    $html = '<input id="'.$this->getHtmlId().'" name="'.$this->getName()
         .'" value="'.$this->getEscapedValue().'" '.$this->serialize($this->getHtmlAttributes()).'/>'."\n";
    $html.= $this->getAfterElementHtml();
    return $html;
}
</code>```

So, when Magento wants to get the value for a system config field, it uses the above PHP code to render the input.  So, if you want to do the same in your template, I'd try something like this

Up in the class, assign a block property with the entire element.  This is actually more efficient that plucking values out of the elements, since all PHP needs to store is an object reference.

```<code>protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
{
    $this->setMyElement($element);
    return $this->_toHtml();
}
</code>```

Then, in the template, copy the code from magento's rendering, replacing the "$this" keyword with your saved element

```<code><?php $_element = $this->getMyElement(); ?>
<!-- check the quoting/escaping on this html/php, I didn't actually run it, but the concept is sound -->
<input  disabled="disabled" id="<?php echo $_element->getHtmlId();?>" name="<?php echo $_element->getName();?>"
        value="<?php echo $_element->getEscapedValue();?>"
        <?php echo $_element->serialize($_element->getHtmlAttributes());?>
/>
<?php echo $_element->getAfterElementHtml(); ?>
</code>```

When you're working with Magento, try to think like a Magento developer.  Instead of "I need to figure out how to make it do X", think "I need to add this feature to the store in the same way the rest of my teammates have".  Then look how the core team did it, and copy their implementation, changing as little as you need to.

It does get easier the more you work with the system!

Body:
I have specified a frontend_model in system.xml for an entry field. I did this because I wanted to make a field read-only. There may have been a more straightforward way to achieve that, but that's where I am at the moment. The thing is I cannot get the field to display the data it should.

I have a button that when pressed, populates the read-only field. That works fine. But when I hit 'Save Config', the data disappears from the field. The reason it disappears is because I can't find out what I should set the field's value to. Below tries using the getEscapedValue() method of Varien_Data_Form_Element_Abstract, but it returns nothing. And as usual with Magento, there is no documentation to speak of.

class Mypackage_MyModule_Block_Adminhtml_System_Config_DisabledText extends Mage_Adminhtml_Block_System_Config_Form_Field
{
    protected function _prepareLayout()
    {
        parent::_prepareLayout();
        if (!$this->getTemplate()) {
            $this->setTemplate('mypackage/system/config/disabled_text.phtml');
        }
        return $this;
    }

    public function render(Varien_Data_Form_Element_Abstract $element)
    {
        $element->unsScope()->unsCanUseWebsiteValue()->unsCanUseDefaultValue();
        return parent::render($element);
    }

    protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
    {
        $originalData = $element->getOriginalData();
        $this->addData(array(
            'my_value' => $element->getEscapedValue(),
            'html_id' => $element->getHtmlId(),
        ));
        return $this->_toHtml();
    }
}

disabled_text.phtml contains the following:

<input id="<?php echo $this->getHtmlId() ?>" value="<?php echo $this->getMyValue(); ?>" class=" input-text" type="text" disabled/>

Thanks.

Body:
This is one of those places where you  need to look at how Magento itself is doing something similar to what you want to do.  If you look at the Mage_Adminhtml_Block_System_Config_Form_Field class's _getElementHtml

protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
{
    return $element->getElementHtml();
}

you can see that this method accepts a form element that's already been instantiated (based on what's in system.xml), and then this element renders itself with getElementHtml.  That means when Magento needs to render (and, in turn, get the value) it does so in from the element object.  Some crude debugging will let us know where getElementHtml can be located

protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
{
    var_dump(get_class($element));
    return $element->getElementHtml();
}

Something like Varien_Data_Form_Element_Text will be dumped to the screen.  In turn, this class inherits form Varien_Data_Form_Element_Abstract, which contains the following definition

public function getElementHtml()
{
    $html = '<input id="'.$this->getHtmlId().'" name="'.$this->getName()
         .'" value="'.$this->getEscapedValue().'" '.$this->serialize($this->getHtmlAttributes()).'/>'."\n";
    $html.= $this->getAfterElementHtml();
    return $html;
}

So, when Magento wants to get the value for a system config field, it uses the above PHP code to render the input.  So, if you want to do the same in your template, I'd try something like this

Up in the class, assign a block property with the entire element.  This is actually more efficient that plucking values out of the elements, since all PHP needs to store is an object reference.

protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
{
    $this->setMyElement($element);
    return $this->_toHtml();
}

Then, in the template, copy the code from magento's rendering, replacing the "$this" keyword with your saved element

<?php $_element = $this->getMyElement(); ?>
<!-- check the quoting/escaping on this html/php, I didn't actually run it, but the concept is sound -->
<input  disabled="disabled" id="<?php echo $_element->getHtmlId();?>" name="<?php echo $_element->getName();?>"
        value="<?php echo $_element->getEscapedValue();?>"
        <?php echo $_element->serialize($_element->getHtmlAttributes());?>
/>
<?php echo $_element->getAfterElementHtml(); ?>

When you're working with Magento, try to think like a Magento developer.  Instead of "I need to figure out how to make it do X", think "I need to add this feature to the store in the same way the rest of my teammates have".  Then look how the core team did it, and copy their implementation, changing as little as you need to.

It does get easier the more you work with the system!


问:
Visual Studio project folder conventions
A few versions back, Visual Studio started using C:\Users\Jonathan\source\repos as the default project folder (instead of C:\Users\Jonathan\Documents\Visual Studio 2019\Projects). I prefer the old location under Documents, but I decided to just accept the newer location because I figure that is more likely to avoid conflicts, avoid having to change it with each new release and just generally the path of least resistance moving forward.

Now I want to create a GitHub repository. But the default Local path is the same path where the project is stored! So without changing this path, I get the following error:

Repository with same name already exists at this location.

Obviously, I can change this path. But I'm trying to go with Microsoft's recommended folder locations to avoid conflicts. And so it seems ironic that I've run into a conflict using these locations!

Questions:

Does anyone know why Visual Studio needs a local repository path in addition to the current project folder?

Does anyone know why Visual Studio is defaulting to the same path for both? What is the intended convention for these locations?

答:
Git needs a local repo. VS is trying to create a local repo, but you want to use the existing repo.

How do I do ?

```<code>File => Add to Source Control
View =>  Team Explorer
Sync
</code>```

It will not ask to create a new repository.

Did I answer your question ?

You are dealing with "git clone" and git clone only works with an empty folder then its ok if it defaults to the projects folder, lets clone the project.

If you already have the project in your computer and just want to push the code, then you should init your local git repo in the project folder, add the github remote and push the code into the remote repository.

Here you have some docs.

Body:
Git needs a local repo. VS is trying to create a local repo, but you want to use the existing repo.

How do I do ?

File => Add to Source Control
View =>  Team Explorer
Sync

It will not ask to create a new repository.

Did I answer your question ?

You are dealing with "git clone" and git clone only works with an empty folder then its ok if it defaults to the projects folder, lets clone the project.

If you already have the project in your computer and just want to push the code, then you should init your local git repo in the project folder, add the github remote and push the code into the remote repository.

Here you have some docs.


问:
how to insert special character in mysql via php and display on html page
how to insert special characters into a database(MySQL) like

Registered symbol ( ® ) OR
Copyright sign ( © ) OR
Trade Mark sign ( ™ )

Also I want to display as original on the html page.

What I have to do in both side (front end and back end), please elaborate

Which function is more effective?

Method 1:

```<code>$_GET = array_map('trim', $_GET);
$_POST = array_map('trim', $_POST);

if(get_magic_quotes_gpc()){
  $_GET = array_map('stripslashes', $_GET);
  $_POST = array_map('stripslashes', $_POST);

  $_GET = array_map('strip_tags', $_GET);
  $_POST = array_map('strip_tags', $_POST);
 }
 else{
  $_GET = array_map('mysql_real_escape_string', $_GET);
  $_POST = array_map('mysql_real_escape_string', $_POST);
 }
</code>```

Method 2:

```<code>  foreach ($_POST as $key=>$value){
        if (!get_magic_quotes_gpc()) {
          return addslashes(htmlentities(strip_tags($value),ENT_QUOTES,'UTF-8'));
          }
          else {
             return htmlentities(strip_tags($value),ENT_QUOTES,'UTF-8');
          }
  }
</code>```

I am a bit confused what is the difference between

htmlentities() and htlspecialchars(), and which one i have to use?

which function should be used addslashes() or stripslashes() when insert into database?

答:
Just use prepared statements.</p>

```<code>$con = <"Your database connection">;
$input = "What's up? ®, ©, ™";
$stmt = $con->prepare("insert into `tablename` (`field`)values(?)");
$stmt->bind_param("s",$input);
$stmt->execute();
</code>```

Body:
how to insert special characters into a database(MySQL) like

Registered symbol ( ® ) OR
Copyright sign ( © ) OR
Trade Mark sign ( ™ )

Also I want to display as original on the html page.

What I have to do in both side (front end and back end), please elaborate

Which function is more effective?

Method 1:

$_GET = array_map('trim', $_GET);
$_POST = array_map('trim', $_POST);

if(get_magic_quotes_gpc()){
  $_GET = array_map('stripslashes', $_GET);
  $_POST = array_map('stripslashes', $_POST);

  $_GET = array_map('strip_tags', $_GET);
  $_POST = array_map('strip_tags', $_POST);
 }
 else{
  $_GET = array_map('mysql_real_escape_string', $_GET);
  $_POST = array_map('mysql_real_escape_string', $_POST);
 }

Method 2:

  foreach ($_POST as $key=>$value){
        if (!get_magic_quotes_gpc()) {
          return addslashes(htmlentities(strip_tags($value),ENT_QUOTES,'UTF-8'));
          }
          else {
             return htmlentities(strip_tags($value),ENT_QUOTES,'UTF-8');
          }
  }

I am a bit confused what is the difference between

htmlentities() and htlspecialchars(), and which one i have to use?

which function should be used addslashes() or stripslashes() when insert into database?

Body:
Just use prepared statements.

$con = <"Your database connection">;
$input = "What's up? ®, ©, ™";
$stmt = $con->prepare("insert into `tablename` (`field`)values(?)");
$stmt->bind_param("s",$input);
$stmt->execute();


问:
flake8: F821 undefined name for a global variable
I've edited my script to remove all of the flake8 warnings except one:

```<code>/tmp/flake8.tempfile.py:535:26: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:536:29: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:554:22: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:602:21: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:602:32: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:609:21: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:609:32: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:623:44: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:646:39: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:651:39: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:654:39: F821 undefined name 'salt'

...
</code>```

salt is a hashlib ojbect that is used by many functions. It is defined in the main section of the script (at the bottom) with the line:

```<code>salt = hashlib.sha512()
</code>```

Before being updated with data. All of my other globals work fine, so I don't know why this one makes flake8 flake out.

答:
I wrapped the entire main section of the file in a:

```<code>if __name__ == "__main__":
</code>```

and the problem magically went away. No explanation why, but at least this might help someone else with this same problem someday.

Body:
I've edited my script to remove all of the flake8 warnings except one:

/tmp/flake8.tempfile.py:535:26: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:536:29: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:554:22: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:602:21: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:602:32: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:609:21: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:609:32: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:623:44: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:646:39: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:651:39: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:654:39: F821 undefined name 'salt'

...

salt is a hashlib ojbect that is used by many functions. It is defined in the main section of the script (at the bottom) with the line:

salt = hashlib.sha512()

Before being updated with data. All of my other globals work fine, so I don't know why this one makes flake8 flake out.

Body:
I wrapped the entire main section of the file in a:

if __name__ == "__main__":

and the problem magically went away. No explanation why, but at least this might help someone else with this same problem someday.


问:
How can I show multiple UIViews by accessing their isHidden property?
I want to show multiple UIViews in a collection cell based on the logic statements below.

This function is for a Calendar view in my tabbar application. I'm reading events from a database on Firebase Firestore and saving it in calData.

```<code>func configureEventDotFor(cell: CalendarCell, cellState: CellState) {
    let dateString = self.globalFormatter.string(from: cellState.date)
        for event in self.calData.events! {
        let eventDateString = self.globalFormatter.string(from: event.startDate)
        if dateString != eventDateString {
            cell.holidayBar.isHidden = true
            cell.birthdayBar.isHidden = true
            cell.defaultBar.isHidden = true
        } else if event.category == "birthday" {
                cell.birthdayBar.isHidden = false
        } else if event.category == "holiday" {
                cell.holidayBar.isHidden = false
        } else if event.category == "default" {
            cell.defaultBar.isHidden = false
        } else {
            return
        }
    }
}
</code>```

There are four events in calData, 2 default, 1 holiday, and 1 birthday. The birthday and holiday events are on the same day and therefore both birthdayBar and holidayBar should be visible for that day. I also expect to see a defaultBar for the other two events however only the holidayBar is visible when I run the app.

答: The problem is that you appear to be trying to mess directly with the subviews of the cells of a UICollectionView. Don't do that. Just have the shown/hidden state of each subview be set in the cellForItemAt method, based on some easily accessible state (typically the contents of your data model). If the state changes, simply reload the collection view.

Body:
I want to show multiple UIViews in a collection cell based on the logic statements below.

This function is for a Calendar view in my tabbar application. I'm reading events from a database on Firebase Firestore and saving it in calData.

func configureEventDotFor(cell: CalendarCell, cellState: CellState) {
    let dateString = self.globalFormatter.string(from: cellState.date)
        for event in self.calData.events! {
        let eventDateString = self.globalFormatter.string(from: event.startDate)
        if dateString != eventDateString {
            cell.holidayBar.isHidden = true
            cell.birthdayBar.isHidden = true
            cell.defaultBar.isHidden = true
        } else if event.category == "birthday" {
                cell.birthdayBar.isHidden = false
        } else if event.category == "holiday" {
                cell.holidayBar.isHidden = false
        } else if event.category == "default" {
            cell.defaultBar.isHidden = false
        } else {
            return
        }
    }
}

There are four events in calData, 2 default, 1 holiday, and 1 birthday. The birthday and holiday events are on the same day and therefore both birthdayBar and holidayBar should be visible for that day. I also expect to see a defaultBar for the other two events however only the holidayBar is visible when I run the app.


问:
Is reading one byte at a time endianness agnostic regardless of value size?
Say I am reading and writing uint32_t values to and from a stream. If I read/write one byte at a time to/from a stream and shift each byte like the below examples, will the results be consistent regardless of machine endianness?

In the examples here the stream is a buffer in memory called p.

static uint32_t s_read_uint32(uint8_t** p)
{
    uint32_t value;
    value  = (*p)[0];
    value |= (((uint32_t)((*p)[1])) << 8);
    value |= (((uint32_t)((*p)[2])) << 16);
    value |= (((uint32_t)((*p)[3])) << 24);
    *p += 4;
    return value;
}

static void s_write_uint32(uint8_t** p, uint32_t value)
{
    (*p)[0] = value & 0xFF;
    (*p)[1] = (value >> 8 ) & 0xFF;
    (*p)[2] = (value >> 16) & 0xFF;
    (*p)[3] = value >> 24;
    *p += 4;
}
```

I don't currently have access to a big-endian machine to test this out, but the idea is if each byte is written one at a time each individual byte can be independently written or read from the stream. Then the CPU can handle endianness by hiding these details behind the shifting operations. Is this true, and if not could anyone please explain why not?

答:
It'll work but a memcpy followed by a conditional byteswap will give you much better codegen for the write function.

```<code>#include <stdint.h>
#include <string.h>

#define LE (((char*)&(uint_least32_t){1})[0]) // little endian ?
void byteswap(char*,size_t);

uint32_t s2_read_uint32(uint8_t** p)
{
    uint32_t value;
    memcpy(&value,*p,sizeof(value));
    if(!LE) byteswap(&value,4);
    return *p+=4, value;
}

 void s2_write_uint32(uint8_t** p, uint32_t value)
{
    memcpy(*p,&value,sizeof(value));
    if(!LE) byteswap(*p,4);
    *p+=4;
}
</code>```

Gcc since the 8th series (but not clang) can eliminate this shifts on a little-endian platforms, but you should help it by restrict-qualifying the doubly-indirect pointer to the destination, or else it might think that a write to (*p)[0] can invalidate *p (uint8_t is a char type and therefore permitted to alias anything).

```<code>void s_write_uint32(uint8_t** restrict p, uint32_t value)
{
    (*p)[0] = value & 0xFF;
    (*p)[1] = (value >> 8 ) & 0xFF;
    (*p)[2] = (value >> 16) & 0xFF;
    (*p)[3] = value >> 24;
    *p += 4;
}
</code>```

Body:
Say I am reading and writing uint32_t values to and from a stream. If I read/write one byte at a time to/from a stream and shift each byte like the below examples, will the results be consistent regardless of machine endianness?

In the examples here the stream is a buffer in memory called p.

static uint32_t s_read_uint32(uint8_t** p)
{
    uint32_t value;
    value  = (*p)[0];
    value |= (((uint32_t)((*p)[1])) << 8);
    value |= (((uint32_t)((*p)[2])) << 16);
    value |= (((uint32_t)((*p)[3])) << 24);
    *p += 4;
    return value;
}

static void s_write_uint32(uint8_t** p, uint32_t value)
{
    (*p)[0] = value & 0xFF;
    (*p)[1] = (value >> 8 ) & 0xFF;
    (*p)[2] = (value >> 16) & 0xFF;
    (*p)[3] = value >> 24;
    *p += 4;
}

I don't currently have access to a big-endian machine to test this out, but the idea is if each byte is written one at a time each individual byte can be independently written or read from the stream. Then the CPU can handle endianness by hiding these details behind the shifting operations. Is this true, and if not could anyone please explain why not?

Body:
It'll work but a memcpy followed by a conditional byteswap will give you much better codegen for the write function.

#include <stdint.h>
#include <string.h>

#define LE (((char*)&(uint_least32_t){1})[0]) // little endian ?
void byteswap(char*,size_t);

uint32_t s2_read_uint32(uint8_t** p)
{
    uint32_t value;
    memcpy(&value,*p,sizeof(value));
    if(!LE) byteswap(&value,4);
    return *p+=4, value;
}

 void s2_write_uint32(uint8_t** p, uint32_t value)
{
    memcpy(*p,&value,sizeof(value));
    if(!LE) byteswap(*p,4);
    *p+=4;
}

Gcc since the 8th series (but not clang) can eliminate this shifts on a little-endian platforms, but you should help it by restrict-qualifying the doubly-indirect pointer to the destination, or else it might think that a write to (*p)[0] can invalidate *p (uint8_t is a char type and therefore permitted to alias anything).

void s_write_uint32(uint8_t** restrict p, uint32_t value)
{
    (*p)[0] = value & 0xFF;
    (*p)[1] = (value >> 8 ) & 0xFF;
    (*p)[2] = (value >> 16) & 0xFF;
    (*p)[3] = value >> 24;
    *p += 4;
}


问:
Changes to a stylesheet in one folder below the root do not take immediate effect with Brackets and XAMPP
I am using a CSS stylesheet along with Bootstrap, Adobe Brackets and XAMPP, running locally on my PC.  If I make a change to the css stylesheet, the change does not take immediate effect upon saving the stylesheet.  The system seems to remember the previous code in the stylesheet.  The changes eventually manifest themselves, but I can't find a rhyme or reason for this.  In other words, I make a change to the stylesheet but the change does not show up when I open the webpage in Bracket's Live Preview.

This problem does not happen if I place the css stylesheet in the root directory.  I cannot see what, if anything, I'm doing wrong. Here is my code showing the path to the stylesheet.  Given:  the folder css is only level beneath the root folder.

Here is my link to the CSS stylesheet.  What could be wrong?

```<code><!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
  <!--  NR Systems -->
  <link rel="stylesheet" href="/css/NatResConStyles.css">
</code>```

答:
I found the answer to my own question.

If a change to the CSS stylesheet is not immediately applied, or if a change to an image is not immediately applied, then you must use Google Chrome to "Clear Browsing Data/Cached Images and Files." Then refresh the web page. You should see that your changes have been applied.

This is in the development environment running Adobe Brackets, using the Live Preview feature, which uses Google Chrome.

Body:
I am using a CSS stylesheet along with Bootstrap, Adobe Brackets and XAMPP, running locally on my PC.  If I make a change to the css stylesheet, the change does not take immediate effect upon saving the stylesheet.  The system seems to remember the previous code in the stylesheet.  The changes eventually manifest themselves, but I can't find a rhyme or reason for this.  In other words, I make a change to the stylesheet but the change does not show up when I open the webpage in Bracket's Live Preview.

This problem does not happen if I place the css stylesheet in the root directory.  I cannot see what, if anything, I'm doing wrong. Here is my code showing the path to the stylesheet.  Given:  the folder css is only level beneath the root folder.

Here is my link to the CSS stylesheet.  What could be wrong?

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">

  <link rel="stylesheet" href="/css/NatResConStyles.css">


答:
I had the same problem with Visual studio 2017 community edition.
I ended up doing this.

For new projects

when creating a new project check "Create new Git repository" option

create Github empty repository

push from local repository to Github as remote using empty repository
link

for other projects

clone empty github repository to folder

add project files

push to github

Title: Visual Studio project folder conventions

Body:
A few versions back, Visual Studio started using C:\Users\Jonathan\source\repos as the default project folder (instead of C:\Users\Jonathan\Documents\Visual Studio 2019\Projects). I prefer the old location under Documents, but I decided to just accept the newer location because I figure that is more likely to avoid conflicts, avoid having to change it with each new release and just generally the path of least resistance moving forward.

Now I want to create a GitHub repository. But the default Local path is the same path where the project is stored! So without changing this path, I get the following error:

Repository with same name already exists at this location.

Obviously, I can change this path. But I'm trying to go with Microsoft's recommended folder locations to avoid conflicts. And so it seems ironic that I've run into a conflict using these locations!

Questions:

Does anyone know why Visual Studio needs a local repository path in addition to the current project folder?

Does anyone know why Visual Studio is defaulting to the same path for both? What is the intended convention for these locations?


问:
How do I append more than one child element to a parent element Javascript
Good day everyone, I am new to programming, so I am sorry if my question looks stupid or too simple. I am trying to append 4 different child elements on a parent element.

I am building a To Do List app, and I want the app to work in such a way that when the 'task' is entered and saved, the entered task will appear on a list with a checkbox, a delete button, and an edit button. I tried appending the child elements on their parent element using .appendchild() but it's not working.

```<code><Ol id="ol">
    <li>
        <input type="checkbox">Read a novel
        <button>Edit</button>
        <button>Delete</button>
    </li>
    <li>
        <input type="checkbox">Take a walk
        <button>Edit</button>
        <button>Delete</button>
    </li>
</Ol>

let inputToDoList= document.getElementById('inputToDoList');

let addButton=  document.getElementById('addButton');
let editButton= document.createElement('button');
let deleteButton= document.createElement('button');
let checkInput= document.createElement('input');

checkInput.type= "checkbox"
deleteButton.innerText= "Delete"
editButton.innerText= "Edit"

addButton.addEventListener('click', () => {
   let ol= document.getElementsByTagName('ol')[0];
   let li= document.createElement('li');

   li.textContent= inputToDoList.value
   ol.appendChild(checkInput)
   ol.appendChild(li)
   ol.appendChild(editButton)
   ol.appendChild(deleteButton)

   if(inputToDoList.value.length > 0){
      inputToDoList.value='';
}
});
</code>```

What I want the program to do is to add inputToDoList.value, checkbox, edit button and delete button to the  each time the 'save' button is clicked on but the function only works when I click on the save button the first time. When I click on the 'save' button the subsequent times, it's only the inputToDoList.value that is added to the list. The other elements i.e. checkbox, edit button and delete button will no longer be added.

答:
Create the button elements inside the click event. Currently you placed the createElement outside the addButton event. As per your requirement the buttons should be created in the add click event, hence the element creation should happen inside the add click event.

let inputToDoList = document.getElementById('inputToDoList');

let addButton = document.getElementById('addButton');

let ol = document.getElementById('ol');
addButton.addEventListener('click', () => {
  let editButton = document.createElement('button');
  let deleteButton = document.createElement('button');
  let checkInput = document.createElement('input');
  checkInput.type = "checkbox"
  deleteButton.innerText = "Delete"
  editButton.innerText = "Edit"
  let li = document.createElement('li');
  li.textContent = inputToDoList.value
  ol.appendChild(checkInput)
  ol.appendChild(li)
  ol.appendChild(editButton)
  ol.appendChild(deleteButton)

  if (inputToDoList.value.length > 0) {
    inputToDoList.value = '';
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="inputToDoList" />
<button id="addButton">
Add
</button>
<ol id="ol">

</ol></code>```

Body:
Good day everyone, I am new to programming, so I am sorry if my question looks stupid or too simple. I am trying to append 4 different child elements on a parent element.

I am building a To Do List app, and I want the app to work in such a way that when the 'task' is entered and saved, the entered task will appear on a list with a checkbox, a delete button, and an edit button. I tried appending the child elements on their parent element using .appendchild() but it's not working.

        <input type="checkbox">Read a novel
        <button>Edit</button>
        <button>Delete</button>

        <input type="checkbox">Take a walk
        <button>Edit</button>
        <button>Delete</button>

let inputToDoList= document.getElementById('inputToDoList');

let addButton=  document.getElementById('addButton');
let editButton= document.createElement('button');
let deleteButton= document.createElement('button');
let checkInput= document.createElement('input');

checkInput.type= "checkbox"
deleteButton.innerText= "Delete"
editButton.innerText= "Edit"

addButton.addEventListener('click', () => {
   let ol= document.getElementsByTagName('ol')[0];
   let li= document.createElement('li');

   li.textContent= inputToDoList.value
   ol.appendChild(checkInput)
   ol.appendChild(li)
   ol.appendChild(editButton)
   ol.appendChild(deleteButton)

   if(inputToDoList.value.length > 0){
      inputToDoList.value='';
}
});

What I want the program to do is to add inputToDoList.value, checkbox, edit button and delete button to the  each time the 'save' button is clicked on but the function only works when I click on the save button the first time. When I click on the 'save' button the subsequent times, it's only the inputToDoList.value that is added to the list. The other elements i.e. checkbox, edit button and delete button will no longer be added.

Body:
Create the button elements inside the click event. Currently you placed the createElement outside the addButton event. As per your requirement the buttons should be created in the add click event, hence the element creation should happen inside the add click event.

let inputToDoList = document.getElementById('inputToDoList');

let addButton = document.getElementById('addButton');

let ol = document.getElementById('ol');
addButton.addEventListener('click', () => {
  let editButton = document.createElement('button');
  let deleteButton = document.createElement('button');
  let checkInput = document.createElement('input');
  checkInput.type = "checkbox"
  deleteButton.innerText = "Delete"
  editButton.innerText = "Edit"
  let li = document.createElement('li');
  li.textContent = inputToDoList.value
  ol.appendChild(checkInput)
  ol.appendChild(li)
  ol.appendChild(editButton)
  ol.appendChild(deleteButton)

  if (inputToDoList.value.length > 0) {
    inputToDoList.value = '';
  }
});

<input type="text" id="inputToDoList" />
<button id="addButton">
Add
</button>
<ol id="ol">

</ol>


问:
Perl file treatment is limited in size?
I've made a translator in perl for a messageboard migration, All I do is applying regexes and print the result. I write stdout to a file and here we go ! But the problem is that my program won't work after 18 MB written !

I've made a translate.pl ( https://gist.github.com/914450 )
and launch it with this line :
$ perl translate.pl mydump.sql > mydump-bbcode.sql

Really sorry for quality of code but I never use perl... I tried sed for same work but didn't manage to apply the regex I found in original script.

[EDIT]
I reworked the code and sanitized some regexes (see gist.github.com/914450) but I'm still stuck. When I splited the big dump in 15M files, I launched translate.pl 7(processes) by 7 to use all cores but the script stops at a variable size. a "tail" command doesn't show a complex message on any url when it stops...

Thanks Guys ! I let you know if I manage finally

答:
You say the "script stops".  It keeps running but produces no more output?  Or actually stops running?  If it stops running, what does:

```<code>perl translate.pl mydump.sql > mydump-bbcode.sql
echo $?
</code>```

show?  And if you add a print STDERR "done!\n"; after your loop, does that show up?

Title: Perl file treatment is limited in size?

Body:
You say the "script stops".  It keeps running but produces no more output?  Or actually stops running?  If it stops running, what does:

perl translate.pl mydump.sql > mydump-bbcode.sql
echo $?

show?  And if you add a print STDERR "done!\n"; after your loop, does that show up?