问:
Can't connect to websocket through proxy
I'm trying to connect to a websocket through my own http proxy using Java's okhttp3 library.

I've set up the proxy on an EC2 instance and have configured the security groups correctly. I'm able to confirm that it works:

```<code>time curl -s --proxy http://X.X.X.X:8888 https://api.binance.com/api/v3/ping

real    0m0.597s
user    0m0.040s
sys     0m0.008s
</code>```

However, my attempts to connect to a websocket through the proxy have failed. Below is the code.

```<code>OkHttpClient client = new OkHttpClient.Builder()
        .proxy(new Proxy(Type.HTTP, new InetSocketAddress("X.X.X.X", 8888)))
        .build();

Request request = new Request.Builder()
        .url("wss://fstream.binance.com/stream")
        .build();

WebSocket webSocket = client.newWebSocket(request, new WebSocketListener() {
    @Override
    public void onFailure(final WebSocket webSocket, final Throwable t, final Response response) {
        t.printStackTrace();
    }
});
</code>```

If I remove the line .proxy(new Proxy(Type.HTTP, new InetSocketAddress("X.X.X.X", 8888))), then it works perfectly well, but if I have that line, I get the exception:

```<code>java.io.IOException: Unexpected response code for CONNECT: 403
    at okhttp3.internal.connection.RealConnection.createTunnel(RealConnection.kt:447)
    at okhttp3.internal.connection.RealConnection.connectTunnel(RealConnection.kt:235)
    at okhttp3.internal.connection.RealConnection.connect(RealConnection.kt:170)
    at okhttp3.internal.connection.ExchangeFinder.findConnection(ExchangeFinder.kt:236)
...
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:112)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:87)
    at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.kt:184)
    at okhttp3.RealCall$AsyncCall.run(RealCall.kt:136)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)
</code>```

I'm at a loss as to what to do? I can access the proxy through terminal but can't connect to a websocket through it.

答: Solved. My tinyproxy config file wasn't allowing my IP address.

Body:
I'm trying to connect to a websocket through my own http proxy using Java's okhttp3 library.

I've set up the proxy on an EC2 instance and have configured the security groups correctly. I'm able to confirm that it works:

time curl -s --proxy http://X.X.X.X:8888 https://api.binance.com/api/v3/ping

real    0m0.597s
user    0m0.040s
sys     0m0.008s

However, my attempts to connect to a websocket through the proxy have failed. Below is the code.

OkHttpClient client = new OkHttpClient.Builder()
        .proxy(new Proxy(Type.HTTP, new InetSocketAddress("X.X.X.X", 8888)))
        .build();

Request request = new Request.Builder()
        .url("wss://fstream.binance.com/stream")
        .build();

WebSocket webSocket = client.newWebSocket(request, new WebSocketListener() {
    @Override
    public void onFailure(final WebSocket webSocket, final Throwable t, final Response response) {
        t.printStackTrace();
    }
});

If I remove the line .proxy(new Proxy(Type.HTTP, new InetSocketAddress("X.X.X.X", 8888))), then it works perfectly well, but if I have that line, I get the exception:

java.io.IOException: Unexpected response code for CONNECT: 403
    at okhttp3.internal.connection.RealConnection.createTunnel(RealConnection.kt:447)
    at okhttp3.internal.connection.RealConnection.connectTunnel(RealConnection.kt:235)
    at okhttp3.internal.connection.RealConnection.connect(RealConnection.kt:170)
    at okhttp3.internal.connection.ExchangeFinder.findConnection(ExchangeFinder.kt:236)
...
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:112)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:87)
    at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.kt:184)
    at okhttp3.RealCall$AsyncCall.run(RealCall.kt:136)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)

I'm at a loss as to what to do? I can access the proxy through terminal but can't connect to a websocket through it.


来源: stackexchange

问:
Count and summation of positive and negative number sequences
I want to write a code to count and sum any positive and negative series of numbers.

Numbers are either positive or negative(no zero).

I have written codes with for loops. Is there any creative alternative?

Data

R

set.seed(100)
x <- round(rnorm(20, sd = 0.02), 3)
```
<h3>python</h3>
<pre class="lang-py prettyprint-override"><code>x = [-0.01, 0.003, -0.002, 0.018, 0.002, 0.006, -0.012, 0.014, -0.017, -0.007,

     0.002, 0.002, -0.004, 0.015, 0.002, -0.001, -0.008, 0.01, -0.018, 0.046]
</code>```

loops

R

sign_indicator <- ifelse(x > 0, 1,-1)
number_of_sequence <- rep(NA, 20)
n <- 1
for (i in 2:20) {
  if (sign_indicator[i] == sign_indicator[i - 1]) {
    n <- n + 1
  } else{
    n <- 1
  }
  number_of_sequence[i] <- n

}
number_of_sequence[1] <- 1

#############################

summation <- rep(NA, 20)

for (i in 1:20) {
  summation[i] <- sum(x[i:(i + 1 - number_of_sequence[i])])
}
```
<h3>python</h3>
<pre class="lang-py prettyprint-override"><code>sign_indicator = [1 if i > 0 else -1 for i in X]

number_of_sequence = [1]
N = 1
for i in range(1, len(sign_indicator)):
    if sign_indicator[i] == sign_indicator[i - 1]:
        N += 1
    else:
        N = 1
    number_of_sequence.append(N)

#############################
summation = []

for i in range(len(X)):
    if number_of_sequence[i] == 1:
          summation.append(X[i])

    else:
        summation.append(sum(X[(i + 1 - number_of_sequence[i]):(i + 1)]))
</code>```

result

```<code>        x n_of_sequence    sum
1  -0.010             1 -0.010
2   0.003             1  0.003
3  -0.002             1 -0.002
4   0.018             1  0.018
5   0.002             2  0.020
6   0.006             3  0.026
7  -0.012             1 -0.012
8   0.014             1  0.014
9  -0.017             1 -0.017
10 -0.007             2 -0.024
11  0.002             1  0.002
12  0.002             2  0.004
13 -0.004             1 -0.004
14  0.015             1  0.015
15  0.002             2  0.017
16 -0.001             1 -0.001
17 -0.008             2 -0.009
18  0.010             1  0.010
19 -0.018             1 -0.018
20  0.046             1  0.046
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to write a code to count and sum any positive and negative series of numbers.

Numbers are either positive or negative(no zero).

I have written codes with for loops. Is there any creative alternative?

Data

R

set.seed(100)
x <- round(rnorm(20, sd = 0.02), 3)

python

x = [-0.01, 0.003, -0.002, 0.018, 0.002, 0.006, -0.012, 0.014, -0.017, -0.007,

     0.002, 0.002, -0.004, 0.015, 0.002, -0.001, -0.008, 0.01, -0.018, 0.046]

loops

R

sign_indicator <- ifelse(x > 0, 1,-1)
number_of_sequence <- rep(NA, 20)
n <- 1
for (i in 2:20) {
  if (sign_indicator[i] == sign_indicator[i - 1]) {
    n <- n + 1
  } else{
    n <- 1
  }
  number_of_sequence[i] <- n

}
number_of_sequence[1] <- 1

#############################

summation <- rep(NA, 20)

for (i in 1:20) {
  summation[i] <- sum(x[i:(i + 1 - number_of_sequence[i])])
}

python

sign_indicator = [1 if i > 0 else -1 for i in X]

number_of_sequence = [1]
N = 1
for i in range(1, len(sign_indicator)):
    if sign_indicator[i] == sign_indicator[i - 1]:
        N += 1
    else:
        N = 1
    number_of_sequence.append(N)

#############################
summation = []

for i in range(len(X)):
    if number_of_sequence[i] == 1:
          summation.append(X[i])

    else:
        summation.append(sum(X[(i + 1 - number_of_sequence[i]):(i + 1)]))

result

        x n_of_sequence    sum
1  -0.010             1 -0.010
2   0.003             1  0.003
3  -0.002             1 -0.002
4   0.018             1  0.018
5   0.002             2  0.020
6   0.006             3  0.026
7  -0.012             1 -0.012
8   0.014             1  0.014
9  -0.017             1 -0.017
10 -0.007             2 -0.024
11  0.002             1  0.002
12  0.002             2  0.004
13 -0.004             1 -0.004
14  0.015             1  0.015
15  0.002             2  0.017
16 -0.001             1 -0.001
17 -0.008             2 -0.009
18  0.010             1  0.010
19 -0.018             1 -0.018
20  0.046             1  0.046

Body:
Here's a simple non-looping function in R:

count_and_sum <- function(x)
{
  runs   <- rle((x > 0) * 1)$lengths
  groups <- split(x, rep(1:length(runs), runs))
  output <- function(group) data.frame(x = group, n = seq_along(group), sum = cumsum(group))
  result <- as.data.frame(do.call(rbind, lapply(groups, output)))
  `rownames<-`(result, 1:nrow(result))
}

So you can do:

set.seed(100)
x <- round(rnorm(20, sd = 0.02), 3)
count_and_sum(x)
#>         x n    sum
#> 1  -0.010 1 -0.010
#> 2   0.003 1  0.003
#> 3  -0.002 1 -0.002
#> 4   0.018 1  0.018
#> 5   0.002 2  0.020
#> 6   0.006 3  0.026
#> 7  -0.012 1 -0.012
#> 8   0.014 1  0.014
#> 9  -0.017 1 -0.017
#> 10 -0.007 2 -0.024
#> 11  0.002 1  0.002
#> 12  0.002 2  0.004
#> 13 -0.004 1 -0.004
#> 14  0.015 1  0.015
#> 15  0.002 2  0.017
#> 16 -0.001 1 -0.001
#> 17 -0.008 2 -0.009
#> 18  0.010 1  0.010
#> 19 -0.018 1 -0.018
#> 20  0.046 1  0.046

Created on 2020-02-16 by the reprex package (v0.3.0)


问:
How to prevent Rest web-service Authentication with stolen Token
As we know Rest services are stateless, General strategies to authenticate is using a token based authentication.

In login service it takes credentials which returns a token.

This token might be set in client cookies, and all subsequent requests uses this token to be validated and process new request if token is valid.

Now my question is how one can validate the token ? If someone has stolen the token and tries to access rest services with stolen token by just editing cookies then how can it be identified and restricted ?

We can never know if the token is fetched by valid user and same user is trying to access subsequent request. but what are the possible ways to make it more hard, like to verify if the request has came from same source ?

One general suggestion is to set aging for token/cookies, but it still not helpful till the age of that token/cookies.

Any suggestions would be appreciated.

答:
You can use jwt is an Internet standard for creating JSON-based access tokens that assert some number of claims. For example, a server could generate a token that has the claim "logged in as admin" and provide that to a client. The client could then use that token to prove that it is logged in as admin .

How it's working ?

First it's contain private key generated by developer  :

let us have this key :sfcqw@sav%$#fvcxv*s_s515 and this one called private key , and we also have a public key this the public key generated depended on user data and private key and it's impossible to know what is contain if you don't know the private key .

to more explain :

public key :

```<code>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.plpJkAcgrgCIsoRyV2kjGsvWF6OsXU1mD785OSWTH4o
</code>```

we have the above key generated by our private key : sfcqw@sav%$#fvcxv*s_s515

To be more clear going to this website : https://jwt.io/ and try to past the public key without put secrite key like picture and you will understand everything .

Body:
You can use jwt is an Internet standard for creating JSON-based access tokens that assert some number of claims. For example, a server could generate a token that has the claim "logged in as admin" and provide that to a client. The client could then use that token to prove that it is logged in as admin .

How it's working ?

First it's contain private key generated by developer  :

let us have this key :sfcqw@sav%$#fvcxv*s_s515 and this one called private key , and we also have a public key this the public key generated depended on user data and private key and it's impossible to know what is contain if you don't know the private key .

to more explain :

public key :

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.plpJkAcgrgCIsoRyV2kjGsvWF6OsXU1mD785OSWTH4o

we have the above key generated by our private key : sfcqw@sav%$#fvcxv*s_s515

To be more clear going to this website : https://jwt.io/ and try to past the public key without put secrite key like picture and you will understand everything .


问:
"Invalid JSON string" in Google visualization API example
I am roughly following this example. But must be doing something silly...

The server side Django view code:

```<code>data_table = gviz_api.DataTable(description)
data_table.LoadData(data)
json = data_table.ToJSon()
return json
</code>```

These are the values of the variables copy-pasted from the pydev debugger: (Im using strings for each description field type just for testing)

description:

```<code>[("sensor","string", "Sensor name"),
 ("timestamp","string", "Time"),
 ("value","string", "Sensor value")]
