问:
How can I accessing nested component in react from parent component?
I want to access a nested component from parent component.

This is Bill Form.jsx

```<code>      import BillDetailForm from './BillDetailForm';

         render(){

          return (
            <form onSubmit={handleSubmit}>

             <FieldArray

               name= 'detail'
               component={BillDetailForm}
               placeholder= '...detail'
               label='Detail'

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

BillForm is the parent component.

This is a nested component or child component of BillForm: BillDetailForm.jsx

```<code>     render(){

    return(
         <form onSubmit={ handleSubmit }>

       <div>Detail:</div>
      <FieldArray
        name= 'detail'
        component={RenderDetail}
        label='Detail'
      />

      </form>

    )

}
</code>```

Inside BillDetailForm is RenderDetail:

```<code>        const RenderDetail = ({fields, meta: { error,submitFailed}},props) => (
          <dl>
         <dt>
            <button type="button" className= 'btn btn-primary' onClick={() => fields.push()}>Add
        Detail</button>
             {submitFailed && error && <span>{error}</span>}
           </dt>
               { fields.map((registerDetail, index) =>
               //In the following line renderDetail is accesing Detail component.
               <Detail detailItem={registerDetail} fields={fields} index={index} key={index}/>

               )
             }

            {error && <dt className="error">{error}</dt>}
            </dl>
            );
</code>```

This is Detail Class Component:

```<code>          class Detail extends Component{

                   render(){

                   const{detailItem,index,fields,isSubtotal} = this.props;

                        return(

                    <dd key={index}>
                    <br></br>
                    <button className= 'btn btn-light mr-2'
                     type="button"
                     title="Remove detail"
                     onClick={() => { fields.remove(index)
                      if(fields.length == 0 || fields.length === undefined){

                        }
                      try{
                     for(let x in fields){
                     fields.remove(index)
                     let d = fields.selectedIndex;
                    if(fields.remove(index) && d >= 1 && d< fields.length ){
                    fields.removeAll(index);
                     }
                     }
                  }catch{console.info("deletes non numerical index")}

                      }}> Delete </button>

              <h4>DetailRegister #{index + 1}</h4>

               <Field
                 id={`${detailItem}._id`}
                 name={`${detailItem}.quantity`}
                 component= {NumberPickerInteger}
                 placeholder= '...quantity'
                 label = "Quantity"
                  />
          <br></br>
          <h3><b>Product</b></h3>
               <Field
                id={`${detailItem}._id`}
                name={`${detailItem}.product.code`}
                type="number"
                component= {RenderFieldNumeric}
                placeholder='...Product's code'
               label = "Product's code"
             />
          <Field
           id={`${detailItem}._id`}
           name={`${detailItem}.product.name`}
           type="text"
           component= {RenderField}
           placeholder='...Product's name'
           label = "Product's name"
         />
            <Field
              id={`${detailItem}._id`}
              name={`${detailItem}.product.price`}
              component= {NumberPickerr}
              placeholder= '...Price'
              label = "Product's price"
             />
         <br></br>
      <h3><b>Subtotal</b></h3>
       <Field
          id={`${detailItem}._id`}
          name={`${detailItem}.subtotal`}
          component= {SubtotalWidget}
          placeholder= '...subtotal'
          label = "Subtotal"
           >
            {isSubtotal}
             </Field>

            </dd>

            );

          }
       }
</code>```

I want to access e.g ${props.detailItem}.subtotal that is in Detail from BillForm. BillForm accesses to BillDetailForm, BillDetailForm accesses to renderDetail, and last renderDetail acceses to Detail.

The question is: How can I access and use props like quantity and subtotal with dynamic index (props.index) from BillForm? I want to access Detail component from BillForm, respecting the following secuence in order access: BillForm -> BillDetailForm -> RenderDetail -> Detail

答:
If I understand correctly what you are saying, it seems you are going against the ethos of React. If your parent component wants access to a piece of data, then that data should start in the parent and be passed down. This way, if the data changes it will call a re-render of components and update all necessary components.

Some other advice. Try not o have so much logic inside your component handlers, it looks messy and will run every render cycle. Abstract this into a method on the class and call it when required.

My example will hopefully help you with your issue, but I recommend having a read of the React documentation as it is very good with simple examples.
The use of class will be deprecated eventually in favour of function components and the Hooks API.

```<code>class ParentComponent {
  state = {
    value: 0,
  }

  methodToDoSomething = (passedVal) => {
    this.setState({
      value: passVal,
    });
  }

  render() {
    const myState = this.state;
    return (
     <Component {...myState} />
    )
  }
}

class Component {
  state = {}

  render() {
    const { value , methodToDoSomething } = this.props;
    return (
     <div onClick={methodToDoSomething}>
      {value}
     </div>
    )
  }
}

// Hooks API

const ParentComponent = () => {

  const [stateVal, updateState] = React.useState('myString');

  return (
    <div>
      {stateVal}
      <Component passedVal={stateVal} passedHandler={updateState} />
    </div>
  )
}

const Component = ({ stateVal, passedHandler }) => {

  function updateMyValue() {
    passedHandler('menewvalue');
  }

  return (
    <div onClick={updateMyValue}>
     {stateValue}
    <div/>
  )
}
</code>```

To avoid passing lots down all the children components, I would recommend reading up on the Context Hook.

*** UPDATE ***
The above example is rudimentary and tries to answer the question presented, there are always many ways to solve a problem.

Passing props can be messy and a maintenance overhead. Most larger applications will benefit from using a state library to manage their global state. The Context API is a good tool to use to wrap a cohesive set of components so they can share data/props without prop-drilling (passing props down many child components).

Custom hooks are another good way to share data. Create a hook containing your data and any other methods for the task and use this hook inside parent and child components to share said data.

Body:
I want to access a nested component from parent component.

This is Bill Form.jsx

      import BillDetailForm from './BillDetailForm';

         render(){

          return (
            <form onSubmit={handleSubmit}>

             <FieldArray

               name= 'detail'
               component={BillDetailForm}
               placeholder= '...detail'
               label='Detail'

                 />
               </form>
                  );
                   }
               }

BillForm is the parent component.

This is a nested component or child component of BillForm: BillDetailForm.jsx

     render(){

    return(
         <form onSubmit={ handleSubmit }>

Detail:

      <FieldArray
        name= 'detail'
        component={RenderDetail}
        label='Detail'
      />

      </form>

    )

}

Inside BillDetailForm is RenderDetail:

        const RenderDetail = ({fields, meta: { error,submitFailed}},props) => (

            <button type="button" className= 'btn btn-primary' onClick={() => fields.push()}>Add
        Detail</button>
             {submitFailed && error && {error}}

               { fields.map((registerDetail, index) =>
               //In the following line renderDetail is accesing Detail component.
               <Detail detailItem={registerDetail} fields={fields} index={index} key={index}/>

               )
             }

            {error &&
{error}
}

            );

This is Detail Class Component:

          class Detail extends Component{

                   render(){

                   const{detailItem,index,fields,isSubtotal} = this.props;

                        return(

                    <button className= 'btn btn-light mr-2'
                     type="button"
                     title="Remove detail"
                     onClick={() => { fields.remove(index)
                      if(fields.length == 0 || fields.length === undefined){

                        }
                      try{
                     for(let x in fields){
                     fields.remove(index)
                     let d = fields.selectedIndex;
                    if(fields.remove(index) && d >= 1 && d< fields.length ){
                    fields.removeAll(index);
                     }
                     }
                  }catch{console.info("deletes non numerical index")}

                      }}> Delete </button>

DetailRegister #{index + 1}

               <Field
                 id={`${detailItem}._id`}
                 name={`${detailItem}.quantity`}
                 component= {NumberPickerInteger}
                 placeholder= '...quantity'
                 label = "Quantity"
                  />

Product

               <Field
                id={`${detailItem}._id`}
                name={`${detailItem}.product.code`}
                type="number"
                component= {RenderFieldNumeric}
                placeholder='...Product's code'
               label = "Product's code"
             />
          <Field
           id={`${detailItem}._id`}
           name={`${detailItem}.product.name`}
           type="text"
           component= {RenderField}
           placeholder='...Product's name'
           label = "Product's name"
         />
            <Field
              id={`${detailItem}._id`}
              name={`${detailItem}.product.price`}
              component= {NumberPickerr}
              placeholder= '...Price'
              label = "Product's price"
             />

Subtotal

       <Field
          id={`${detailItem}._id`}
          name={`${detailItem}.subtotal`}
          component= {SubtotalWidget}
          placeholder= '...subtotal'
          label = "Subtotal"
           >
            {isSubtotal}
             </Field>

            );

          }
       }

I want to access e.g ${props.detailItem}.subtotal that is in Detail from BillForm. BillForm accesses to BillDetailForm, BillDetailForm accesses to renderDetail, and last renderDetail acceses to Detail.

The question is: How can I access and use props like quantity and subtotal with dynamic index (props.index) from BillForm? I want to access Detail component from BillForm, respecting the following secuence in order access: BillForm -> BillDetailForm -> RenderDetail -> Detail

Body:
If I understand correctly what you are saying, it seems you are going against the ethos of React. If your parent component wants access to a piece of data, then that data should start in the parent and be passed down. This way, if the data changes it will call a re-render of components and update all necessary components.

Some other advice. Try not o have so much logic inside your component handlers, it looks messy and will run every render cycle. Abstract this into a method on the class and call it when required.

My example will hopefully help you with your issue, but I recommend having a read of the React documentation as it is very good with simple examples.
The use of class will be deprecated eventually in favour of function components and the Hooks API.

class ParentComponent {
  state = {
    value: 0,
  }

  methodToDoSomething = (passedVal) => {
    this.setState({
      value: passVal,
    });
  }

  render() {
    const myState = this.state;
    return (
     <Component {...myState} />
    )
  }
}

class Component {
  state = {}

  render() {
    const { value , methodToDoSomething } = this.props;
    return (
     <div onClick={methodToDoSomething}>
      {value}
     </div>
    )
  }
}

// Hooks API

const ParentComponent = () => {

  const [stateVal, updateState] = React.useState('myString');

  return (
    <div>
      {stateVal}
      <Component passedVal={stateVal} passedHandler={updateState} />
    </div>
  )
}

const Component = ({ stateVal, passedHandler }) => {

  function updateMyValue() {
    passedHandler('menewvalue');
  }

  return (
    <div onClick={updateMyValue}>
     {stateValue}
    <div/>
  )
}

To avoid passing lots down all the children components, I would recommend reading up on the Context Hook.

*** UPDATE ***
The above example is rudimentary and tries to answer the question presented, there are always many ways to solve a problem.

Passing props can be messy and a maintenance overhead. Most larger applications will benefit from using a state library to manage their global state. The Context API is a good tool to use to wrap a cohesive set of components so they can share data/props without prop-drilling (passing props down many child components).

Custom hooks are another good way to share data. Create a hook containing your data and any other methods for the task and use this hook inside parent and child components to share said data.


来源: stackexchange

问:
Regex with multiple square brackets
I'm working with some transcriptions and I've struggled with their normalization. Some of them have square brackets within other square brackets to specify the different noises / sound events that can be found when listening to the corresponding audio file. This is an example of one file's line:

```<code>U012_W038 [other_speech_adult: [laughter] yeah you can you can read [undefined] tomorrow] [other_speech_adult: are you recording me now] this is annoying eh [noise] [noise_bkgspeech/]
</code>```

In every line the format corresponds to

```<code><audio file reference> <transcription>
</code>```

My ideal output would be:

Get the text that is not enclosed by any square brackets: e.g: "this is annoying eh"

Extract the text that's inside of square brackets only if ":" is found. The text to catch would be the one after the colon. e.g: yeah you can you can read

The output should look something similar to this:

```<code>U012_W038 yeah you can you can read tomorrow are you recording me now this is annoying eh
</code>```

I tried to solve this problem using sed, but I wouldn't mind trying perl or any other text processing tool. My closest attempt so far is:

```<code>sed 's/\[[^]]*]//g'
</code>```

Do you think there's a way to solve this out by coding or it's to be by a manual checking?

Thanks in advance!

答:
You can use this command if your file is named audio:

```<code>sed 's/\[\([^]]*:\)//g; s/\[[^]]*]//g; s/]//g; s/  */ /g' audio
</code>```

This gave me on your example :

U012_W038 yeah you can you can read tomorrow are you recording me now this is annoying eh

Step by step this command does:

sed 's/\[\([^]]*:\)//g': deletes everything between [ and : included

sed 's/\[[^]]*]//g': deletes everything between [ and ] included.

sed 's/]//g': deletes the remaining ]

sed 's/  */ /g': deletes all consecutive blanks.

ContentLicense: CC BY-SA 4.0

Title: Regex with multiple square brackets

Body:
I'm working with some transcriptions and I've struggled with their normalization. Some of them have square brackets within other square brackets to specify the different noises / sound events that can be found when listening to the corresponding audio file. This is an example of one file's line:

U012_W038 [other_speech_adult: [laughter] yeah you can you can read [undefined] tomorrow] [other_speech_adult: are you recording me now] this is annoying eh [noise] [noise_bkgspeech/]

In every line the format corresponds to

<audio file reference> <transcription>

My ideal output would be:

Get the text that is not enclosed by any square brackets: e.g: "this is annoying eh"

Extract the text that's inside of square brackets only if ":" is found. The text to catch would be the one after the colon. e.g: yeah you can you can read

The output should look something similar to this:

U012_W038 yeah you can you can read tomorrow are you recording me now this is annoying eh

I tried to solve this problem using sed, but I wouldn't mind trying perl or any other text processing tool. My closest attempt so far is:

sed 's/\[[^]]*]//g'

Do you think there's a way to solve this out by coding or it's to be by a manual checking?

Thanks in advance!

Body:
You can use this command if your file is named audio:

sed 's/\[\([^]]*:\)//g; s/\[[^]]*]//g; s/]//g; s/  */ /g' audio

This gave me on your example :

U012_W038 yeah you can you can read tomorrow are you recording me now this is annoying eh

Step by step this command does:

sed 's/\[\([^]]*:\)//g': deletes everything between [ and : included

sed 's/\[[^]]*]//g': deletes everything between [ and ] included.

sed 's/]//g': deletes the remaining ]

sed 's/  */ /g': deletes all consecutive blanks.


问:
show content from right to left in web (html and css)
I want to show the content in my website from right to left, I'm trying using Flex from bootstrap but still doesn't work, did javascript library like jquery needed to show content from right to left?

this is the look I want
enter image description here

this is my web look like
enter image description here

this is myhtml

```<code>    <div class="container">
    @foreach ($books as $book)

    <div class="d-flex justify-content-center " style="width:150px; direction:rtl">
        <div class="card bg-info mb-3" style="width: 18rem;">
            <img src="{{ asset("img/books/$book->gambar") }}" width="150" class="card-img-top" alt="...">
                <div class="card-body">
                <h5 class="card-title">{{ $book->judul }}</h5>
                <a href="#" class="btn btn-primary" >detail</a>
            </div>
        </div>
    </div>
    @endforeach
