问:
In CyberSource, how do you use a credit card flexible token with payments API?
Trying to get my head around how CyberSource works..

In CyberSource, the Secure Acceptance Flexible Token API can be used to tokenize a credit card on client-side for processing for future processing.

That part is easy enough. There's plenty of documentation and a few packages that do it.

How do I then use that token to create a charge with the CyberSource Payments API ?

All examples i've found show how to tokenize the card on client, and how to charge an untokenized card (i.e. card data is sent to server) but I can't find an example that show how to use the Flexible token to create a charge (or pre-auth).

In most other gateways like Stripe, it's pretty clear in documentations but CyberSource doesn't seem to provide that.

Am I missing something?

I'm using Node but happy with solutions in other languages.

https://developer.cybersource.com/api-reference-assets/index.html#flex

https://developer.visa.com/capabilities/cybersource/reference

答:
Ok, thanks to @rhldr for pointing out to this particular documentation.

The answer is in this page https://developer.cybersource.com/api/developer-guides/dita-flex/SAFlexibleToken/FlexMicroform/GetStarted.html under "Using the Token".

Note: Some of the other documentations (not sure why they have some many variations of the docs), like this one don't mention this at all.

See the RESTPaymentAPI section. It needs to be provided as a customerId field.

```<code>"paymentInformation": {
    "customer": {
        "customerId": "7500BB199B4270EFE05340588D0AFCAD"
    }
}
</code>```

Here's a minimal example of how it can be implemented on the API side

```<code>var cybersourceRestApi = require('cybersource-rest-client');
var configuration = require('./cybersource/config.js');

var configObject = new configuration();
var instance = new cybersourceRestApi.PaymentsApi(configObject);

var clientReferenceInformation = new cybersourceRestApi.Ptsv2paymentsClientReferenceInformation();
clientReferenceInformation.code = 'test_payment';

var processingInformation = new cybersourceRestApi.Ptsv2paymentsProcessingInformation();
processingInformation.commerceIndicator = 'internet';

var amountDetails = new cybersourceRestApi.Ptsv2paymentsOrderInformationAmountDetails();
amountDetails.totalAmount = "100.00";
amountDetails.currency = 'USD';

var orderInformation = new cybersourceRestApi.Ptsv2paymentsOrderInformation();
orderInformation.amountDetails = amountDetails;

var paymentInformation = new cybersourceRestApi.Ptsv2paymentsPaymentInformation();

// THIS IS THE IMPORTANT BIT
var customer = new cybersourceRestApi.Ptsv2paymentsPaymentInformationCustomer()
customer.customerId = token
paymentInformation.customer = customer

var request = new cybersourceRestApi.CreatePaymentRequest();
request.clientReferenceInformation = clientReferenceInformation;
request.processingInformation = processingInformation;
request.orderInformation = orderInformation;
request.paymentInformation = paymentInformation;

if (!authoriseOnly) {
    request.processingInformation.capture = true;
}
</code>```

Code based on the CyberSource nodejs REST samples: https://github.com/CyberSource/cybersource-rest-samples-node

More info. Once you know where to look, it's actually explained in a few places.

Example, go to https://developer.cybersource.com/cybs-dev-api-ref/index.html#payments-process-a-payment, expand the "REQUEST FIELD DESCRIPTION" underneath and go to

```<code>customer
    .. customerId
</code>```

Unique identifier for the customer's card
  and billing information.

When you use Payment Tokenization or Recurring Billing and you include
  this value in your request, many of the fields that are normally
  required for an authorization or credit become optional.

NOTE When you use Payment Tokenization or Recurring Billing, the value
  for the Customer ID is actually the Cybersource payment token for a
  customer. This token stores information such as the consumer’s card
  number so it can be applied towards bill payments, recurring payments,
  or one-time payments. By using this token in a payment API request,
  the merchant doesn't need to pass in data such as the card number or
  expiration date in the request itself.

See "Payment Tokenization," page 222, and "Recurring Billing," page
  225.

Body:
Ok, thanks to @rhldr for pointing out to this particular documentation.

The answer is in this page https://developer.cybersource.com/api/developer-guides/dita-flex/SAFlexibleToken/FlexMicroform/GetStarted.html under "Using the Token".

Note: Some of the other documentations (not sure why they have some many variations of the docs), like this one don't mention this at all.

See the RESTPaymentAPI section. It needs to be provided as a customerId field.

"paymentInformation": {
    "customer": {
        "customerId": "7500BB199B4270EFE05340588D0AFCAD"
    }
}

Here's a minimal example of how it can be implemented on the API side

var cybersourceRestApi = require('cybersource-rest-client');
var configuration = require('./cybersource/config.js');

var configObject = new configuration();
var instance = new cybersourceRestApi.PaymentsApi(configObject);

var clientReferenceInformation = new cybersourceRestApi.Ptsv2paymentsClientReferenceInformation();
clientReferenceInformation.code = 'test_payment';

var processingInformation = new cybersourceRestApi.Ptsv2paymentsProcessingInformation();
processingInformation.commerceIndicator = 'internet';

var amountDetails = new cybersourceRestApi.Ptsv2paymentsOrderInformationAmountDetails();
amountDetails.totalAmount = "100.00";
amountDetails.currency = 'USD';

var orderInformation = new cybersourceRestApi.Ptsv2paymentsOrderInformation();
orderInformation.amountDetails = amountDetails;

var paymentInformation = new cybersourceRestApi.Ptsv2paymentsPaymentInformation();

// THIS IS THE IMPORTANT BIT
var customer = new cybersourceRestApi.Ptsv2paymentsPaymentInformationCustomer()
customer.customerId = token
paymentInformation.customer = customer

var request = new cybersourceRestApi.CreatePaymentRequest();
request.clientReferenceInformation = clientReferenceInformation;
request.processingInformation = processingInformation;
request.orderInformation = orderInformation;
request.paymentInformation = paymentInformation;

if (!authoriseOnly) {
    request.processingInformation.capture = true;
}

Code based on the CyberSource nodejs REST samples: https://github.com/CyberSource/cybersource-rest-samples-node

More info. Once you know where to look, it's actually explained in a few places.

Example, go to https://developer.cybersource.com/cybs-dev-api-ref/index.html#payments-process-a-payment, expand the "REQUEST FIELD DESCRIPTION" underneath and go to

customer
    .. customerId

Unique identifier for the customer's card
  and billing information.

When you use Payment Tokenization or Recurring Billing and you include
  this value in your request, many of the fields that are normally
  required for an authorization or credit become optional.

NOTE When you use Payment Tokenization or Recurring Billing, the value
  for the Customer ID is actually the Cybersource payment token for a
  customer. This token stores information such as the consumer’s card
  number so it can be applied towards bill payments, recurring payments,
  or one-time payments. By using this token in a payment API request,
  the merchant doesn't need to pass in data such as the card number or
  expiration date in the request itself.

See "Payment Tokenization," page 222, and "Recurring Billing," page
  225.


来源: stackexchange

问:
Cannot upgrading gradle Android Studio 3.4., Gradle 5 dependencies break randomly
When I was trying to upgrade my Android Studio to 3.4, the update does not go smoothly rather, some dependencies break. In my case, the RxJava/RxKotlin dependencies are breaking without giving any clue. Even that is happening randomly as I have RxJava/RxKotlin Code in each of my 4 modules but the dependency is failing in only one module.

What I tried :

Invalidate Cache and restart.

Delete /build *module/build/ *module/.gradle/  & .gradle/

Clean Project

Try find answers on the internet and these are the closest but does not solve the problem. (They did not recommend to upgrade to 3.4)

i) Unresolved reference: Observable in Android Studio 3.4
Explains the problem I have but the thread is moving to either not upgrading the Gradle (Which is last option for me) or making sure RxJava that is being used in the project or any of its library is 2.2.8). For that reason I tried explicitly adding RxJava 2.2.8 (I was not previously as I was getting it inside RxKotlin) and wrote a  resolutionStrategy to force Android studio to use RxJava 2.2.8 like this in that particular module i.e. domain, but did not solve the issue :

```<code>configurations.all {
       resolutionStrategy.force 'io.reactivex.rxjava2:rxjava:2.2.8'
}
</code>```

ii) RxKotlin is not resolved properly after updating Gradle to 3.4.0 which does not yet give any solution. And I am even suspicious if it's the issue with RxJava/RxKotlin or the Gradle plugin itself. Or even if it's the case with RxKotlin or any other libraries too.

Edit: My dependencies in domain module looks like this :

```<code>dependencies {
    implementation Deps.kotlinStdLib
    implementation Deps.rxKotlin
    implementation Deps.dagger
    implementation Deps.timber
    implementation Deps.mobiusCore
    implementation Deps.mapboxGeoJSONCore
}
</code>```

答:
try to add rxkotlin to the dependencies (if not already added):

```<code>dependencies {

    // rxKotlin ...is likely missing
    implementation "io.reactivex.rxjava2:rxkotlin:2.3.0"

    // rxJava:
    implementation "io.reactivex.rxjava2:rxjava:2.2.0"

    // rxAndroid bindings:
    implementation "io.reactivex.rxjava2:rxandroid:2.1.0"
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
When I was trying to upgrade my Android Studio to 3.4, the update does not go smoothly rather, some dependencies break. In my case, the RxJava/RxKotlin dependencies are breaking without giving any clue. Even that is happening randomly as I have RxJava/RxKotlin Code in each of my 4 modules but the dependency is failing in only one module.

What I tried :

Invalidate Cache and restart.

Delete /build *module/build/ *module/.gradle/  & .gradle/

Clean Project

Try find answers on the internet and these are the closest but does not solve the problem. (They did not recommend to upgrade to 3.4)

i) Unresolved reference: Observable in Android Studio 3.4
Explains the problem I have but the thread is moving to either not upgrading the Gradle (Which is last option for me) or making sure RxJava that is being used in the project or any of its library is 2.2.8). For that reason I tried explicitly adding RxJava 2.2.8 (I was not previously as I was getting it inside RxKotlin) and wrote a  resolutionStrategy to force Android studio to use RxJava 2.2.8 like this in that particular module i.e. domain, but did not solve the issue :

configurations.all {
       resolutionStrategy.force 'io.reactivex.rxjava2:rxjava:2.2.8'
}

ii) RxKotlin is not resolved properly after updating Gradle to 3.4.0 which does not yet give any solution. And I am even suspicious if it's the issue with RxJava/RxKotlin or the Gradle plugin itself. Or even if it's the case with RxKotlin or any other libraries too.

Edit: My dependencies in domain module looks like this :

dependencies {
    implementation Deps.kotlinStdLib
    implementation Deps.rxKotlin
    implementation Deps.dagger
    implementation Deps.timber
    implementation Deps.mobiusCore
    implementation Deps.mapboxGeoJSONCore
}

Body:
try to add rxkotlin to the dependencies (if not already added):

dependencies {

    // rxKotlin ...is likely missing
    implementation "io.reactivex.rxjava2:rxkotlin:2.3.0"

    // rxJava:
    implementation "io.reactivex.rxjava2:rxjava:2.2.0"

    // rxAndroid bindings:
    implementation "io.reactivex.rxjava2:rxandroid:2.1.0"
}


问:
Method not implemented exception on Take method in Microsoft.Spark
I am trying to setup spark with the new Microsoft.Spark library. The method DataFrame.PrintSchema works fine, however the method DataFrame.Take() gives an System.NotImplementedException. Allot of other methods also give this exception.

I took a look in the sources and that the 'Take' method calls the collect method and and it fails on the call to collectToPython.

```<code>SparkSession spark = SparkSession
    .Builder()
    .AppName(".NET Spark")
    .GetOrCreate();