</code>```

data:

```<code>[['testsensor', '2011-05-09 16:06:43.936000', '22.0'],
['testsensor', '2011-05-09 16:56:23.367000', '23.0']]
</code>```

json (generated by the google api):

```<code>{cols:[{id:'sensor',label:'Sensor name',type:'string'},{id:'timestamp',label:'Time',type:'string'},{id:'value',label:'Sensor value',type:'string'}],rows:[{c:[{v:'testsensor'},{v:'2011-05-09 16:06:43.936000'},{v:'22.0'}]},{c:[{v:'testsensor'},{v:'2011-05-09 16:56:23.367000'},{v:'23.0'}]}]}
</code>```

The client side javascript code that receives the json:

```<code>var json_table = new google.visualization.Table(document.getElementById('dataview'));
var json_data = new google.visualization.DataTable(data, 0.6);
json_table.draw(json_data, {showRowNumber: true});
</code>```

This causes the following error on constructing the DataTable object (second line):

```<code>Uncaught Error: Invalid JSON string: {cols:[{id:'sensor',label:'Sensor name',type:'string'},{id:'timestamp',label:'Time',type:'string'},{id:'value',label:'Sensor value',type:'string'}],rows:[{c:[{v:'testsensor'},{v:'2011-05-09 16:06:43.936000'},{v:'22.0'}]},{c:[{v:'testsensor'},{v:'2011-05-09 16:56:23.367000'},{v:'23.0'}]}]}
in default,table.I.js:152
</code>```

I understood that the whole clue was making sure that the schema format matches the data format but this seems to be the case.  It must be something simple.

答:
Unfortunately I can't comment so this isn't exactly a full answer, but could you try eval'ing the JSON before trying to use it for the chart?

```<code>var json_table = new google.visualization.Table(document.getElementById('dataview'));
var evalledData = eval("("+data+")");
var json_data = new google.visualization.DataTable(evalledData, 0.6);
json_table.draw(json_data, {showRowNumber: true});
</code>```

I think that may have solved this problem for me in the past; it may not be the safest way to go about it, but you could at least try it for testing.

Alternatively, perhaps play with simplejson to dump your json string from the python instead of just returning the gviz string?

ContentLicense: CC BY-SA 3.0

Body:
I am roughly following this example. But must be doing something silly...

The server side Django view code:

data_table = gviz_api.DataTable(description)
data_table.LoadData(data)
json = data_table.ToJSon()
return json

These are the values of the variables copy-pasted from the pydev debugger: (Im using strings for each description field type just for testing)

description:

[("sensor","string", "Sensor name"),
 ("timestamp","string", "Time"),
 ("value","string", "Sensor value")]

data:

[['testsensor', '2011-05-09 16:06:43.936000', '22.0'],
['testsensor', '2011-05-09 16:56:23.367000', '23.0']]

json (generated by the google api):

{cols:[{id:'sensor',label:'Sensor name',type:'string'},{id:'timestamp',label:'Time',type:'string'},{id:'value',label:'Sensor value',type:'string'}],rows:[{c:[{v:'testsensor'},{v:'2011-05-09 16:06:43.936000'},{v:'22.0'}]},{c:[{v:'testsensor'},{v:'2011-05-09 16:56:23.367000'},{v:'23.0'}]}]}

The client side javascript code that receives the json:

var json_table = new google.visualization.Table(document.getElementById('dataview'));
var json_data = new google.visualization.DataTable(data, 0.6);
json_table.draw(json_data, {showRowNumber: true});

This causes the following error on constructing the DataTable object (second line):

Uncaught Error: Invalid JSON string: {cols:[{id:'sensor',label:'Sensor name',type:'string'},{id:'timestamp',label:'Time',type:'string'},{id:'value',label:'Sensor value',type:'string'}],rows:[{c:[{v:'testsensor'},{v:'2011-05-09 16:06:43.936000'},{v:'22.0'}]},{c:[{v:'testsensor'},{v:'2011-05-09 16:56:23.367000'},{v:'23.0'}]}]}
in default,table.I.js:152

I understood that the whole clue was making sure that the schema format matches the data format but this seems to be the case.  It must be something simple.

Body:
Unfortunately I can't comment so this isn't exactly a full answer, but could you try eval'ing the JSON before trying to use it for the chart?

var json_table = new google.visualization.Table(document.getElementById('dataview'));
var evalledData = eval("("+data+")");
var json_data = new google.visualization.DataTable(evalledData, 0.6);
json_table.draw(json_data, {showRowNumber: true});

I think that may have solved this problem for me in the past; it may not be the safest way to go about it, but you could at least try it for testing.

Alternatively, perhaps play with simplejson to dump your json string from the python instead of just returning the gviz string?


问:
Why didn't Moxy initialize the Presenter (Kotlin, Android)
I got error that mPresenter has not been initialized. I didn't understand WHY?

I got this error when I use Kotlin but if I use JAVA everything is fine

Here is my code

View

```<code>@StateStrategyType(value = AddToEndStrategy::class)
interface IHelloWorldView : MvpView {
    fun showMessage(message: Int)
}
</code>```

Presenter

```<code>@InjectViewState
class HelloWorldPresenter : MvpPresenter<IHelloWorldView>() {
    fun show() = viewState.showMessage(R.string.message)
}
</code>```

MainActivity

```<code>class MainActivity : MvpAppCompatActivity(), IHelloWorldView {

    @InjectPresenter
    lateinit var mPresenter: HelloWorldPresenter

    lateinit var mText: TextView
    lateinit var mButton: Button

    override fun showMessage(message: Int) {
        mText.setText(message)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        mText = findViewById(R.id.text)
        mButton = findViewById(R.id.button)
        mButton.setOnClickListener {
            mPresenter.show()
        }
    }
}
</code>```

答: type = PresenterType.GLOBAL - do not exist (at least in kotlin)

Body:
I got error that mPresenter has not been initialized. I didn't understand WHY?

I got this error when I use Kotlin but if I use JAVA everything is fine

Here is my code

View

@StateStrategyType(value = AddToEndStrategy::class)
interface IHelloWorldView : MvpView {
    fun showMessage(message: Int)
}

Presenter

@InjectViewState
class HelloWorldPresenter : MvpPresenter<IHelloWorldView>() {
    fun show() = viewState.showMessage(R.string.message)
}

MainActivity

class MainActivity : MvpAppCompatActivity(), IHelloWorldView {

    @InjectPresenter
    lateinit var mPresenter: HelloWorldPresenter

    lateinit var mText: TextView
    lateinit var mButton: Button

    override fun showMessage(message: Int) {
        mText.setText(message)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        mText = findViewById(R.id.text)
        mButton = findViewById(R.id.button)
        mButton.setOnClickListener {
            mPresenter.show()
        }
    }
}


问:
How to use Redux state in function?
I have a function that I keep in a separate file for clarity and I try to make a Redux Action and also get the state from it. I call this function this inside my App.js that is connected to the Provider, but it says props.jwt is undefined. I tried to connect and export it as a Component, but did not work. </p>

```<code>import {connect} from 'react-redux';
import {getCurrentUserInformation} from '../actions/actions';
import instance from '../config/instance';

function getUserInformation(props) {
  instance
    .get('/api/user_information/', {
      headers: {Authorization: 'Token ' + props.jwt},
    })
    .then(response => {
      props.getCurrentUserInformation(
        response.data.id,
        response.data.username,
        response.data.profile_image,
        response.data.followers,
        response.data.following,
      );
    })
    .catch(error => {});
}

function mapStateToProps(state) {
  return {
    currentUser: state.userReducer.currentUser,
    jwt: state.userReducer.jwt,
  };
}