</code>```

答:
Bootstrap has a .flex-row-reverse class that can be used to change the direction of a flex row. So you should be able to do something like this:

```<code><div class="container">
  <div class="d-flex flex-row-reverse">
    @foreach ($books as $book)
      <div class="justify-content-center" style="width:150px; direction:rtl">
        <div class="card bg-info mb-3" style="width: 18rem;">
          <img src="{{ asset('img/books/$book->gambar') }}" width="150" class="card-img-top" alt="...">
          <div class="card-body">
            <h5 class="card-title">{{ $book->judul }}</h5>
            <a href="#" class="btn btn-primary" >detail</a>
          </div>
        </div>
      </div>
    @endforeach
  </div>
</div>
</code>```

Body:
I want to show the content in my website from right to left, I'm trying using Flex from bootstrap but still doesn't work, did javascript library like jquery needed to show content from right to left?

this is the look I want
enter image description here

this is my web look like
enter image description here

this is myhtml

    @foreach ($books as $book)

            gambar") }}" width="150" class="card-img-top" alt="...">

{{ $book->judul }}

                detail

    @endforeach

Body:
Bootstrap has a .flex-row-reverse class that can be used to change the direction of a flex row. So you should be able to do something like this:

<div class="container">
  <div class="d-flex flex-row-reverse">
    @foreach ($books as $book)
      <div class="justify-content-center" style="width:150px; direction:rtl">
        <div class="card bg-info mb-3" style="width: 18rem;">
          <img src="{{ asset('img/books/$book->gambar') }}" width="150" class="card-img-top" alt="...">
          <div class="card-body">
            <h5 class="card-title">{{ $book->judul }}</h5>
            <a href="#" class="btn btn-primary" >detail</a>
          </div>
        </div>
      </div>
    @endforeach
  </div>
</div>


问:
Retrieve different string every day on firebase - swift
Sorry if some post already exists about this, but here is what I'm trying to do:

I have a game for iOS (developed with swift and firebase);

I'd like to give clues for every day, during a long time. I may change these clues;

Therefore, my firebase would associate a day with the sentence of the day.

How do I retrieve one string for the day it's associated, since I wouldn't like to code locally sentences in a way that I have always to make a new version in the app store just to change those minimum details? Thank you for any help or alternative suggestions!

答:
The more firebase-ish way to created a "Sentences" collection of...

```<code>{ sentence: 'some sentence', unused: true }
</code>```

Once a day, search it, like...

```<code>db.collection('Sentences').where('unused', true)  // returns a promise with results
</code>```

Choose a random element from results.docs and save it in a "SentenceDuJour" collection

```<code>let docs = results.docs
let doc = docs[Math.floor(Math.random() * docs.length)]

doc.ref.update({ unused: false })
db.collection('SentenceDuJour').doc('alwaysthesamedocid').set(doc.data())
</code>```

Body:
The more firebase-ish way to created a "Sentences" collection of...

{ sentence: 'some sentence', unused: true }

Once a day, search it, like...

db.collection('Sentences').where('unused', true)  // returns a promise with results

Choose a random element from results.docs and save it in a "SentenceDuJour" collection

let docs = results.docs
let doc = docs[Math.floor(Math.random() * docs.length)]

doc.ref.update({ unused: false })
db.collection('SentenceDuJour').doc('alwaysthesamedocid').set(doc.data())


问:
Can't open a file when not running from __main__
This is my file tree:

```<code>run.py
foo/
    file.py
    foo.json
</code>```

In file.py there is the following code:

```<code>import json

print(json.load(open('foo.json')))
</code>```

In run.py there is the following code:

```<code>import foo.foo as foo
</code>```

When running run.py I get the following error:

```<code>Traceback (most recent call last):
  File "run.py", line 1, in <module>
    import foo.foo as foo
  File "C:\Users\user\Desktop\foo\foo.py", line 3, in <module>
    print(json.load(open('foo.json')))
FileNotFoundError: [Errno 2] No such file or directory: 'foo.json'
</code>```

How do I run run.py without getting that error and without run.py being in the same directory. Any help is appreciated!

答:
Get the absolute path
os.path.abspath(os.path.join(os.path.dirname(__file__), 'your file')

In your file put the path from the top of the project, should be /foo/foo.json

Body:
This is my file tree:

run.py
foo/
    file.py
    foo.json

In file.py there is the following code:

import json

print(json.load(open('foo.json')))

In run.py there is the following code:

import foo.foo as foo

When running run.py I get the following error:

Traceback (most recent call last):
  File "run.py", line 1, in <module>
    import foo.foo as foo
  File "C:\Users\user\Desktop\foo\foo.py", line 3, in <module>
    print(json.load(open('foo.json')))
FileNotFoundError: [Errno 2] No such file or directory: 'foo.json'

How do I run run.py without getting that error and without run.py being in the same directory. Any help is appreciated!


问:
SQL query join in Pandas
I would like to join two tables in Pandas.

df_types
Contains range size of type product (5000 rows)

```<code>| Table: TYPES |          |      |
|--------------|----------|------|
| size_max     | size_min | type |
| 1            | 5        | S    |
| 6            | 16       | M    |
| 16           | 24       | L    |
| 25           | 50       | XL   |
</code>```

Dataframe code in Pandas:

```<code>df_types = pd.DataFrame([[1,5,'S'],
                         [6,16,'M'],
                         [16,24,'L'],
                         [25,50,'XL']],
                        columns = ['size_min','size_max','type'])
</code>```

df_products
Contains products id and size (12000 rows)

```<code>| Table: Products |      |
|-----------------|------|
| id_product      | size |
| A               | 6    |
| B               | 25   |
| C               | 7    |
| D               | 2    |
| F               | 45   |
| E               | 10   |
| G               | 16   |
</code>```

Dataframe code in Pandas:

```<code>df_products = pd.DataFrame([['A',6,],
                            ['B',25],
                            ['C',7],
                            ['D',2],
                            ['F',45],
                            ['E',10],
                            ['G',16]],columns = ['id_product','size'])
</code>```

I´d like to make this SQL join in Pandas:

```<code>SELECT  *.df_products
        type.df_types
FROM    df_products     LEFT JOIN df_types
                        ON  df_products.size >= df_types.size_min
                            AND df_products.size <= df_types.size_max