DataFrame dataFrame = spark.Read().Json("people.json");
IEnumerable<Row> rows =  dataFrame.Take(1);
</code>```

Is this just a Microsoft library that isn't finished yet? Or am I doing something wrong?

答:
Did you try the latest version released? I used v0.2.0 and the following works fine as expected:</p>

```<code>var spark = SparkSession.Builder().GetOrCreate();
var df = spark.Read().Json("people.json");

IEnumerable<Row> rows = df.Take(1);
foreach (var row in rows)
{
    Console.WriteLine(row.Get("name"));
}
spark.Stop();
</code>```

Body:
I am trying to setup spark with the new Microsoft.Spark library. The method DataFrame.PrintSchema works fine, however the method DataFrame.Take() gives an System.NotImplementedException. Allot of other methods also give this exception.

I took a look in the sources and that the 'Take' method calls the collect method and and it fails on the call to collectToPython.

SparkSession spark = SparkSession
    .Builder()
    .AppName(".NET Spark")
    .GetOrCreate();

DataFrame dataFrame = spark.Read().Json("people.json");
IEnumerable<Row> rows =  dataFrame.Take(1);

Is this just a Microsoft library that isn't finished yet? Or am I doing something wrong?

Body:
Did you try the latest version released? I used v0.2.0 and the following works fine as expected:

var spark = SparkSession.Builder().GetOrCreate();
var df = spark.Read().Json("people.json");

IEnumerable<Row> rows = df.Take(1);
foreach (var row in rows)
{
    Console.WriteLine(row.Get("name"));
}
spark.Stop();


问:
Angular project not working after installation of newer version of node.js
I am working with an angular 7 project.
initially, I was using node version 10 and by mistake, I upgrade the node to version 12.

after that, I tried to compile my Angular 7 project it is the thrwing error. I again reinstall the older version but still, it is throwing the error as below.

```<code>ERROR in ./src/app/pages/pages.component.scss
Module build failed (from ./node_modules/sass-loader/lib/loader.js):
Error: Cannot find module 'node-sass'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:582:15)
    at Function.Module._load (internal/modules/cjs/loader.js:508:25)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at Object.sassLoader (E:\QiwkCollaborator\QiwkCollaboratorTool\node_modules\sass-loader\lib\loader.js:46:72)
ERROR in ./node_modules/ionicons/scss/ionicons.scss (./node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/raw-css-loader.js!./node_modules/postcss-loader/src??embedded!./node_modules/sass-loader/lib/loader.js??ref--14-3!./node_modules/ionicons/scss/ionicons.scss)
</code>```

I don't have any idea how to resolve this error. any suggestions, please.

Thanks in Advance!

答: Currently having same issue, solution I am implementing is to use docker to run the older version of node that is compatible with the node-sass or install a newer version of the package.</p>

Body:
I am working with an angular 7 project.
initially, I was using node version 10 and by mistake, I upgrade the node to version 12.

after that, I tried to compile my Angular 7 project it is the thrwing error. I again reinstall the older version but still, it is throwing the error as below.

ERROR in ./src/app/pages/pages.component.scss
Module build failed (from ./node_modules/sass-loader/lib/loader.js):
Error: Cannot find module 'node-sass'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:582:15)
    at Function.Module._load (internal/modules/cjs/loader.js:508:25)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at Object.sassLoader (E:\QiwkCollaborator\QiwkCollaboratorTool\node_modules\sass-loader\lib\loader.js:46:72)
ERROR in ./node_modules/ionicons/scss/ionicons.scss (./node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/raw-css-loader.js!./node_modules/postcss-loader/src??embedded!./node_modules/sass-loader/lib/loader.js??ref--14-3!./node_modules/ionicons/scss/ionicons.scss)

I don't have any idea how to resolve this error. any suggestions, please.

Thanks in Advance!


问:
Handling equivalent file extensions in Snakemake
Essentially, I want to know what the recomended way of handling equivalent file extensions is in snakemake. For example, lets say I have a rule that counts the number of entries in a fasta file. The rule might look something like....

```<code>rule count_entries:
    input:
        ["{some}.fasta"]
    output:
        ["{some}.entry_count"]
    shell:
        'grep -c ">" {input[0]} > {output[0]}'
</code>```

This works great. But what if I want this rule to also permit "{some}.fa" as input?

Is there any clean way to do this?

EDIT:

Here is my best guess at the first proposed sollution. This can probably be turned into a higher order function to be more general purpose but this is the basic idea as I understand it. I don't think this idea really fits any general use case though as it doesn't cooperate with other rules at the "building DAG" stage.

```<code>import os

def handle_ext(wcs):
    base = wcs["base"]
    for file_ext in [".fasta", ".fa"]:
        if(os.path.exists(base + file_ext)):
            return [base + file_ext]

rule count_entries:
    input:
        handle_ext
    output:
        ["{base}.entry_count"]
    shell:
        'grep -c ">" {input[0]} > {output[0]}'
</code>```

EDIT2: Here is the best current sollution as I see it...

```<code>count_entries_cmd = 'grep -c ">" {input} > {output}'
count_entries_output = "{some}.entry_count"

rule count_entries_fasta:
    input:
        "{some}.fasta"
    output:
        count_entries_output
    shell:
        count_entries_cmd

rule count_entries_fa:
    input:
        "{some}.fa"
    output:
        count_entries_output
    shell:
        count_entries_cmd
</code>```

答:
One possible solution is to only allow the original rule to take .fasta files as input, but enable .fa files to be renamed to that.  For example,

```<code>rule fa_to_fasta:
    input:
        "{some}.fa"
    output:
        temp("{some}.fasta")
    shell:
        """
        cp {input} {output}
        """
</code>```

Clearly this has the disadvantage of making a temporary copy of the file. Also, if foo.fa and foo.fasta are both provided (not through the copying), then foo.fasta will silently overshadow foo.fa, even if they are different.

Body:
Essentially, I want to know what the recomended way of handling equivalent file extensions is in snakemake. For example, lets say I have a rule that counts the number of entries in a fasta file. The rule might look something like....

rule count_entries:
    input:
        ["{some}.fasta"]
    output:
        ["{some}.entry_count"]
    shell:
        'grep -c ">" {input[0]} > {output[0]}'

This works great. But what if I want this rule to also permit "{some}.fa" as input?

Is there any clean way to do this?

EDIT:

Here is my best guess at the first proposed sollution. This can probably be turned into a higher order function to be more general purpose but this is the basic idea as I understand it. I don't think this idea really fits any general use case though as it doesn't cooperate with other rules at the "building DAG" stage.

import os

def handle_ext(wcs):
    base = wcs["base"]
    for file_ext in [".fasta", ".fa"]:
        if(os.path.exists(base + file_ext)):
            return [base + file_ext]

rule count_entries:
    input:
        handle_ext
    output:
        ["{base}.entry_count"]
    shell:
        'grep -c ">" {input[0]} > {output[0]}'

EDIT2: Here is the best current sollution as I see it...

count_entries_cmd = 'grep -c ">" {input} > {output}'
count_entries_output = "{some}.entry_count"

rule count_entries_fasta:
    input:
        "{some}.fasta"
    output:
        count_entries_output
    shell:
        count_entries_cmd

rule count_entries_fa:
    input:
        "{some}.fa"
    output:
        count_entries_output
    shell:
        count_entries_cmd

Body:
One possible solution is to only allow the original rule to take .fasta files as input, but enable .fa files to be renamed to that.  For example,

rule fa_to_fasta:
    input:
        "{some}.fa"
    output:
        temp("{some}.fasta")
    shell:
        """
        cp {input} {output}
        """

Clearly this has the disadvantage of making a temporary copy of the file. Also, if foo.fa and foo.fasta are both provided (not through the copying), then foo.fasta will silently overshadow foo.fa, even if they are different.


问:
Java Spring: How convert HTML character codes in hex format from textarea to plain text?
I have web application writed in React JS and Java Spring boot. In my Board Component I have form with textarea and button. While debugging when I click on button I am redirect to PostMapping in UserController spring project. My method has one parameter. It's @RequestBody String query.
I get text from textarea in HTML character codes in hex code. I need to plain text from this String.

I get something what look like this:

CREATE+TABLE+users+%28%0A%09id+INT%2C%0A%09fullName+VARCHAR%28220%29+NOT+NULL%2C%0A%09city+VARCHAR%28120%29+NOT+NULL%2C%0A%09country+VARCHAR%2860%29+NOT+NULL%2C%0A%09PRIMARY+KEY%28id%29%0A%29%3 ...

where + does mean space

I was trying resolve this problem.
Nothing works.

First way:

```<code>byte[] s = DatatypeConverter.parseHexBinary(query);
System.out.println(new String(s, "UTF-8"));
</code>```

Second way:
Apache Commons Codec - Hex

```<code>byte[] bytes = Hex.decodeHex(query.toCharArray());
System.out.println(new String(bytes, "UTF-8"));
</code>```

Here is my code

Spring project:

UserController class

```<code>@Controller
@RequestMapping("fiddle")
public class MainController {

@PostMapping
public ResponseEntity<?> processingQueries(@RequestBody String query) {
    System.out.println(query);

    return new ResponseEntity<String>("Query prcessed successfully.", HttpStatus.OK);
}

}
</code>```

React JS project:

Board component

```<code>import React from 'react';
import TableButton from './TableButton';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { processQueries } from '../actions/queryActions';

class Board extends React.Component {
constructor() {
    super();

    this.state = {
        query: 'Write here your SQL query...'
    }
    this.onChange = this.onChange.bind(this);
    this.resetField = this.resetField.bind(this);
    this.onSubmitRun = this.onSubmitRun.bind(this);
}

onChange(e) {
    this.setState({ [e.target.name]: e.target.value });
}

resetField(e) {
    this.setState({ query: '' });
}

onSubmitRun(e) {
    e.preventDefault();
    console.log(this.state.query);
    this.props.processQueries(this.state.query, this.props.history);
}

render() {
    return (
        <div className="box flex-stretch">
            <div className="blue smallClass">
                <TableButton />
            </div>
            <div className="mediumClass">
                <form onSubmit={this.onSubmitRun}>
                    <textarea
                        name="query"
                        className="txtArea"
                        value={this.state.query}
                        onChange={this.onChange}
                        onClick={this.resetField}
                        rows="27"
                    >
                        Write here your SQL queries...
                    </textarea>
                    <input type="submit" value="Run" className="runButton"/>
                </form>
            </div>
            <div className="red largeClass">
                One of three columns
            </div>
        </div>
    );
}
}

Board.propTypes = {
query: PropTypes.string
}

const mapStateToProps = state => ({
query: state.query
})

export default connect(mapStateToProps, { processQueries })(Board);
</code>```

queryReducer

```<code>import { PROCESS_QUERY } from '../actions/types';

const initialState = {
query: ''
}