function mapDispatchToProps(dispatch) {
  return {
    getCurrentUserInformation: (
      id,
      username,
      profileImage,
      followers,
      following,
    ) =>
      dispatch(
        getCurrentUserInformation(
          id,
          username,
          profileImage,
          followers,
          following,
        ),
      ),
  };
}
</code>```

答: Try Redux Hooks. Instead of mapDispatchToProps and mapStateToProps you can use useSelector and useDispatch to get access to your state in the function. You can find more in the official documentation here: https://react-redux.js.org/next/api/hooks</p>

Title: How to use Redux state in function?

Body:
I have a function that I keep in a separate file for clarity and I try to make a Redux Action and also get the state from it. I call this function this inside my App.js that is connected to the Provider, but it says props.jwt is undefined. I tried to connect and export it as a Component, but did not work.

import {connect} from 'react-redux';
import {getCurrentUserInformation} from '../actions/actions';
import instance from '../config/instance';

function getUserInformation(props) {
  instance
    .get('/api/user_information/', {
      headers: {Authorization: 'Token ' + props.jwt},
    })
    .then(response => {
      props.getCurrentUserInformation(
        response.data.id,
        response.data.username,
        response.data.profile_image,
        response.data.followers,
        response.data.following,
      );
    })
    .catch(error => {});
}

function mapStateToProps(state) {
  return {
    currentUser: state.userReducer.currentUser,
    jwt: state.userReducer.jwt,
  };
}

function mapDispatchToProps(dispatch) {
  return {
    getCurrentUserInformation: (
      id,
      username,
      profileImage,
      followers,
      following,
    ) =>
      dispatch(
        getCurrentUserInformation(
          id,
          username,
          profileImage,
          followers,
          following,
        ),
      ),
  };
}


问:
I have problems when I try to put the text of the label from a function
I'm doing a calculator with Python 3.8 and Visual Studio. I'm trying to print the result in the label on button click.

This is the error:

Undefined variable 'resultado' pylint(undefined-variable) [37, 32]

This is my code:

```<code>from tkinter import *

r = Tk()
r.title("CALCULADORA")

def operar(num1, num2, signo):

    resultado = IntVar()

    if signo == "+":
        resultado = num1 + num2

    elif signo == "-":
        resultado = num1 - num2

    elif signo == "/":
        resultado = num1 / num2

    elif signo == "X":
        resultado = num1 * num2

    return resultado

textNumUno = Entry(r, width=7)
textNumUno.grid(row=0, column=0)

textOperacion = Entry(r, width=3)
textOperacion.grid(row=0, column=1)

textNumDos = Entry(r, width=7)
textNumDos.grid(row=0, column=2)

btn = Button(r, text="=", width=2, command=operar(textNumUno.get(), textNumDos.get(), textOperacion.get()))
btn.grid(row=0, column=3)

labelResultado = Label(r, text=resultado)
labelResultado.grid(row=0, column=4)

r.mainloop()
</code>```

答:
There are few mistakes

resultado is local variable - you have to create it outside function

IntVar(), (StringVar(), etc.) is not normal variable and it needs .get(), .set() to work with this

```<code>resultado.set( int(num1) + int(num2) )

print( resultado.get() )
</code>```

Button doesn't work like input() - it doesn't wait for your answer so Label(   text=) is created before you put text and press button. You can use textvarable= to assign IntVar() (StringVar(), etc.) and when you change value in IntVar then it will change text on Label.

Button will execute function later but it can't get result so using return in operar is useless.

command= need function name without () and arguments (so called callback) and later (when you press button) it will add () to this name to execute it. If you have to use function with arguments then you may use lambda to create function without arguments.

```<code>command=lambda:operar(textNumUno.get(), textNumDos.get(), textOperacion.get()))
</code>```

Entry gives strings which you have to convert to int() (or float())

```<code>#from tkinter import * # PEP8: not preferred
import tkinter as tk

# --- functions ---

def operar(num1, num2, signo):

    if signo == "+":
        resultado.set( int(num1) + int(num2) )

    elif signo == "-":
        resultado.set( int(num1) - int(num2) )

    elif signo == "/":
        resultado.set( int(num1) / int(num2) )

    elif signo in "*xX":
        resultado.set( int(num1) * int(num2) )

# --- main ---

r = tk.Tk()
r.title("CALCULADORA")

resultado = tk.IntVar()

textNumUno = tk.Entry(r, width=7)
textNumUno.grid(row=0, column=0)

textOperacion = tk.Entry(r, width=3)
textOperacion.grid(row=0, column=1)

textNumDos = tk.Entry(r, width=7)
textNumDos.grid(row=0, column=2)

btn = tk.Button(r, text="=", width=2, command=lambda:operar(textNumUno.get(), textNumDos.get(), textOperacion.get()))
btn.grid(row=0, column=3)

labelResultado = tk.Label(r, textvariable=resultado)
labelResultado.grid(row=0, column=4)

r.mainloop()
</code>```

BTW: as for import * see PEP 8 -- Style Guide for Python Code

Body:
I'm doing a calculator with Python 3.8 and Visual Studio. I'm trying to print the result in the label on button click.

This is the error:

Undefined variable 'resultado' pylint(undefined-variable) [37, 32]

This is my code:

from tkinter import *

r = Tk()
r.title("CALCULADORA")

def operar(num1, num2, signo):

    resultado = IntVar()

    if signo == "+":
        resultado = num1 + num2

    elif signo == "-":
        resultado = num1 - num2

    elif signo == "/":
        resultado = num1 / num2

    elif signo == "X":
        resultado = num1 * num2

    return resultado

textNumUno = Entry(r, width=7)
textNumUno.grid(row=0, column=0)

textOperacion = Entry(r, width=3)
textOperacion.grid(row=0, column=1)

textNumDos = Entry(r, width=7)
textNumDos.grid(row=0, column=2)

btn = Button(r, text="=", width=2, command=operar(textNumUno.get(), textNumDos.get(), textOperacion.get()))
btn.grid(row=0, column=3)

labelResultado = Label(r, text=resultado)
labelResultado.grid(row=0, column=4)

r.mainloop()

Body:
There are few mistakes

resultado is local variable - you have to create it outside function

IntVar(), (StringVar(), etc.) is not normal variable and it needs .get(), .set() to work with this

resultado.set( int(num1) + int(num2) )

print( resultado.get() )

Button doesn't work like input() - it doesn't wait for your answer so Label(   text=) is created before you put text and press button. You can use textvarable= to assign IntVar() (StringVar(), etc.) and when you change value in IntVar then it will change text on Label.

Button will execute function later but it can't get result so using return in operar is useless.

command= need function name without () and arguments (so called callback) and later (when you press button) it will add () to this name to execute it. If you have to use function with arguments then you may use lambda to create function without arguments.

command=lambda:operar(textNumUno.get(), textNumDos.get(), textOperacion.get()))

Entry gives strings which you have to convert to int() (or float())

#from tkinter import * # PEP8: not preferred
import tkinter as tk

# --- functions ---

def operar(num1, num2, signo):

    if signo == "+":
        resultado.set( int(num1) + int(num2) )

    elif signo == "-":
        resultado.set( int(num1) - int(num2) )

    elif signo == "/":
        resultado.set( int(num1) / int(num2) )

    elif signo in "*xX":
        resultado.set( int(num1) * int(num2) )

# --- main ---

r = tk.Tk()
r.title("CALCULADORA")

resultado = tk.IntVar()

textNumUno = tk.Entry(r, width=7)
textNumUno.grid(row=0, column=0)

textOperacion = tk.Entry(r, width=3)
textOperacion.grid(row=0, column=1)

textNumDos = tk.Entry(r, width=7)
textNumDos.grid(row=0, column=2)

btn = tk.Button(r, text="=", width=2, command=lambda:operar(textNumUno.get(), textNumDos.get(), textOperacion.get()))
btn.grid(row=0, column=3)

labelResultado = tk.Label(r, textvariable=resultado)
labelResultado.grid(row=0, column=4)

r.mainloop()

BTW: as for import * see PEP 8 -- Style Guide for Python Code


问:
Rails: Webpacker::Manifest::MissingEntryError in Home#index
Webpacker::Manifest::MissingEntryError in Home#index
    Showing /Users/khalidhosein/Desktop/myEPKmedia/builder/khalid101/app/views/layouts/embedded_app.html.erb where line #7 raised:

```<code>Webpacker can't find hello_react.js in /Users/khalidhosein/Desktop/myEPKmedia/builder/khalid101/public/packs/manifest.json. Possible causes:
1. You want to set webpacker.yml value of compile to true for your environment
   unless you are using the `webpack -w` or the webpack-dev-server.