</code>```

RESULT:

```<code>| id_product | size | type |
|------------|------|------|
| A          | 6    | M    |
| B          | 25   | XL   |
| C          | 7    | M    |
| D          | 2    | S    |
| F          | 45   | XL   |
| E          | 10   | M    |
| G          | 16   | M    |
</code>```

thank you! ;-)

答:
This is way longer than Erfan's solution; I am just offering this because I believe it could help avoid the increase in number of rows resulting from a merge.

What this does is look for the cond1 and cond2 that match the where clause in the SQL query. Next step zips both lists and finds the index of the element (True, True) ...  the index obtained is the equivalent of the index for df_types. concatenate all the dataframes extracted from df_types based on the indices, and concat again to df_products.

There should be a better way than this; I do believe however, that SQL does this way better.

```<code>cond1 = df_products['size'].apply(lambda x: [x>=i for i in [*df_types.size_min.array]])

cond2 = df_products['size'].apply(lambda x: [x<i for i in [*df_types.size_max.array]])

t = [list(zip(i,j)).index((True,True))
     for i,j in zip(cond1.array,cond2.array)]

result = (pd.concat([df_types.iloc[[i]]
                     for i in t])
          .filter(['type'])
          .reset_index(drop=True))

outcome = (pd.concat([df_products,result],
           axis=1,
           ignore_index=True,
           join='outer'))

outcome.columns = ['id_product', 'size', 'type']

    id_product  size    type
0   A   6   M
1   B   25  XL
2   C   7   M
3   D   2   S
4   F   45  XL
5   E   10  M
6   G   16  L
</code>```

Update

Time passes, and hopefully we get better. I gave this another shot, and I moved the transaction into vanilla Python before taking the final result back to Pandas:

```<code>from itertools import product
test = [(id_product,first,last)
        for (id_product,first), (second, third,last)
        in product(zip(df_products.id_product,df_products['size']),
                   df_types.to_numpy()
                  )
        if second <= first <= third
       ]

test

[('A', 6, 'M'),
 ('B', 25, 'XL'),
 ('C', 7, 'M'),
 ('D', 2, 'S'),
 ('F', 45, 'XL'),
 ('E', 10, 'M'),
 ('G', 16, 'M'),
 ('G', 16, 'L')]
</code>```

get the pandas dataframe :

```<code>pd.DataFrame(test,columns=['id_product', 'size', 'type'])
    id_product  size    type
0      A         6       M
1      B        25       XL
2      C        7        M
3      D        2        S
4      F        45       XL
5      E        10       M
6      G        16       M
7      G        16       L
</code>```

Note that the last item 'G' returns two rows, since it matches those, based on the conditions.

Update 2023

Use conditional_join from pyjanitor for non-equi joins:

# pip install pyjanitor
import pandas as pd

(df_products
.conditional_join(
    df_types,
    # column from left, column from right, comparator
    ('size', 'size_min', '>='),
    ('size', 'size_max', '<='),
    # depending on the data size,
    # you could get better performance
    # by using numba, if it is installed
    use_numba=False,
    right_columns='type')
)
  id_product  size type
0          A     6    M
1          B    25   XL
2          C     7    M
3          D     2    S
4          F    45   XL
5          E    10    M
6          G    16    M
7          G    16    L
```

Title: SQL query join in Pandas

Body:
I would like to join two tables in Pandas.

df_types
Contains range size of type product (5000 rows)

| Table: TYPES |          |      |
|--------------|----------|------|
| size_max     | size_min | type |
| 1            | 5        | S    |
| 6            | 16       | M    |
| 16           | 24       | L    |
| 25           | 50       | XL   |

Dataframe code in Pandas:

df_types = pd.DataFrame([[1,5,'S'],
                         [6,16,'M'],
                         [16,24,'L'],
                         [25,50,'XL']],
                        columns = ['size_min','size_max','type'])

df_products
Contains products id and size (12000 rows)

| Table: Products |      |
|-----------------|------|
| id_product      | size |
| A               | 6    |
| B               | 25   |
| C               | 7    |
| D               | 2    |
| F               | 45   |
| E               | 10   |
| G               | 16   |

Dataframe code in Pandas:

df_products = pd.DataFrame([['A',6,],
                            ['B',25],
                            ['C',7],
                            ['D',2],
                            ['F',45],
                            ['E',10],
                            ['G',16]],columns = ['id_product','size'])

I´d like to make this SQL join in Pandas:

SELECT  *.df_products
        type.df_types
FROM    df_products     LEFT JOIN df_types
                        ON  df_products.size >= df_types.size_min
                            AND df_products.size <= df_types.size_max

RESULT:

| id_product | size | type |
|------------|------|------|
| A          | 6    | M    |
| B          | 25   | XL   |
| C          | 7    | M    |
| D          | 2    | S    |
| F          | 45   | XL   |
| E          | 10   | M    |
| G          | 16   | M    |

thank you! ;-)

Body:
This is way longer than Erfan's solution; I am just offering this because I believe it could help avoid the increase in number of rows resulting from a merge.

What this does is look for the cond1 and cond2 that match the where clause in the SQL query. Next step zips both lists and finds the index of the element (True, True) ...  the index obtained is the equivalent of the index for df_types. concatenate all the dataframes extracted from df_types based on the indices, and concat again to df_products.

There should be a better way than this; I do believe however, that SQL does this way better.

cond1 = df_products['size'].apply(lambda x: [x>=i for i in [*df_types.size_min.array]])

cond2 = df_products['size'].apply(lambda x: [x<i for i in [*df_types.size_max.array]])

t = [list(zip(i,j)).index((True,True))
     for i,j in zip(cond1.array,cond2.array)]

result = (pd.concat([df_types.iloc[[i]]
                     for i in t])
          .filter(['type'])
          .reset_index(drop=True))

outcome = (pd.concat([df_products,result],
           axis=1,
           ignore_index=True,
           join='outer'))

outcome.columns = ['id_product', 'size', 'type']

    id_product  size    type
0   A   6   M
1   B   25  XL
2   C   7   M
3   D   2   S
4   F   45  XL
5   E   10  M
6   G   16  L

Update

Time passes, and hopefully we get better. I gave this another shot, and I moved the transaction into vanilla Python before taking the final result back to Pandas:

from itertools import product
test = [(id_product,first,last)
        for (id_product,first), (second, third,last)
        in product(zip(df_products.id_product,df_products['size']),
                   df_types.to_numpy()
                  )
        if second <= first <= third
       ]

test

[('A', 6, 'M'),
 ('B', 25, 'XL'),
 ('C', 7, 'M'),
 ('D', 2, 'S'),
 ('F', 45, 'XL'),
 ('E', 10, 'M'),
 ('G', 16, 'M'),
 ('G', 16, 'L')]

get the pandas dataframe :

pd.DataFrame(test,columns=['id_product', 'size', 'type'])
    id_product  size    type
0      A         6       M
1      B        25       XL
2      C        7        M
3      D        2        S
4      F        45       XL
5      E        10       M
6      G        16       M
7      G        16       L

Note that the last item 'G' returns two rows, since it matches those, based on the conditions.

Update 2023

Use conditional_join from pyjanitor for non-equi joins:

# pip install pyjanitor
import pandas as pd

(df_products
.conditional_join(
    df_types,
    # column from left, column from right, comparator
    ('size', 'size_min', '>='),
    ('size', 'size_max', '<='),
    # depending on the data size,
    # you could get better performance
    # by using numba, if it is installed
    use_numba=False,
    right_columns='type')
)
  id_product  size type
0          A     6    M
1          B    25   XL
2          C     7    M
3          D     2    S
4          F    45   XL
5          E    10    M
6          G    16    M
7          G    16    L


问:
Scroll down to an element with protractor
I have an element on the page that I'm testing that I have to scroll down to be visible. When I execute my test, I get  Element is not clickable at point (94, 188) for example.

I tried the following:

```<code>dvr.executeScript('window.scrollTo(0,250);');
</code>```

But it didn't work. Does anyone know how this works?

答:
pass the xpath to this method dynamically it will scroll to the element

```<code>   scrollToElement: function (element) {
        return element.getLocation().then(function (location) {
            return browser.executeScript('window.scrollTo(' + location.x + ', ' + location.y + ');');
        });
    },
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an element on the page that I'm testing that I have to scroll down to be visible. When I execute my test, I get  Element is not clickable at point (94, 188) for example.

I tried the following:

dvr.executeScript('window.scrollTo(0,250);');

But it didn't work. Does anyone know how this works?

Body:
pass the xpath to this method dynamically it will scroll to the element

   scrollToElement: function (element) {
        return element.getLocation().then(function (location) {
            return browser.executeScript('window.scrollTo(' + location.x + ', ' + location.y + ');');
        });
    },


问:
Using count in in query with left join
I am currently trying to count how many dislikes and likes users have given to an image on my website, underneath you will see the database setup I did for exactly that. Vote_type keeps the like and dislike information where 1 is equal to a like, 0 is equal to a dislike.

this table is called projects
Project table

This table is called projects_votes

Now I want to include that when I make a query to drag information from my database for a blog post. This is currently the query I am making to get the necessary information to display a list of blogs on the frontpage. Here I am getting the uploader, project ID for links and so on.

```<code>    $query = "
SELECT * FROM projects
LEFT JOIN users
ON fk_usr_id = usr_id
LEFT JOIN projects_maps
ON fk_project_id = project_id
ORDER BY RAND()
";
</code>```

So what I have a hard time understanding is how to count my Likes and Dislikes on a specific blog, so I can display this information on my website.

答:
I solved my problem by changing my query to this statement here.</p>

```<code>$query = "
    SELECT project_id, usr_publicname, project_name, photofile_name, map_version, usr_publicname, map_date, project_id AS project, (SELECT COUNT(*) FROM projects_votes WHERE vote_type = 1) AS likes,
    (SELECT COUNT(*) FROM projects_votes WHERE vote_type = 0) AS dislikes FROM projects

    LEFT JOIN projects_votes ON fk_project_id = project_id

    LEFT JOIN users ON projects.fk_usr_id = usr_id
    LEFT JOIN projects_maps ON projects_maps.fk_project_id = projects.project_id
    LEFT JOIN photos ON photos.fk_project_id = projects.project_id

    GROUP BY project_id ORDER BY RAND()