export default function(state = initialState, action) {
switch(action.type) {
    case PROCESS_QUERY:
        return {
            ...state,
            query: action.payload
        }
    default:
        return state;
}
}
</code>```

queryActions

```<code>import axios from 'axios';
import { GET_ERRORS, PROCESS_QUERY } from './types';

export const processQueries = (query, history) => async dispatch =>
{
try {
    console.log(query);
    await axios.post("/fiddle", query);
    history.push("/fiddle");

    dispatch({
        type: PROCESS_QUERY,
        payload: ''
    })
} catch(error) {
    dispatch({
        type: GET_ERRORS,
        payload: error.response.data
    })
}
}
</code>```

I need to convert this string from textarea to plain text. Data inserted to textarea are plan SQL queries.

答:
All you need to decode string with UrlDecoder.

```<code>String result = java.net.URLDecoder.decode(query, StandardCharsets.UTF_8.displayName());
</code>```

Body:
I have web application writed in React JS and Java Spring boot. In my Board Component I have form with textarea and button. While debugging when I click on button I am redirect to PostMapping in UserController spring project. My method has one parameter. It's @RequestBody String query.
I get text from textarea in HTML character codes in hex code. I need to plain text from this String.

I get something what look like this:

CREATE+TABLE+users+%28%0A%09id+INT%2C%0A%09fullName+VARCHAR%28220%29+NOT+NULL%2C%0A%09city+VARCHAR%28120%29+NOT+NULL%2C%0A%09country+VARCHAR%2860%29+NOT+NULL%2C%0A%09PRIMARY+KEY%28id%29%0A%29%3 ...

where + does mean space

I was trying resolve this problem.
Nothing works.

First way:

byte[] s = DatatypeConverter.parseHexBinary(query);
System.out.println(new String(s, "UTF-8"));

Second way:
Apache Commons Codec - Hex

byte[] bytes = Hex.decodeHex(query.toCharArray());
System.out.println(new String(bytes, "UTF-8"));

Here is my code

Spring project:

UserController class

@Controller
@RequestMapping("fiddle")
public class MainController {

@PostMapping
public ResponseEntity<?> processingQueries(@RequestBody String query) {
    System.out.println(query);

    return new ResponseEntity<String>("Query prcessed successfully.", HttpStatus.OK);
}

}

React JS project:

Board component

import React from 'react';
import TableButton from './TableButton';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { processQueries } from '../actions/queryActions';

class Board extends React.Component {
constructor() {
    super();

    this.state = {
        query: 'Write here your SQL query...'
    }
    this.onChange = this.onChange.bind(this);
    this.resetField = this.resetField.bind(this);
    this.onSubmitRun = this.onSubmitRun.bind(this);
}

onChange(e) {
    this.setState({ [e.target.name]: e.target.value });
}

resetField(e) {
    this.setState({ query: '' });
}

onSubmitRun(e) {
    e.preventDefault();
    console.log(this.state.query);
    this.props.processQueries(this.state.query, this.props.history);
}

render() {
    return (

                <TableButton />

                <form onSubmit={this.onSubmitRun}>
                    <textarea
                        name="query"
                        className="txtArea"
                        value={this.state.query}
                        onChange={this.onChange}
                        onClick={this.resetField}
                        rows="27"
                    >
                        Write here your SQL queries...
                    </textarea>
                    <input type="submit" value="Run" className="runButton"/>
                </form>

                One of three columns

    );
}
}

Board.propTypes = {
query: PropTypes.string
}

const mapStateToProps = state => ({
query: state.query
})

export default connect(mapStateToProps, { processQueries })(Board);

queryReducer

import { PROCESS_QUERY } from '../actions/types';

const initialState = {
query: ''
}

export default function(state = initialState, action) {
switch(action.type) {
    case PROCESS_QUERY:
        return {
            ...state,
            query: action.payload
        }
    default:
        return state;
}
}

queryActions

import axios from 'axios';
import { GET_ERRORS, PROCESS_QUERY } from './types';

export const processQueries = (query, history) => async dispatch =>
{
try {
    console.log(query);
    await axios.post("/fiddle", query);
    history.push("/fiddle");

    dispatch({
        type: PROCESS_QUERY,
        payload: ''
    })
} catch(error) {
    dispatch({
        type: GET_ERRORS,
        payload: error.response.data
    })
}
}

I need to convert this string from textarea to plain text. Data inserted to textarea are plan SQL queries.

Body:
All you need to decode string with UrlDecoder.

String result = java.net.URLDecoder.decode(query, StandardCharsets.UTF_8.displayName());


问:
Calling an attribute or function of a variable obtained through a template filter
This is what I want to write:

```<code>categories|last.translated_name
</code>```

Where categories is a list of Category objects and translated_name is a function in the Category class.

This is the error when the above invalid syntax is used:

Could not parse the remainder:
  '.translated_name' from
  'categories|last.translated_name'

答:
```<code>{% with categories|last as last_category %}
    {{ last_category.translated_name }}
{% endwith %}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This is what I want to write:

categories|last.translated_name

Where categories is a list of Category objects and translated_name is a function in the Category class.

This is the error when the above invalid syntax is used:

Could not parse the remainder:
  '.translated_name' from
  'categories|last.translated_name'


问:
Why is Vue changing the parent value from a child without emitting an event
I am fairly new to Vue but doesn't this behavior completely contradict the design of props down, events up?

I have managed to stop it by using Object.assign({}, this.test_object ); when initializing the value in child-component but shouldn't that be the default behaviour?

Here is some background.

I am trying to have a dirty state in a much larger application (Eg a value has changed so a user must save the data back to the database before continuing on their way)

I had an event being emitted, and caught by the parent but the code I had to test the value and init the dirty state was not running as the value had already been changed in the parent component.

Vue.component( 'parent-component', {
  template: '#parent-component',
  data: function() {
    return {
      testObject: {
        val: 'Test Value'
      }
    }
  }
});

Vue.component( 'child-component', {
  template: '#child-component',
  props: {
    test_object: Object
  },
  data: function() {
    return {
      child_object: this.test_object
    }
  }
});

Vue.config.productionTip = false;