2. webpack has not yet re-run to reflect updates.
3. You have misconfigured Webpacker's config/webpacker.yml file.
4. Your webpack configuration is not creating a manifest.
Your manifest contains:
{
  "application.js": "/packs/application-68dcba18197451fbb79e.js",
  "application.js.map": "/packs/application-68dcba18197451fbb79e.js.map"
}
Extracted source (around line #7):
5
6
7
8
9
10

    <% application_name = ShopifyApp.configuration.application_name %>
    <title><%= application_name %></title>
    <%= javascript_pack_tag 'hello_react' %>
    <%= stylesheet_link_tag 'application' %>
    <%= javascript_include_tag 'application', "data-turbolinks-track" => true %>
    <%= csrf_meta_tags %>

Rails.root: /Users/khalidhosein/Desktop/myEPKmedia/builder/khalid101

Application Trace | Framework Trace | Full Trace
app/views/layouts/embedded_app.html.erb:7:in `_app_views_layouts_embedded_app_html_erb___4509380428416253144_70127991029820'
Request
Parameters:

None
</code>```

I am getting this error when trying to connect my Rails app with a React front end. I've tried researching and re-configuring files from all sources. I have also recreated manifiest.json files and packs libraries. I am following this tutorial:

```<code>https://github.com/natemacinnes/natemacinnes.github.io/blob/master/rails-5-shopify-app-setup.md
</code>```

If anyone has any ideas it would be greatly appreciated as there isn't much documentation or tutorials out there going over connecting Rails Shopify API with React.

MY CODE---->https://github.com/KhalidH82/ShopifyApp-React-Rails

答:
may be you missed to install npm install. I faced exactly same issue which you have mention. Just type npm install in your terminal or Dockerfile. I hope this issue will be solved.

```<code>$ npm install
</code>```

Body:
Webpacker::Manifest::MissingEntryError in Home#index
    Showing /Users/khalidhosein/Desktop/myEPKmedia/builder/khalid101/app/views/layouts/embedded_app.html.erb where line #7 raised:

Webpacker can't find hello_react.js in /Users/khalidhosein/Desktop/myEPKmedia/builder/khalid101/public/packs/manifest.json. Possible causes:
1. You want to set webpacker.yml value of compile to true for your environment
   unless you are using the `webpack -w` or the webpack-dev-server.
2. webpack has not yet re-run to reflect updates.
3. You have misconfigured Webpacker's config/webpacker.yml file.
4. Your webpack configuration is not creating a manifest.
Your manifest contains:
{
  "application.js": "/packs/application-68dcba18197451fbb79e.js",
  "application.js.map": "/packs/application-68dcba18197451fbb79e.js.map"
}
Extracted source (around line #7):
5
6
7
8
9
10

    <% application_name = ShopifyApp.configuration.application_name %>
    <title><%= application_name %></title>
    <%= javascript_pack_tag 'hello_react' %>
    <%= stylesheet_link_tag 'application' %>
    <%= javascript_include_tag 'application', "data-turbolinks-track" => true %>
    <%= csrf_meta_tags %>

Rails.root: /Users/khalidhosein/Desktop/myEPKmedia/builder/khalid101

Application Trace | Framework Trace | Full Trace
app/views/layouts/embedded_app.html.erb:7:in `_app_views_layouts_embedded_app_html_erb___4509380428416253144_70127991029820'
Request
Parameters:

None

I am getting this error when trying to connect my Rails app with a React front end. I've tried researching and re-configuring files from all sources. I have also recreated manifiest.json files and packs libraries. I am following this tutorial:

https://github.com/natemacinnes/natemacinnes.github.io/blob/master/rails-5-shopify-app-setup.md

If anyone has any ideas it would be greatly appreciated as there isn't much documentation or tutorials out there going over connecting Rails Shopify API with React.

MY CODE---->https://github.com/KhalidH82/ShopifyApp-React-Rails

Body:
may be you missed to install npm install. I faced exactly same issue which you have mention. Just type npm install in your terminal or Dockerfile. I hope this issue will be solved.

$ npm install


问:
How to implement zip function using LiveData
I'm using twos LiveDatas to get data from my server, and want to result after both LiveData finished?

LiveData live1 = ...;
LiveData live2 = ...;
MutableLiveData live3 = ...;

live1.observe(this, value -> {
    live3.postValue(value);
});

live2.observe(this, value -> {
   live3.postValue(value);
});

live3.observe(this,  value -> {
// TODO: Get both values from live1, live2
}
```

I expect the both values from live1 and live2

答:
My solution is somewhat inspired from rxjava zip operator,

```<code>inline fun <reified I1, I2, O> biZip(inputLiveData1: LiveData<I1>, inputLiveData2: LiveData<I2>, crossinline tranform: (data1: I1, data2: I2) -> O): LiveData<O> {

    var input1: I1? = null
    var input2: I2? = null
    val mediatorLiveData = MediatorLiveData<O>()
    mediatorLiveData.addSource(inputLiveData1) {
        input1 = it
        if (input1 != null && input2 != null) {
            mediatorLiveData.value = tranform.invoke(input1!!, input2!!)
        }
    }
    mediatorLiveData.addSource(inputLiveData2) {
        input2 = it
        if (input1 != null && input2 != null) {
            mediatorLiveData.value = tranform.invoke(input1!!, input2!!)
        }
    }

    return mediatorLiveData
}
</code>```

now you can use it like,

```<code>val liveDataString = MutableLiveData<String>()
val liveDataInt = MutableLiveData<Int>()

val liveDataofTest = biZip<String, Int, Test>(liveDataString, liveDataInt) { data1:String, data2:Int ->
      return@biZip Test(data1, data2)
}

</code>```

Test pojo is like

data class Test(val name:String,value:Int)

Body:
I'm using twos LiveDatas to get data from my server, and want to result after both LiveData finished?

LiveData live1 = ...;
LiveData live2 = ...;
MutableLiveData live3 = ...;

live1.observe(this, value -> {
    live3.postValue(value);
});

live2.observe(this, value -> {
   live3.postValue(value);
});

live3.observe(this,  value -> {
// TODO: Get both values from live1, live2
}

I expect the both values from live1 and live2

Body:
My solution is somewhat inspired from rxjava zip operator,

inline fun <reified I1, I2, O> biZip(inputLiveData1: LiveData<I1>, inputLiveData2: LiveData<I2>, crossinline tranform: (data1: I1, data2: I2) -> O): LiveData<O> {

    var input1: I1? = null
    var input2: I2? = null
    val mediatorLiveData = MediatorLiveData<O>()
    mediatorLiveData.addSource(inputLiveData1) {
        input1 = it
        if (input1 != null && input2 != null) {
            mediatorLiveData.value = tranform.invoke(input1!!, input2!!)
        }
    }
    mediatorLiveData.addSource(inputLiveData2) {
        input2 = it
        if (input1 != null && input2 != null) {
            mediatorLiveData.value = tranform.invoke(input1!!, input2!!)
        }
    }

    return mediatorLiveData
}

now you can use it like,

val liveDataString = MutableLiveData<String>()
val liveDataInt = MutableLiveData<Int>()

val liveDataofTest = biZip<String, Int, Test>(liveDataString, liveDataInt) { data1:String, data2:Int ->
      return@biZip Test(data1, data2)
}

Test pojo is like

data class Test(val name:String,value:Int)


问:
Can glReadPixels be used to read layers from GL_TEXTURE_3D?
I'm trying to read a 3D texture I rendered using an FBO. This texture is so large that glGetTexImage results in GL_OUT_OF_MEMORY error due to failure of nvidia driver to allocate memory for intermediate storage* (needed, I suppose, to avoid changing destination buffer in case of error).

So I then thought of getting this texture layer by layer, using glReadPixels after I render each layer. But glReadPixels doesn't have layer index as a parameter. The only place where it actually appears as something that directs I/O to the particular layer is gl_Layer output in the geometry shader. And that is for the writing stage, not reading.

As I tried simply doing the calls to glReadPixels anyway after I render each layer, I only got the texels for layer 0. So glReadPixels at least doesn't fail to get something.

But the question is: can I get arbitrary layer of a 3D texture using glReadPixels? And if not, what should I use instead, given the above described memory constraints? Do I have to sample the layer from 3D texture in a shader to render the result to a 2D texture, and read this 2D texture afterwards?

*It's not a guess, I've actually tracked it down to a failing malloc call (with the size of the texture as argument) from within the nvidia driver's shared library.

答:
So once you got your 3D texture you can do this:

```<code>for (z=0;z<z_resolution_of_your_txr;z++)
 {
 render_textured_quad(using z slice of 3D texture);
 glReadPixels(...);
 }
</code>```

Its best to match the QUAD size ot your 3D texture x,y resolutions and use GL_NEAREST filtering...

This will be slow so if you are not on Intel and want to be more fast you can use render to 2D Texture instead and use glGetTexImage on the target 2D texture instead of glReadPixels.

Here example shaders for rendering slice z:

Vertex:

```<code>//------------------------------------------------------------------
#version 420 core
//------------------------------------------------------------------
uniform float aspect;
layout(location=0) in vec2 pos;

out smooth vec2 vpos;
//------------------------------------------------------------------
void main(void)
    {
    vpos=pos;
    gl_Position=vec4(pos.x,pos.y*aspect,0.0,1.0);
    }
//------------------------------------------------------------------
</code>```

Fragment:

```<code>//------------------------------------------------------------------
#version 420 core
//------------------------------------------------------------------
uniform float slice=0.25;       // <0,1> slice of txr
in smooth vec2      vpos;
uniform sampler3D   vol_txr;    // 3D texture unit used
out layout(location=0) vec4 frag_col;
void main()
    {
    frag_col=texture(vol_txr,vec3(0.5*(vpos+1.0),slice));
    }
//---------------------------------------------------------------------------
</code>```

So you need to change the slice uniform before each slice render. The rendering itself is just single QUAD covering the screen <-1,+1> while viewport matches the texture x,y resolution...

Body:
So once you got your 3D texture you can do this:

for (z=0;z<z_resolution_of_your_txr;z++)
 {
 render_textured_quad(using z slice of 3D texture);
 glReadPixels(...);
 }

Its best to match the QUAD size ot your 3D texture x,y resolutions and use GL_NEAREST filtering...

This will be slow so if you are not on Intel and want to be more fast you can use render to 2D Texture instead and use glGetTexImage on the target 2D texture instead of glReadPixels.

Here example shaders for rendering slice z:

Vertex:

//------------------------------------------------------------------
#version 420 core
//------------------------------------------------------------------
uniform float aspect;
layout(location=0) in vec2 pos;

out smooth vec2 vpos;
//------------------------------------------------------------------
void main(void)
    {
    vpos=pos;
    gl_Position=vec4(pos.x,pos.y*aspect,0.0,1.0);
    }
//------------------------------------------------------------------

Fragment:

//------------------------------------------------------------------
#version 420 core
//------------------------------------------------------------------
uniform float slice=0.25;       // <0,1> slice of txr
in smooth vec2      vpos;
uniform sampler3D   vol_txr;    // 3D texture unit used
out layout(location=0) vec4 frag_col;
void main()
    {
    frag_col=texture(vol_txr,vec3(0.5*(vpos+1.0),slice));
    }
//---------------------------------------------------------------------------

So you need to change the slice uniform before each slice render. The rendering itself is just single QUAD covering the screen <-1,+1> while viewport matches the texture x,y resolution...


问:
unable to update text field on event using js - undefined
my intention is to set the value of the input using js when I change de select option. But its getting undefined value

This is my html (jsp) file.

```<code><body>
        <center><h1>Ventas</h1>
            <table border="2">
                <tr>
                    <th>Producto</th>
                    <th>Precio</th>
                </tr>
                <tr>
                    <th>
                        <select name="productos" onchange="ponerPrecio(event)">
                            <c:forEach items="${product}" var="prdct">
                                <option value="${prdct.idProducto}" data="${prdct.precioUnidad}">${prdct.nombre}</option>
                            </c:forEach>
                        </select>
                        <td><input type="text" name="precio" id="price" value="" readonly></input></td>
                    </th>
                </ tr>
                <script>

                    function ponerPrecio(e) {

                        var precio = e.target.data;
                        document.getElementById("price").value = precio ;

                    }
                </script>
            </table>
                    <input type="button" name="begin" value="Inicio"onclick="window.location.href='principal.htm'" />
        </center>
    </body>

</code>```

From ${product} im getting all the items of my DB to use it. The idea is to use "data" to update the input with the name precio with the value of ${prdct.precioUnidad}.

答:
Use data-price instead of data attribute

Ventas

            Producto
            Precio

                <select name="productos" onchange="ponerPrecio(event)">
                    <c:forEach items="${product}" var="prdct">
                        <option value="${prdct.idProducto}" data-price="${prdct.precioUnidad}">${prdct.nombre}</option>
                        <option value="2" data-price="10">Custom Item</option>
                    </c:forEach>
                </select>

            <input type="text" name="precio" id="price" value="" readonly></input>

    <input type="button" name="begin" value="Inicio" onclick="window.location.href='principal.htm'" />

    ```

Body:
my intention is to set the value of the input using js when I change de select option. But its getting undefined value

This is my html (jsp) file.

Ventas

                    Producto
                    Precio

                        <select name="productos" onchange="ponerPrecio(event)">
                            <c:forEach items="${product}" var="prdct">
                                <option value="${prdct.idProducto}" data="${prdct.precioUnidad}">${prdct.nombre}</option>
                            </c:forEach>
                        </select>
                        <input type="text" name="precio" id="price" value="" readonly></input>

                    <input type="button" name="begin" value="Inicio"onclick="window.location.href='principal.htm'" />

From ${product} im getting all the items of my DB to use it. The idea is to use "data" to update the input with the name precio with the value of ${prdct.precioUnidad}.

Body:
Use data-price instead of data attribute

<center>
    <h1>Ventas</h1>
    <table border="2">
        <tr>
            <th>Producto</th>
            <th>Precio</th>
        </tr>
        <tr>
            <th>
                <select name="productos" onchange="ponerPrecio(event)">
                    <c:forEach items="${product}" var="prdct">
                        <option value="${prdct.idProducto}" data-price="${prdct.precioUnidad}">${prdct.nombre}</option>
                        <option value="2" data-price="10">Custom Item</option>
                    </c:forEach>
                </select>
            </th>
            <td><input type="text" name="precio" id="price" value="" readonly></input></td>
        </tr>
    </table>
    <input type="button" name="begin" value="Inicio" onclick="window.location.href='principal.htm'" />

    <script>
        function ponerPrecio(e) {
            var precio = e.target.options[e.target.selectedIndex].dataset.price;
            document.getElementById("price").value = precio;
        }
    </script>
</center>


问:
Concatenate directory and file name in GNU parallel
I have the following directory structure:

```<code>dir1/file.ogg
dir2/file.ogg
dir3/file.ogg
     file2.ogg
</code>```

I would like to convert all .ogg files to .wav with GNU Parallel. Here's where I got thus far:

```<code>find . -name '*.*' -type f -print0 | parallel -0 ffmpeg -i {} outputdir/{/.}.wav
</code>```

The problem here is that although obviously directories have different names, the files inside have the same name. The aforementioned command will continuously overwrite the content of the directory. What I'd like instead is:

```<code>outputdir/dir1_file.ogg
outputdir/dir2_file.ogg
outputdir/dir3_file.ogg
outputdir/dir3_file2.ogg
</code>```

Essentially, I'd like to extract the subdirectory name and concatenate it with file basename and put my own extension.

Any ideas?

答:
Using perl transformation, this command should achieve the required effect :

```<code>find . -name '*.ogg' -type f -print0 | parallel -0 echo ffmpeg -i {} outputdir/{= '$_ =~ s[^\./][]; $_ =~ s[/][_]g; $_ =~ s[ogg$][wav]g;' =}
</code>```

Remove echo to run ffmpeg command

Body:
I have the following directory structure:

dir1/file.ogg
dir2/file.ogg
dir3/file.ogg
     file2.ogg

I would like to convert all .ogg files to .wav with GNU Parallel. Here's where I got thus far:

find . -name '*.*' -type f -print0 | parallel -0 ffmpeg -i {} outputdir/{/.}.wav

The problem here is that although obviously directories have different names, the files inside have the same name. The aforementioned command will continuously overwrite the content of the directory. What I'd like instead is:

outputdir/dir1_file.ogg
outputdir/dir2_file.ogg
outputdir/dir3_file.ogg
outputdir/dir3_file2.ogg

Essentially, I'd like to extract the subdirectory name and concatenate it with file basename and put my own extension.

Any ideas?

Body:
Using perl transformation, this command should achieve the required effect :

find . -name '*.ogg' -type f -print0 | parallel -0 echo ffmpeg -i {} outputdir/{= '$_ =~ s[^\./][]; $_ =~ s[/][_]g; $_ =~ s[ogg$][wav]g;' =}

Remove echo to run ffmpeg command


问:
Generating variable by groups taking values of certain observations
I have a dataset with only variable values:

```<code>clear
input value new_var
1   1
3   3
5   5
30  1
40  3
50  5
11  1
12  3
13  5
end
</code>```

How can I generate a new variable new_var containing a repeating sequence of the first three observations in value?

Body:
I have a dataset with only variable values:

clear
input value new_var
1   1
3   3
5   5
30  1
40  3
50  5
11  1
12  3
13  5
end

How can I generate a new variable new_var containing a repeating sequence of the first three observations in value?

Body:
Many ways to do it: here are two:

clear
input value new_var
1   1
3   3
5   5
30  1
40  3
50  5
11  1
12  3
13  5
end

egen index = seq(), to(3)
generate wanted = value[index]

generate direct = cond(mod(_n, 3) == 1, 1, cond(mod(_n, 3) == 2, 3, 5))

list, sep(3)

     +-------------------------------------------+
     | value   new_var   index   wanted   direct |
     |-------------------------------------------|
  1. |     1         1       1        1        1 |
  2. |     3         3       2        3        3 |
  3. |     5         5       3        5        5 |
     |-------------------------------------------|
  4. |    30         1       1        1        1 |
  5. |    40         3       2        3        3 |
  6. |    50         5       3        5        5 |
     |-------------------------------------------|
  7. |    11         1       1        1        1 |
  8. |    12         3       2        3        3 |
  9. |    13         5       3        5        5 |
     +-------------------------------------------+


问:
React Navigation hide/show navigation bar
I am facing a problem with hiding or showing the navigation bar with ReactNavigation 5.x.

For example if I have a navigation stack with ScreenA, ScreenB & ScreenC. ScreenA shouldn't show the navigation bar, but on moving to ScreenB or ScreenC the bar should be visible. On popping to ScreenA, the bar should no longer be there. I have used the following code, but that makes the bar hidden always. This has to be achieved in both iOS and Android.

```<code>class App extends Component {
  render() {
    return(
      <NavigationContainer>
        <Stack.Navigator screenOptions={{headerShown: false}}>
          <Stack.Screen
            name="Login"
            component={LoginScreen}/>
          <Stack.Screen
            title='Parent Info'
            name='ParentInfo'
            component={ParentInfoScreen}
          />
        </Stack.Navigator>
      </NavigationContainer>
    )}
}
</code>```

答:
Each screen also has an options prop so instead of using screenOptions on stack.navigator use options on stack.screen like this:

```<code><Stack.Navigator>
  <Stack.Screen
    options={{headerShown: false}}
    name="Login"
    component={LoginScreen}
  />
  <Stack.Screen
    title="Parent Info"
    name="ParentInfo"
    component={ParentInfoScreen}
  />
</Stack.Navigator>
</code>```

Then you can specify by screen

Body:
I am facing a problem with hiding or showing the navigation bar with ReactNavigation 5.x.

For example if I have a navigation stack with ScreenA, ScreenB & ScreenC. ScreenA shouldn't show the navigation bar, but on moving to ScreenB or ScreenC the bar should be visible. On popping to ScreenA, the bar should no longer be there. I have used the following code, but that makes the bar hidden always. This has to be achieved in both iOS and Android.

class App extends Component {
  render() {
    return(
      <NavigationContainer>
        <Stack.Navigator screenOptions={{headerShown: false}}>
          <Stack.Screen
            name="Login"
            component={LoginScreen}/>
          <Stack.Screen
            title='Parent Info'
            name='ParentInfo'
            component={ParentInfoScreen}
          />
        </Stack.Navigator>
      </NavigationContainer>
    )}
}

Body:
Each screen also has an options prop so instead of using screenOptions on stack.navigator use options on stack.screen like this:

<Stack.Navigator>
  <Stack.Screen
    options={{headerShown: false}}
    name="Login"
    component={LoginScreen}
  />
  <Stack.Screen
    title="Parent Info"
    name="ParentInfo"
    component={ParentInfoScreen}
  />
</Stack.Navigator>

Then you can specify by screen


问:
Parse error: syntax error, unexpected '$user' (T_VARIABLE), expecting function (T_FUNCTION) or const (T_CONST)
I did a function that calculates the total price, by a specific user and his cart shopping, with PHP.

I`m getting this error:

Parse error: syntax error, unexpected '$user' (T_VARIABLE), expecting function (T_FUNCTION) or const (T_CONST) in C:\xampp\htdocs\myPrograms\projectTest.php on line 43.

This is my code (the problematic line is the 2nd line below):

```<code>    Class bill {

    $username= 'almog';

    echo "Your total price for this bought is:" .Total_bill($username). "Dollars"."<br>";

    function Total_bill($username)
    {
        $total = 0;
        $query= $this-> db->query ("select serial_number, count_purchase, price_item from bought_history LEFT JOIN
        product ON bought_history. serial_number = product. serial_number where username=username and date_purchase= date_purchase");

    foreach($query as $key=> $value )
    {

        if ($bought_history. $serial_number->$count_purchase ==1)
        {
            $total = $total + $product. $serial_number->$price_item;
        }
        else
        {
            $total = $total + ($product. $serial_number->$price_item * $bought_history. $serial_number->$count_purchase);
        }
    }

    return $total;
    }
}
</code>```

答:
```<code>Class bill {

    $username= 'almog';

    echo "Your total price for this bought is:" .Total_bill($username). "Dollars"."<br>";

    function Total_bill($username)
    {
</code>```

You can't put "code" directly inside the class definition - which is what it looks like you are trying to do here. By "code" I'm refering to the $username variable assignment and the echo statement that follows. (Fix the $username parse error and you'll get the same parse error refering to the echo statement.)

However, it's not clear where that code should go (inside a class method OR called from outside the class OR not use a class at all?) since you are referencing the Total_bill() class method as a global function (which it is not in your example).

To get your code into a "working" state, either:

Move your "code" outside of the class definition entirely. For example:

```<code>Class bill {

    // Class definition here...

}

$username = 'almog';

$billInstance = new bill();

echo "Your total price for this bought is:" .$billInstance->Total_bill($username). "Dollars"."<br>";
</code>```

OR, move your code into another class method (although this probably doesn't make much sense given what you are trying to do). For example:

```<code>Class bill()

    // Rest of class definition here...

    function outputTotalBill()
    {
        $username = 'almog';
        echo "Your total price for this bought is:" .$this->Total_bill($username). "Dollars"."<br>";
    }
}

$billInstance = new bill();

$billInstance->outputTotalBill();
</code>```

OR, perhaps you shouldn't be using a class here at all? And Total_bill() should be a global function in your example?

Reference:

https://www.php.net/manual/en/language.oop5.basic.php

Body:
I did a function that calculates the total price, by a specific user and his cart shopping, with PHP.

I`m getting this error:

Parse error: syntax error, unexpected '$user' (T_VARIABLE), expecting function (T_FUNCTION) or const (T_CONST) in C:\xampp\htdocs\myPrograms\projectTest.php on line 43.

This is my code (the problematic line is the 2nd line below):

    Class bill {

    $username= 'almog';

    echo "Your total price for this bought is:" .Total_bill($username). "Dollars"."
";

    function Total_bill($username)
    {
        $total = 0;
        $query= $this-> db->query ("select serial_number, count_purchase, price_item from bought_history LEFT JOIN
        product ON bought_history. serial_number = product. serial_number where username=username and date_purchase= date_purchase");

    foreach($query as $key=> $value )
    {

        if ($bought_history. $serial_number->$count_purchase ==1)
        {
            $total = $total + $product. $serial_number->$price_item;
        }
        else
        {
            $total = $total + ($product. $serial_number->$price_item * $bought_history. $serial_number->$count_purchase);
        }
    }

    return $total;
    }
}

Body:
Class bill {

    $username= 'almog';

    echo "Your total price for this bought is:" .Total_bill($username). "Dollars"."<br>";

    function Total_bill($username)
    {

You can't put "code" directly inside the class definition - which is what it looks like you are trying to do here. By "code" I'm refering to the $username variable assignment and the echo statement that follows. (Fix the $username parse error and you'll get the same parse error refering to the echo statement.)

However, it's not clear where that code should go (inside a class method OR called from outside the class OR not use a class at all?) since you are referencing the Total_bill() class method as a global function (which it is not in your example).

To get your code into a "working" state, either:

Move your "code" outside of the class definition entirely. For example:

Class bill {

    // Class definition here...

}

$username = 'almog';

$billInstance = new bill();

echo "Your total price for this bought is:" .$billInstance->Total_bill($username). "Dollars"."<br>";

OR, move your code into another class method (although this probably doesn't make much sense given what you are trying to do). For example:

Class bill()

    // Rest of class definition here...

    function outputTotalBill()
    {
        $username = 'almog';
        echo "Your total price for this bought is:" .$this->Total_bill($username). "Dollars"."<br>";
    }
}

$billInstance = new bill();

$billInstance->outputTotalBill();

OR, perhaps you shouldn't be using a class here at all? And Total_bill() should be a global function in your example?

Reference:

https://www.php.net/manual/en/language.oop5.basic.php


问:
Floating Action Button android
Could someone help me? the moment I press on the FloatingActionButton the activity is closed and goes back. What am I doing wrong?

```<code>    public class Regolamento extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_regolamento);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "English", Snackbar.LENGTH_LONG);
                TextView tv = (TextView) findViewById(R.id.text);
                tv.setText("ciao");

            }
        });
    }}