";
</code>```

Title: Using count in in query with left join

Body:
I am currently trying to count how many dislikes and likes users have given to an image on my website, underneath you will see the database setup I did for exactly that. Vote_type keeps the like and dislike information where 1 is equal to a like, 0 is equal to a dislike.

this table is called projects
Project table

This table is called projects_votes

Now I want to include that when I make a query to drag information from my database for a blog post. This is currently the query I am making to get the necessary information to display a list of blogs on the frontpage. Here I am getting the uploader, project ID for links and so on.

    $query = "
SELECT * FROM projects
LEFT JOIN users
ON fk_usr_id = usr_id
LEFT JOIN projects_maps
ON fk_project_id = project_id
ORDER BY RAND()
";

So what I have a hard time understanding is how to count my Likes and Dislikes on a specific blog, so I can display this information on my website.

Body:
I solved my problem by changing my query to this statement here.

$query = "
    SELECT project_id, usr_publicname, project_name, photofile_name, map_version, usr_publicname, map_date, project_id AS project, (SELECT COUNT(*) FROM projects_votes WHERE vote_type = 1) AS likes,
    (SELECT COUNT(*) FROM projects_votes WHERE vote_type = 0) AS dislikes FROM projects

    LEFT JOIN projects_votes ON fk_project_id = project_id

    LEFT JOIN users ON projects.fk_usr_id = usr_id
    LEFT JOIN projects_maps ON projects_maps.fk_project_id = projects.project_id
    LEFT JOIN photos ON photos.fk_project_id = projects.project_id

    GROUP BY project_id ORDER BY RAND()
";


问:
Best way to save huge text in android
So I was in need of a container to save a lot of dialogue for my apps(branching dialogue), I was thinking about using string value XML but I'm still not quite sure since I have a lot of text and need some kind of tag/attribute to do the branching,
can I have another value XML that only contain the dialogue text? or should I use SQLite database?
or are there any method best used for my case that I could learn?

Newbie here would appreciate any suggestions. Thanks in advance

答:
Messaging apps are mostly using sqlite databases.
Simply saving message with id and parent id is sufficient to restore branching dialogue.</p>

Title: Best way to save huge text in android


问:
Comparing timestamp with date variable (MySQL and PHP)
Any help is highly appreciated.

Say I have a MySQL database with a timestamp column with the value "1305590400", how can I compare that with a PHP variable of say "2011-05-17"? I want to completely ignore the time part and only compare the date.

At the moment I am trying to get it working with the following but it returns no results:

```<code>WHERE  FROM_UNIXTIME('timestamp_column','%Y-%m-%d') = '" . $date. "'
</code>```

答:
You don't get results that probably $date has some time offset and is not equal to 00:00:00 in your timezone.

```<code>WHERE timestamp_column BETWEEN '" . strtotime($date) . "' AND '" . strtotime($date, '+1 day') . "'
</code>```

or to be more precise:

```<code>    WHERE timestamp_column >= '" . strtotime($date) . "'
      AND timestamp_column < '" . strtotime($date, '+1 day') . "'
</code>```

Body:
Any help is highly appreciated.

Say I have a MySQL database with a timestamp column with the value "1305590400", how can I compare that with a PHP variable of say "2011-05-17"? I want to completely ignore the time part and only compare the date.

At the moment I am trying to get it working with the following but it returns no results:

WHERE  FROM_UNIXTIME('timestamp_column','%Y-%m-%d') = '" . $date. "'

Body:
You don't get results that probably $date has some time offset and is not equal to 00:00:00 in your timezone.

WHERE timestamp_column BETWEEN '" . strtotime($date) . "' AND '" . strtotime($date, '+1 day') . "'

or to be more precise:

    WHERE timestamp_column >= '" . strtotime($date) . "'
      AND timestamp_column < '" . strtotime($date, '+1 day') . "'


问:
Why am I getting a an error when creating a generated column in PostgreSQL?
```<code>CREATE TABLE my_app.person
(
    person_id smallserial NOT NULL,
    first_name character varying(50),
    last_name character varying(50),
    full_name character varying(100) generated always as (concat(first_name, ' ', last_name)) STORED,
    birth_date date,
    created_timestamp timestamp default current_timestamp,
    PRIMARY KEY (person_id)
);
</code>```

Error: generation expression is not immutable

The goal is to populate the first name and last into the full name column.

答:
This works with the || operator:

```<code>CREATE TABLE person (
    person_id smallserial NOT NULL,
    first_name character varying(50),
    last_name character varying(50),
    full_name character varying(100) generated always as (first_name || ' ' || last_name) STORED,
    birth_date date,
    created_timestamp timestamp default current_timestamp,
    PRIMARY KEY (person_id)
);
</code>```

I am not sure of the technical reasons why concat() is considered mutable, but || is not.

If you want to handle NULL values in the columns, then it is a little more complicated.  I might recommend:

```<code>trim(both ' ' from
     (' ' || coalesce(first_name, '') || ' ' || coalesce(last_name, '')
     )
    )