new Vue({
  el: '#app',
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<script type="text/x-template" id="parent-component">
    <div>
        <child-component :test_object="testObject"></child-component>

        <p>This is in the parent component</p>
        <p><code>testObject.val = {{testObject.val}}</code></p>

    </div>
</script>

<script type="text/x-template" id="child-component">
    <div>
        <label for="html_input">HTML Input</label>
        <input style="border:1px solid #CCC; display:block;" type="text" name="html_input" v-model="child_object.val" />
    </div>
</script>

<div id="app">
  <parent-component></parent-component>
</div></code>```

答:
Use of v-model is a very deceptive thing. If you are not careful, you might end-up mutating data that doesn't belong to your component. In your case, you are accidentally passing read-only props directly to the v-model. It doesn't know if it is a prop or a local component state.

What you are doing is the right solution but considering one-way/unidirectional data flow in mind, we can rewrite this example in more explicit and elegant fashion:

Your component definition would be:

```<code>Vue.component( 'parent-component', {
  template: '#parent-component',
  data: function() {
    return {
      testObject: {
        val: 'Test Value'
      }
    }
  },

  methods: {
    // Added this method to listen for input event changes
    onChange(newValue) {
      this.testObject.val = newValue;

      // Or if you favor immutability
      // this.testObject = {
      //   ...this.testObject,
      //   val: newValue
      // };
    }
  }
});
</code>```

Your templates should be:

```<code><script type="text/x-template" id="parent-component">
  <div>
    <child-component :test_object="testObject"
      @inputChange="onChange"></child-component>

    <p>This is in the parent component</p>
    <p><code>testObject.val = {{testObject.val}}</code></p>

  </div>
</script>

<!-- Instead of v-model, you can use :value and @input binding. -->
<script type="text/x-template" id="child-component">
  <div>
    <label for="html_input">HTML Input</label>
    <input type="text" name="html_input"
      :value="test_object.val"
      @input="$emit('inputChange', $event.target.value)" />
  </div>
</script>
</code>```

Key things to note:

When using v-model, ensure that you are strictly working on a local value/data of the component. By no means, it should be referenced copy of external prop.

A custom form-like component can be readily converted into the one that can work with v-model provided you accept current value as :value prop and event as @input. v-model will just work out of the box.

Any modification to the value should happen in the same component.

Body:
I am fairly new to Vue but doesn't this behavior completely contradict the design of props down, events up?

I have managed to stop it by using Object.assign({}, this.test_object ); when initializing the value in child-component but shouldn't that be the default behaviour?

Here is some background.

I am trying to have a dirty state in a much larger application (Eg a value has changed so a user must save the data back to the database before continuing on their way)

I had an event being emitted, and caught by the parent but the code I had to test the value and init the dirty state was not running as the value had already been changed in the parent component.

Vue.component( 'parent-component', {
  template: '#parent-component',
  data: function() {
    return {
      testObject: {
        val: 'Test Value'
      }
    }
  }
});

Vue.component( 'child-component', {
  template: '#child-component',
  props: {
    test_object: Object
  },
  data: function() {
    return {
      child_object: this.test_object
    }
  }
});

Vue.config.productionTip = false;

new Vue({
  el: '#app',
});

  <parent-component></parent-component>

Body:
Use of v-model is a very deceptive thing. If you are not careful, you might end-up mutating data that doesn't belong to your component. In your case, you are accidentally passing read-only props directly to the v-model. It doesn't know if it is a prop or a local component state.

What you are doing is the right solution but considering one-way/unidirectional data flow in mind, we can rewrite this example in more explicit and elegant fashion:

Your component definition would be:

Vue.component( 'parent-component', {
  template: '#parent-component',
  data: function() {
    return {
      testObject: {
        val: 'Test Value'
      }
    }
  },

  methods: {
    // Added this method to listen for input event changes
    onChange(newValue) {
      this.testObject.val = newValue;

      // Or if you favor immutability
      // this.testObject = {
      //   ...this.testObject,
      //   val: newValue
      // };
    }
  }
});

Your templates should be:

<script type="text/x-template" id="parent-component">
  <div>
    <child-component :test_object="testObject"
      @inputChange="onChange"></child-component>

    <p>This is in the parent component</p>
    <p><code>testObject.val = {{testObject.val}}</code></p>

  </div>
</script>

<!-- Instead of v-model, you can use :value and @input binding. -->
<script type="text/x-template" id="child-component">
  <div>
    <label for="html_input">HTML Input</label>
    <input type="text" name="html_input"
      :value="test_object.val"
      @input="$emit('inputChange', $event.target.value)" />
  </div>
</script>

Key things to note:

When using v-model, ensure that you are strictly working on a local value/data of the component. By no means, it should be referenced copy of external prop.

A custom form-like component can be readily converted into the one that can work with v-model provided you accept current value as :value prop and event as @input. v-model will just work out of the box.

Any modification to the value should happen in the same component.


问:
Custom dplyr function and multiple ggplot of multiple argument
I need some help for a technical manipulation on R plz.

My problem : I have some observation data of bird by presence/absence in differents habitat types. I want know the sucess ratio of observation in these differents habitats according to their surface range :

```<code>data_observation <- data.frame(
  habitat_bush = c(
    0, 0, 0, 0, 10,
    10, 30, 30, 30, 45,
    65, 65, 65, 80, 80,
    80, 90, 95, 100
  ),
  obs = c(
    "yes", "no", "no", "no", "yes",
    "no", "no", "yes", "no", "yes",
    "yes", "no", "yes", "no", "yes",
    "yes", "yes", "yes", "yes"
  )
)
</code>```

Here you have just data for 'habitat_bush" but in have 10 more time habitats.

Help by a colleague, we have made this function to make a ggplot of the ratio success of observation under differents area size of 'habitat_bush" :

```<code>library(dplyr)
library(ggplot2)
library(scales)

plot_forest_test <- function(data = NULL, habitat_type = NULL, colour = NULL) {
  x <- enquo(habitat_type)
  fill <- enquo(colour)

  ggdata <- data %>%
    select(x = !!x, fill = !!fill) %>%
    mutate(
      group = case_when(
        x == 0 ~ "[0]",
        x > 0.0001 & x < 10.0001 ~ "]0-10]",
        x > 10.0001 & x < 25.0001 ~ "]10-25]",
        x > 25.0001 & x < 50.0001 ~ "]25-50]",
        x > 50.0001 & x < 75.0001 ~ "]50-75]",
        x > 75.0001 ~ "]75- 100]"
      )
    ) %>%
    select(-x) %>%
    group_by(group, fill) %>%
    count() %>%
    group_by(group) %>%
    group_modify(~ mutate(.data = .x, freq = n / sum(n)))

  ggplot(data = ggdata, mapping = aes(x = group, y = freq, fill = fill)) +
    geom_bar(stat = "identity") +
    scale_fill_brewer(palette = "Greens") +
    scale_y_continuous(labels = scales::percent) +
    theme_minimal() +
    labs(x = expr(!!x), fill = expr(!!fill))
}

plot_forest_test(data = data_observation, habitat_type = habitat_bush, colour = obs)
</code>```

It's work very well. But the observation can depend of effort put by technicien to looking for the presence of bird. So, I have data like that :

```<code>data_observation_2 <- data.frame(
  superficie_essence = c(
    0, 0, 0, 0, 10,
    10, 30, 30, 30, 45,
    65, 65, 65, 80, 80,
    80, 90, 95, 100
  ),
  obs = c(
    "yes", "no", "no", "no", "yes",
    "no", "no", "yes", "no", "yes",
    "yes", "no", "yes", "no", "yes",
    "yes", "yes", "yes", "yes"
  ),
  effort = c(low, low, mid-low, mid-low, low, mid-low, mid-low,
            mid-high, mid-high, high, mid-low, mid-low, mid-high, mid-low, mid-high, high, high, mid-high, high)
)
</code>```

My R skills stop here. I want have the same previously graph but
subdivided by effort_type for each modalities of habitats types, in the same graphical (like multipanel graphical). In other word I want 5 sub-graph of previous graph with 1 barplot by efforts modalities. But I have lot of data, so I would like put this processu into a function like :

```<code>plot_forest_test_2(data = data_observation, habitat_type = habitat_bush, effort = Q_effort, colour = obs)
</code>```

Can you help me please ? Thanks for your help !

cdlt

答:
Quosures are not my forte, especially when they might be missing but give this a shot. I created a new column for the facetted item and then add facet_wrap(). You could also use facet_grid(). Hope it helps.

plot_forest_test <- function(data = NULL, habitat_type = NULL, colour = NULL, facet = NULL) {
  x <- enquo(habitat_type)
  fill <- enquo(colour)

  # this is new ####################
  facet <- enquo(facet)
  has_facet <- quo_name(facet) != "NULL"

  df <-
    data %>%
    mutate(
      x = !!x,
      fill = !!fill,
      facet = ""
    )

  if (has_facet) {
    df <-
      df %>%
      mutate(facet = !!facet)
  }
  ##################################

  ggdata <-
    df %>%
    mutate(
      group = case_when(
        x == 0 ~ "[0]",
        x > 0.0001 & x < 10.0001 ~ "]0-10]",
        x > 10.0001 & x < 25.0001 ~ "]10-25]",
        x > 25.0001 & x < 50.0001 ~ "]25-50]",
        x > 50.0001 & x < 75.0001 ~ "]50-75]",
        x > 75.0001 ~ "]75- 100]"
      )
    ) %>%
    select(-x) %>%
    # adding facet here
    group_by(group, fill, facet) %>%
    count() %>%
    group_by(group, facet) %>%
    arrange(desc(fill)) %>%
    mutate(
      freq = n/sum(n),
      # these steps set up the label placement
      running_freq = cumsum(freq),
      prev_freq = lag(running_freq, default = 0),
      label_y = (prev_freq + running_freq)/2 ,
      label_n = paste0("n = ", sum(n))
    ) %>%
    ungroup()

  # create plot w/o facet
  p <-
    ggplot(data = ggdata, mapping = aes(x = group, y = freq, fill = fill)) +
    geom_bar(stat = "identity") +
    geom_hline(yintercept = 0) +
    geom_text(aes(y = -0.05, label = label_n), size = 3.5) +
    #geom_text(aes(y = label_y, label = n)) +
    scale_fill_brewer(palette = "Greens") +
    scale_y_continuous(labels = scales::percent) +
    theme(
      panel.background = element_rect(fill = "white"),
      panel.border = element_rect(color = "grey90", fill = NA)
    ) +
    labs(x = expr(!!x), fill = expr(!!fill))

  # add in if facet was mentioned
  if (has_facet) {
    p <-
      p +
      facet_grid(~facet)
  }

  # return final plot
  p
}
```

<p>I am including an edit to <code>data_observation_2</code> as the strings were not in quotes and some of the values has spaces around the hyphens when others did not. I made them all consistent w/o spaces</p>

<pre class="lang-r prettyprint-override"><code>data_observation_2 <- data.frame(
  superficie_essence = c(
    0, 0, 0, 0, 10,
    10, 30, 30, 30, 45,
    65, 65, 65, 80, 80,
    80, 90, 95, 100
  ),
  obs = c(
    "yes", "no", "no", "no", "yes",
    "no", "no", "yes", "no", "yes",
    "yes", "no", "yes", "no", "yes",
    "yes", "yes", "yes", "yes"
  ),
  effort = c(
    "low", "low", "mid-low", "mid-low", "low", "mid-low", "mid-low",
    "mid-high", "mid-high", "high", "mid-low", "mid-low",
    "mid-high", "mid-low", "mid-high", "high", "high", "mid-high", "high"
  )
  )
)
</code>```

And the final outcome. I used fct_relevel() to put them in order of effort.

plot_forest_test(
  data = data_observation,
  habitat_type = habitat_bush,
  colour = obs
)

data_observation_2 %>%
  mutate(effort = fct_relevel(effort, "low", "mid-low", "mid-high", "high")) %>%
  plot_forest_test(
    habitat_type = superficie_essence,
    colour = obs,
    facet = effort
  )
```

Body:
I need some help for a technical manipulation on R plz.

My problem : I have some observation data of bird by presence/absence in differents habitat types. I want know the sucess ratio of observation in these differents habitats according to their surface range :

data_observation <- data.frame(
  habitat_bush = c(
    0, 0, 0, 0, 10,
    10, 30, 30, 30, 45,
    65, 65, 65, 80, 80,
    80, 90, 95, 100
  ),
  obs = c(
    "yes", "no", "no", "no", "yes",
    "no", "no", "yes", "no", "yes",
    "yes", "no", "yes", "no", "yes",
    "yes", "yes", "yes", "yes"
  )
)

Here you have just data for 'habitat_bush" but in have 10 more time habitats.

Help by a colleague, we have made this function to make a ggplot of the ratio success of observation under differents area size of 'habitat_bush" :

library(dplyr)
library(ggplot2)
library(scales)

plot_forest_test <- function(data = NULL, habitat_type = NULL, colour = NULL) {
  x <- enquo(habitat_type)
  fill <- enquo(colour)

  ggdata <- data %>%
    select(x = !!x, fill = !!fill) %>%
    mutate(
      group = case_when(
        x == 0 ~ "[0]",
        x > 0.0001 & x < 10.0001 ~ "]0-10]",
        x > 10.0001 & x < 25.0001 ~ "]10-25]",
        x > 25.0001 & x < 50.0001 ~ "]25-50]",
        x > 50.0001 & x < 75.0001 ~ "]50-75]",
        x > 75.0001 ~ "]75- 100]"
      )
    ) %>%
    select(-x) %>%
    group_by(group, fill) %>%
    count() %>%
    group_by(group) %>%
    group_modify(~ mutate(.data = .x, freq = n / sum(n)))

  ggplot(data = ggdata, mapping = aes(x = group, y = freq, fill = fill)) +
    geom_bar(stat = "identity") +
    scale_fill_brewer(palette = "Greens") +
    scale_y_continuous(labels = scales::percent) +
    theme_minimal() +
    labs(x = expr(!!x), fill = expr(!!fill))
}

plot_forest_test(data = data_observation, habitat_type = habitat_bush, colour = obs)

It's work very well. But the observation can depend of effort put by technicien to looking for the presence of bird. So, I have data like that :

data_observation_2 <- data.frame(
  superficie_essence = c(
    0, 0, 0, 0, 10,
    10, 30, 30, 30, 45,
    65, 65, 65, 80, 80,
    80, 90, 95, 100
  ),
  obs = c(
    "yes", "no", "no", "no", "yes",
    "no", "no", "yes", "no", "yes",
    "yes", "no", "yes", "no", "yes",
    "yes", "yes", "yes", "yes"
  ),
  effort = c(low, low, mid-low, mid-low, low, mid-low, mid-low,
            mid-high, mid-high, high, mid-low, mid-low, mid-high, mid-low, mid-high, high, high, mid-high, high)
)

My R skills stop here. I want have the same previously graph but
subdivided by effort_type for each modalities of habitats types, in the same graphical (like multipanel graphical). In other word I want 5 sub-graph of previous graph with 1 barplot by efforts modalities. But I have lot of data, so I would like put this processu into a function like :

plot_forest_test_2(data = data_observation, habitat_type = habitat_bush, effort = Q_effort, colour = obs)

Can you help me please ? Thanks for your help !

cdlt

Body:
Quosures are not my forte, especially when they might be missing but give this a shot. I created a new column for the facetted item and then add facet_wrap(). You could also use facet_grid(). Hope it helps.

plot_forest_test <- function(data = NULL, habitat_type = NULL, colour = NULL, facet = NULL) {
  x <- enquo(habitat_type)
  fill <- enquo(colour)

  # this is new ####################
  facet <- enquo(facet)
  has_facet <- quo_name(facet) != "NULL"

  df <-
    data %>%
    mutate(
      x = !!x,
      fill = !!fill,
      facet = ""
    )

  if (has_facet) {
    df <-
      df %>%
      mutate(facet = !!facet)
  }
  ##################################

  ggdata <-
    df %>%
    mutate(
      group = case_when(
        x == 0 ~ "[0]",
        x > 0.0001 & x < 10.0001 ~ "]0-10]",
        x > 10.0001 & x < 25.0001 ~ "]10-25]",
        x > 25.0001 & x < 50.0001 ~ "]25-50]",
        x > 50.0001 & x < 75.0001 ~ "]50-75]",
        x > 75.0001 ~ "]75- 100]"
      )
    ) %>%
    select(-x) %>%
    # adding facet here
    group_by(group, fill, facet) %>%
    count() %>%
    group_by(group, facet) %>%
    arrange(desc(fill)) %>%
    mutate(
      freq = n/sum(n),
      # these steps set up the label placement
      running_freq = cumsum(freq),
      prev_freq = lag(running_freq, default = 0),
      label_y = (prev_freq + running_freq)/2 ,
      label_n = paste0("n = ", sum(n))
    ) %>%
    ungroup()

  # create plot w/o facet
  p <-
    ggplot(data = ggdata, mapping = aes(x = group, y = freq, fill = fill)) +
    geom_bar(stat = "identity") +
    geom_hline(yintercept = 0) +
    geom_text(aes(y = -0.05, label = label_n), size = 3.5) +
    #geom_text(aes(y = label_y, label = n)) +
    scale_fill_brewer(palette = "Greens") +
    scale_y_continuous(labels = scales::percent) +
    theme(
      panel.background = element_rect(fill = "white"),
      panel.border = element_rect(color = "grey90", fill = NA)
    ) +
    labs(x = expr(!!x), fill = expr(!!fill))

  # add in if facet was mentioned
  if (has_facet) {
    p <-
      p +
      facet_grid(~facet)
  }

  # return final plot
  p
}

I am including an edit to data_observation_2 as the strings were not in quotes and some of the values has spaces around the hyphens when others did not. I made them all consistent w/o spaces

data_observation_2 <- data.frame(
  superficie_essence = c(
    0, 0, 0, 0, 10,
    10, 30, 30, 30, 45,
    65, 65, 65, 80, 80,
    80, 90, 95, 100
  ),
  obs = c(
    "yes", "no", "no", "no", "yes",
    "no", "no", "yes", "no", "yes",
    "yes", "no", "yes", "no", "yes",
    "yes", "yes", "yes", "yes"
  ),
  effort = c(
    "low", "low", "mid-low", "mid-low", "low", "mid-low", "mid-low",
    "mid-high", "mid-high", "high", "mid-low", "mid-low",
    "mid-high", "mid-low", "mid-high", "high", "high", "mid-high", "high"
  )
  )
)