</code>```

```<code><androidx.core.widget.NestedScrollView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:context=".Regolamento"
        tools:showIn="@layout/activity_regolamento">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="@dimen/text_margin"
            android:text="wow"/>
    </androidx.core.widget.NestedScrollView>

</code>```

How should i do? Can someone help me? until just before everything worked then suddenly it stopped working

java.lang.NullPointerException: Attempt to invoke virtual
     method 'void
     android.widget.TextView.setText(java.lang.CharSequence)' on a
      null object reference
      at     com.example.bbmarinablu.Regolamento$1.onClick(Regolamento.java:29)
      at android.view.View.performClick(Unknown Source:17)
      at android.view.View.performClickInternal(Unknown Source:3)
      at android.view.View.access$3500(Unknown Source:0)
      at android.view.View$PerformClick.run(Unknown Source:8)
      at android.os.Handler.handleCallback(Unknown Source:2)
      at android.os.Handler.dispatchMessage(Unknown Source:4)
      at android.os.Looper.loop(Unknown Source:242)
      at android.app.ActivityThread.main(Unknown Source:98)
      at java.lang.reflect.Method.invoke(Native Method)
      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(Unknown Source:11)
      at com.android.internal.os.ZygoteInit.main(Unknown Source:275)

答:
You need to define id text in activity_regolamento.xml.

Add android:id="@+id/text" in TextView element.

Title: Floating Action Button android

Body:
Could someone help me? the moment I press on the FloatingActionButton the activity is closed and goes back. What am I doing wrong?

    public class Regolamento extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_regolamento);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "English", Snackbar.LENGTH_LONG);
                TextView tv = (TextView) findViewById(R.id.text);
                tv.setText("ciao");

            }
        });
    }}

<androidx.core.widget.NestedScrollView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:context=".Regolamento"
        tools:showIn="@layout/activity_regolamento">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="@dimen/text_margin"
            android:text="wow"/>
    </androidx.core.widget.NestedScrollView>

How should i do? Can someone help me? until just before everything worked then suddenly it stopped working

java.lang.NullPointerException: Attempt to invoke virtual
     method 'void
     android.widget.TextView.setText(java.lang.CharSequence)' on a
      null object reference
      at     com.example.bbmarinablu.Regolamento$1.onClick(Regolamento.java:29)
      at android.view.View.performClick(Unknown Source:17)
      at android.view.View.performClickInternal(Unknown Source:3)
      at android.view.View.access$3500(Unknown Source:0)
      at android.view.View$PerformClick.run(Unknown Source:8)
      at android.os.Handler.handleCallback(Unknown Source:2)
      at android.os.Handler.dispatchMessage(Unknown Source:4)
      at android.os.Looper.loop(Unknown Source:242)
      at android.app.ActivityThread.main(Unknown Source:98)
      at java.lang.reflect.Method.invoke(Native Method)
      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(Unknown Source:11)
      at com.android.internal.os.ZygoteInit.main(Unknown Source:275)


问:
EFCore 3.1 Adding default shadow properties and use them for softdelete
I am developing an application with C# .NET Core 3.1 and EFCore. Based on this document, I tried to add new column and use Queryfilter.

```<code>        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.ApplyConfiguration(new UserEntityTypeConfiguration());
            ....
            //Other configurations
            ...

            // Assures consistent naming and configuration of audit fields.
            foreach (IMutableEntityType entityType in modelBuilder.Model.GetEntityTypes().Where(item => !item.IsOwned()))
            {
                //Settings related to softdelete
                modelBuilder.Entity(entityType.Name).Property<bool>(nameof(DefaultColumnName.IsDeleted)).HasDefaultValue(false);
                var IsDeletedProperty = entityType.FindProperty(nameof(DefaultColumnName.IsDeleted));
                if (IsDeletedProperty != null && IsDeletedProperty.ClrType == typeof(bool))
                {
                    var parameter = Expression.Parameter(entityType.ClrType, "p");
                    var prop = Expression.Property(parameter, IsDeletedProperty.PropertyInfo);
                    var filter = Expression.Lambda(Expression.Not(prop), parameter);
                    MutableEntityTypeExtensions.SetQueryFilter(entityType, filter);
                }
            }