</code>```

Of course, this isn't exactly the same as your expression, because it removes spaces from the beginning and end of the names.

Body:
CREATE TABLE my_app.person
(
    person_id smallserial NOT NULL,
    first_name character varying(50),
    last_name character varying(50),
    full_name character varying(100) generated always as (concat(first_name, ' ', last_name)) STORED,
    birth_date date,
    created_timestamp timestamp default current_timestamp,
    PRIMARY KEY (person_id)
);

Error: generation expression is not immutable

The goal is to populate the first name and last into the full name column.

Body:
This works with the || operator:

CREATE TABLE person (
    person_id smallserial NOT NULL,
    first_name character varying(50),
    last_name character varying(50),
    full_name character varying(100) generated always as (first_name || ' ' || last_name) STORED,
    birth_date date,
    created_timestamp timestamp default current_timestamp,
    PRIMARY KEY (person_id)
);

I am not sure of the technical reasons why concat() is considered mutable, but || is not.

If you want to handle NULL values in the columns, then it is a little more complicated.  I might recommend:

trim(both ' ' from
     (' ' || coalesce(first_name, '') || ' ' || coalesce(last_name, '')
     )
    )

Of course, this isn't exactly the same as your expression, because it removes spaces from the beginning and end of the names.


问:
C++ Code Translation with Eigen Matrix Library
I have the following code I am translating to C# from C++ which is using Eigen.

```<code>template <typename PointT> inline unsigned int
pcl::SamplingSurfaceNormal<PointT>::computeMeanAndCovarianceMatrix (const pcl::PointCloud<PointT> &cloud,
                                                                    Eigen::Matrix3f &covariance_matrix,
                                                                    Eigen::Vector4f &centroid)
{
    // create the buffer on the stack which is much faster than using cloud.points[indices[i]] and centroid as a buffer
    Eigen::Matrix<float, 1, 9, Eigen::RowMajor> accu = Eigen::Matrix<float, 1, 9, Eigen::RowMajor>::Zero ();
    std::size_t point_count = 0;
    for (std::size_t i = 0; i < cloud.points.size (); i++)
    {
        if (!isFinite (cloud[i]))
        {
          continue;
        }

        ++point_count;
        accu [0] += cloud[i].x * cloud[i].x;
        accu [1] += cloud[i].x * cloud[i].y;
        accu [2] += cloud[i].x * cloud[i].z;
        accu [3] += cloud[i].y * cloud[i].y; // 4
        accu [4] += cloud[i].y * cloud[i].z; // 5
        accu [5] += cloud[i].z * cloud[i].z; // 8
        accu [6] += cloud[i].x;
        accu [7] += cloud[i].y;
        accu [8] += cloud[i].z;
    }

    accu /= static_cast<float> (point_count);
    centroid[0] = accu[6]; centroid[1] = accu[7]; centroid[2] = accu[8];
    centroid[3] = 0;
    covariance_matrix.coeffRef (0) = accu [0] - accu [6] * accu [6];
    covariance_matrix.coeffRef (1) = accu [1] - accu [6] * accu [7];
    covariance_matrix.coeffRef (2) = accu [2] - accu [6] * accu [8];
    covariance_matrix.coeffRef (4) = accu [3] - accu [7] * accu [7];
    covariance_matrix.coeffRef (5) = accu [4] - accu [7] * accu [8];
    covariance_matrix.coeffRef (8) = accu [5] - accu [8] * accu [8];
    covariance_matrix.coeffRef (3) = covariance_matrix.coeff (1);
    covariance_matrix.coeffRef (6) = covariance_matrix.coeff (2);
    covariance_matrix.coeffRef (7) = covariance_matrix.coeff (5);

    return (static_cast<unsigned int> (point_count));
}
</code>```

In Eigens documentation, I can find NO WHERE what it means to call someMatix3f.coeffRef(x) or someMatrix3f.coeff(x) on a 2D matrix. What do these operators do?

Note, I have seen the documentation (https://eigen.tuxfamily.org/dox/classEigen_1_1PlainObjectBase.html#a72e84dc1bb573ad8ecc9109fbbc1b63b) and even with my PhD in mathematics, it means nothing to me.

I have attempted the translation using MathNET.Numerics and this method is

```<code>private int ComputeMeanAndCovarianceMatrix(
    PointCloud cloud,
    Matrix<float> covariance_matrix,
    MathNet.Numerics.LinearAlgebra.Vector<float> centroid)
{
    int point_count = 0;
    Matrix<float> accu = Matrix<float>.Build.DenseOfRowMajor(1, 9, Enumerable.Repeat(0.0f, 9));

    for (int i = 0; i < cloud.Vertices.Length; ++i)
    {
        //if (!isFinite(cloud.Vertices[i].Point.))
        //{
        //  continue;
        //}

        ++point_count;
        accu[0, 0] += cloud.Vertices[i].Point.X * cloud.Vertices[i].Point.X;
        accu[0, 1] += cloud.Vertices[i].Point.X * cloud.Vertices[i].Point.Y;
        accu[0, 2] += cloud.Vertices[i].Point.X * cloud.Vertices[i].Point.Z;
        accu[0, 3] += cloud.Vertices[i].Point.Y * cloud.Vertices[i].Point.Y; // 4
        accu[0, 4] += cloud.Vertices[i].Point.Y * cloud.Vertices[i].Point.Z; // 5
        accu[0, 5] += cloud.Vertices[i].Point.Z * cloud.Vertices[i].Point.Z; // 8
        accu[0, 6] += cloud.Vertices[i].Point.X;
        accu[0, 7] += cloud.Vertices[i].Point.Y;
        accu[0, 8] += cloud.Vertices[i].Point.Z;
    }
    accu /= point_count;

    centroid[0] = accu[0, 6];
    centroid[1] = accu[0, 7];
    centroid[2] = accu[0, 8];
    centroid[3] = 0;

    covariance_matrix[0, 0] = accu[0, 0] - accu[0, 6] * accu[0, 6];
    covariance_matrix[0, 1] = accu[0, 1] - accu[0, 6] * accu[0, 7];
    covariance_matrix[0, 2] = accu[0, 2] - accu[0, 6] * accu[0, 8];
    covariance_matrix[1, 1] = accu[0, 3] - accu[0, 7] * accu[0, 7];
    covariance_matrix[1, 2] = accu[0, 4] - accu[0, 7] * accu[0, 8];
    covariance_matrix[2, 2] = accu[0, 5] - accu[0, 8] * accu[0, 8];
    covariance_matrix[1, 0] = covariance_matrix[0, 1];
    covariance_matrix[2, 0] = covariance_matrix[0, 2];
    covariance_matrix[2, 1] = covariance_matrix[1, 2];

    return point_count;
}
</code>```

Look right?

答:
coeffRef just provides access to the underlying data array. Therefore, your translation to covariance_matrix[i, j] should be equivalent. Note that the expression covariance_matrix.coeffRef(k) just gives the kth element in the data array, irrelevant of storage order. And yes, it would have made more sense for the original code to use coeffRef(i,j), IMO.

The reason this would be there (I'm guessing here. ggael and chtz will probably be able to confirm/refute) is that is that Eigen uses a lot of expression templates to determine when and how to evaluate parts of expressions. Some are dependent on storage order of matrices, some aren't. In cases where it's not dependent on storage order (e.g. scalar * matrix) being able to "short circuit" the expression reduces the amount of steps the compiler has to go through in order to decide how to evaluate a given expression can reduce compile times. If we explicitly state coeffRef, then we tell the compiler that we're talking about a concrete object with storage, and not an expression.

Body:
I have the following code I am translating to C# from C++ which is using Eigen.

template <typename PointT> inline unsigned int
pcl::SamplingSurfaceNormal<PointT>::computeMeanAndCovarianceMatrix (const pcl::PointCloud<PointT> &cloud,
                                                                    Eigen::Matrix3f &covariance_matrix,
                                                                    Eigen::Vector4f &centroid)
{
    // create the buffer on the stack which is much faster than using cloud.points[indices[i]] and centroid as a buffer
    Eigen::Matrix<float, 1, 9, Eigen::RowMajor> accu = Eigen::Matrix<float, 1, 9, Eigen::RowMajor>::Zero ();
    std::size_t point_count = 0;
    for (std::size_t i = 0; i < cloud.points.size (); i++)
    {
        if (!isFinite (cloud[i]))
        {
          continue;
        }

        ++point_count;
        accu [0] += cloud[i].x * cloud[i].x;
        accu [1] += cloud[i].x * cloud[i].y;
        accu [2] += cloud[i].x * cloud[i].z;
        accu [3] += cloud[i].y * cloud[i].y; // 4
        accu [4] += cloud[i].y * cloud[i].z; // 5
        accu [5] += cloud[i].z * cloud[i].z; // 8
        accu [6] += cloud[i].x;
        accu [7] += cloud[i].y;
        accu [8] += cloud[i].z;
    }

    accu /= static_cast<float> (point_count);
    centroid[0] = accu[6]; centroid[1] = accu[7]; centroid[2] = accu[8];
    centroid[3] = 0;
    covariance_matrix.coeffRef (0) = accu [0] - accu [6] * accu [6];
    covariance_matrix.coeffRef (1) = accu [1] - accu [6] * accu [7];
    covariance_matrix.coeffRef (2) = accu [2] - accu [6] * accu [8];
    covariance_matrix.coeffRef (4) = accu [3] - accu [7] * accu [7];
    covariance_matrix.coeffRef (5) = accu [4] - accu [7] * accu [8];
    covariance_matrix.coeffRef (8) = accu [5] - accu [8] * accu [8];
    covariance_matrix.coeffRef (3) = covariance_matrix.coeff (1);
    covariance_matrix.coeffRef (6) = covariance_matrix.coeff (2);
    covariance_matrix.coeffRef (7) = covariance_matrix.coeff (5);

    return (static_cast<unsigned int> (point_count));
}

In Eigens documentation, I can find NO WHERE what it means to call someMatix3f.coeffRef(x) or someMatrix3f.coeff(x) on a 2D matrix. What do these operators do?

Note, I have seen the documentation (https://eigen.tuxfamily.org/dox/classEigen_1_1PlainObjectBase.html#a72e84dc1bb573ad8ecc9109fbbc1b63b) and even with my PhD in mathematics, it means nothing to me.

I have attempted the translation using MathNET.Numerics and this method is

private int ComputeMeanAndCovarianceMatrix(
    PointCloud cloud,
    Matrix<float> covariance_matrix,
    MathNet.Numerics.LinearAlgebra.Vector<float> centroid)
{
    int point_count = 0;
    Matrix<float> accu = Matrix<float>.Build.DenseOfRowMajor(1, 9, Enumerable.Repeat(0.0f, 9));

    for (int i = 0; i < cloud.Vertices.Length; ++i)
    {
        //if (!isFinite(cloud.Vertices[i].Point.))
        //{
        //  continue;
        //}

        ++point_count;
        accu[0, 0] += cloud.Vertices[i].Point.X * cloud.Vertices[i].Point.X;
        accu[0, 1] += cloud.Vertices[i].Point.X * cloud.Vertices[i].Point.Y;
        accu[0, 2] += cloud.Vertices[i].Point.X * cloud.Vertices[i].Point.Z;
        accu[0, 3] += cloud.Vertices[i].Point.Y * cloud.Vertices[i].Point.Y; // 4
        accu[0, 4] += cloud.Vertices[i].Point.Y * cloud.Vertices[i].Point.Z; // 5
        accu[0, 5] += cloud.Vertices[i].Point.Z * cloud.Vertices[i].Point.Z; // 8
        accu[0, 6] += cloud.Vertices[i].Point.X;
        accu[0, 7] += cloud.Vertices[i].Point.Y;
        accu[0, 8] += cloud.Vertices[i].Point.Z;
    }
    accu /= point_count;

    centroid[0] = accu[0, 6];
    centroid[1] = accu[0, 7];
    centroid[2] = accu[0, 8];
    centroid[3] = 0;

    covariance_matrix[0, 0] = accu[0, 0] - accu[0, 6] * accu[0, 6];
    covariance_matrix[0, 1] = accu[0, 1] - accu[0, 6] * accu[0, 7];
    covariance_matrix[0, 2] = accu[0, 2] - accu[0, 6] * accu[0, 8];
    covariance_matrix[1, 1] = accu[0, 3] - accu[0, 7] * accu[0, 7];
    covariance_matrix[1, 2] = accu[0, 4] - accu[0, 7] * accu[0, 8];
    covariance_matrix[2, 2] = accu[0, 5] - accu[0, 8] * accu[0, 8];
    covariance_matrix[1, 0] = covariance_matrix[0, 1];
    covariance_matrix[2, 0] = covariance_matrix[0, 2];
    covariance_matrix[2, 1] = covariance_matrix[1, 2];

    return point_count;
}

Look right?


问:
Is the cacerts file missing in ubuntu 15.10 and openjdk-8-jdk?
I just installed Ubuntu 15.10 and their openjdk-8-jdk (by apt-get).

Now I am missing the cacerts file.

There is a link at the usual location:

```<code>ls -l /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/security/cacerts
lrwxrwxrwx 1 root root 27 Oct 22 01:47 /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/security/cacerts -> /etc/ssl/certs/java/cacerts
</code>```

but nothing at /etc/ssl/certs/java/cacerts:

```<code>stat /etc/ssl/certs/java/cacerts
stat: cannot stat ‘/etc/ssl/certs/java/cacerts’: No such file or directory
</code>```

答:
Just to add an error here that Gergely answer solved, if you trying to call external apis with ssl and got this error:

```<code>java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
javax.net.ssl.SSLException: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:208)
    at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1946)
    at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1903)
</code>```

This solved

```<code>$ sudo dpkg --purge --force-depends ca-certificates-java
$ sudo apt-get install ca-certificates-java
</code>```

Body:
I just installed Ubuntu 15.10 and their openjdk-8-jdk (by apt-get).

Now I am missing the cacerts file.

There is a link at the usual location:

ls -l /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/security/cacerts
lrwxrwxrwx 1 root root 27 Oct 22 01:47 /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/security/cacerts -> /etc/ssl/certs/java/cacerts

but nothing at /etc/ssl/certs/java/cacerts:

stat /etc/ssl/certs/java/cacerts
stat: cannot stat ‘/etc/ssl/certs/java/cacerts’: No such file or directory

Body:
Just to add an error here that Gergely answer solved, if you trying to call external apis with ssl and got this error:

java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
javax.net.ssl.SSLException: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:208)
    at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1946)
    at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1903)

This solved

$ sudo dpkg --purge --force-depends ca-certificates-java
$ sudo apt-get install ca-certificates-java


答:
if the text is dynamic and will change by time you should consider receiving it from API

if it's static and won't change you could store it in the string xml file
you can''t store it in the local sql lite cause all data will be lost if the user clear the cache from settings

Title: Best way to save huge text in android

Body:
So I was in need of a container to save a lot of dialogue for my apps(branching dialogue), I was thinking about using string value XML but I'm still not quite sure since I have a lot of text and need some kind of tag/attribute to do the branching,
can I have another value XML that only contain the dialogue text? or should I use SQLite database?
or are there any method best used for my case that I could learn?

Newbie here would appreciate any suggestions. Thanks in advance


问:
ASP.NET Post to Facebook Wall
I'm trying to post to a facebook wall, without using an API such as the C# Facebook SDK. I'm correctly getting the access token and all that,  but I'm getting a 403 forbidden using the following code:

```<code>protected string postToWall()
{
    var accessToken = Session["_FB_ACCESS_TOKEN"];
    var graphId = Session["_FB_USER_GRAPH_ID"];

    var url = string.Format(
        "https://graph.facebook.com/{0}/feed",
        graphId
    );

    var req = WebRequest.Create(url);
    req.Method = "POST";
    req.ContentType = "application/x-www-form-urlencoded";

    string postData = string.Format(
        @"curl -F 'access_token={0}' -F 'message=This is a test...' https://graph.facebook.com/{1}/feed",
        accessToken,
        graphId
    );

    byte[] byteArray = Encoding.UTF8.GetBytes(postData);
    var stream = req.GetRequestStream();
    stream.Write(byteArray, 0, byteArray.Length);
    stream.Close();

    WebResponse response = req.GetResponse();
    Console.WriteLine(((HttpWebResponse)response).StatusDescription);
    stream = response.GetResponseStream();
    StreamReader reader = new StreamReader(stream);

    return reader.ReadToEnd();
}
</code>```

答: You shouldn't be posting curl -F... as the body of the post request. curl is a command line utility that allows you to interact with http. You want to post to an https://graph.facebook.com/{graphId}/feed?access_token={token} with the postData being "message=This is a test" replacing things in brackets with their values.

Title: ASP.NET Post to Facebook Wall

Body:
I'm trying to post to a facebook wall, without using an API such as the C# Facebook SDK. I'm correctly getting the access token and all that,  but I'm getting a 403 forbidden using the following code:

protected string postToWall()
{
    var accessToken = Session["_FB_ACCESS_TOKEN"];
    var graphId = Session["_FB_USER_GRAPH_ID"];

    var url = string.Format(
        "https://graph.facebook.com/{0}/feed",
        graphId
    );

    var req = WebRequest.Create(url);
    req.Method = "POST";
    req.ContentType = "application/x-www-form-urlencoded";

    string postData = string.Format(
        @"curl -F 'access_token={0}' -F 'message=This is a test...' https://graph.facebook.com/{1}/feed",
        accessToken,
        graphId
    );

    byte[] byteArray = Encoding.UTF8.GetBytes(postData);
    var stream = req.GetRequestStream();
    stream.Write(byteArray, 0, byteArray.Length);
    stream.Close();

    WebResponse response = req.GetResponse();
    Console.WriteLine(((HttpWebResponse)response).StatusDescription);
    stream = response.GetResponseStream();
    StreamReader reader = new StreamReader(stream);

    return reader.ReadToEnd();
}


问:
Calling a function out of several other functions?
So I have several functions written and I want to call one of them for use, my input code I used at the bottom asks for the function name but doesn't do much of anything with it. I'm a newbie so I might have missed something here, thanks.</p>

```<code>    def summ(num1 = 0, num2 = 0):
        num1 = int(input('första num: '))
        num2 = int(input('andra num: '))
        total = num1 + num2
        print(total)
        return num1 + num2

    def kvad(num = 0):
        num = int(input('kvadrerat nummer..'))
        power = num**2
        print(power)
        return power

    def udda(udd = 0):
        udd = int(input('jämnt eller udda?'))
        if udd % 2 != 0:
                print('Udda..')
        elif udd % 2:
            print('jämnt')
        return udda

    import operator
    def kalkylera(num1 = 0, num2 = 0):

        num1 = int(input('first num'))
        num2 = int(input('second num'))
        #operators
        subb = operator.sub(num1, num2)
        addd = operator.add(num1,num2)
        mull = operator.mul(num1,num2)
        divv = operator.truediv(num1,num2)

        oper8 = input('Vilket operation ska tillämpas?')
        if oper8 == '-':
            print(subb)
        elif oper8 == '+':
            print(addd)
        elif oper8 == '*':
            print(mull)
        elif oper8 == '/':
            print(divv)