And the final outcome. I used fct_relevel() to put them in order of effort.

plot_forest_test(
  data = data_observation,
  habitat_type = habitat_bush,
  colour = obs
)

data_observation_2 %>%
  mutate(effort = fct_relevel(effort, "low", "mid-low", "mid-high", "high")) %>%
  plot_forest_test(
    habitat_type = superficie_essence,
    colour = obs,
    facet = effort
  )


问:
How to map object array to formarray in Angular
What is the proper way to map data array to checkboxes form array?
I tried code bellow but it doesn't work...Goal is to get informations from httpclient and map it to data array that's ok, but cannot map data array to form array correctly...

```<code>data = [
      { id: false, name: "Ovo" },
      { id: false, name: "Ono" },
      { id: false, name: "Levo" },
      { id: false, name: "Desno" }
    ];
</code>```

```<code>this.postForm = this.fb.group({
      osnovne: this.fb.group({
        sekcija: ["market", Validators.required],
        kategorija: "",
        cena: [""],
        dogovor: false,
        opis: ""
      }),
      detaljne: this.fb.group({
        select: this.fb.array([]),
        checkboxes: this.fb.array([])
      }),

      imagePath: this.fb.group({
        data: ""
      })
    });
</code>```

Template

```<code><form [formGroup]="postForm">
  <div formGroupName="detaljne">
    <div
      formArrayName="checkboxes"
      *ngFor="let data of data; let i = index"
    >
      <input [id]="data.id" type="checkbox" [formControl]="checkboxes[i]" />
      <label [for]="data.id">
        {{ data.name }}</label
      >
    </div>
  </div>
</form>
</code>```

答:
you just need to set the formControtName in the checkboxes array base of the index

this how I set the controls data updateDataControls

```<code>  ngOnInit() {
    const cData: IControls<boolean>[] = [
      { value: false, name: "Ovo" },
      { value: true, name: "Ono" },
      { value: false, name: "Levo" },
      { value: true, name: "Desno" }
    ]
    this.updateDataControls(cData)

  }

  updateDataControls(controls: IControls<any>[]) {
    this.data = controls;
    const controlsForm = this.form.get('controls').get('checkboxes') as FormArray;
    for (const c of controls) {
      controlsForm.push(this.fb.control(c.value))
    }
  }
</code>```

template

```<code><div [formGroup]="form">
    <div formGroupName="controls">
        <div formArrayName="checkboxes">
            <div *ngFor="let c of data;let index = index">
                <label>{{c.name}}</label>
        <input type="checkbox" [formControlName]="index" >
      </div>
     </div>
  </div>
</div>
</code>```

check the complete example at  stackblitz demo

Body:
What is the proper way to map data array to checkboxes form array?
I tried code bellow but it doesn't work...Goal is to get informations from httpclient and map it to data array that's ok, but cannot map data array to form array correctly...

data = [
      { id: false, name: "Ovo" },
      { id: false, name: "Ono" },
      { id: false, name: "Levo" },
      { id: false, name: "Desno" }
    ];

this.postForm = this.fb.group({
      osnovne: this.fb.group({
        sekcija: ["market", Validators.required],
        kategorija: "",
        cena: [""],
        dogovor: false,
        opis: ""
      }),
      detaljne: this.fb.group({
        select: this.fb.array([]),
        checkboxes: this.fb.array([])
      }),

      imagePath: this.fb.group({
        data: ""
      })
    });

Template

<form [formGroup]="postForm">

      <input [id]="data.id" type="checkbox" [formControl]="checkboxes[i]" />

        {{ data.name }}

</form>

Body:
you just need to set the formControtName in the checkboxes array base of the index

this how I set the controls data updateDataControls

  ngOnInit() {
    const cData: IControls<boolean>[] = [
      { value: false, name: "Ovo" },
      { value: true, name: "Ono" },
      { value: false, name: "Levo" },
      { value: true, name: "Desno" }
    ]
    this.updateDataControls(cData)

  }

  updateDataControls(controls: IControls<any>[]) {
    this.data = controls;
    const controlsForm = this.form.get('controls').get('checkboxes') as FormArray;
    for (const c of controls) {
      controlsForm.push(this.fb.control(c.value))
    }
  }

template

<div [formGroup]="form">
    <div formGroupName="controls">
        <div formArrayName="checkboxes">
            <div *ngFor="let c of data;let index = index">
                <label>{{c.name}}</label>
        <input type="checkbox" [formControlName]="index" >
      </div>
     </div>
  </div>
</div>

check the complete example at  stackblitz demo


问:
Facebook-wall like MySQL Structure problem
I don’t want any code just a how-to answer.

I’m trying to add a facebook-wall-like feature to a webapp (not commercial, only experimental).

The first thing I thought about was to store something like “1/2011-10-10/texthere,2/2011-10-10/texthere” where 1 would be the id & 2011-10-10 the date. Then I would explode it in php and have an array. (Then search for each id in the users table etc…)

But this has some problems. One would be if I have too many posts, it will be extremely heavy to a webpage and very difficult to limit results (without talking about character restriction for the array’s sake).

So I thought about two other solutions that have the pros and cons for me.

Use one table with 4 columns: Poster
id, Receiver id, Message, Date Posted

One table for each user (desperate
solution :))

So, should I direclty go for my first other solution or there is a better one?

Adv thanks

答:
The solution to your problem would be a standard Database Table.

Use a table with columns

PosterId

Wall/RecieverId

Message

Date Posted

This would be a standard database structure.  Use the mysql PDO functions to access your data and place in a php array.


问:
How do I include a JavaScript file in another JavaScript file?
How do I include a JavaScript file inside another JavaScript file, similar to @import in CSS?

答:
You can use my loadScript ES module for loading of the JavaScript files.

Usage:

In your head tag, include the following code:

```<code><script src="https://raw.githack.com/anhr/loadScriptNodeJS/master/build/loadScript.js"></script>
</code>```

or

```<code><script src="https://raw.githack.com/anhr/loadScriptNodeJS/master/build/loadScript.min.js"></script>
</code>```

Now you can use window.loadScript for loading of your JavaScript files.

loadScript.async( src, [options] )

Asynchronous load JavaScript file.

src: URL of an external script file or array of the script file names.

options: the following options are available

```<code>onload: function () The onload event occurs when a script has been loaded. Default is undefined.

onerror: function ( str, e ) The onerror event occurs when an error has been occurred. The default is undefined.

    str: error details

    e: event

appendTo: The node to which the new script will be append. The default is the head node.
</code>```

For example

```<code>loadScript.async( "JavaScript.js",
        {
            onload: function () {

                var str = 'file has been loaded successfully';
                console.log( str );
            },
            onerror: function ( str, e ) {

                console.error( str );
            },
        } );
</code>```

Example of usage

Body:
You can use my loadScript ES module for loading of the JavaScript files.

Usage:

In your head tag, include the following code:

<script src="https://raw.githack.com/anhr/loadScriptNodeJS/master/build/loadScript.js"></script>

or

<script src="https://raw.githack.com/anhr/loadScriptNodeJS/master/build/loadScript.min.js"></script>

Now you can use window.loadScript for loading of your JavaScript files.

loadScript.async( src, [options] )

Asynchronous load JavaScript file.

src: URL of an external script file or array of the script file names.

options: the following options are available

onload: function () The onload event occurs when a script has been loaded. Default is undefined.

onerror: function ( str, e ) The onerror event occurs when an error has been occurred. The default is undefined.

    str: error details

    e: event

appendTo: The node to which the new script will be append. The default is the head node.

For example

loadScript.async( "JavaScript.js",
        {
            onload: function () {

                var str = 'file has been loaded successfully';
                console.log( str );
            },
            onerror: function ( str, e ) {

                console.error( str );
            },
        } );

Example of usage


问:
Getting "unable to decode APP fields" while playing USB webcam stream through ffplay
I am trying to play USB Webcam stream(not sure in which format it is..) using ffplay in windows. I can see the video without any issue, But I am keep getting below error in console.

ffplay.exe -f dshow -i video="Logitech HD Webcam C615" -loglevel debug

[mjpeg @97a118cc80] unable to decode APP fields: Invalid data found when processing input
check logs for more details

Do I really need to worry about this error? Or any filter that I need to provide in command to get ride of this error .

Note: I tried to save stream to a file using ffmpeg getting the same issue.

Thanks in advance.

答:
Those APP field messages are not errors.  What you are seeing is Logitech's proprietary motion-jpeg format that they use in many of their web cameras.  I have seen it in the C270 and the newer c922, for example.  The mjpeg stream contains a sequence of jpeg images, some are key frames, the complete image, and some are other frames such as delta frames, describing the differences between frames.   What Logitech does is embed an H264 stream into the mjpeg stream by attaching H264 data onto the jpeg frames as APP attachments, i.e. it's a stream within a stream.   As you play or transcode data from the mjpeg stream, ffmpeg runs into these APP attachments and doesn't know what to do with them.   I believe programs such as Skype are able to read both the outer mjpeg stream and the inner H264 stream.

If you want to see this for yourself, you can encode a small video from the mjpeg stream of your cam, then extract the jpeg images, then view the structure of the jpeg images and you will see the embedded video.