</code>```

However, when I migrate with dotnet ef migrations add Init, following error appears and cannot migrate well.

```<code>Value cannot be null. (Parameter 'property')
</code>```

According to my investigation, this error occurrs at this line, but I do not know how to fix the problem.

```<code>var prop = Expression.Property(parameter, IsDeletedProperty.PropertyInfo);
</code>```

Could anyone tell me how to fix the issue?

答:
Shadow properties are not real properties of a class, hence have no associated PropertyInfo or FieldInfo. As explained in Accessing shadow properties
:

Shadow property values can be obtained and changed through the ChangeTracker API

Shadow properties can be referenced in LINQ queries via the EF.Property static method

The second applies to filter expressions as well. So you need property accessor like

```<code>EF.Property<bool>(p, "IsDeleted")
</code>```

which for your code means changing the line in question as follows

```<code>var prop = Expression.Call(
    typeof(EF), nameof(EF.Property), new[] { typeof(bool) },
    parameter, Expression.Constant(IsDeletedProperty.Name));
</code>```

Body:
I am developing an application with C# .NET Core 3.1 and EFCore. Based on this document, I tried to add new column and use Queryfilter.

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.ApplyConfiguration(new UserEntityTypeConfiguration());
            ....
            //Other configurations
            ...

            // Assures consistent naming and configuration of audit fields.
            foreach (IMutableEntityType entityType in modelBuilder.Model.GetEntityTypes().Where(item => !item.IsOwned()))
            {
                //Settings related to softdelete
                modelBuilder.Entity(entityType.Name).Property<bool>(nameof(DefaultColumnName.IsDeleted)).HasDefaultValue(false);
                var IsDeletedProperty = entityType.FindProperty(nameof(DefaultColumnName.IsDeleted));
                if (IsDeletedProperty != null && IsDeletedProperty.ClrType == typeof(bool))
                {
                    var parameter = Expression.Parameter(entityType.ClrType, "p");
                    var prop = Expression.Property(parameter, IsDeletedProperty.PropertyInfo);
                    var filter = Expression.Lambda(Expression.Not(prop), parameter);
                    MutableEntityTypeExtensions.SetQueryFilter(entityType, filter);
                }
            }

However, when I migrate with dotnet ef migrations add Init, following error appears and cannot migrate well.

Value cannot be null. (Parameter 'property')

According to my investigation, this error occurrs at this line, but I do not know how to fix the problem.

var prop = Expression.Property(parameter, IsDeletedProperty.PropertyInfo);

Could anyone tell me how to fix the issue?

Body:
Shadow properties are not real properties of a class, hence have no associated PropertyInfo or FieldInfo. As explained in Accessing shadow properties
:

Shadow property values can be obtained and changed through the ChangeTracker API

Shadow properties can be referenced in LINQ queries via the EF.Property static method

The second applies to filter expressions as well. So you need property accessor like

EF.Property<bool>(p, "IsDeleted")

which for your code means changing the line in question as follows

var prop = Expression.Call(
    typeof(EF), nameof(EF.Property), new[] { typeof(bool) },
    parameter, Expression.Constant(IsDeletedProperty.Name));


问:
How to convert values from 0: 270 to 0:1023 in Python?
Hi i need help with my script for Arduino with Python
I have python script it put out angle between 0-270
I need to convert this value to servo-read-able in meaning 0-1023
Can some one from community help me
Thanks</p>

答:
So you just want to convert one number into another? Or the list of numbers?
It sounds simple

```<code>new_angle = int(old_angle*3.78 )
</code>```

3.78 # Because it's 1023/270

And then int() to convert to integer

Body:
So you just want to convert one number into another? Or the list of numbers?
It sounds simple

new_angle = int(old_angle*3.78 )

3.78 # Because it's 1023/270

And then int() to convert to integer


问:
Why is call to constructor not displayed when using "step into" in eclipse even without step filter
I'm trying to understand how Math.random() generates a random number. Therefore I used eclipse debugger and the feature "step into".

When I set a breakpoint at

```<code>        double mathRandom = Math.random();
</code>```

And use "step into" this takes me into the Math.class to the code:

```<code>public static double random() {
    return RandomNumberGeneratorHolder.randomNumberGenerator.nextDouble();
}
</code>```

So calling random() calls constructor randomNumberGenerator in the class RandomNumberGeneratorHolder which is within the Math class.

The constructor randomNumberGenerator is also in the Math class in the line

```<code>private static final class RandomNumberGeneratorHolder {
    static final Random randomNumberGenerator = new Random();
}
</code>```

But when I use "step into" in the line

```<code>public static double random() {
    return RandomNumberGeneratorHolder.randomNumberGenerator.nextDouble();
}
</code>```

Why does this not take me to the constructor

```<code>private static final class RandomNumberGeneratorHolder {
    static final Random randomNumberGenerator = new Random();
}
</code>```

But instead takes me into the Random class to the line

```<code>public double nextDouble() {
    return (((long)(next(26)) << 27) + next(27)) * DOUBLE_UNIT;
}
</code>```

I have "Use step filters" disabled. So what is the reason eclipse skips the call to the constructor

```<code>static final Random randomNumberGenerator = new Random()
</code>```

答:
With Math.random() you call a static method. Static methods do not depend on having an instance of the class.

A non-static call would be:

```<code>Math math=new Math();
double m = math.random();
</code>```

But that does not compile because the default constructor of Math is private.

You wrote "So calling random() calls constructor randomNumberGenerator in the class", which is not true. There is no "new" keyword, hence no constructor call.

```<code>RandomNumberGeneratorHolder.randomNumberGenerator.nextDouble();
</code>```

Here "randomNumberGenerator" is a static attribute (variable) of the RandomNumberGeneratorHolder class. Static access does not depend on calling a constructor.

Java classes may optionally contain a nameless static initializer which is executed by the Java VM when the class gets loaded into memory. Static initializer can initialize static attributes of the class. Such an initializer did obviously fill the static "randomNumberGenerator" attribute with an instance of a class. Therefore you are able to call its non-static nextDouble() method.

Other well known examples are System.out and System.in.

I give you two examples how to program such a static initializer:

```<code>import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Main
{
    static List<String> names;
    static List<String> colors= Arrays.asList("red","green");

    static // notice that this method has no name!
    {
        names=new ArrayList<String>();
        names.add("CuriousIndeed");
        names.add("Stefan");
    }

    public static void main(String[] args)
    {
        System.out.println(names);
        System.out.println(colors);
    }
}
</code>```

Outputs:

```<code>[CuriousIndeed, Stefan]
[red, green]
</code>```

Both, the names and colors have been statically initialized but in two different ways.

Body:
I'm trying to understand how Math.random() generates a random number. Therefore I used eclipse debugger and the feature "step into".

When I set a breakpoint at

        double mathRandom = Math.random();

And use "step into" this takes me into the Math.class to the code:

public static double random() {
    return RandomNumberGeneratorHolder.randomNumberGenerator.nextDouble();
}

So calling random() calls constructor randomNumberGenerator in the class RandomNumberGeneratorHolder which is within the Math class.

The constructor randomNumberGenerator is also in the Math class in the line

private static final class RandomNumberGeneratorHolder {
    static final Random randomNumberGenerator = new Random();
}

But when I use "step into" in the line

public static double random() {
    return RandomNumberGeneratorHolder.randomNumberGenerator.nextDouble();
}

Why does this not take me to the constructor

private static final class RandomNumberGeneratorHolder {
    static final Random randomNumberGenerator = new Random();
}

But instead takes me into the Random class to the line

public double nextDouble() {
    return (((long)(next(26)) << 27) + next(27)) * DOUBLE_UNIT;
}

I have "Use step filters" disabled. So what is the reason eclipse skips the call to the constructor

static final Random randomNumberGenerator = new Random()

Body:
With Math.random() you call a static method. Static methods do not depend on having an instance of the class.

A non-static call would be:

Math math=new Math();
double m = math.random();

But that does not compile because the default constructor of Math is private.

You wrote "So calling random() calls constructor randomNumberGenerator in the class", which is not true. There is no "new" keyword, hence no constructor call.

RandomNumberGeneratorHolder.randomNumberGenerator.nextDouble();

Here "randomNumberGenerator" is a static attribute (variable) of the RandomNumberGeneratorHolder class. Static access does not depend on calling a constructor.

Java classes may optionally contain a nameless static initializer which is executed by the Java VM when the class gets loaded into memory. Static initializer can initialize static attributes of the class. Such an initializer did obviously fill the static "randomNumberGenerator" attribute with an instance of a class. Therefore you are able to call its non-static nextDouble() method.

Other well known examples are System.out and System.in.

I give you two examples how to program such a static initializer:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Main
{
    static List<String> names;
    static List<String> colors= Arrays.asList("red","green");

    static // notice that this method has no name!
    {
        names=new ArrayList<String>();
        names.add("CuriousIndeed");
        names.add("Stefan");
    }

    public static void main(String[] args)
    {
        System.out.println(names);
        System.out.println(colors);
    }
}

Outputs:

[CuriousIndeed, Stefan]
[red, green]

Both, the names and colors have been statically initialized but in two different ways.


问:
Svg to png many files conversion using Inkscape from batch file
I have a folder containing many svg files and I would like to convert them to png files using inkscape with a batch script (Windows 10 *.bat file).
the following script works correctly for a single file but, how to iterate the same command for hundreds of files inside a directory?

```<code>PATH = "C:\Program Files\Inkscape"