call = input('vilket funktion?')

if call == summ:
    summ()
elif call == kvad:
    kvad()
elif call == udda:
    udda()
elif call == kalkylera:
    kalkylera()
</code>```

答:
below code should work as per your requirement

you need to use single or double quotes otherwise it will treat as variable

```<code>import operator

def summ(num1=0, num2=0):
    num1 = int(input('första num: '))
    num2 = int(input('andra num: '))
    total = num1 + num2
    print(total)
    return num1 + num2

def kvad(num=0):
    num = int(input('kvadrerat nummer..'))
    power = num**2
    print(power)
    return power

def udda(udd=0):
    udd = int(input('jämnt eller udda?'))
    if udd % 2 != 0:
        print('Udda..')
    elif udd % 2:
        print('jämnt')
    return udda

def kalkylera(num1=0, num2=0):

    num1 = int(input('first num'))
    num2 = int(input('second num'))
    # operators
    subb = operator.sub(num1, num2)
    addd = operator.add(num1, num2)
    mull = operator.mul(num1, num2)
    divv = operator.truediv(num1, num2)

    oper8 = input('Vilket operation ska tillämpas?')
    if oper8 == '-':
        print(subb)
    elif oper8 == '+':
        print(addd)
    elif oper8 == '*':
        print(mull)
    elif oper8 == '/':
        print(divv)

call = input('vilket funktion?')
if call == "summ":
    summ()
elif call == "kvad":
    kvad()
elif call == "udda":
    udda()
elif call == "kalkylera":
    kalkylera()
</code>```

Body:
So I have several functions written and I want to call one of them for use, my input code I used at the bottom asks for the function name but doesn't do much of anything with it. I'm a newbie so I might have missed something here, thanks.

    def summ(num1 = 0, num2 = 0):
        num1 = int(input('första num: '))
        num2 = int(input('andra num: '))
        total = num1 + num2
        print(total)
        return num1 + num2

    def kvad(num = 0):
        num = int(input('kvadrerat nummer..'))
        power = num**2
        print(power)
        return power

    def udda(udd = 0):
        udd = int(input('jämnt eller udda?'))
        if udd % 2 != 0:
                print('Udda..')
        elif udd % 2:
            print('jämnt')
        return udda

    import operator
    def kalkylera(num1 = 0, num2 = 0):

        num1 = int(input('first num'))
        num2 = int(input('second num'))
        #operators
        subb = operator.sub(num1, num2)
        addd = operator.add(num1,num2)
        mull = operator.mul(num1,num2)
        divv = operator.truediv(num1,num2)

        oper8 = input('Vilket operation ska tillämpas?')
        if oper8 == '-':
            print(subb)
        elif oper8 == '+':
            print(addd)
        elif oper8 == '*':
            print(mull)
        elif oper8 == '/':
            print(divv)

call = input('vilket funktion?')

if call == summ:
    summ()
elif call == kvad:
    kvad()
elif call == udda:
    udda()
elif call == kalkylera:
    kalkylera()

Body:
below code should work as per your requirement

you need to use single or double quotes otherwise it will treat as variable

import operator

def summ(num1=0, num2=0):
    num1 = int(input('första num: '))
    num2 = int(input('andra num: '))
    total = num1 + num2
    print(total)
    return num1 + num2

def kvad(num=0):
    num = int(input('kvadrerat nummer..'))
    power = num**2
    print(power)
    return power

def udda(udd=0):
    udd = int(input('jämnt eller udda?'))
    if udd % 2 != 0:
        print('Udda..')
    elif udd % 2:
        print('jämnt')
    return udda

def kalkylera(num1=0, num2=0):

    num1 = int(input('first num'))
    num2 = int(input('second num'))
    # operators
    subb = operator.sub(num1, num2)
    addd = operator.add(num1, num2)
    mull = operator.mul(num1, num2)
    divv = operator.truediv(num1, num2)

    oper8 = input('Vilket operation ska tillämpas?')
    if oper8 == '-':
        print(subb)
    elif oper8 == '+':
        print(addd)
    elif oper8 == '*':
        print(mull)
    elif oper8 == '/':
        print(divv)

call = input('vilket funktion?')
if call == "summ":
    summ()
elif call == "kvad":
    kvad()
elif call == "udda":
    udda()
elif call == "kalkylera":
    kalkylera()


问:
set height of imageview as matchparent programmatically
I need to set the height of an imageview as matchparent programatically.if it is a fixed height i know how to set.

but how can i set it as matchparent?

EDIT:

actually height of the parent layout is dynamic.so i need to make the height of the imageview as the height of parent.

答:
I had same issue. Resolved by firstly setting :

```<code>imageView.setMinHeight(0);
imageView.setMinimumHeight(0);
</code>```

And then :

```<code>imageView.getLayoutParams().height= ViewGroup.LayoutParams.MATCH_PARENT;
</code>```

setMinHeight is defined by ImageView, while setMinimumHeight is defined by View. According to the docs, the greater of the two values is used, so both must be set.

Body:
I had same issue. Resolved by firstly setting :

imageView.setMinHeight(0);
imageView.setMinimumHeight(0);

And then :

imageView.getLayoutParams().height= ViewGroup.LayoutParams.MATCH_PARENT;

setMinHeight is defined by ImageView, while setMinimumHeight is defined by View. According to the docs, the greater of the two values is used, so both must be set.


答:
The problem in that you should wrap the summ and kvad and other methods with double quotation marks.

```<code>call = input('vilket funktion?')

if call == "summ":
    summ()
elif call == "kvad":
    kvad()
elif call == "udda":
    udda()
elif call == "kalkylera":
    kalkylera()
</code>```

But it's a better solution to do that via eval:

```<code>eval(f"{input()}()")
</code>```

Title: Calling a function out of several other functions?

Body:
The problem in that you should wrap the summ and kvad and other methods with double quotation marks.

call = input('vilket funktion?')

if call == "summ":
    summ()
elif call == "kvad":
    kvad()
elif call == "udda":
    udda()
elif call == "kalkylera":
    kalkylera()

But it's a better solution to do that via eval:

eval(f"{input()}()")


问:
Simulating a select event with Enzyme
I am a little confused because this seems to be such a trivial and easy thing, yet there is hardly any proper documentation in Enzyme on how to do this.

I want to do one of the simplest things in the world. I just want to simulate a select event in a drop down select (HTML select/combo) by selecting an option called "dogs".

When I have this option selected would like to see that the option is "selected", and I would also like to see that the select value is set to "dogs".

What am I doing wrong here?

```<code>import React from 'react';
import {shallow, mount} from "enzyme"

    test(' change  ', () => {
        let Compoment =
            <select className="sel" name="selectComp" required="">
                <option value="empty">Please make your choice ...</option>
                <option value="cats">feline</option>
                <option value="dogs">canine</option>
            </select>;

        const wrapper = mount(Compoment);

        let sel = wrapper.find(".sel").at(0)
        sel.simulate('change', { target: { name: 'selectComp', value: "dogs" } });

        expect(wrapper.find(".sel").at(0).getElement().value).toBe("dogs")
        expect(wrapper.find(".sel").at(0).find("option").at(2).props().selected).toBe(true)
    })
</code>```

答:
React syncs prop=>DOM property only one way.

If you set selected prop on <option> element React would write it into DOM selected property(but you actually don't use selected prop at all).

You browser(or JSDOM in case of Jest tests) also changes selected property for relevant <option> element upon user selection.

So that's why prop does not reflect change.

You can use getDOMNode to access underlying DOM node:

```<code>expect(wrapper.find(".sel").at(0).find("option").at(2).getDOMNode().selected).toBe(true)
</code>```

but know what? you don't need that. This would just test browser highlights right option upon user selection. It's just a wasted time to check if browser and/or React do their job responsibly.

Title: Simulating a select event with Enzyme

Body:
I am a little confused because this seems to be such a trivial and easy thing, yet there is hardly any proper documentation in Enzyme on how to do this.

I want to do one of the simplest things in the world. I just want to simulate a select event in a drop down select (HTML select/combo) by selecting an option called "dogs".

When I have this option selected would like to see that the option is "selected", and I would also like to see that the select value is set to "dogs".

What am I doing wrong here?

import React from 'react';
import {shallow, mount} from "enzyme"

    test(' change  ', () => {
        let Compoment =
            <select className="sel" name="selectComp" required="">
                <option value="empty">Please make your choice ...</option>
                <option value="cats">feline</option>
                <option value="dogs">canine</option>
            </select>;

        const wrapper = mount(Compoment);

        let sel = wrapper.find(".sel").at(0)
        sel.simulate('change', { target: { name: 'selectComp', value: "dogs" } });

        expect(wrapper.find(".sel").at(0).getElement().value).toBe("dogs")
        expect(wrapper.find(".sel").at(0).find("option").at(2).props().selected).toBe(true)
    })

Body:
React syncs prop=>DOM property only one way.

If you set selected prop on <option> element React would write it into DOM selected property(but you actually don't use selected prop at all).

You browser(or JSDOM in case of Jest tests) also changes selected property for relevant <option> element upon user selection.

So that's why prop does not reflect change.

You can use getDOMNode to access underlying DOM node:

expect(wrapper.find(".sel").at(0).find("option").at(2).getDOMNode().selected).toBe(true)

but know what? you don't need that. This would just test browser highlights right option upon user selection. It's just a wasted time to check if browser and/or React do their job responsibly.


答:
Simply

```<code>SELECT [...] WHERE '$you_var' = date(`timestamp_column`);
</code>```

MySQL date() function

Title: Comparing timestamp with date variable (MySQL and PHP)

Body:
Simply

SELECT [...] WHERE '$you_var' = date(`timestamp_column`);

MySQL date() function


问:
Uncaught TypeError: Inventory.updateInventory is not a function
When i enter the site, the console swears at the error:

```<code>Uncaught TypeError: Inventory.updateInventory is not a function
    at HTMLDocument.<anonymous> (inventory.js:353)
    at j (jquery.min.js:2)
    at k (jquery.min.js:2)