```<code># create a small mp4, copying mjpeg stream off the cam for a second or two
$ ffmpeg -f v4l2 -input_format mjpeg -i /dev/video0 -c:v copy test.mp4

# extract the unaltered jpeg files inside the stream
$ ffmpeg -i test.mp4 -vcodec copy %03d.jpg

# view any of the jpeg files for APP attachments
$ exiv2 -pS 001.jpg

STRUCTURE OF JPEG FILE: 001.jpg address | marker       |  length | data
   0 | 0xffd8 SOI
   2 | 0xffe0 APP0  |      33 | AVI1.....x.x....................
  37 | 0xffdb DQT   |      67
 106 | 0xffdb DQT   |      67
 175 | 0xffdd DRI   |       4
 181 | 0xffe0 APP0  |       4 | ....
 187 | 0xffc0 SOF0  |      17
 206 | 0xffda SOS
</code>```

See those APP0 attachments on the jpeg?  That's the embedded H264 data that the decoders/players are complaining about.

Body:
Those APP field messages are not errors.  What you are seeing is Logitech's proprietary motion-jpeg format that they use in many of their web cameras.  I have seen it in the C270 and the newer c922, for example.  The mjpeg stream contains a sequence of jpeg images, some are key frames, the complete image, and some are other frames such as delta frames, describing the differences between frames.   What Logitech does is embed an H264 stream into the mjpeg stream by attaching H264 data onto the jpeg frames as APP attachments, i.e. it's a stream within a stream.   As you play or transcode data from the mjpeg stream, ffmpeg runs into these APP attachments and doesn't know what to do with them.   I believe programs such as Skype are able to read both the outer mjpeg stream and the inner H264 stream.

If you want to see this for yourself, you can encode a small video from the mjpeg stream of your cam, then extract the jpeg images, then view the structure of the jpeg images and you will see the embedded video.

# create a small mp4, copying mjpeg stream off the cam for a second or two
$ ffmpeg -f v4l2 -input_format mjpeg -i /dev/video0 -c:v copy test.mp4

# extract the unaltered jpeg files inside the stream
$ ffmpeg -i test.mp4 -vcodec copy %03d.jpg

# view any of the jpeg files for APP attachments
$ exiv2 -pS 001.jpg

STRUCTURE OF JPEG FILE: 001.jpg address | marker       |  length | data
   0 | 0xffd8 SOI
   2 | 0xffe0 APP0  |      33 | AVI1.....x.x....................
  37 | 0xffdb DQT   |      67
 106 | 0xffdb DQT   |      67
 175 | 0xffdd DRI   |       4
 181 | 0xffe0 APP0  |       4 | ....
 187 | 0xffc0 SOF0  |      17
 206 | 0xffda SOS

See those APP0 attachments on the jpeg?  That's the embedded H264 data that the decoders/players are complaining about.


问:
What does char*** mean in C?
I need help understanding what char*** means and how do I initialize a variable that is of type char***.

For example, if there is a function that reads the lines of a file, while keeping track of the number of lines and printing out each line with its corresponding number:

```<code>void read_lines(FILE* fp, char*** lines, int* num_lines){}
</code>```

What would char*** represent in this case and how would I initialize the variable lines?

答:
It's a pointer-to-pointer-to-pointer-to-char.  In this case, it's very likely to be an output parameter.  Since C passes arguments by value, output parameters require an extra level of indirection.  That is, the read_lines function wants to give the caller a char**, and to accomplish that via an output parameter, it needs to take a pointer to a char**.  Likely all you'd need to do to invoke it is:

char** lines = null;
int num_lines;
read_lines(fp, &lines, &num_lines);
```

Also see C Programming: malloc() inside another function.

Title: What does char*** mean in C?

Body:
I need help understanding what char*** means and how do I initialize a variable that is of type char***.

For example, if there is a function that reads the lines of a file, while keeping track of the number of lines and printing out each line with its corresponding number:

void read_lines(FILE* fp, char*** lines, int* num_lines){}

What would char*** represent in this case and how would I initialize the variable lines?

Body:
It's a pointer-to-pointer-to-pointer-to-char.  In this case, it's very likely to be an output parameter.  Since C passes arguments by value, output parameters require an extra level of indirection.  That is, the read_lines function wants to give the caller a char**, and to accomplish that via an output parameter, it needs to take a pointer to a char**.  Likely all you'd need to do to invoke it is:

char** lines = null;
int num_lines;
read_lines(fp, &lines, &num_lines);

Also see C Programming: malloc() inside another function.


问:
How can I draw a black shadow in webkit browsers?
How can I draw a BLACK shadow in webkit browsers with the HTML5 canvas?</p>

答:
shadowColor = "rgb(255,100,100)";

See an example here.


问:
Serial Input in Ubuntu, Usb to serial converter (Pl2303 - Prolific) not working in ubuntu 18.04
I am trying to read input from a Electronic weighing scale (Weigh sensor) connected to Ubuntu enabled UDOO board using a Prolific PL2303 serial converter cable (CA-US9), but am unable to read any input from the sensor. To monitor the input I have tried using (Coolterm & GTKTerm), assuming an issue with the driver I have referred and tried updating the DTR line as the solutions suggested in the following stack overflow resources Reference 1,Reference 2,Reference 3.

I have tied the same on the ubuntu based computer too but the issue remain the same. Using the dmesg command i was able to check that the device has been detected properly when connected. The output to the command executed as dmesg | tail is as follows :

```<code>[ 7365.393110] usb 1-3: new full-speed USB device number 53 using xhci_hcd
[ 7365.542407] usb 1-3: New USB device found, idVendor=067b, idProduct=2303, bcdDevice= 4.00
[ 7365.542424] usb 1-3: New USB device strings: Mfr=1, Product=2, SerialNumber=0
[ 7365.542437] usb 1-3: Product: USB-Serial Controller D
[ 7365.542448] usb 1-3: Manufacturer: Prolific Technology Inc.
[ 7365.545546] pl2303 1-3:1.0: pl2303 converter detected
[ 7365.552313] usb 1-3: pl2303 converter now attached to ttyUSB0
[ 7373.296214] usb 1-3: USB disconnect, device number 53
[ 7373.297492] pl2303 ttyUSB0: pl2303 converter now disconnected from ttyUSB0
[ 7373.297644] pl2303 1-3:1.0: device disconnected
</code>```

The device remains connected physically but seems disconnected by the command output, Also please suggest how to find the port id for the serial port connected.

答:
Need to set the permissions for /dev/ttyUSB0.
If user dialout is cumbersome, then we have to grant universal permissions to /dev/ttyUSB0.
Command is "sudo chmod 666 /dev/ttyUSB0"</p>

Body:
I am trying to read input from a Electronic weighing scale (Weigh sensor) connected to Ubuntu enabled UDOO board using a Prolific PL2303 serial converter cable (CA-US9), but am unable to read any input from the sensor. To monitor the input I have tried using (Coolterm & GTKTerm), assuming an issue with the driver I have referred and tried updating the DTR line as the solutions suggested in the following stack overflow resources Reference 1,Reference 2,Reference 3.

I have tied the same on the ubuntu based computer too but the issue remain the same. Using the dmesg command i was able to check that the device has been detected properly when connected. The output to the command executed as dmesg | tail is as follows :

[ 7365.393110] usb 1-3: new full-speed USB device number 53 using xhci_hcd
[ 7365.542407] usb 1-3: New USB device found, idVendor=067b, idProduct=2303, bcdDevice= 4.00
[ 7365.542424] usb 1-3: New USB device strings: Mfr=1, Product=2, SerialNumber=0
[ 7365.542437] usb 1-3: Product: USB-Serial Controller D
[ 7365.542448] usb 1-3: Manufacturer: Prolific Technology Inc.
[ 7365.545546] pl2303 1-3:1.0: pl2303 converter detected
[ 7365.552313] usb 1-3: pl2303 converter now attached to ttyUSB0
[ 7373.296214] usb 1-3: USB disconnect, device number 53
[ 7373.297492] pl2303 ttyUSB0: pl2303 converter now disconnected from ttyUSB0
[ 7373.297644] pl2303 1-3:1.0: device disconnected

The device remains connected physically but seems disconnected by the command output, Also please suggest how to find the port id for the serial port connected.


问:
Trying to run truffle and it says command not found on my mac
I've been trying to start Truffle but when I do $ truffle it says command not found. I've done npm init, npm i truffle and ./node_modules/.bin/truffle init but nothing works. I have the latest version of node but it still makes no difference.

```<code>Roberts-MacBook-Pro-9:~ rbeit$ truffle init
-bash: truffle: command not found
Roberts-MacBook-Pro-9:~ rbeit$ truffle
-bash: truffle: command not found
Roberts-MacBook-Pro-9:~ rbeit$
</code>```

答:
You have only installed the truffle npm locally, you can ether install it globally with npm install -g truffle or call it from npm by adding

```<code>  "scripts": {
    "truffle": "truffle init",
  }
</code>```

to your package.json

and call it like this npm run truffle

Body:
I've been trying to start Truffle but when I do $ truffle it says command not found. I've done npm init, npm i truffle and ./node_modules/.bin/truffle init but nothing works. I have the latest version of node but it still makes no difference.

Roberts-MacBook-Pro-9:~ rbeit$ truffle init
-bash: truffle: command not found
Roberts-MacBook-Pro-9:~ rbeit$ truffle
-bash: truffle: command not found
Roberts-MacBook-Pro-9:~ rbeit$

Body:
You have only installed the truffle npm locally, you can ether install it globally with npm install -g truffle or call it from npm by adding

  "scripts": {
    "truffle": "truffle init",
  }

to your package.json

and call it like this npm run truffle


问:
How to get each student's highest Score, in order
I have Student class and the initialized list of students to the Program class in my project.
Now I want to get the highest score of each student, in order

How to get that using Max()?

```<code>public class Student
{
    public string First { get; set; }

    public string Last { get; set; }

    public int ID { get; set; }

    public List<int> Scores;
}

// Create a data source by using a collection initializer.

static List<Student> students = new List<Student>
{
   new Student {First="Svetlana", Last="Omelchenko", ID=111, Scores= new List<int> {97, 92, 81, 60}},
   new Student {First="Claire", Last="O’Donnell", ID=112, Scores= new List<int> {75, 84, 91, 39}},
   new Student {First="Sven", Last="Mortensen", ID=113, Scores= new List<int> {88, 94, 65, 91}},
   new Student {First="Cesar", Last="Garcia", ID=114, Scores= new List<int> {97, 89, 85, 82}},
   new Student {First="Debra", Last="Garcia", ID=115, Scores= new List<int> {35, 72, 91, 70}},
   new Student {First="Fadi", Last="Fakhouri", ID=116, Scores= new List<int> {99, 86, 90, 94}},
   new Student {First="Hanying", Last="Feng", ID=117, Scores= new List<int> {93, 92, 80, 87}},
   new Student {First="Hugo", Last="Garcia", ID=118, Scores= new List<int> {92, 90, 83, 78}},
   new Student {First="Lance", Last="Tucker", ID=119, Scores= new List<int> {68, 79, 88, 92}},
   new Student {First="Terry", Last="Adams", ID=120, Scores= new List<int> {99, 82, 81, 79}},
   new Student {First="Eugene", Last="Zabokritski", ID=121, Scores= new List<int> {96, 85, 91, 60}},
   new Student {First="Michael", Last="Tucker", ID=122, Scores= new List<int> {94, 92, 91, 91} }
};
</code>```

答:
Traversing students and then using the bubble sorting algorithm to maximize</p>

```<code>    static void Main(string[] args)
    {
        List<Student> students = new List<Student>();
        students.Add(new Student { First = "Svetlana", Last = "Omelchenko", ID = 111, Scores = new List<int> { 97, 92, 81, 60 } });
        students.Add(new Student { First = "Svetlana", Last = "Omelchenko", ID = 111, Scores = new List<int> { 75, 84, 91, 39 } });

        for (int i = 0; i < students.Count; i++)
        {
            Student item = students[i];
            List<int> scores = item.Scores;
            int max = SortGetMax(scores);
            Debug.WriteLine(max);
        }
    }

    public static int SortGetMax(List<int> arrays)
    {
        int max = 0;
        for (int i = 0; i < arrays.Count; i++)
        {
            if (arrays[i] > max)
            {
                int flag = arrays[i];
                arrays[i] = max;
                max = flag;
            }
        }
        return max;
    }