inkscape myfile.svg --export-png=myfile.png
</code>```

答:
<pre class="lang-bash prettyprint-override"><code>@echo off
for %%i in ("%~dp0*.svg") do (
    echo %%i to %%~ni.png
    "C:\Program Files\Inkscape\bin\inkscape.exe" --export-type="png" "%%i"
)
</code>```
<p>Additional options for export are listed in this Wiki page, and in the man page (official documentation): in particular, you can set the DPI, height/width, what zone you export, etc.</p>
<p>To speed things up by utilizing all of your logic cores, you can use this multitasking approach:<br />
Parallel execution of shell processes</p>
<pre class="lang-bat prettyprint-override"><code>@echo off
setlocal enableDelayedExpansion

:: Define the command that will be run to obtain the list of files to process
set listCmd=dir /b /a-d "%~dp0*.svg"

:: Define the command to run for each file, where "%%F" is an iterated file name from the list
::   something like YOUR_COMMAND -in "%%F" -out "%%~nF.ext"
set runCmd=""C:\Program Files\Inkscape\bin\inkscape.exe" --export-type="png" "%%F""

:: Define the maximum number of parallel processes to run.
set "maxProc=%NUMBER_OF_PROCESSORS%"

::---------------------------------------------------------------------------------
:: The remainder of the code should remain constant
::

:: Get a unique base lock name for this particular instantiation.
:: Incorporate a timestamp from WMIC if possible, but does not fail if
:: WMIC not available. Also incorporate a random number.
  set "lock="
  for /f "skip=1 delims=-+ " %%T in ('2^>nul wmic os get localdatetime') do (
    set "lock=%%T"
    goto :break
  )
  :break
  set "lock=%temp%\lock%lock%_%random%_"

:: Initialize the counters
  set /a "startCount=0, endCount=0"

:: Clear any existing end flags
  for /l %%N in (1 1 %maxProc%) do set "endProc%%N="

:: Launch the commands in a loop
  set launch=1
  for /f "tokens=* delims=:" %%F in ('%listCmd%') do (
    if !startCount! lss %maxProc% (
      set /a "startCount+=1, nextProc=startCount"
    ) else (
      call :wait
    )
    set cmd!nextProc!=%runCmd%
    echo -------------------------------------------------------------------------------
    echo !time! - proc!nextProc!: starting %runCmd%
    2>nul del %lock%!nextProc!
    %= Redirect the lock handle to the lock file. The CMD process will     =%
    %= maintain an exclusive lock on the lock file until the process ends. =%
    start /b "" cmd /c >"%lock%!nextProc!" 2^>^&1 %runCmd%
  )
  set "launch="

:wait
:: Wait for procs to finish in a loop
:: If still launching then return as soon as a proc ends
:: else wait for all procs to finish
  :: redirect stderr to null to suppress any error message if redirection
  :: within the loop fails.
  for /l %%N in (1 1 %startCount%) do 2>nul (
    %= Redirect an unused file handle to the lock file. If the process is    =%
    %= still running then redirection will fail and the IF body will not run =%
    if not defined endProc%%N if exist "%lock%%%N" 9>>"%lock%%%N" (
      %= Made it inside the IF body so the process must have finished =%
      echo ===============================================================================
      echo !time! - proc%%N: finished !cmd%%N!
      type "%lock%%%N"
      if defined launch (
        set nextProc=%%N
        exit /b
      )
      set /a "endCount+=1, endProc%%N=1"
    )
  )
  if %endCount% lss %startCount% (
    timeout /t 1 /nobreak >nul
    goto :wait
  )