</code>```

inventory.js:353: if (USER_ID !== 'null') Inventory.updateInventory();

My full JS code:

```<code>class Inventory {

    constructor() {
        this.selectedItem = 0;
        this.sumItems = 0;
    }

    noty(msg, status) {
        // noty({
        //     text: msg,
        //     type: status,
        //     layout: 'topRight',
        //     timeout: 4000,
        //     animation: {
        //         open: 'animated bounceInRight',
        //         close: 'animated bounceOutRight'
        //     }
        // }).show();
    }

    updateInventory() {
        $.ajax({
            url: '/api/inventory/update',
            type: 'POST'
        })
            .done( (data) => {
                if (data.success) {
                    const items = data.items;
                    const balance = data.balance;
                    let itemsCount = 0;

                    $('.userBalance').html(balance);
                    $('.invent-main').html('');
                    items.forEach( (item) => {
                        itemsCount++;
                        $('.invent-main').append('<div id="item" title="'+item.market_hash_name+'" data-id="'+item.assetid+'" data-price="'+item.price+'" onclick="Inventory.selectItemInventory('+item.assetid+')" class="rarity-'+item.type+'">\n' +
                            '                            <img src="https://steamcommunity-a.akamaihd.net/economy/image/'+item.classid+'//60fx60f" class="invent-item">\n' +
                            '                            <div class="item-bottom">\n' +
                            '                                <div class="item-bottom-l">\n' +
                            '                                    '+item.price+'\n' +
                            '                                </div>\n' +
                            '                                <div class="item-bottom-r">\n' +
                            '                                    <i class="fa fa-database" aria-hidden="true"></i>\n' +
                            '                                </div>\n' +
                            '                            </div>\n' +
                            '                        </div>');
                    });

                    $('#itemsInventory').html(itemsCount);
                    $('#sumInventoryAll').html(data.sum);
                }
            })
            .fail( (error) => {
                toastr.error('Error', 'error');
                console.log(error);
            })
    }

    selectItemInventory(id) {
        if (this.selectedItem >= 30) {
            toastr.error('Only 30 items', 'warning');
            return;
        }

        $('[data-id="'+id+'"]').attr('onclick', 'Inventory.unselectedItemInventory(' + id + ');');
        $('[data-id="'+id+'"]').attr('id', 'item-a');

        this.selectedItem++;
        this.sumItems += $('[data-id="'+id+'"]').data('price');

        $('#takeInventory').html(`${this.selectedItem}`);
        $('#sumInventory').html(`${this.sumItems}`);
    }

    unselectedItemInventory(id) {
        $('[data-id="'+id+'"]').attr('onclick', 'Inventory.selectItemInventory(' + id + ');');
        $('[data-id="'+id+'"]').attr('id', 'item');

        this.selectedItem--;
        this.sumItems -= $('[data-id="'+id+'"]').data('price');

        $('#takeInventory').html(`${this.selectedItem}`);
        $('#sumInventory').html(`${this.sumItems}`);
    }

    openModalTrade(trade) {
        $('#tradeModal').attr('href', `https://steamcommunity.com/tradeoffer/${trade}/`);
        $('#tradeoffer-modal').arcticmodal();
    }

    unselectAll() {
        this.selectedItem = 0;
        this.sumItems = 0;

        $('#takeInventory').html(`${this.selectedItem}`);
        $('#sumInventory').html(`${this.sumItems}`);
    }
}

/**
 * Variable
 */
let selectedItems = 0;
let sumItems = 0;

/**
 * Select ITEM Inventory-Steam
 */
const selectItem = (id) => {
    if (selectedItems >= 30) {
        toastr.error('Only 30 items', 'warning');
        return;
    }
    $('[data-id="'+id+'"]').attr('onclick', 'unselectedItem(' + id + ');');
    $('[data-id="'+id+'"]').attr('id', 'item1-a');
    selectedItems++;
    sumItems += $('[data-id="'+id+'"]').data('price');

    $('#total-count').html(selectedItems);
    $('#total-price').html(sumItems);
};

/**
 * Unselected ITEM Inventory-Steam
 */
const unselectedItem = (id) => {
    $('[data-id="'+id+'"]').attr('onclick', 'selectItem(' + id + ');');
    $('[data-id="'+id+'"]').attr('id', 'item1');
    selectedItems--;
    sumItems -= $('[data-id="'+id+'"]').data('price');

    $('#total-count').html(selectedItems);
    $('#total-price').html(sumItems);
};

/**
 * Deposit Inventory Steam
 */
const AddItemsInInventory = () => {
    let items = [];
    $('[id="item1-a"]').each( (item, i, arr) => {
        items.push($(i).data('id'));
    });
    $.ajax({
        url: '/api/inventory/trade',
        type: 'POST',
        data: {items: items}
    })
        .done( (data) => {
            return toastr[data.status](data.msg);
        })
        .fail( (error) => {
            toastr.error('Uncknown error', 'error');
            console.log(error);
        })
};

$(document).ready(() => {

    const socket = io.connect(':8080', {secure: true});

    /**
     * Modal Inventory
     */
    $('.buttons-invent-in-2').click( () => {
        $('#loadinventorysteam').html('');
        $('#inventory');
        selectedItems = 0;
        sumItems = 0;
        $.ajax({
            url: '/api/inventory/load',
            type: 'POST'
        })
            .done( (data) => {
                if (!data.success) return Inventory.noty(data.msg, 'warning');
                if (data.items.length == 0) return toastr.error('Empty inventory', 'warning');
                LoadSteamInventory(data.items);
            })
            .fail( (error) => {
                toastr.error('Can't received inventory', 'error');
                console.log(error);
            })
    });

    /**
     * Withdraw
     */
    $('.buttons-invent-in-4').click( () => {
        let items = [];
        $('[id="item-a"]').each( (item, i, arr) => {
            items.push($(i).data('id'));
        });

        if (items.length == 0) {
            toastr.error('Choose items!', 'warning');
            return;
        }

        $.ajax({
            url: '/api/inventory/withdraw',
            type: 'POST',
            data: {items: items}
        })
            .done( (data) => {
                if (data.success) {
                    $('[id="item-a"]').each( (item, i, arr) => {
                        $(i).remove();
                    });
                    Inventory.unselectAll();
                }
                return toastr[data.status](data.msg);
            })
            .fail( (error) => {
                toastr.error('Error', 'error');
                console.log(error);
            })
    });

    /**
     * Send friend
     */
    $('.buttons-invent-in-5').click( () => {
        const idUser = prompt('Write ID');
        if (idUser) {
            let items = [];
            $('[id="item-a"]').each((item, i, arr) => {
                items.push($(i).data('id'));
            });

            if (items.length == 0) {
                toastr.error('Choose items!', 'warning');
                return;
            }

            $.ajax({
                url: '/api/inventory/sendUser',
                type: 'POST',
                data: {items: items, user: idUser}
            })
                .done((data) => {
                    if (data.success) {
                        $('[id="item-a"]').each((item, i, arr) => {
                            $(i).remove();
                        });
                        Game.unselectAll();
                    }
                    return toastr[data.status](data.msg);
                })
                .fail((error) => {
                    toastr.error('Error', 'error');
                    console.log(error);
                })
        }
    });

    /**
     * Sell items
     */
    $('.buttons-invent-in-3').click( () => {
        if (confirm('You want sell?')) {
            let items = [];
            $('[id="item-a"]').each((item, i, arr) => {
                items.push($(i).data('id'));
            });

            if (items.length == 0) {
                toastr.error('Choose items!', 'warning');
                return;
            }

            $.ajax({
                url: '/api/inventory/sell',
                type: 'POST',
                data: {items: items}
            })
                .done((data) => {
                    if (data.success) {
                        $('[id="item-a"]').each((item, i, arr) => {
                            $(i).remove();
                        });
                        Inventory.unselectAll();
                        Inventory.updateInventory();
                        $('.userBalance').html(data.balance);
                    }
                    return toastr[data.status](data.msg);
                })
                .fail((error) => {
                    toastr.error('Error', 'error');
                    console.log(error);
                })
        }
    });
    /**
     * New Bet
     */
    $('.add-items').click( () => {
        let items = [];
        $('[id="item-a"]').each( (item, i, arr) => {
            items.push($(i).data('id'));
        });

        if (items.length == 0) {
            toastr.error('Choose items!', 'warning');
            return;
        }

        $.ajax({
            url: '/api/game/newBet',
            type: 'POST',
            data: {items: items}
        })
            .done( (data) => {
                if (data.success) {
                    $('[id="item-a"]').each( (item, i, arr) => {
                        $(i).remove();
                    });
                    Inventory.unselectAll();
                }
                return toastr[data.status](data.msg);
            })
            .fail( (error) => {
                toastr.error('Error', 'error');
                console.log(error);
            })
    });

    /**
     * Inventory
     */
    const LoadSteamInventory = (data) => {
        data.forEach( (item) => {
            $('#loadinventorysteam').append('<div id="item1" class="rarity-'+item.type+'" data-id="'+item.id+'" data-price="'+item.price+'" onclick="selectItem('+item.id+')"><img src="https://steamcommunity-a.akamaihd.net/economy/image/'+item.classid+'//60fx60f" class="invent-item"><div class="item-bottom"><div class="item-bottom-l">'+item.price+'</div><div class="item-bottom-r"><i class="fa fa-rub" aria-hidden="true"></i></div></div></div>');
        });
    };

    /**
     * Notify
     */
    socket.on('notify', (data) => {
        if (data.steamid === USER_ID) {
            toastr[data.status](data.msg);
            Inventory.updateInventory();

            if (data.trade) {
                Inventory.openModalTrade(data.trade);
            }
        }
    });

    /**
     * Update
     */
    if (USER_ID !== 'null') Inventory.updateInventory();
    socket.on('updateInventory', (data) => {
        if (data.steamid === USER_ID) {
            Inventory.updateInventory();
        }
    });
});
</code>```

What's wrong? How i can fix this error?

答:
Well.. the good news are that you are using JS ES6

If you intend to create multiple instances from your class (each has a different state) you should use:

```<code>const inv = new Inventory()

...

inv.updateInventory()
</code>```

If you intend to use the methods directly from your class (without multi-state management) you should define your methods as static

```<code>class Inventory {

    static updateInventory() {
    }

...

Inventory.updateInventory()
</code>```

Note that when using the static approach your constuctor will not be called

Body:
When i enter the site, the console swears at the error:

Uncaught TypeError: Inventory.updateInventory is not a function
    at HTMLDocument.<anonymous> (inventory.js:353)
    at j (jquery.min.js:2)
    at k (jquery.min.js:2)

inventory.js:353: if (USER_ID !== 'null') Inventory.updateInventory();

My full JS code:

class Inventory {

    constructor() {
        this.selectedItem = 0;
        this.sumItems = 0;
    }

    noty(msg, status) {
        // noty({
        //     text: msg,
        //     type: status,
        //     layout: 'topRight',
        //     timeout: 4000,
        //     animation: {
        //         open: 'animated bounceInRight',
        //         close: 'animated bounceOutRight'
        //     }
        // }).show();
    }

    updateInventory() {
        $.ajax({
            url: '/api/inventory/update',
            type: 'POST'
        })
            .done( (data) => {
                if (data.success) {
                    const items = data.items;
                    const balance = data.balance;
                    let itemsCount = 0;

                    $('.userBalance').html(balance);
                    $('.invent-main').html('');
                    items.forEach( (item) => {
                        itemsCount++;
                        $('.invent-main').append('
\n' +
                            '                            \n' +
                            '
\n' +
                            '
\n' +
                            '                                    '+item.price+'\n' +
                            '
\n' +
                            '
\n' +
                            '                                    \n' +
                            '
\n' +
                            '
\n' +
                            '
');
                    });

                    $('#itemsInventory').html(itemsCount);
                    $('#sumInventoryAll').html(data.sum);
                }
            })
            .fail( (error) => {
                toastr.error('Error', 'error');
                console.log(error);
            })
    }

    selectItemInventory(id) {
        if (this.selectedItem >= 30) {
            toastr.error('Only 30 items', 'warning');
            return;
        }

        $('[data-id="'+id+'"]').attr('onclick', 'Inventory.unselectedItemInventory(' + id + ');');
        $('[data-id="'+id+'"]').attr('id', 'item-a');

        this.selectedItem++;
        this.sumItems += $('[data-id="'+id+'"]').data('price');

        $('#takeInventory').html(`${this.selectedItem}`);
        $('#sumInventory').html(`${this.sumItems}`);
    }

    unselectedItemInventory(id) {
        $('[data-id="'+id+'"]').attr('onclick', 'Inventory.selectItemInventory(' + id + ');');
        $('[data-id="'+id+'"]').attr('id', 'item');

        this.selectedItem--;
        this.sumItems -= $('[data-id="'+id+'"]').data('price');

        $('#takeInventory').html(`${this.selectedItem}`);
        $('#sumInventory').html(`${this.sumItems}`);
    }

    openModalTrade(trade) {
        $('#tradeModal').attr('href', `https://steamcommunity.com/tradeoffer/${trade}/`);
        $('#tradeoffer-modal').arcticmodal();
    }

    unselectAll() {
        this.selectedItem = 0;
        this.sumItems = 0;

        $('#takeInventory').html(`${this.selectedItem}`);
        $('#sumInventory').html(`${this.sumItems}`);
    }
}