</code>```

Body:
I have Student class and the initialized list of students to the Program class in my project.
Now I want to get the highest score of each student, in order

How to get that using Max()?

public class Student
{
    public string First { get; set; }

    public string Last { get; set; }

    public int ID { get; set; }

    public List<int> Scores;
}

// Create a data source by using a collection initializer.

static List<Student> students = new List<Student>
{
   new Student {First="Svetlana", Last="Omelchenko", ID=111, Scores= new List<int> {97, 92, 81, 60}},
   new Student {First="Claire", Last="O’Donnell", ID=112, Scores= new List<int> {75, 84, 91, 39}},
   new Student {First="Sven", Last="Mortensen", ID=113, Scores= new List<int> {88, 94, 65, 91}},
   new Student {First="Cesar", Last="Garcia", ID=114, Scores= new List<int> {97, 89, 85, 82}},
   new Student {First="Debra", Last="Garcia", ID=115, Scores= new List<int> {35, 72, 91, 70}},
   new Student {First="Fadi", Last="Fakhouri", ID=116, Scores= new List<int> {99, 86, 90, 94}},
   new Student {First="Hanying", Last="Feng", ID=117, Scores= new List<int> {93, 92, 80, 87}},
   new Student {First="Hugo", Last="Garcia", ID=118, Scores= new List<int> {92, 90, 83, 78}},
   new Student {First="Lance", Last="Tucker", ID=119, Scores= new List<int> {68, 79, 88, 92}},
   new Student {First="Terry", Last="Adams", ID=120, Scores= new List<int> {99, 82, 81, 79}},
   new Student {First="Eugene", Last="Zabokritski", ID=121, Scores= new List<int> {96, 85, 91, 60}},
   new Student {First="Michael", Last="Tucker", ID=122, Scores= new List<int> {94, 92, 91, 91} }
};

Body:
Traversing students and then using the bubble sorting algorithm to maximize

    static void Main(string[] args)
    {
        List<Student> students = new List<Student>();
        students.Add(new Student { First = "Svetlana", Last = "Omelchenko", ID = 111, Scores = new List<int> { 97, 92, 81, 60 } });
        students.Add(new Student { First = "Svetlana", Last = "Omelchenko", ID = 111, Scores = new List<int> { 75, 84, 91, 39 } });

        for (int i = 0; i < students.Count; i++)
        {
            Student item = students[i];
            List<int> scores = item.Scores;
            int max = SortGetMax(scores);
            Debug.WriteLine(max);
        }
    }

    public static int SortGetMax(List<int> arrays)
    {
        int max = 0;
        for (int i = 0; i < arrays.Count; i++)
        {
            if (arrays[i] > max)
            {
                int flag = arrays[i];
                arrays[i] = max;
                max = flag;
            }
        }
        return max;
    }


问:
How to center a SearchBar in React Native Elements
I am new to React Native and am using React Native Elements to build a UI for an app I am creating. My problem is that I can not seem to get the search bar placed in the middle of the screen. Is there a prop or something that I am missing.</p>

答:
You can add styles for containerStyle prop for SearchBar

```<code><View styles={{ flex:1 }}>
   <SearchBar
      placeholder="Type Here..."
      onChangeText={this.updateSearch}
      value={search}
      containerStyle = {{ alignItems:'center', justifyContent:'center' }}
   />