2>nul del %lock%*
echo ===============================================================================
</code>```

Body:
I have a folder containing many svg files and I would like to convert them to png files using inkscape with a batch script (Windows 10 *.bat file).
the following script works correctly for a single file but, how to iterate the same command for hundreds of files inside a directory?

PATH = "C:\Program Files\Inkscape"

inkscape myfile.svg --export-png=myfile.png

Body:
@echo off
for %%i in ("%~dp0*.svg") do (
    echo %%i to %%~ni.png
    "C:\Program Files\Inkscape\bin\inkscape.exe" --export-type="png" "%%i"
)

Additional options for export are listed in this Wiki page, and in the man page (official documentation): in particular, you can set the DPI, height/width, what zone you export, etc.

To speed things up by utilizing all of your logic cores, you can use this multitasking approach:

Parallel execution of shell processes

@echo off
setlocal enableDelayedExpansion

:: Define the command that will be run to obtain the list of files to process
set listCmd=dir /b /a-d "%~dp0*.svg"

:: Define the command to run for each file, where "%%F" is an iterated file name from the list
::   something like YOUR_COMMAND -in "%%F" -out "%%~nF.ext"
set runCmd=""C:\Program Files\Inkscape\bin\inkscape.exe" --export-type="png" "%%F""

:: Define the maximum number of parallel processes to run.
set "maxProc=%NUMBER_OF_PROCESSORS%"

::---------------------------------------------------------------------------------
:: The remainder of the code should remain constant
::

:: Get a unique base lock name for this particular instantiation.
:: Incorporate a timestamp from WMIC if possible, but does not fail if
:: WMIC not available. Also incorporate a random number.
  set "lock="
  for /f "skip=1 delims=-+ " %%T in ('2^>nul wmic os get localdatetime') do (
    set "lock=%%T"
    goto :break
  )
  :break
  set "lock=%temp%\lock%lock%_%random%_"

:: Initialize the counters
  set /a "startCount=0, endCount=0"

:: Clear any existing end flags
  for /l %%N in (1 1 %maxProc%) do set "endProc%%N="

:: Launch the commands in a loop
  set launch=1
  for /f "tokens=* delims=:" %%F in ('%listCmd%') do (
    if !startCount! lss %maxProc% (
      set /a "startCount+=1, nextProc=startCount"
    ) else (
      call :wait
    )
    set cmd!nextProc!=%runCmd%
    echo -------------------------------------------------------------------------------
    echo !time! - proc!nextProc!: starting %runCmd%
    2>nul del %lock%!nextProc!
    %= Redirect the lock handle to the lock file. The CMD process will     =%
    %= maintain an exclusive lock on the lock file until the process ends. =%
    start /b "" cmd /c >"%lock%!nextProc!" 2^>^&1 %runCmd%
  )
  set "launch="

:wait
:: Wait for procs to finish in a loop
:: If still launching then return as soon as a proc ends
:: else wait for all procs to finish
  :: redirect stderr to null to suppress any error message if redirection
  :: within the loop fails.
  for /l %%N in (1 1 %startCount%) do 2>nul (
    %= Redirect an unused file handle to the lock file. If the process is    =%
    %= still running then redirection will fail and the IF body will not run =%
    if not defined endProc%%N if exist "%lock%%%N" 9>>"%lock%%%N" (
      %= Made it inside the IF body so the process must have finished =%
      echo ===============================================================================
      echo !time! - proc%%N: finished !cmd%%N!
      type "%lock%%%N"
      if defined launch (
        set nextProc=%%N
        exit /b
      )
      set /a "endCount+=1, endProc%%N=1"
    )
  )
  if %endCount% lss %startCount% (
    timeout /t 1 /nobreak >nul
    goto :wait
  )

2>nul del %lock%*
echo ===============================================================================


问:
How to submit the form to a different server and from that server return to the same page php
I'm trying to verify user apiKey. so the I have a application which user installs on their server and they need to add their apiKey to activate it. so I've created a form where they can add their apiKey and it'll submit the key to my server and then my server verify the key. but I want to know how to get from which URL we recieved the request so we can send back results to that url?

```<code><form action="my-server-.com/verifyfile.php" method="post">
    <div class="form-group row">
        <label for="email" class="col-lg-2 col-form-label">Enter API Key</label>
        <div class="col-lg-6">
            <input type="text" placeholder="paste your api key here" name="apiKey" class="form-control" required="">
        </div>
        <div class="form-group col-lg-2">
            <input type="submit" value="Register" name="verify-api" class="btn btn-outline-success btn-sm">
        </div>
    </div>
</form>
</code>```

答:
If i have understood your question,

someone sends an apiKey to your site

you capture the apiKey

you verify the apiKey

after verifying the apiKey you respond to the url that submitted the apiKey

Below php code can sit in your server on a php page to do the task

```<code><?php
//If the API Key is sent lets validate it
if (isset($_GET['apiKey'])) {

   $apikey = $_GET['apiKey'];  //The apikey

   if(isset($_SERVER['HTTP_REFERER'])) {
   $from_url = $_SERVER['HTTP_REFERER'];
   } else
   {
   die(); //end
   }

   //Do your validation for the apiKey
   if ($apikey == 'is_okay') { //do your own validation to test if its okay

    //what you want to append to the url received
    $query_parameter = 'result=yes';

   //append your parameter strings to the url you want to respond to
   if(strpos($from_url,'?') !== false) {
    $from_url .=  '&'.$query_parameter;
   } else {
    $from_url .=  '?'.$query_parameter;
   }

   //your site then automatically navigates to the url with an appended query string
   header('Location: '.$from_url);

   } else {
   die(); //do something here if apiKey not verified
   }

}

?>
</code>```

Body:
I'm trying to verify user apiKey. so the I have a application which user installs on their server and they need to add their apiKey to activate it. so I've created a form where they can add their apiKey and it'll submit the key to my server and then my server verify the key. but I want to know how to get from which URL we recieved the request so we can send back results to that url?

<form action="my-server-.com/verifyfile.php" method="post">

        Enter API Key

            <input type="text" placeholder="paste your api key here" name="apiKey" class="form-control" required="">

            <input type="submit" value="Register" name="verify-api" class="btn btn-outline-success btn-sm">

</form>

Body:
If i have understood your question,

someone sends an apiKey to your site

you capture the apiKey

you verify the apiKey

after verifying the apiKey you respond to the url that submitted the apiKey

Below php code can sit in your server on a php page to do the task

<?php
//If the API Key is sent lets validate it
if (isset($_GET['apiKey'])) {

   $apikey = $_GET['apiKey'];  //The apikey

   if(isset($_SERVER['HTTP_REFERER'])) {
   $from_url = $_SERVER['HTTP_REFERER'];
   } else
   {
   die(); //end
   }

   //Do your validation for the apiKey
   if ($apikey == 'is_okay') { //do your own validation to test if its okay

    //what you want to append to the url received
    $query_parameter = 'result=yes';

   //append your parameter strings to the url you want to respond to
   if(strpos($from_url,'?') !== false) {
    $from_url .=  '&'.$query_parameter;
   } else {
    $from_url .=  '?'.$query_parameter;
   }

   //your site then automatically navigates to the url with an appended query string
   header('Location: '.$from_url);

   } else {
   die(); //do something here if apiKey not verified
   }

}

?>


问:
useState what am I doing wrong?
I'm creating an app that reads the alarm state of several ELK alarm systems. I'm using useState to process the data that I am receiving via socket.io from my server. The data that the server is streaming is an array of arrays.

This is the code that I am using:

```<code>const [startData, updateData] = React.useState([]);

  const socket = io("http://localhost:5000");

  socket.on('data', (dta) => {
    updateData(dta.data);
  });
</code>```

If I console.log(startData) then it becomes evident that my code is causing an infinite loop. I read through examples of users in this forum with similar issues but I wasn't successful in tailoring their solutions to my problem. I was somewhat able to manage the amount of requests with setTimeout but after the app is running for about 2 hours, the page becomes unresponsive (memory leak????).

Do you people have any suggestion on how I could improve my code?

答:
actually as Jonas said you should call socket once:

```<code>import socketIOClient from "socket.io-client";

const [startData, updateData] = React.useState([]);
  const endpoint= "http://localhost:5000";
  useEffect(() => {

       //Very simply connect to the socket
       const socket = socketIOClient(endpoint);

       //Listen for data on the "outgoing data"
       socket.on("outgoing data", (dta)=>updateData(dta.data));
       });
    }, []);
</code>```

this is a good example : express socket react

Title: useState what am I doing wrong?

Body:
I'm creating an app that reads the alarm state of several ELK alarm systems. I'm using useState to process the data that I am receiving via socket.io from my server. The data that the server is streaming is an array of arrays.

This is the code that I am using:

const [startData, updateData] = React.useState([]);

  const socket = io("http://localhost:5000");

  socket.on('data', (dta) => {
    updateData(dta.data);
  });

If I console.log(startData) then it becomes evident that my code is causing an infinite loop. I read through examples of users in this forum with similar issues but I wasn't successful in tailoring their solutions to my problem. I was somewhat able to manage the amount of requests with setTimeout but after the app is running for about 2 hours, the page becomes unresponsive (memory leak????).

Do you people have any suggestion on how I could improve my code?

Body:
actually as Jonas said you should call socket once:

import socketIOClient from "socket.io-client";

const [startData, updateData] = React.useState([]);
  const endpoint= "http://localhost:5000";
  useEffect(() => {

       //Very simply connect to the socket
       const socket = socketIOClient(endpoint);

       //Listen for data on the "outgoing data"
       socket.on("outgoing data", (dta)=>updateData(dta.data));
       });
    }, []);

this is a good example : express socket react


问:
Removing javascript print code embedded in pdf
I have a server that generates a PDF, I have no access or ability to change the settings on the server.

When the server produces the pdf it embeds the following javascript code into the file so that when any PDF reader/viewer opens it, the PRINT DOCUMENT screen automatically opens. This is very inconvenient and frustrating.

The code inside the file at the very start looks like this:

%PDF-1.4
%âãÏÓ
1 0 obj
<</S/JavaScript/JS(this.print\(true , 0,this.numPages-1,false\);\r)>>
endobj
3 0 obj
<</Length 10/Filter/FlateDecode>>stream
xœ+ä
SNIP

I thought it would be an easy task just to remove the javascript line and prevent the auto print screen from popping up.

I have tried this (just did a string search and replace and removed line 4). This DOES stop the print screen appearing - BUT when opened in a few PDF viewers (goodreader etc) instantly flags up as a corrupted PDF.

I can click the repair option and everything works fine, but I would like to know, is there anything I could do to replace the javascript code with some sort of NOOP code to keep the file from being corrupt whilst still preventing the print page?

Here's a link to a source file: https://www.dropbox.com/s/kziy6evi57cfhb3/2014-04-04_EIKY.pdf (800k)

Is there a way to nullify a pdf object or something similar?

Thank you.

答:
@SakthiSureshAnand was looking for my code/library I used. It really is nothing special, but I thought I'd leave it here.

A simple php script requests the original file and then we get the contents of the file as a string:

Then preg_replace is all I use to replace the unwanted printing code and write the admended file to disk.

```<code>$fileString = file_get_contents('source.pdf');

$pdf = preg_replace(
  '%(<</S/Javascript/JS\()(.*;)(.*)%i',
  '<</S/Javascript/JS(;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\r)>>',
  $fileString
);

//Do what you want with the fixed $pdf string.

</code>```

Hope that helps someone.

Body:
@SakthiSureshAnand was looking for my code/library I used. It really is nothing special, but I thought I'd leave it here.

A simple php script requests the original file and then we get the contents of the file as a string:

Then preg_replace is all I use to replace the unwanted printing code and write the admended file to disk.

$fileString = file_get_contents('source.pdf');

$pdf = preg_replace(
  '%(<</S/Javascript/JS\()(.*;)(.*)%i',
  '<</S/Javascript/JS(;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\r)>>',
  $fileString
);

//Do what you want with the fixed $pdf string.

Hope that helps someone.