/**
 * Variable
 */
let selectedItems = 0;
let sumItems = 0;

/**
 * Select ITEM Inventory-Steam
 */
const selectItem = (id) => {
    if (selectedItems >= 30) {
        toastr.error('Only 30 items', 'warning');
        return;
    }
    $('[data-id="'+id+'"]').attr('onclick', 'unselectedItem(' + id + ');');
    $('[data-id="'+id+'"]').attr('id', 'item1-a');
    selectedItems++;
    sumItems += $('[data-id="'+id+'"]').data('price');

    $('#total-count').html(selectedItems);
    $('#total-price').html(sumItems);
};

/**
 * Unselected ITEM Inventory-Steam
 */
const unselectedItem = (id) => {
    $('[data-id="'+id+'"]').attr('onclick', 'selectItem(' + id + ');');
    $('[data-id="'+id+'"]').attr('id', 'item1');
    selectedItems--;
    sumItems -= $('[data-id="'+id+'"]').data('price');

    $('#total-count').html(selectedItems);
    $('#total-price').html(sumItems);
};

/**
 * Deposit Inventory Steam
 */
const AddItemsInInventory = () => {
    let items = [];
    $('[id="item1-a"]').each( (item, i, arr) => {
        items.push($(i).data('id'));
    });
    $.ajax({
        url: '/api/inventory/trade',
        type: 'POST',
        data: {items: items}
    })
        .done( (data) => {
            return toastr[data.status](data.msg);
        })
        .fail( (error) => {
            toastr.error('Uncknown error', 'error');
            console.log(error);
        })
};

$(document).ready(() => {

    const socket = io.connect(':8080', {secure: true});

    /**
     * Modal Inventory
     */
    $('.buttons-invent-in-2').click( () => {
        $('#loadinventorysteam').html('');
        $('#inventory');
        selectedItems = 0;
        sumItems = 0;
        $.ajax({
            url: '/api/inventory/load',
            type: 'POST'
        })
            .done( (data) => {
                if (!data.success) return Inventory.noty(data.msg, 'warning');
                if (data.items.length == 0) return toastr.error('Empty inventory', 'warning');
                LoadSteamInventory(data.items);
            })
            .fail( (error) => {
                toastr.error('Can't received inventory', 'error');
                console.log(error);
            })
    });

    /**
     * Withdraw
     */
    $('.buttons-invent-in-4').click( () => {
        let items = [];
        $('[id="item-a"]').each( (item, i, arr) => {
            items.push($(i).data('id'));
        });

        if (items.length == 0) {
            toastr.error('Choose items!', 'warning');
            return;
        }

        $.ajax({
            url: '/api/inventory/withdraw',
            type: 'POST',
            data: {items: items}
        })
            .done( (data) => {
                if (data.success) {
                    $('[id="item-a"]').each( (item, i, arr) => {
                        $(i).remove();
                    });
                    Inventory.unselectAll();
                }
                return toastr[data.status](data.msg);
            })
            .fail( (error) => {
                toastr.error('Error', 'error');
                console.log(error);
            })
    });

    /**
     * Send friend
     */
    $('.buttons-invent-in-5').click( () => {
        const idUser = prompt('Write ID');
        if (idUser) {
            let items = [];
            $('[id="item-a"]').each((item, i, arr) => {
                items.push($(i).data('id'));
            });

            if (items.length == 0) {
                toastr.error('Choose items!', 'warning');
                return;
            }

            $.ajax({
                url: '/api/inventory/sendUser',
                type: 'POST',
                data: {items: items, user: idUser}
            })
                .done((data) => {
                    if (data.success) {
                        $('[id="item-a"]').each((item, i, arr) => {
                            $(i).remove();
                        });
                        Game.unselectAll();
                    }
                    return toastr[data.status](data.msg);
                })
                .fail((error) => {
                    toastr.error('Error', 'error');
                    console.log(error);
                })
        }
    });

    /**
     * Sell items
     */
    $('.buttons-invent-in-3').click( () => {
        if (confirm('You want sell?')) {
            let items = [];
            $('[id="item-a"]').each((item, i, arr) => {
                items.push($(i).data('id'));
            });

            if (items.length == 0) {
                toastr.error('Choose items!', 'warning');
                return;
            }

            $.ajax({
                url: '/api/inventory/sell',
                type: 'POST',
                data: {items: items}
            })
                .done((data) => {
                    if (data.success) {
                        $('[id="item-a"]').each((item, i, arr) => {
                            $(i).remove();
                        });
                        Inventory.unselectAll();
                        Inventory.updateInventory();
                        $('.userBalance').html(data.balance);
                    }
                    return toastr[data.status](data.msg);
                })
                .fail((error) => {
                    toastr.error('Error', 'error');
                    console.log(error);
                })
        }
    });
    /**
     * New Bet
     */
    $('.add-items').click( () => {
        let items = [];
        $('[id="item-a"]').each( (item, i, arr) => {
            items.push($(i).data('id'));
        });

        if (items.length == 0) {
            toastr.error('Choose items!', 'warning');
            return;
        }

        $.ajax({
            url: '/api/game/newBet',
            type: 'POST',
            data: {items: items}
        })
            .done( (data) => {
                if (data.success) {
                    $('[id="item-a"]').each( (item, i, arr) => {
                        $(i).remove();
                    });
                    Inventory.unselectAll();
                }
                return toastr[data.status](data.msg);
            })
            .fail( (error) => {
                toastr.error('Error', 'error');
                console.log(error);
            })
    });

    /**
     * Inventory
     */
    const LoadSteamInventory = (data) => {
        data.forEach( (item) => {
            $('#loadinventorysteam').append('

'+item.price+'

');
        });
    };

    /**
     * Notify
     */
    socket.on('notify', (data) => {
        if (data.steamid === USER_ID) {
            toastr[data.status](data.msg);
            Inventory.updateInventory();

            if (data.trade) {
                Inventory.openModalTrade(data.trade);
            }
        }
    });

    /**
     * Update
     */
    if (USER_ID !== 'null') Inventory.updateInventory();
    socket.on('updateInventory', (data) => {
        if (data.steamid === USER_ID) {
            Inventory.updateInventory();
        }
    });
});

What's wrong? How i can fix this error?

Body:
Well.. the good news are that you are using JS ES6

If you intend to create multiple instances from your class (each has a different state) you should use:

const inv = new Inventory()

...

inv.updateInventory()

If you intend to use the methods directly from your class (without multi-state management) you should define your methods as static

class Inventory {

    static updateInventory() {
    }

...

Inventory.updateInventory()

Note that when using the static approach your constuctor will not be called


问:
How to change flutter app display name at runtime
How do I change flutter app name at runtime, I have seen this flutter plugin which changes app's icon at runtime. I would like to know if there is a way to do this for the app name as well, thanks.</p>

答:
If your app name is a variable which is accessed to be displayed, you can change it using setState like so

```<code>randomMethod() {
setState(() {
  myAppNameVariable = myNewNameString;
  //Do the same for the icon
  });
}
</code>```

setState will reload the entire structure of the app while keeping variables and currenSstate of the components, so the name displayed will be different.

Body:
If your app name is a variable which is accessed to be displayed, you can change it using setState like so

randomMethod() {
setState(() {
  myAppNameVariable = myNewNameString;
  //Do the same for the icon
  });
}

setState will reload the entire structure of the app while keeping variables and currenSstate of the components, so the name displayed will be different.