</View>
</code>```

Body:
You can add styles for containerStyle prop for SearchBar

<View styles={{ flex:1 }}>
   <SearchBar
      placeholder="Type Here..."
      onChangeText={this.updateSearch}
      value={search}
      containerStyle = {{ alignItems:'center', justifyContent:'center' }}
   />
</View>


问:
How to update the cart in database with sessions variables?
image of the cart (sorry it's in Frensh)

I have already set the cart using sessions but now I'm updating the code to add it to the database, but I have an issue in updating when the quantity changes and I don't know where the problem is.

Adding and deleting work perfectly but when I increase the quantity it's always set to zero in the database and the total stay the same.

Here's the code of the three buttons : remove - add - delete

```<code> <td><a class='btn btn-warning' href='../Ressources/cart.php?remove=
{$row['product_id']}'><span class='glyphicon glyphicon-minus'></span></a>
    <a class='btn btn-success' href='../Ressources/cart.php?add=
{$row['product_id']}'><span class='glyphicon glyphicon-plus'></span></a>
    <a class='btn btn-danger' href='../Ressources/cart.php?delete=
{$row['product_id']}'><span class='glyphicon glyphicon-remove'></span></a>
</td>
</code>```

and this is the PHP code :

```<code>/*****************************add**********************/
if (isset($_GET['add'])) {
    $id = $_SESSION['id_user'];
    $idp = $_GET['add'];
    $query = query("SELECT * FROM products WHERE product_id=".escape_string($_GET['add']). " ");
    confirm($query);

    while ($row = fetch_array($query)) {
        if ($row['product_quantity'] != $_SESSION['product_' . $_GET['add']]) {
            $_SESSION['product_' . $_GET['add']] += 1;
            $quantity = $_SESSION['product_' . $_GET['add']];
            $total = $quantity * $row['product_price'];
            $query2 = query("SELECT * FROM cart where id_product=$idp and id_user=$id");
            confirm($query2);
            if (mysqli_num_rows($query2) == 0) {
                $query1 = query("INSERT into cart values ($id,$idp,$quantity,$total)");
            } else {
                $query1 = query("UPDATE cart set quantity=$quantity and total=$total where id_product=$idp and id_user=$id");
            }
            confirm($query1);
            redirect("../Public/checkout.php");
        } else {
            set_message("there's only " . $row['product_quantity'] . "
            " . "available");
            redirect("../Public/checkout.php");
        }
    }
}

/*************** remove *********************/
if (isset($_GET['remove'])) {
    $idp = $_GET['remove'];
    $id = $_SESSION['id_user'];
    $_SESSION['product_' . $_GET['remove']]--;
    $quantity = $_SESSION['product_' . $_GET['remove']];
    $total = $_SESSION['item_total'];
    $query = query("UPDATE cart set quantity=$quantity and total=$total
        where id_product=$idp and id_user=$id");
    confirm($query);
    if ($_SESSION['product_' . $_GET['remove']] < 1) {
        unset($_SESSION['item_total']);
        unset($_SESSION['item_quantity']);
        unset($_SESSION['nb_product']);
        $query1 = query("DELETE FROM cart where id_product=$idp and id_user=$id");
        confirm($query1);
        redirect("../Public/checkout.php");
    } else {
        redirect("../Public/checkout.php");
    }
}

/*************** delete ********************/
if (isset($_GET['delete'])) {
    $idp = $_GET['delete'];
    $id = $_SESSION['id_user'];
    $_SESSION['product_' . $_GET['delete']] = '0';
    unset($_SESSION['item_total']);
    unset($_SESSION['item_quantity']);
    unset($_SESSION['nb_produit']);
    $query1 = query("DELETE FROM cart where id_product=$idp and id_user=$id");
    confirm($query1);
    redirect("../Public/checkout.php");
}
</code>```

There's still a function in the code to display the products in the cart ( in a table) but I need to solve this problem first)

I expect the values of the quantity and total to be stored in the database as the sessions, any help would be appreciated

答: i had an error in the syntax of the update query, it works now</p>

Body:
image of the cart (sorry it's in Frensh)

I have already set the cart using sessions but now I'm updating the code to add it to the database, but I have an issue in updating when the quantity changes and I don't know where the problem is.

Adding and deleting work perfectly but when I increase the quantity it's always set to zero in the database and the total stay the same.

Here's the code of the three buttons : remove - add - delete

and this is the PHP code :

/*****************************add**********************/
if (isset($_GET['add'])) {
    $id = $_SESSION['id_user'];
    $idp = $_GET['add'];
    $query = query("SELECT * FROM products WHERE product_id=".escape_string($_GET['add']). " ");
    confirm($query);

    while ($row = fetch_array($query)) {
        if ($row['product_quantity'] != $_SESSION['product_' . $_GET['add']]) {
            $_SESSION['product_' . $_GET['add']] += 1;
            $quantity = $_SESSION['product_' . $_GET['add']];
            $total = $quantity * $row['product_price'];
            $query2 = query("SELECT * FROM cart where id_product=$idp and id_user=$id");
            confirm($query2);
            if (mysqli_num_rows($query2) == 0) {
                $query1 = query("INSERT into cart values ($id,$idp,$quantity,$total)");
            } else {
                $query1 = query("UPDATE cart set quantity=$quantity and total=$total where id_product=$idp and id_user=$id");
            }
            confirm($query1);
            redirect("../Public/checkout.php");
        } else {
            set_message("there's only " . $row['product_quantity'] . "
            " . "available");
            redirect("../Public/checkout.php");
        }
    }
}

/*************** remove *********************/
if (isset($_GET['remove'])) {
    $idp = $_GET['remove'];
    $id = $_SESSION['id_user'];
    $_SESSION['product_' . $_GET['remove']]--;
    $quantity = $_SESSION['product_' . $_GET['remove']];
    $total = $_SESSION['item_total'];
    $query = query("UPDATE cart set quantity=$quantity and total=$total
        where id_product=$idp and id_user=$id");
    confirm($query);
    if ($_SESSION['product_' . $_GET['remove']] < 1) {
        unset($_SESSION['item_total']);
        unset($_SESSION['item_quantity']);
        unset($_SESSION['nb_product']);
        $query1 = query("DELETE FROM cart where id_product=$idp and id_user=$id");
        confirm($query1);
        redirect("../Public/checkout.php");
    } else {
        redirect("../Public/checkout.php");
    }
}

/*************** delete ********************/
if (isset($_GET['delete'])) {
    $idp = $_GET['delete'];
    $id = $_SESSION['id_user'];
    $_SESSION['product_' . $_GET['delete']] = '0';
    unset($_SESSION['item_total']);
    unset($_SESSION['item_quantity']);
    unset($_SESSION['nb_produit']);
    $query1 = query("DELETE FROM cart where id_product=$idp and id_user=$id");
    confirm($query1);
    redirect("../Public/checkout.php");
}

There's still a function in the code to display the products in the cart ( in a table) but I need to solve this problem first)

I expect the values of the quantity and total to be stored in the database as the sessions, any help would be appreciated


问:
Complex(ish) Joins Question:
I have the following table in a mySQL database, (nb: these are summarised so they are relevant to this question, some columns have been omitted).

```<code>author (id, username, password etc.)
thread (id, title, content)
tag (id, name)
reply (id, content)
thread_replies (thread_id, reply_id)
author_replies (author_id, reply_id)
thread_tags (thread_id, tag_id)
author_threads (author_id, thread_id)
</code>```

Now to get threads by a certain Author, I normally do this:

```<code>SELECT thread.title, thread.id AS thread_id, thread.content, author.username, author.id AS author_id
FROM thread
JOIN author_threads ON thread.id = author_threads.thread_id
JOIN author ON author_threads.author_id = author.id
WHERE author.id = '12'
</code>```

This works fine, however when I try getting the tags associated with these threads:

```<code>SELECT thread.title, thread.id AS thread_id, thread.content, author.username, author.id AS author_id, GROUP_CONCAT( DISTINCT tag.name
ORDER BY tag.name DESC
SEPARATOR ',' ) AS tags
FROM thread
JOIN thread_tags ON thread.id = thread_tags.thread_id
JOIN tag ON thread_tags.tag_id = tag.id
JOIN author_threads ON thread.id = author_threads.thread_id
JOIN author ON author_threads.author_id = author.id
WHERE author.id = '12'
LIMIT 0 , 30
</code>```

It only shows the first thread, and all the tags associated with this author in one column.

What am I doing wrong here?

Also If I wanted to count the number of replies the author got for each thread how would this be done?

答:
I would prequery the threads and tag info ONLY inside first... Then, that will already have the author and valid threads to join to whatever else you need...

If you DO want to apply a limit, put that on the INNER "PREQUERY" as that will become the basis for joining the outer level tables... Otherwise, you get the inner query of 100's or 1000's plus entries just to be joined to the other tables and chopped to 30 records... have IT stop at 30 and you're done..

You may also want to order by most current threads when limiting the entries returned too.

```<code>select STRAIGHT_JOIN
      PreQuery.*,
      Author.username,
      Thread.title,
      Thread.Content

   from
      ( select STRAIGHT_JOIN
              author_threads.author_id,
              author_threads.thread_id,
              group_concat(distinct tag.name order by tag.name desc separator ',') as tags
           from
              author_threads
                 join thread_tags
                    on author_threads.thread_id = thread_tags.thread_id
                    join tag
                       on thread_tags.tag_id = tag.id
           where
              author_threads.author_id = '12'
           group by
              author_threads.author_id,
              author_threads.thread_id
           limit 0, 30 ) PreQuery

      join author
         on PreQuery.Author_ID = author.id

      join thread
         on PreQuery.Thread_id = thread.id
</code>```

Title: Complex(ish) Joins Question:

Body:
I have the following table in a mySQL database, (nb: these are summarised so they are relevant to this question, some columns have been omitted).

author (id, username, password etc.)
thread (id, title, content)
tag (id, name)
reply (id, content)
thread_replies (thread_id, reply_id)
author_replies (author_id, reply_id)
thread_tags (thread_id, tag_id)
author_threads (author_id, thread_id)

Now to get threads by a certain Author, I normally do this:

SELECT thread.title, thread.id AS thread_id, thread.content, author.username, author.id AS author_id
FROM thread
JOIN author_threads ON thread.id = author_threads.thread_id
JOIN author ON author_threads.author_id = author.id
WHERE author.id = '12'

This works fine, however when I try getting the tags associated with these threads:

SELECT thread.title, thread.id AS thread_id, thread.content, author.username, author.id AS author_id, GROUP_CONCAT( DISTINCT tag.name
ORDER BY tag.name DESC
SEPARATOR ',' ) AS tags
FROM thread
JOIN thread_tags ON thread.id = thread_tags.thread_id
JOIN tag ON thread_tags.tag_id = tag.id
JOIN author_threads ON thread.id = author_threads.thread_id
JOIN author ON author_threads.author_id = author.id
WHERE author.id = '12'
LIMIT 0 , 30

It only shows the first thread, and all the tags associated with this author in one column.

What am I doing wrong here?

Also If I wanted to count the number of replies the author got for each thread how would this be done?

Body:
I would prequery the threads and tag info ONLY inside first... Then, that will already have the author and valid threads to join to whatever else you need...

If you DO want to apply a limit, put that on the INNER "PREQUERY" as that will become the basis for joining the outer level tables... Otherwise, you get the inner query of 100's or 1000's plus entries just to be joined to the other tables and chopped to 30 records... have IT stop at 30 and you're done..

You may also want to order by most current threads when limiting the entries returned too.

select STRAIGHT_JOIN
      PreQuery.*,
      Author.username,
      Thread.title,
      Thread.Content

   from
      ( select STRAIGHT_JOIN
              author_threads.author_id,
              author_threads.thread_id,
              group_concat(distinct tag.name order by tag.name desc separator ',') as tags
           from
              author_threads
                 join thread_tags
                    on author_threads.thread_id = thread_tags.thread_id
                    join tag
                       on thread_tags.tag_id = tag.id
           where
              author_threads.author_id = '12'
           group by
              author_threads.author_id,
              author_threads.thread_id
           limit 0, 30 ) PreQuery

      join author
         on PreQuery.Author_ID = author.id

      join thread
         on PreQuery.Thread_id = thread.id


问:
Gunicorn timeout during file download
I'm using nginx as reverse-proxy to be able to access my Django API and also serve static files.
My Django API is using gunicorn.

I have an endpoint allowing a user to download a csv file. I followed the instructions here, Streaming large CSV files: https://docs.djangoproject.com/en/2.2/howto/outputting-csv/

Here is the nginx configuration:

```<code>upstream docker-api {
    server api;
}

server {
    listen 443 ssl;
    server_name xxxx.com;

    ssl_certificate /path/to/fullchain.pem;
    ssl_certificate_key /path/to//privkey.pem;
    include /path/to/options-ssl-nginx.conf;
    ssl_dhparam /path/to/ssl-dhparams.pem;

    location /static {
        autoindex on;
        alias /static/;
    }

    location /uploads {
        autoindex on;
        alias /uploads/;
    }

    location / {
        proxy_pass         http://docker-api;
        proxy_set_header   Host $host;
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Host $server_name;
        proxy_set_header   X-Forwarded-Proto $scheme;
    }
}
</code>```

This is the command I use to launch my gunicorn server:

```<code>gunicorn my_api.wsgi -b 0.0.0.0:80 --enable-stdio-inheritance -w 2 -t 180 -k gevent
</code>```

And when I try to download the file, Gunicorn always timeout my request after 3 minutes. It should not timeout a streaming http response.

答:
The problem is your gunicorn command.

Let's take a look:

gunicorn my_api.wsgi -b 0.0.0.0:80 --enable-stdio-inheritance -w 2 -t 180 -k gevent

-t  on your gunicorn command stands for timeout, it's in seconds, and your gunicorn worker timeouts because you've set the timeout to 180 seconds (3 minutes).

And when I try to download the file, Gunicorn always timeout my request after 3 minutes.

To solve this issue, you can simply increase the timeout, for example, the following gunicorn command will set the timeout to 5 minutes:

gunicorn my_api.wsgi -b 0.0.0.0:80 --enable-stdio-inheritance -w 2 -t 300 -k gevent

Check the documentation for more information: http://docs.gunicorn.org/en/stable/settings.html#timeout

Title: Gunicorn timeout during file download

Body:
I'm using nginx as reverse-proxy to be able to access my Django API and also serve static files.
My Django API is using gunicorn.

I have an endpoint allowing a user to download a csv file. I followed the instructions here, Streaming large CSV files: https://docs.djangoproject.com/en/2.2/howto/outputting-csv/

Here is the nginx configuration:

upstream docker-api {
    server api;
}

server {
    listen 443 ssl;
    server_name xxxx.com;

    ssl_certificate /path/to/fullchain.pem;
    ssl_certificate_key /path/to//privkey.pem;
    include /path/to/options-ssl-nginx.conf;
    ssl_dhparam /path/to/ssl-dhparams.pem;

    location /static {
        autoindex on;
        alias /static/;
    }

    location /uploads {
        autoindex on;
        alias /uploads/;
    }

    location / {
        proxy_pass         http://docker-api;
        proxy_set_header   Host $host;
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Host $server_name;
        proxy_set_header   X-Forwarded-Proto $scheme;
    }
}

This is the command I use to launch my gunicorn server:

gunicorn my_api.wsgi -b 0.0.0.0:80 --enable-stdio-inheritance -w 2 -t 180 -k gevent

And when I try to download the file, Gunicorn always timeout my request after 3 minutes. It should not timeout a streaming http response.


问:
Why Could not find artifacts for contract from any sources
I am using windows 10 with truffle and ganache-cli. I have 2 contracts file to be deployed contain interfaces of other contracts defined within the contract:

Contracts:

ERC721Mintable.sol

Ownable

Pausable is Ownable

ERC165

ERC721 is Pausable, ERC165

ERC721Enumerable is ERC165, ERC721

ERC721MetaData is ERC721Enumerable, usingOraclize

CraveuERC721Token is ERC721MetaData

Verifier.sol

SolnSquareVerifier.sol

```<code>pragma solidity >=0.4.21 <0.6.0;

import "./ERC721Mintable.sol";
import "./Verifier.sol";

contract SolnSqaureVerifier is CraveuERC721Token {

    SquareVerifier squareVerifier;

    constructor(address verifierAddress) public {
        squareVerifier = SquareVerifier(verifierAddress);
    }
</code>```

Here's my deploy_contracts.js:

```<code>const SquareVerifier = artifacts.require("Verifier");
const SolnSquareVerifier = artifacts.require("SolnSquareVerifier");

module.exports = function(deployer) {
  deployer.deploy(SquareVerifier).then( () => {
    return deployer.deploy(SolnSquareVerifier, SquareVerifier.address);
  });
};
</code>```

I am using truffle version 5.0.18

Error Produced: Error: Error: Could not find artifacts for
  SolnSquareVerifier from any sources

答: There is a typo in your contract name SolnSqaureVerifier, it should be SolnSquareVerifier

Body:
I am using windows 10 with truffle and ganache-cli. I have 2 contracts file to be deployed contain interfaces of other contracts defined within the contract:

Contracts:

ERC721Mintable.sol

Ownable

Pausable is Ownable

ERC165

ERC721 is Pausable, ERC165

ERC721Enumerable is ERC165, ERC721

ERC721MetaData is ERC721Enumerable, usingOraclize

CraveuERC721Token is ERC721MetaData

Verifier.sol

SolnSquareVerifier.sol

pragma solidity >=0.4.21 <0.6.0;

import "./ERC721Mintable.sol";
import "./Verifier.sol";

contract SolnSqaureVerifier is CraveuERC721Token {

    SquareVerifier squareVerifier;

    constructor(address verifierAddress) public {
        squareVerifier = SquareVerifier(verifierAddress);
    }

Here's my deploy_contracts.js:

const SquareVerifier = artifacts.require("Verifier");
const SolnSquareVerifier = artifacts.require("SolnSquareVerifier");

module.exports = function(deployer) {
  deployer.deploy(SquareVerifier).then( () => {
    return deployer.deploy(SolnSquareVerifier, SquareVerifier.address);
  });
};

I am using truffle version 5.0.18

Error Produced: Error: Error: Could not find artifacts for
  SolnSquareVerifier from any sources