问:
Deploying a minimal flask app in docker - server connection issues
I have an app whose only dependency is flask, which runs fine outside docker and binds to the default port 5000. Here is the full source:

from flask import Flask

app = Flask(__name__)
app.debug = True

@app.route('/')
def main():
    return 'hi'

if __name__ == '__main__':
    app.run()
```
<p>The problem is that when I deploy this in docker, the server is running but is unreachable from outside the container.</p>
<p>Below is my <code>Dockerfile</code>. The image is ubuntu with flask installed. The tar just contains the <code>index.py</code> listed above;</p>
```# Dockerfile
FROM dreen/flask
MAINTAINER dreen
WORKDIR /srv

# Get source
RUN mkdir -p /srv
COPY perfektimprezy.tar.gz /srv/perfektimprezy.tar.gz
RUN tar x -f perfektimprezy.tar.gz
RUN rm perfektimprezy.tar.gz

# Run server
EXPOSE 5000
CMD ["python", "index.py"]
```
<p>Here are the steps I am doing to deploy</p>
<p><code>$> sudo docker build -t perfektimprezy .</code></p>
<p>As far as I know the above runs fine, the image has the contents of the tar in <code>/srv</code>. Now, let's start the server in a container:</p>
```$> sudo docker run -i -p 5000:5000 -d perfektimprezy
1c50b67d45b1a4feade72276394811c8399b1b95692e0914ee72b103ff54c769
```
<p>Is it actually running?</p>
```$> sudo docker ps
CONTAINER ID        IMAGE                   COMMAND             CREATED             STATUS              PORTS                    NAMES
1c50b67d45b1        perfektimprezy:latest   "python index.py"   5 seconds ago       Up 5 seconds        0.0.0.0:5000->5000/tcp   loving_wozniak
```
```$> sudo docker logs 1c50b67d45b1
    * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
    * Restarting with stat
```
<p>Yep, seems like the flask server is running. Here is where it gets weird. Lets make a request to the server:</p>
```$> curl 127.0.0.1:5000 -v
* Rebuilt URL to: 127.0.0.1:5000/
* Hostname was NOT found in DNS cache
*   Trying 127.0.0.1...
* Connected to 127.0.0.1 (127.0.0.1) port 5000 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.35.0
> Host: 127.0.0.1:5000
> Accept: */*
>
* Empty reply from server
* Connection #0 to host 127.0.0.1 left intact
curl: (52) Empty reply from server
```
<p>Empty reply... But is the process running?</p>
```$> sudo docker top 1c50b67d45b1
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                2084                812                 0                   10:26               ?                   00:00:00            python index.py
root                2117                2084                0                   10:26               ?                   00:00:00            /usr/bin/python index.py
```
<p>Now let's ssh into the server and check...</p>
```$> sudo docker exec -it 1c50b67d45b1 bash
root@1c50b67d45b1:/srv# netstat -an
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 127.0.0.1:5000          0.0.0.0:*               LISTEN
tcp        0      0 127.0.0.1:47677         127.0.0.1:5000          TIME_WAIT
Active UNIX domain sockets (servers and established)
Proto RefCnt Flags       Type       State         I-Node   Path
root@1c50b67d45b1:/srv# curl -I 127.0.0.1:5000
HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 5447
Server: Werkzeug/0.10.4 Python/2.7.6
Date: Tue, 19 May 2015 12:18:14 GMT
```

It's fine... But not from the outside.

What am I doing wrong?

答:
First of all in your python script you need to change code from

```<code>app.run()
</code>```

to

```<code>app.run(host="0.0.0.0")
</code>```

Second, In your docker file, last line should be like

```<code>CMD ["flask", "run", "-h", "0.0.0.0", "-p", "5000"]
</code>```

And on host machine if 0.0.0.0:5000 doesn't work then you should try with localhost:5000

Note - The CMD command has to be proper. Because CMD command provide defaults for executing container.

Body:
I have an app whose only dependency is flask, which runs fine outside docker and binds to the default port 5000. Here is the full source:

from flask import Flask

app = Flask(__name__)
app.debug = True

@app.route('/')
def main():
    return 'hi'

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

The problem is that when I deploy this in docker, the server is running but is unreachable from outside the container.

Below is my Dockerfile. The image is ubuntu with flask installed. The tar just contains the index.py listed above;

# Dockerfile
FROM dreen/flask
MAINTAINER dreen
WORKDIR /srv

# Get source
RUN mkdir -p /srv
COPY perfektimprezy.tar.gz /srv/perfektimprezy.tar.gz
RUN tar x -f perfektimprezy.tar.gz
RUN rm perfektimprezy.tar.gz

# Run server
EXPOSE 5000
CMD ["python", "index.py"]

Here are the steps I am doing to deploy

$> sudo docker build -t perfektimprezy .

As far as I know the above runs fine, the image has the contents of the tar in /srv. Now, let's start the server in a container:

$> sudo docker run -i -p 5000:5000 -d perfektimprezy
1c50b67d45b1a4feade72276394811c8399b1b95692e0914ee72b103ff54c769

Is it actually running?

$> sudo docker ps
CONTAINER ID        IMAGE                   COMMAND             CREATED             STATUS              PORTS                    NAMES
1c50b67d45b1        perfektimprezy:latest   "python index.py"   5 seconds ago       Up 5 seconds        0.0.0.0:5000->5000/tcp   loving_wozniak

$> sudo docker logs 1c50b67d45b1
    * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
    * Restarting with stat

Yep, seems like the flask server is running. Here is where it gets weird. Lets make a request to the server:

$> curl 127.0.0.1:5000 -v
* Rebuilt URL to: 127.0.0.1:5000/
* Hostname was NOT found in DNS cache
*   Trying 127.0.0.1...
* Connected to 127.0.0.1 (127.0.0.1) port 5000 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.35.0
> Host: 127.0.0.1:5000
> Accept: */*
>
* Empty reply from server
* Connection #0 to host 127.0.0.1 left intact
curl: (52) Empty reply from server

Empty reply... But is the process running?

$> sudo docker top 1c50b67d45b1
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                2084                812                 0                   10:26               ?                   00:00:00            python index.py
root                2117                2084                0                   10:26               ?                   00:00:00            /usr/bin/python index.py

Now let's ssh into the server and check...

$> sudo docker exec -it 1c50b67d45b1 bash
root@1c50b67d45b1:/srv# netstat -an
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 127.0.0.1:5000          0.0.0.0:*               LISTEN
tcp        0      0 127.0.0.1:47677         127.0.0.1:5000          TIME_WAIT
Active UNIX domain sockets (servers and established)
Proto RefCnt Flags       Type       State         I-Node   Path
root@1c50b67d45b1:/srv# curl -I 127.0.0.1:5000
HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 5447
Server: Werkzeug/0.10.4 Python/2.7.6
Date: Tue, 19 May 2015 12:18:14 GMT

It's fine... But not from the outside.

What am I doing wrong?

Body:
First of all in your python script you need to change code from

app.run()

to

app.run(host="0.0.0.0")

Second, In your docker file, last line should be like

CMD ["flask", "run", "-h", "0.0.0.0", "-p", "5000"]

And on host machine if 0.0.0.0:5000 doesn't work then you should try with localhost:5000

Note - The CMD command has to be proper. Because CMD command provide defaults for executing container.


来源: stackexchange

问:
C: how to convert foreach_point(t->board) to for loop?
I need to separate values with a comma in each case but the last.
Various posts suggest to use for instead of foreach,
but as this is a patch, and I don't use C, how can I convert
foreach_point(t->board)  to a for loop?

答:
I don't know what foreach_point does, but if I guessed correctly, I usually do something like:

```<code>printf("%d", t_board[0]);            /* print the 1st element */
for (k = 1; k < NUM_ELEMENTS; k++) { /* notice `k = 1`, not the usual `k = 0` */
    printf(", %d", t_board[k]);
}
puts("");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I don't know what foreach_point does, but if I guessed correctly, I usually do something like:

printf("%d", t_board[0]);            /* print the 1st element */
for (k = 1; k < NUM_ELEMENTS; k++) { /* notice `k = 1`, not the usual `k = 0` */
    printf(", %d", t_board[k]);
}
puts("");


问:
How to Convert DataRow to an Object
I created a DataRow on my project:

```<code>DataRow datarow;
</code>```

I want to convert this DataRow to any Type of Object.
How could I do it?

答:
With less complications ;), two steps will solve the task:
1. cast to dictionary (ToDictionary).
2. map dictionary to entity (MapToEntity).

```<code>    public static IDictionary<string, object> ToDictionary(
        this DataRow content
        )
    {
        var values = content.ItemArray;
        var columns = content
            .Table
            .Columns
            .Cast<DataColumn>()
            .Select(x => x.ColumnName);
        return values
            .Select((v, m) => new { v, m })
            .ToDictionary(
                x => columns.ElementAt(x.m)
                , x => (x.v == DBNull.Value ? null : x.v)
             );
    }
    public static T MapToEntity<T>(
        this IDictionary<string, object> source
        )
        where T : class, new()
    {
        // t - target
        T t_object = new T();
        Type t_type = t_object.GetType();

        foreach (var kvp in source)
        {
            PropertyInfo t_property = t_type.GetProperty(kvp.Key);
            if (t_property != null)
            {
                t_property.SetValue(t_object, kvp.Value);
            }
        }
        return t_object;
    }
</code>```

...and the usage would be:

```<code>DataRow dr = getSomeDataRow(someArgs);
ABC result = dr.ToDictionary()
  .MapToEntity<ABC>();
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to Convert DataRow to an Object

Body:
I created a DataRow on my project:

DataRow datarow;

I want to convert this DataRow to any Type of Object.
How could I do it?

Body:
With less complications ;), two steps will solve the task:
1. cast to dictionary (ToDictionary).
2. map dictionary to entity (MapToEntity).

    public static IDictionary<string, object> ToDictionary(
        this DataRow content
        )
    {
        var values = content.ItemArray;
        var columns = content
            .Table
            .Columns
            .Cast<DataColumn>()
            .Select(x => x.ColumnName);
        return values
            .Select((v, m) => new { v, m })
            .ToDictionary(
                x => columns.ElementAt(x.m)
                , x => (x.v == DBNull.Value ? null : x.v)
             );
    }
    public static T MapToEntity<T>(
        this IDictionary<string, object> source
        )
        where T : class, new()
    {
        // t - target
        T t_object = new T();
        Type t_type = t_object.GetType();

        foreach (var kvp in source)
        {
            PropertyInfo t_property = t_type.GetProperty(kvp.Key);
            if (t_property != null)
            {
                t_property.SetValue(t_object, kvp.Value);
            }
        }
        return t_object;
    }

...and the usage would be:

DataRow dr = getSomeDataRow(someArgs);
ABC result = dr.ToDictionary()
  .MapToEntity<ABC>();


问:
indexing names in a std::vector
I made a program that lets you enter your name and outputs it.
I can't find a way to index my names. For example, if you enter "John, Jason, Jam", you would get the names numbered like so: "1:John, 2:Jason, 3:Jam"</p>

```<code>int main()
{
    vector<string> names;

    names.push_back(read_string("Enter a name: "));
    names.push_back(read_string("Enter a name: "));
    names.push_back(read_string("Enter a name: "));

    for(int  i = 0; i < names.size(); i++)
    {
            write_line( names[i]);
    }

    int total;
    total = total_length(names);

    write("Total length: ");
    write_line(total);

    bool has_John;
    has_John = contains(names, "John");

    if ( has_John ) write_line("Contain's John");

    write_line(shortest_name(names));

    return 0;
}
</code>```

答:
I think you are looking for something like this: </p>

```<code> for(int  i = 0; i < names.size(); i++)
{
        write_line( (i+1) +names[i]);
}
</code>```

Title: indexing names in a std::vector

Body:
I made a program that lets you enter your name and outputs it.
I can't find a way to index my names. For example, if you enter "John, Jason, Jam", you would get the names numbered like so: "1:John, 2:Jason, 3:Jam"

int main()
{
    vector<string> names;

    names.push_back(read_string("Enter a name: "));
    names.push_back(read_string("Enter a name: "));
    names.push_back(read_string("Enter a name: "));

    for(int  i = 0; i < names.size(); i++)
    {
            write_line( names[i]);
    }

    int total;
    total = total_length(names);

    write("Total length: ");
    write_line(total);

    bool has_John;
    has_John = contains(names, "John");

    if ( has_John ) write_line("Contain's John");

    write_line(shortest_name(names));

    return 0;
}

Body:
I think you are looking for something like this:

 for(int  i = 0; i < names.size(); i++)
{
        write_line( (i+1) +names[i]);
}


问:
Passing data to another after receiving data from call back in react js
I am a beginner in react js so what I want to do it is :
I want to pass the quizData array to another component ,  data in quizData is set from a callback function which is submitForm function . But when I try to print the prop in another Component(QuizScreen)
it prints 1 as the value console .

Can anybody Please suggest . Am I doing something wrong with the design pattern ?

Thanks in Advance.

```<code>import React from 'react';
import logo from './logo.svg';
import './App.css';
import QuizForm from './QuizForm.js'
import QuizScreen from './QuizScreen';

class App extends React.Component{

state = {
isSubmitted : false,
 quizData : [],

}
submitForm = (data) =>{

  this.setState({isSubmitted : true,
            quizData : this.state.quizData.push(data)
  })
 console.log("Value of quizData is "+ JSON.stringify(this.state.quizData))
}

render() {
  return (
    <div className="App">
      <div className= "container">

    {(!this.state.isSubmitted) ? <QuizForm isFormSubmit= {this.submitForm} /> : <QuizScreen details={this.state.quizData}/>}

      </div>

    </div>
  );
}
}
export default App;

import React from 'react'

class QuizScreen extends React.Component {`enter code here`

constructor(props)
{
    super(props)

    console.log("Props is "+JSON.stringify(props.details))

}

render(){

    return(
        <div className= "App">
        </div>
    )
}
}
export default QuizScreen;
import React , {Component} from 'react'
import FileUpload from './FileUpload';
import QuizScreen from './QuizScreen.js'
import  './QuizForm.css'
import InputTextField from './InputTextField';
import fields from './Fields.js';

class QuizForm  extends Component {
    constructor(props) {
      super(props);
      this.state = {
        value: '',
        fileData : [],
        negativeMarking : 0,
        quizName  : '',
        category :'',
        weightage : 0,
        quizTime: '',
        isSubmitted: false
      };

      this.handleChange = this.handleChange.bind(this);
      this.handleSubmit = this.handleSubmit.bind(this);
    }

    myfile = (fileUploadData) =>{

      console.log("Hello from myfile"+JSON.stringify(fileUploadData));
      this.setState({fileData : fileUploadData})

   }

    handleChange(event) {

      console.log("My values are "+event.target.name)
      const value =  event.target.value;
      this.setState({[event.target.name] :value })
      }

    handleSubmit(event) {
      alert('QuizName is '+event.target.quizName.value)
      event.preventDefault();
      this.setState({isSubmitted : true})
      this.props.isFormSubmit(this.state)
    }

    render() {
      return (
        <div className="form-style-6">
          <h1>Create Quiz</h1>
        <form onSubmit={this.handleSubmit}>

          {fields.map(form =>{
        return(

            <InputTextField
            type={form.type}
            name={form.name}
            _handleChange={this.handleChange}
            placeholder= {form.placeholder}
            key={form.placeholder}
            />
              );

          } )}

           <FileUpload onFileUpload = {this.myfile}/>

          <input type="submit" value="Submit"/>
        </form>
        </div>

      );
    }
  }
  export default QuizForm;
</code>```

答:
You have to refer the current component scope by putting this keyword when you want to access props. Plus, print it on your console by calling it inside a componentDidMount().

```<code>import React from 'react';

class QuizScreen extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    console.log('Props is ' + JSON.stringify(this.props.details)); //<-- Here you have to put `this` keyword.
  }

  render() {
    return <div className="App"></div>;
  }
}

export default QuizScreen;

import React , {Component} from 'react'
import FileUpload from './FileUpload';
import QuizScreen from './QuizScreen.js'
import  './QuizForm.css'
import InputTextField from './InputTextField';
import fields from './Fields.js';

class QuizForm  extends Component {
    constructor(props) {
      super(props);
      this.state = {
        value: '',
        fileData : [],
        negativeMarking : 0,
        quizName  : '',
        category :'',
        weightage : 0,
        quizTime: '',
        isSubmitted: false
      };

      this.handleChange = this.handleChange.bind(this);
      this.handleSubmit = this.handleSubmit.bind(this);
    }

    myfile = (fileUploadData) =>{

      console.log("Hello from myfile"+JSON.stringify(fileUploadData));
      this.setState({fileData : fileUploadData})

   }

    handleChange(event) {

      console.log("My values are "+event.target.name)
      const value =  event.target.value;
      this.setState({[event.target.name] :value })
      }

    handleSubmit(event) {
      alert('QuizName is '+event.target.quizName.value)
      event.preventDefault();
      this.setState({isSubmitted : true})
      this.props.isFormSubmit(this.state)
    }

    render() {
      return (
        <div className="form-style-6">
          <h1>Create Quiz</h1>
        <form onSubmit={this.handleSubmit}>

          {fields.map(form =>{
        return(

            <InputTextField
            type={form.type}
            name={form.name}
            _handleChange={this.handleChange}
            placeholder= {form.placeholder}
            key={form.placeholder}
            />
              );

          } )}

           <FileUpload onFileUpload = {this.myfile}/>

          <input type="submit" value="Submit"/>
        </form>
        </div>

      );
    }
  }
  export default QuizForm;
</code>```

Body:
I am a beginner in react js so what I want to do it is :
I want to pass the quizData array to another component ,  data in quizData is set from a callback function which is submitForm function . But when I try to print the prop in another Component(QuizScreen)
it prints 1 as the value console .

Can anybody Please suggest . Am I doing something wrong with the design pattern ?

Thanks in Advance.

import React from 'react';
import logo from './logo.svg';
import './App.css';
import QuizForm from './QuizForm.js'
import QuizScreen from './QuizScreen';

class App extends React.Component{

state = {
isSubmitted : false,
 quizData : [],

}
submitForm = (data) =>{

  this.setState({isSubmitted : true,
            quizData : this.state.quizData.push(data)
  })
 console.log("Value of quizData is "+ JSON.stringify(this.state.quizData))
}

render() {
  return (

    {(!this.state.isSubmitted) ? <QuizForm isFormSubmit= {this.submitForm} /> : <QuizScreen details={this.state.quizData}/>}

  );
}
}
export default App;

import React from 'react'

class QuizScreen extends React.Component {`enter code here`

constructor(props)
{
    super(props)

    console.log("Props is "+JSON.stringify(props.details))

}

render(){

    return(

    )
}
}
export default QuizScreen;
import React , {Component} from 'react'
import FileUpload from './FileUpload';
import QuizScreen from './QuizScreen.js'
import  './QuizForm.css'
import InputTextField from './InputTextField';
import fields from './Fields.js';

class QuizForm  extends Component {
    constructor(props) {
      super(props);
      this.state = {
        value: '',
        fileData : [],
        negativeMarking : 0,
        quizName  : '',
        category :'',
        weightage : 0,
        quizTime: '',
        isSubmitted: false
      };

      this.handleChange = this.handleChange.bind(this);
      this.handleSubmit = this.handleSubmit.bind(this);
    }

    myfile = (fileUploadData) =>{

      console.log("Hello from myfile"+JSON.stringify(fileUploadData));
      this.setState({fileData : fileUploadData})

   }

    handleChange(event) {

      console.log("My values are "+event.target.name)
      const value =  event.target.value;
      this.setState({[event.target.name] :value })
      }

    handleSubmit(event) {
      alert('QuizName is '+event.target.quizName.value)
      event.preventDefault();
      this.setState({isSubmitted : true})
      this.props.isFormSubmit(this.state)
    }

    render() {
      return (

Create Quiz

        <form onSubmit={this.handleSubmit}>

          {fields.map(form =>{
        return(

            <InputTextField
            type={form.type}
            name={form.name}
            _handleChange={this.handleChange}
            placeholder= {form.placeholder}
            key={form.placeholder}
            />
              );

          } )}

           <FileUpload onFileUpload = {this.myfile}/>

          <input type="submit" value="Submit"/>
        </form>

      );
    }
  }
  export default QuizForm;

Body:
You have to refer the current component scope by putting this keyword when you want to access props. Plus, print it on your console by calling it inside a componentDidMount().

import React from 'react';

class QuizScreen extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    console.log('Props is ' + JSON.stringify(this.props.details)); //<-- Here you have to put `this` keyword.
  }

  render() {
    return <div className="App"></div>;
  }
}

export default QuizScreen;

import React , {Component} from 'react'
import FileUpload from './FileUpload';
import QuizScreen from './QuizScreen.js'
import  './QuizForm.css'
import InputTextField from './InputTextField';
import fields from './Fields.js';

class QuizForm  extends Component {
    constructor(props) {
      super(props);
      this.state = {
        value: '',
        fileData : [],
        negativeMarking : 0,
        quizName  : '',
        category :'',
        weightage : 0,
        quizTime: '',
        isSubmitted: false
      };

      this.handleChange = this.handleChange.bind(this);
      this.handleSubmit = this.handleSubmit.bind(this);
    }

    myfile = (fileUploadData) =>{

      console.log("Hello from myfile"+JSON.stringify(fileUploadData));
      this.setState({fileData : fileUploadData})

   }

    handleChange(event) {

      console.log("My values are "+event.target.name)
      const value =  event.target.value;
      this.setState({[event.target.name] :value })
      }

    handleSubmit(event) {
      alert('QuizName is '+event.target.quizName.value)
      event.preventDefault();
      this.setState({isSubmitted : true})
      this.props.isFormSubmit(this.state)
    }

    render() {
      return (
        <div className="form-style-6">
          <h1>Create Quiz</h1>
        <form onSubmit={this.handleSubmit}>

          {fields.map(form =>{
        return(

            <InputTextField
            type={form.type}
            name={form.name}
            _handleChange={this.handleChange}
            placeholder= {form.placeholder}
            key={form.placeholder}
            />
              );

          } )}

           <FileUpload onFileUpload = {this.myfile}/>

          <input type="submit" value="Submit"/>
        </form>
        </div>

      );
    }
  }
  export default QuizForm;


问:
RVM and Passenger: No such file to load - bundler
I've seen other similar errors, but none of the solutions have worked for me:

On Snow Leopard, I'm using RVM with project-based gemsets. I have both Rails 2 and Rails 3 apps. When I use bundler with Rails 2 or with Rails 3, I get:

```<code>no such file to load -- bundler
</code>```

In my Rails 2 apps that don't use bundler, I just get a message that Rails needs to be installed when it is.

My RVM install has a global gemset with REE version of Ruby.

```<code>$ rvm list

rvm rubies

=> ree-1.8.7-2011.03 [ x86_64 ]
   ruby-1.8.7-p174 [ x86_64 ]
   ruby-1.9.2-head [ x86_64 ]

$ rvm gemset list

gemsets for ree-1.8.7-2011.03 (found in /Users/dwayne/.rvm/gems/ree-1.8.7-2011.03)
   cm
   duke
=> global
</code>```

My global gems:

```<code>$ gem list

*** LOCAL GEMS ***

bundler (1.0.14)
daemon_controller (0.2.6)
fastthread (1.0.7)
passenger (3.0.7)
rack (1.3.0)
rake (0.9.0)
rdoc (3.6.1)
</code>```

Passenger lines in Apache config:

```<code>LoadModule passenger_module /Users/dwayne/.rvm/gems/ree-1.8.7-2011.03@global/gems/passenger-3.0.7/ext/apache2/mod_passenger.so
PassengerRoot /Users/dwayne/.rvm/gems/ree-1.8.7-2011.03@global/gems/passenger-3.0.7
PassengerRuby /Users/dwayne/.rvm/wrappers/ree-1.8.7-2011.03@global/ruby
</code>```

RubyGems environment for "duke" project:

```<code>- RUBYGEMS VERSION: 1.6.2
- RUBY VERSION: 1.8.7 (2011-02-18 patchlevel 334) [i686-darwin10.7.0]
- INSTALLATION DIRECTORY: /Users/dwayne/.rvm/gems/ree-1.8.7-2011.03@duke
- RUBY EXECUTABLE: /Users/dwayne/.rvm/rubies/ree-1.8.7-2011.03/bin/ruby
- EXECUTABLE DIRECTORY: /Users/dwayne/.rvm/gems/ree-1.8.7-2011.03@duke/bin
- RUBYGEMS PLATFORMS:
  - ruby
  - x86-darwin-10
- GEM PATHS:
   - /Users/dwayne/.rvm/gems/ree-1.8.7-2011.03@duke
   - /Users/dwayne/.rvm/gems/ree-1.8.7-2011.03@global
- GEM CONFIGURATION:
   - :update_sources => true
   - :verbose => true
   - :benchmark => false
   - :backtrace => false
   - :bulk_threshold => 1000
   - "gem" => "--no-ri --no-rdoc"
   - :sources => ["http://rubygems.org/", "http://gemcutter.org/"]
- REMOTE SOURCES:
   - http://rubygems.org/
   - http://gemcutter.org/
</code>```

.rvmrc for duke:

```<code>rvm --create use  "ree@duke"
</code>```

'gem list' within duke directory:

```<code>$ gem list

*** LOCAL GEMS ***

actionmailer (2.3.5)
actionpack (2.3.5)
activerecord (2.3.5)
activeresource (2.3.5)
activesupport (2.3.5)
arel (2.0.10)
authlogic (2.1.3)
builder (2.1.2)
bundler (1.0.14)
daemon_controller (0.2.6)
fastthread (1.0.7)
i18n (0.5.0)
mysql (2.8.1)
passenger (3.0.7)
pdfkit (0.5.0)
rack (1.3.0, 1.0.1)
rails (2.3.5)
rake (0.9.0)
rdoc (3.6.1)
tzinfo (0.3.27)
</code>```

Last few lines of the backtrace:

```<code>0   /Users/dwayne/.rvm/rubies/ree-1.8.7-2011.03/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb   36  in `gem_original_require'
1   /Users/dwayne/.rvm/rubies/ree-1.8.7-2011.03/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb   36  in `require'
2   /Users/dwayne/.rvm/gems/ree-1.8.7-2011.03@global/gems/passenger-3.0.7/lib/phusion_passenger/utils.rb    325 in `prepare_app_process'
3   /Users/dwayne/.rvm/gems/ree-1.8.7-2011.03@global/gems/passenger-3.0.7/lib/phusion_passenger/classic_rails/application_spawner.rb    176 in `initialize_server'
4   /Users/dwayne/.rvm/gems/ree-1.8.7-2011.03@global/gems/passenger-3.0.7/lib/phusion_passenger/utils.rb    572 in `report_app_init_status'
5   /Users/dwayne/.rvm/gems/ree-1.8.7-2011.03@global/gems/passenger-3.0.7/lib/phusion_passenger/classic_rails/application_spawner.rb
</code>```

The same is true of my Rails 3 projects.

Can anyone help with this? It sure seems like a path issue, but I can't figure out the problem.

Thanks.

答: Ah, one last place to look, and I found the problem. Turns out I still had some old virtual host settings for Passenger (using PassengerPreferencePane), and for some apps, I also needed to add the setup_load_paths.rb mentioned in the RVM/Passenger installation documentation.</p>

Body:
I've seen other similar errors, but none of the solutions have worked for me:

On Snow Leopard, I'm using RVM with project-based gemsets. I have both Rails 2 and Rails 3 apps. When I use bundler with Rails 2 or with Rails 3, I get:

no such file to load -- bundler

In my Rails 2 apps that don't use bundler, I just get a message that Rails needs to be installed when it is.

My RVM install has a global gemset with REE version of Ruby.

$ rvm list

rvm rubies

=> ree-1.8.7-2011.03 [ x86_64 ]
   ruby-1.8.7-p174 [ x86_64 ]
   ruby-1.9.2-head [ x86_64 ]

$ rvm gemset list

gemsets for ree-1.8.7-2011.03 (found in /Users/dwayne/.rvm/gems/ree-1.8.7-2011.03)
   cm
   duke
=> global

My global gems:

$ gem list

*** LOCAL GEMS ***

bundler (1.0.14)
daemon_controller (0.2.6)
fastthread (1.0.7)
passenger (3.0.7)
rack (1.3.0)
rake (0.9.0)
rdoc (3.6.1)

Passenger lines in Apache config:

LoadModule passenger_module /Users/dwayne/.rvm/gems/ree-1.8.7-2011.03@global/gems/passenger-3.0.7/ext/apache2/mod_passenger.so
PassengerRoot /Users/dwayne/.rvm/gems/ree-1.8.7-2011.03@global/gems/passenger-3.0.7
PassengerRuby /Users/dwayne/.rvm/wrappers/ree-1.8.7-2011.03@global/ruby

RubyGems environment for "duke" project:

- RUBYGEMS VERSION: 1.6.2
- RUBY VERSION: 1.8.7 (2011-02-18 patchlevel 334) [i686-darwin10.7.0]
- INSTALLATION DIRECTORY: /Users/dwayne/.rvm/gems/ree-1.8.7-2011.03@duke
- RUBY EXECUTABLE: /Users/dwayne/.rvm/rubies/ree-1.8.7-2011.03/bin/ruby
- EXECUTABLE DIRECTORY: /Users/dwayne/.rvm/gems/ree-1.8.7-2011.03@duke/bin
- RUBYGEMS PLATFORMS:
  - ruby
  - x86-darwin-10
- GEM PATHS:
   - /Users/dwayne/.rvm/gems/ree-1.8.7-2011.03@duke
   - /Users/dwayne/.rvm/gems/ree-1.8.7-2011.03@global
- GEM CONFIGURATION:
   - :update_sources => true
   - :verbose => true
   - :benchmark => false
   - :backtrace => false
   - :bulk_threshold => 1000
   - "gem" => "--no-ri --no-rdoc"
   - :sources => ["http://rubygems.org/", "http://gemcutter.org/"]
- REMOTE SOURCES:
   - http://rubygems.org/
   - http://gemcutter.org/

.rvmrc for duke:

rvm --create use  "ree@duke"

'gem list' within duke directory:

$ gem list

*** LOCAL GEMS ***

actionmailer (2.3.5)
actionpack (2.3.5)
activerecord (2.3.5)
activeresource (2.3.5)
activesupport (2.3.5)
arel (2.0.10)
authlogic (2.1.3)
builder (2.1.2)
bundler (1.0.14)
daemon_controller (0.2.6)
fastthread (1.0.7)
i18n (0.5.0)
mysql (2.8.1)
passenger (3.0.7)
pdfkit (0.5.0)
rack (1.3.0, 1.0.1)
rails (2.3.5)
rake (0.9.0)
rdoc (3.6.1)
tzinfo (0.3.27)

Last few lines of the backtrace:

0   /Users/dwayne/.rvm/rubies/ree-1.8.7-2011.03/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb   36  in `gem_original_require'
1   /Users/dwayne/.rvm/rubies/ree-1.8.7-2011.03/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb   36  in `require'
2   /Users/dwayne/.rvm/gems/ree-1.8.7-2011.03@global/gems/passenger-3.0.7/lib/phusion_passenger/utils.rb    325 in `prepare_app_process'
3   /Users/dwayne/.rvm/gems/ree-1.8.7-2011.03@global/gems/passenger-3.0.7/lib/phusion_passenger/classic_rails/application_spawner.rb    176 in `initialize_server'
4   /Users/dwayne/.rvm/gems/ree-1.8.7-2011.03@global/gems/passenger-3.0.7/lib/phusion_passenger/utils.rb    572 in `report_app_init_status'
5   /Users/dwayne/.rvm/gems/ree-1.8.7-2011.03@global/gems/passenger-3.0.7/lib/phusion_passenger/classic_rails/application_spawner.rb

The same is true of my Rails 3 projects.

Can anyone help with this? It sure seems like a path issue, but I can't figure out the problem.

Thanks.


问:
jQuery DataTables: hide search bar
I seem not able to hide DataTables default search bar. So far, I have tried solution from this thread, but setting bFilter:false disables filtering entirely, so my search boxes in the footer simply do not work any longer.

I have put up jsfiddle

My HTML:

```<code><thead>
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css">
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script>
</thead>
<tbody>
    <table id="mytable">
        <thead>
            <tr>
                <th>name</th>
                <th>type</th>
                <th>color</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th></th>
                <th></th>
                <th></th>
            </tr>
        </tfoot>
        <tbody>
            <tr>
                <td>apple</td>
                <td>fruit</td>
                <td>red</td>
            </tr>
            <tr>
                <td>banana</td>
                <td>fruit</td>
                <td>yellow</td>
            </tr>
            <tr>
                <td>carrot</td>
                <td>vegie</td>
                <td>red</td>
            </tr>
            <tr>
                <td>potato</td>
                <td>vegie</td>
                <td>brown</td>
            </tr>
        </tbody>
    </table>
</tbody>
</code>```

and jQuery code:

```<code>$(document).ready(function(){
    let table = $('#mytable').DataTable();
  $('#mytable tfoot th').each( function (i) {
        let title = $('#mytable thead th').eq( $(this).index() ).text();
        $(this).html( '<input type="text" placeholder="Search '+title+'" data-index="'+i+'" />' );
    } );
  $( table.table().container() ).on( 'keyup', 'tfoot input', function () {
    table
      .column( $(this).data('index') )
      .search( this.value )
      .draw();
  } );
});
</code>```

Any help is much appreciated.

答:
```<code>let table = $('#mytable').DataTable({sDom: 'lrtip'});
</code>```

this worked for me

Title: jQuery DataTables: hide search bar

Body:
I seem not able to hide DataTables default search bar. So far, I have tried solution from this thread, but setting bFilter:false disables filtering entirely, so my search boxes in the footer simply do not work any longer.

I have put up jsfiddle

My HTML:

    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css">

                name
                type
                color

                apple
                fruit
                red

                banana
                fruit
                yellow

                carrot
                vegie
                red

                potato
                vegie
                brown

and jQuery code:

$(document).ready(function(){
    let table = $('#mytable').DataTable();
  $('#mytable tfoot th').each( function (i) {
        let title = $('#mytable thead th').eq( $(this).index() ).text();
        $(this).html( '<input type="text" placeholder="Search '+title+'" data-index="'+i+'" />' );
    } );
  $( table.table().container() ).on( 'keyup', 'tfoot input', function () {
    table
      .column( $(this).data('index') )
      .search( this.value )
      .draw();
  } );
});

Any help is much appreciated.

Body:
let table = $('#mytable').DataTable({sDom: 'lrtip'});

this worked for me


问:
How to visualize the result of pcl::FPFHEstimation in point cloud using PCL?
I'm using pcl::FPFHEstimation class to detect feature point like this:

```<code>pcl::FPFHEstimationOMP<pcl::PointXYZ, pcl::Normal, pcl::FPFHSignature33> fest;
pcl::PointCloud<pcl::FPFHSignature33>::Ptr object_features(new pcl::PointCloud<pcl::FPFHSignature33>());
fest.setRadiusSearch(feature_radius);
fest.setInputCloud(source_cloud);
fest.setInputNormals(point_normal);
fest.compute(*object_features);
</code>```

My question is how to visulize detected feature points in pointcloud? like detected feature points in red color and non-feature points in white color.

I have searched a lot for this, but I only find some ways to display histogram which is not what I want.

答:
Fast point feature histogram is a point descriptor (which in pcl comes in the form of pcl::FPFHSignature33). This means that the algorithm computes a histogram for all points in the input point cloud. Once the descriptors of the points are computed, then you can classify, segment... the points. But the process of classifying or segmenting the points would be another algorithm.

In this paper I use FPFH to coarsely align point clouds. In there I use the FPFH descriptors to decide which point from cloud A corresponds to which point from cloud B (associate points). In this publication, what I do is I compute the curvature for all points before the FPFH, and then, I only compute the FPFH of the subset of points that which curvature is above a given threshold. This is how I extract key points. Then, I use the FPFH of these key points fo the rest of the things (in my case associate points from different point clouds).

The analogy that you propose in one of your comments: "So the feature descriptor computed by FPFH is more like a multi-dimentional eigenvector or something " would be a good one.

So, to answer your question: No, there is no other tool apart from histograms to visualize the FPFH data (or at least not an out-of-the-box pcl class that you can use).

Body:
I'm using pcl::FPFHEstimation class to detect feature point like this:

pcl::FPFHEstimationOMP<pcl::PointXYZ, pcl::Normal, pcl::FPFHSignature33> fest;
pcl::PointCloud<pcl::FPFHSignature33>::Ptr object_features(new pcl::PointCloud<pcl::FPFHSignature33>());
fest.setRadiusSearch(feature_radius);
fest.setInputCloud(source_cloud);
fest.setInputNormals(point_normal);
fest.compute(*object_features);

My question is how to visulize detected feature points in pointcloud? like detected feature points in red color and non-feature points in white color.

I have searched a lot for this, but I only find some ways to display histogram which is not what I want.


问:
In OCaml, write a function that works Base.Map and Base.Hashtbl
So I want to write a function that takes a first class module as an argument that works on Base.Map and Base.Hashtbl, but I'm running into a problem. This code illustrates what's going on:

```<code>module type Len_intf = sig
  type t
  val length : t -> int
end

let show (type a) (module L : Len_intf with type t = a) h =
  printf "len: %d\n" @@ L.length h

let test (type a) h =
  show (module Hashtbl : Len_intf with type t = a) h
</code>```

Attempting to compile this results in:

```<code>Error: Signature mismatch:
   ...
   Type declarations do not match:
     type ('a, 'b) t = ('a, 'b) Poly.t
   is not included in
     type t
   They have different arities.
   File "test.ml", line 2, characters 2-8:
     Expected declaration
   File "src/hashtbl_intf.ml", line 552, characters 2-17:
     Actual declaration
</code>```

Is this even possible, due to the different type arity of Hashtbl and Map?

答:
Writing a function that takes a first-class module is certainly possible (you did so), and it can be called like that:

let test (type a) (type b) h =
  let module M = struct
      type t = (a,b) Hashtbl.t
      let length = Hashtbl.length
    end in
  show (module M) h
```

But I do not think it is possible to do it the way you want. Indeed, type equalities come afterwards, in addition to what the signature already describes. They cannot prevent a type arity mismatch.

Body:
So I want to write a function that takes a first class module as an argument that works on Base.Map and Base.Hashtbl, but I'm running into a problem. This code illustrates what's going on:

module type Len_intf = sig
  type t
  val length : t -> int
end

let show (type a) (module L : Len_intf with type t = a) h =
  printf "len: %d\n" @@ L.length h

let test (type a) h =
  show (module Hashtbl : Len_intf with type t = a) h

Attempting to compile this results in:

Error: Signature mismatch:
   ...
   Type declarations do not match:
     type ('a, 'b) t = ('a, 'b) Poly.t
   is not included in
     type t
   They have different arities.
   File "test.ml", line 2, characters 2-8:
     Expected declaration
   File "src/hashtbl_intf.ml", line 552, characters 2-17:
     Actual declaration

Is this even possible, due to the different type arity of Hashtbl and Map?

Body:
Writing a function that takes a first-class module is certainly possible (you did so), and it can be called like that:

let test (type a) (type b) h =
  let module M = struct
      type t = (a,b) Hashtbl.t
      let length = Hashtbl.length
    end in
  show (module M) h

But I do not think it is possible to do it the way you want. Indeed, type equalities come afterwards, in addition to what the signature already describes. They cannot prevent a type arity mismatch.


问:
Template Driven Form Validation on Text area
I added a text area to my angular form. all the input/mat-select fields work fine with the requried attribute. For the textarea I added a custom class to show a red border. For some reason when I click the clear button the two input fields automatically applies its own red class but my custom class for the texareaa does not unless it has been touched. Which is fine but does not match the styles of the input fields. How do I apply the same validation styles to the text area: https://stackblitz.com/edit/angular-mpefsn

```<code>.text-error.ng-invalid.ng-touched{
  border: 1px solid #b00b00;
}
</code>```

If you click on the clear button initially when the stack blitz loads you will see the two inputfields turn red but not the textarea. This is because I have the ngtouched class. But if I remove it then the textarea will initially be red.

答:
Use the

```<code><ion-textarea></ion-textarea>
</code>```

instead of the native

```<code><textarea></textarea>
</code>```

in order to see validation results like with the

```<code><ion-input></ion-input>
</code>```

Body:
I added a text area to my angular form. all the input/mat-select fields work fine with the requried attribute. For the textarea I added a custom class to show a red border. For some reason when I click the clear button the two input fields automatically applies its own red class but my custom class for the texareaa does not unless it has been touched. Which is fine but does not match the styles of the input fields. How do I apply the same validation styles to the text area: https://stackblitz.com/edit/angular-mpefsn

.text-error.ng-invalid.ng-touched{
  border: 1px solid #b00b00;
}

If you click on the clear button initially when the stack blitz loads you will see the two inputfields turn red but not the textarea. This is because I have the ngtouched class. But if I remove it then the textarea will initially be red.

Body:
Use the

<ion-textarea></ion-textarea>

instead of the native

<textarea></textarea>

in order to see validation results like with the

<ion-input></ion-input>


问:
How to upload file on Google Drive using vb.net?

I need help uploading the file to Google Drive.

Everything works fine but with an error during first trial.

During the debug at request.upload the cursor don't wait (wait for the file to upload) and skips to the next line Dim responsefile As New Data.File and I get nothing in request.ResponseBody.

After that I run the function cursor actually waits on request.upload and it uploads file successfully.

I don't know what is actually happening. I checked the data every time and it is the same.

```<code>Public Async Function UploadFile3(service As DriveService, FilePath As String) As Tasks.Task(Of Data.File)

        If service3.ApplicationName <> "netGDriveApi" Then CreateService()
            If IO.File.Exists(FilePath) Then
                Dim body As New Data.File()
                body.Name = IO.Path.GetFileName(FilePath)
                body.Description = "BackUP file"
                body.MimeType = "application/octet-stream"
                'body.FileExtension = ".bak"

                '-------------------------------------------------UPLOAD FILE PROCESS-------------------------------------------------------------

                Dim byteArray As Byte() = IO.File.ReadAllBytes(FilePath)
                Dim stream As New IO.MemoryStream(byteArray)
                Try
                    Dim request As FilesResource.CreateMediaUpload = service.Files.Create(body, stream, body.MimeType)
                    Await request.UploadAsync() 'Cursor skips first time here and dont wait for response.
                    Dim responsefile As New Data.File 'Cursor waits from the above step to here till the file uploaded.

                    responsefile = request.ResponseBody

                    If IsNothing(responsefile) Then
                        MessageBox.Show("Try Again")
                    Else
                        MessageBox.Show(responsefile.Id.ToString)
                    End If

                Catch e As Exception
                    MessageBox.Show("An error occurred: " + e.Message)
                    Return Nothing
                End Try

            Else
                MessageBox.Show("FILE DOES NOT EXISTS." + FilePath)
                Return Nothing
            End If
End Function
</code>```

答:
request.UploadAsync() returns a Task(Of IUploadProgress). At the very least, you should be examining the result of this task. It might give you clues as to the cause of your problems.

For example, while debugging you could do something like the following:

```<code>Try
    Dim request As FilesResource.CreateMediaUpload = service.Files.Create(body, stream, body.MimeType)

    Dim Upload As IUploadProgress = Await request.UploadAsync() 'Cursor skips first time here and dont wait for response.

    If Upload.Status <> UploadStatus.Completed Then
        Dim ex As Exception = Upload.Exception
        MessageBox.Show(ex.Message, "UploadAsync Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Return Nothing
    Else
        MessageBox.Show(Upload.Status.ToString, "Upload Status:")
    End If

    Dim responsefile As New Data.File 'Cursor waits from the above step to here till the file uploaded.
    responsefile = request.ResponseBody
</code>```

Always check what information methods return, and use that information as necessary in your production code.

Body:
I need help uploading the file to Google Drive.

Everything works fine but with an error during first trial.

During the debug at request.upload the cursor don't wait (wait for the file to upload) and skips to the next line Dim responsefile As New Data.File and I get nothing in request.ResponseBody.

After that I run the function cursor actually waits on request.upload and it uploads file successfully.

I don't know what is actually happening. I checked the data every time and it is the same.

Public Async Function UploadFile3(service As DriveService, FilePath As String) As Tasks.Task(Of Data.File)

        If service3.ApplicationName <> "netGDriveApi" Then CreateService()
            If IO.File.Exists(FilePath) Then
                Dim body As New Data.File()
                body.Name = IO.Path.GetFileName(FilePath)
                body.Description = "BackUP file"
                body.MimeType = "application/octet-stream"
                'body.FileExtension = ".bak"

                '-------------------------------------------------UPLOAD FILE PROCESS-------------------------------------------------------------

                Dim byteArray As Byte() = IO.File.ReadAllBytes(FilePath)
                Dim stream As New IO.MemoryStream(byteArray)
                Try
                    Dim request As FilesResource.CreateMediaUpload = service.Files.Create(body, stream, body.MimeType)
                    Await request.UploadAsync() 'Cursor skips first time here and dont wait for response.
                    Dim responsefile As New Data.File 'Cursor waits from the above step to here till the file uploaded.

                    responsefile = request.ResponseBody

                    If IsNothing(responsefile) Then
                        MessageBox.Show("Try Again")
                    Else
                        MessageBox.Show(responsefile.Id.ToString)
                    End If

                Catch e As Exception
                    MessageBox.Show("An error occurred: " + e.Message)
                    Return Nothing
                End Try

            Else
                MessageBox.Show("FILE DOES NOT EXISTS." + FilePath)
                Return Nothing
            End If
End Function

Body:
request.UploadAsync() returns a Task(Of IUploadProgress). At the very least, you should be examining the result of this task. It might give you clues as to the cause of your problems.

For example, while debugging you could do something like the following:

Try
    Dim request As FilesResource.CreateMediaUpload = service.Files.Create(body, stream, body.MimeType)

    Dim Upload As IUploadProgress = Await request.UploadAsync() 'Cursor skips first time here and dont wait for response.

    If Upload.Status <> UploadStatus.Completed Then
        Dim ex As Exception = Upload.Exception
        MessageBox.Show(ex.Message, "UploadAsync Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Return Nothing
    Else
        MessageBox.Show(Upload.Status.ToString, "Upload Status:")
    End If

    Dim responsefile As New Data.File 'Cursor waits from the above step to here till the file uploaded.
    responsefile = request.ResponseBody

Always check what information methods return, and use that information as necessary in your production code.


问:
AnyCable : Retrieve information gRPC info on ROR App
I work to switch Action Cable to AnyCable.

I don't use cookies to identify users, I use JWT because my app provide only API.

So in case of a chat, we need to retrieve the user who send the message.

In log, I see this message1:

```<code>RPC Command: <AnyCable::CommandMessage: command: "subscribe", identifier: "{\"channel\":\"RoomChannel\",\"room_id\":\"566\"}", connection_identifiers: "{\"current_user\":{\"id\":\"XXXXXXXX\",\"login_time\":1589745276,\"okta_id\":\"xxxxx@gmail.com\"
</code>```

How can I retrieve the value of the object "connection_identifiers"?

Below the current connection Class :
`Class : module ApplicationCable
  class Connection < ActionCable::Connection::Base
    include Authentication

```<code>identified_by :current_user

def connect
  self.current_user = create_user_from_tokens

  reject_unauthorized_connection unless current_user.valid
end
</code>```

end
end`

create_user_from_tokens > Create a user object from JWT token

And the current reception method for a new message :
`def receive(content)
    return false unless receive_params
    return false unless conversation

```<code>message = content['content']

message_params = {conversation_id: @conversation.id,
                  conversation: @conversation,
                  sender_id: @connection.current_user.okta_id,
                  sender_name: @connection.current_user.name,
                  content: message}

ConversationMessageService.post message_params
</code>```

rescue StandardError
    Rails.logger.error I18n.t('log.api.websocket.error_receive')
    render json: {error: :bad_request, error_description: I18n.t('log.api.websocket.error_receive'), error_uri: ''}, status: :bad_request
  end`

As I undertand it is impossible to retrieve @connection.

答:
To access the current user from the channel, you can use #current_user accessor (Rails adds this delegation for you automatically).

So, the code should be:

message_params = {conversation_id: @conversation.id,
                  conversation: @conversation,
                  sender_id: current_user.okta_id,
                  sender_name: current_user.name,
                  content: message}
```

<p>If I understood you correctly, your <code>current_user</code> object is not an AR record but a plain Ruby class, right?</p>

<p>Then <code>current_user</code> in channels would simply return a JSON-encoded string, not the object.</p>

<p>Currently, AnyCable uses GlobalID to serialize/deserialize connection identifiers. You must add GlobalID functionality to your class to make it work with AnyCable the same way as with Action Cable. For example:</p>

<pre class="lang-rb prettyprint-override"><code>class User
  include GlobalID::Identification

  def self.find_by_gid(gid)
    new(gid.params)
  end

  def to_global_id
    super(to_h.merge!(app: :custom))
  end

  alias to_gid to_global_id
end

# setup GlobalID to correctly resolve your custom class
GlobalID::Locator.use :custom do |gid|
  gid.model_name.constantize.find_by_gid(gid)
end
</code>```

Body:
I work to switch Action Cable to AnyCable.

I don't use cookies to identify users, I use JWT because my app provide only API.

So in case of a chat, we need to retrieve the user who send the message.

In log, I see this message1:

RPC Command: <AnyCable::CommandMessage: command: "subscribe", identifier: "{\"channel\":\"RoomChannel\",\"room_id\":\"566\"}", connection_identifiers: "{\"current_user\":{\"id\":\"XXXXXXXX\",\"login_time\":1589745276,\"okta_id\":\"xxxxx@gmail.com\"

How can I retrieve the value of the object "connection_identifiers"?

Below the current connection Class :
`Class : module ApplicationCable
  class Connection < ActionCable::Connection::Base
    include Authentication

identified_by :current_user

def connect
  self.current_user = create_user_from_tokens

  reject_unauthorized_connection unless current_user.valid
end

end
end`

create_user_from_tokens > Create a user object from JWT token

And the current reception method for a new message :
`def receive(content)
    return false unless receive_params
    return false unless conversation

message = content['content']

message_params = {conversation_id: @conversation.id,
                  conversation: @conversation,
                  sender_id: @connection.current_user.okta_id,
                  sender_name: @connection.current_user.name,
                  content: message}

ConversationMessageService.post message_params

rescue StandardError
    Rails.logger.error I18n.t('log.api.websocket.error_receive')
    render json: {error: :bad_request, error_description: I18n.t('log.api.websocket.error_receive'), error_uri: ''}, status: :bad_request
  end`

As I undertand it is impossible to retrieve @connection.

Body:
To access the current user from the channel, you can use #current_user accessor (Rails adds this delegation for you automatically).

So, the code should be:

message_params = {conversation_id: @conversation.id,
                  conversation: @conversation,
                  sender_id: current_user.okta_id,
                  sender_name: current_user.name,
                  content: message}

If I understood you correctly, your current_user object is not an AR record but a plain Ruby class, right?

Then current_user in channels would simply return a JSON-encoded string, not the object.

Currently, AnyCable uses GlobalID to serialize/deserialize connection identifiers. You must add GlobalID functionality to your class to make it work with AnyCable the same way as with Action Cable. For example:

class User
  include GlobalID::Identification

  def self.find_by_gid(gid)
    new(gid.params)
  end

  def to_global_id
    super(to_h.merge!(app: :custom))
  end

  alias to_gid to_global_id
end

# setup GlobalID to correctly resolve your custom class
GlobalID::Locator.use :custom do |gid|
  gid.model_name.constantize.find_by_gid(gid)
end


问:
old instances in box.info.vclock
Good afternoon, I can’t clean  old instaces in box.info.vclock.
Now I have cluster (master id = 3 / slave id = 4) and in box.info.vclock contains old instences (id = 1 and id = 2) which I deleted a long time ago (removed from the box.space._cluster and box.cfg.replication)

答: The log sequence number values are never deleted from vclock, even when the corresponding instance is removed from the cluster. This is done to make sure vclock always grows monotonically. An instance vclock component will be re-used when a new instance is added, (different instance uuid, but re-used instance id), in which case this instance will start counting its local changes from this component's value.</p>

Title: old instances in box.info.vclock


问:
MySQL LOAD DATA INFILE doesn't load complete data
I am trying to insert 1 million rows of data in a CSV file to MySQL table. Every time I run the following script from node.js, it inserts only portion of rows, which changes every time I run the script.

```<code>        await mysqlDB.sequelize.query(`LOAD DATA LOCAL INFILE './out.csv'
                            INTO TABLE product_inventories_product_code_TEMP
                            COLUMNS TERMINATED BY ','
                            OPTIONALLY ENCLOSED BY '"'
                            ESCAPED BY '"'
                            LINES TERMINATED BY '\n'
                            IGNORE 1 ROWS;`)
</code>```

I am not sure why is it not inserting all the rows from CSV.

CSV format is simple.

```<code>id,product_code
26,STM-iY-ofyRH
27,STM-UmHBxU71
28,STM-UmHBeU71
29,STM-UmHBtU71
30,STM-UmHBwU71
</code>```

I am using sequelize raw query to insert. Please help.

答:
Here is code to upload a csv in Mysql using nodejs</p>

```<code>var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "Your UserName",
password: "Your Password",
database: "Your DB"
});

con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "LOAD DATA LOCAL INFILE 'FilePath' REPLACE INTO TABLE YOUR_TABLE_NAME FIELDS
TERMINATED BY ';' ENCLOSED BY '\"' LINES TERMINATED BY '\n' IGNORE 1 LINES (Column
names Comma Separed) set id = NULL;"
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});
</code>```

Body:
I am trying to insert 1 million rows of data in a CSV file to MySQL table. Every time I run the following script from node.js, it inserts only portion of rows, which changes every time I run the script.

        await mysqlDB.sequelize.query(`LOAD DATA LOCAL INFILE './out.csv'
                            INTO TABLE product_inventories_product_code_TEMP
                            COLUMNS TERMINATED BY ','
                            OPTIONALLY ENCLOSED BY '"'
                            ESCAPED BY '"'
                            LINES TERMINATED BY '\n'
                            IGNORE 1 ROWS;`)

I am not sure why is it not inserting all the rows from CSV.

CSV format is simple.

id,product_code
26,STM-iY-ofyRH
27,STM-UmHBxU71
28,STM-UmHBeU71
29,STM-UmHBtU71
30,STM-UmHBwU71

I am using sequelize raw query to insert. Please help.

Body:
Here is code to upload a csv in Mysql using nodejs

var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "Your UserName",
password: "Your Password",
database: "Your DB"
});

con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "LOAD DATA LOCAL INFILE 'FilePath' REPLACE INTO TABLE YOUR_TABLE_NAME FIELDS
TERMINATED BY ';' ENCLOSED BY '\"' LINES TERMINATED BY '\n' IGNORE 1 LINES (Column
names Comma Separed) set id = NULL;"
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});


问:
How to save the minimum time taken in unity?
I am making a maze game in unity 3d where the least time taken to complete the level is the highscore. Is there a way to save the highscore using Playerprefs? Scripting is done in C#.</p>

答:
You can make it easier using Get/Set Assessors.</p>

```<code>public class GameManager: MonoBehavior {
    ...
    public float HighScore {
        get {
            return PlayerPrefs.GetFloat("HIGHSCORE", 0);
        }
        set {
            if(value > HighScore) {
                PlayerPrefs.SetFloat("HIGHSCORE", value);
            }
        }
    }
    ...
    public void GameOver() {
        HighScore = currentScore;
    }
}
</code>```

Body:
You can make it easier using Get/Set Assessors.

public class GameManager: MonoBehavior {
    ...
    public float HighScore {
        get {
            return PlayerPrefs.GetFloat("HIGHSCORE", 0);
        }
        set {
            if(value > HighScore) {
                PlayerPrefs.SetFloat("HIGHSCORE", value);
            }
        }
    }
    ...
    public void GameOver() {
        HighScore = currentScore;
    }
}


问:
Angular 5 Query Parameters Disappear
When I navigate to a page with query parameters in my Angular application, the parameters end up disappearing.

For example, if I go here:

```<code>http://example.com:8080/TestComponent?OtherName=foo
</code>```

If reroutes me to here:

```<code>http://example.com:8080/TestComponent
</code>```

Thus, since the query parameters get erased, my subscription to ActivatedRoute returns nothing. This is my routing:

```<code>import { Routes } from '@angular/router';
import { TestComponent, PageNotFoundComponent } from './exports/components';

export const ROUTES: Routes = [
    {
        path: 'TestComponent',
        component: TestComponent
    },
    {
        path: '**',
        component: PageNotFoundComponent
    }
];
</code>```

Subscription (route is an instance of ActivatedRoute):

```<code>this.route.queryParams.subscribe((params: Params) => {
    if (params && Object.keys(params).length > 0) {
        const OTHER_NAME = params['OtherName'];
    }
});
</code>```

Even if I remove the wildcard path, it still removes the parameters from the URL; therefore, it never goes inside the the above if statement. How can I prevent the query parameter from disappearing?

答:
This is can be an exact solution for this, but I found an approximate solution.

```<code>url = localhost:4200/#/test?id=1234
</code>```

use auth-guard-service and CanActivate your page.

1.Angular routing

```<code>{ path: 'test', component: TestComponent, canActivate: [AuthGuardService]}
</code>```

2.AuthGuardService

```<code>@Injectable({ providedIn: 'root' })
export class AuthGuardService implements CanActivate {

constructor(private app: ApplicationService) {
    // window.location.href => gives you exact url (localhost:4200/#/test?id=1234).
    // you can parse url like this.

    id = getUrlParameterByName('id', window.location.href);
}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
   const curPage = route.url[0].path;
   if('test' === curPage) { return true; }
   else {
      // your decision...
   }
}
getUrlParameterByName(name: string, url?: any) {
    if (!url) { url = window.location.href; }
    name = name.replace(/[\[\]]/g, '\\$&');
    const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
    const results = regex.exec(url);
    if (!results) { return null; }
    if (!results[2]) { return ''; }
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
</code>```

Title: Angular 5 Query Parameters Disappear

Body:
When I navigate to a page with query parameters in my Angular application, the parameters end up disappearing.

For example, if I go here:

http://example.com:8080/TestComponent?OtherName=foo

If reroutes me to here:

http://example.com:8080/TestComponent

Thus, since the query parameters get erased, my subscription to ActivatedRoute returns nothing. This is my routing:

import { Routes } from '@angular/router';
import { TestComponent, PageNotFoundComponent } from './exports/components';

export const ROUTES: Routes = [
    {
        path: 'TestComponent',
        component: TestComponent
    },
    {
        path: '**',
        component: PageNotFoundComponent
    }
];

Subscription (route is an instance of ActivatedRoute):

this.route.queryParams.subscribe((params: Params) => {
    if (params && Object.keys(params).length > 0) {
        const OTHER_NAME = params['OtherName'];
    }
});

Even if I remove the wildcard path, it still removes the parameters from the URL; therefore, it never goes inside the the above if statement. How can I prevent the query parameter from disappearing?

Body:
This is can be an exact solution for this, but I found an approximate solution.

url = localhost:4200/#/test?id=1234

use auth-guard-service and CanActivate your page.

1.Angular routing

{ path: 'test', component: TestComponent, canActivate: [AuthGuardService]}

2.AuthGuardService

@Injectable({ providedIn: 'root' })
export class AuthGuardService implements CanActivate {

constructor(private app: ApplicationService) {
    // window.location.href => gives you exact url (localhost:4200/#/test?id=1234).
    // you can parse url like this.

    id = getUrlParameterByName('id', window.location.href);
}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
   const curPage = route.url[0].path;
   if('test' === curPage) { return true; }
   else {
      // your decision...
   }
}
getUrlParameterByName(name: string, url?: any) {
    if (!url) { url = window.location.href; }
    name = name.replace(/[\[\]]/g, '\\$&');
    const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
    const results = regex.exec(url);
    if (!results) { return null; }
    if (!results[2]) { return ''; }
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}


问:
How to get the meridian (am / pm) with momentsjs and angularjs
I have a question about the library moments.js, I have an application in angularjs where I have six select elements for the year, month, day, hour, minutes, and am / pm format. I am using the following format moment to build m.format date ('YYYY-MM-DD hh: mm: ss a).

The code is as follows:

```<code>var m = moment([scope.val.year, scope.val.month, scope.val.date, scope.val.hour, scope.val.minute]); //build date

model.$setViewValue(m.format('YYYY-MM-DD hh:mm:ss a'))
</code>```

I get the data m.hour (), m.minute (), etc but there is a way to get the am / pm format, I have not found anything about it, something perhaps as m.meridian () => "am "or" pm ".

I would build the array passing as parameter if am or pm, and then also would get from any date if am or pm date.

答:
You can extend the moment with the following function and use it in the same style as you set & get hour, day, minute etc..

moment.fn.meridiem = function(newMeridiem) {
  if (!newMeridiem) {
    return this.format('A'); // or `return this.hours() < 12 ? 'AM' : 'PM';`
  }
  if (newMeridiem.toUpperCase() === 'AM' && this.hours() > 12) {
    this.hours(this.hours() - 12);
  } else if (newMeridiem.toUpperCase() === 'PM' && this.hours() <= 12) {
    this.hours(this.hours() + 12);
  }
  return this;
}

console.log("Current:",moment().meridiem());

console.log("Set as am result:",moment().meridiem('am').meridiem());

console.log("Set as pm result:",moment().meridiem('pm').meridiem());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script></code>```

Copied from https://github.com/moment/moment/issues/3873

Body:
I have a question about the library moments.js, I have an application in angularjs where I have six select elements for the year, month, day, hour, minutes, and am / pm format. I am using the following format moment to build m.format date ('YYYY-MM-DD hh: mm: ss a).

The code is as follows:

var m = moment([scope.val.year, scope.val.month, scope.val.date, scope.val.hour, scope.val.minute]); //build date

model.$setViewValue(m.format('YYYY-MM-DD hh:mm:ss a'))

I get the data m.hour (), m.minute (), etc but there is a way to get the am / pm format, I have not found anything about it, something perhaps as m.meridian () => "am "or" pm ".

I would build the array passing as parameter if am or pm, and then also would get from any date if am or pm date.

Body:
You can extend the moment with the following function and use it in the same style as you set & get hour, day, minute etc..

moment.fn.meridiem = function(newMeridiem) {
  if (!newMeridiem) {
    return this.format('A'); // or `return this.hours() < 12 ? 'AM' : 'PM';`
  }
  if (newMeridiem.toUpperCase() === 'AM' && this.hours() > 12) {
    this.hours(this.hours() - 12);
  } else if (newMeridiem.toUpperCase() === 'PM' && this.hours() <= 12) {
    this.hours(this.hours() + 12);
  }
  return this;
}

console.log("Current:",moment().meridiem());

console.log("Set as am result:",moment().meridiem('am').meridiem());

console.log("Set as pm result:",moment().meridiem('pm').meridiem());

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script>

Copied from https://github.com/moment/moment/issues/3873


问:
Declare custom Types in Swift and Java-Kotlin
I'm beginner in programming. I'm learning Swift and Java-Kotlin to develop apps.
Also I'm student in IT Engineering.

I have learnt in C Language modularity that means to have a library where declare the types and the actions and functions and I call these actions, functions and types in the main file declaring the files in the header.

I was trying to do something similar in Swift and Kotlin, to have a file where declare my custom types and call them in the different views-classes.

In Swift I know that is not necessary to import the file where the types are.

For instance, I have declared the following types in Swift

```<code>struct tUser {

    var userId: Int
    var name: String
    var birthday: tDate
    var location: String
    var province: String
    var email: String
    var userPassword: String
    var picture: Image
    var favorites: tFavorite
}

struct tDate {

    var day: Int
    var month: Int
    var year: Int
}

struct tFavorite {

    var identifyer: Int
}

If I would initialize the types in C I would do

tUser newUser;

newUser.userId = 001;
newUser.name = "John"
</code>```

I'm trying to do the same in Swift and Kotlin but, in Swift I get error "Expressions are not allowed at the top level" also in Kotlin I have errors.

Perhaps the answer is that there is no sense to do this in a Object Oriented Language,

Can someone help me in this matter?

Thanks,

答:
Glad to see a new person diving into Swift, welcome!

You can do what you are trying to do in Swift, but you have to be in a scope where it's allowed (e.g. a class or struct).

If you create a new Playground instead of an XCode project, you should be able to do it like you do in C.

If you want to use a project instead, the "New Project" template in XCode should give you a "ViewController.swift" file you can work on.

Just for starters, create a new "Example.swift" file in your project and paste your struct definitions there. After that, go back to your ViewController.swift file and see the function viewDidLoad. Inside there, try to initialize your objects like you did.

That should solve the scope problem. As for the initialization problem, you can't exactly create your objects like C without providing default values for your properties:

```<code>struct tUser {
    var userId: Int = 0
    var name: String = ""
    var birthday: tDate
    var location: String = ""
    var province: String = ""
    var email: String = ""
    var userPassword: String = ""
    var picture: Image
    var favorites: tFavorite
}
</code>```

I'll let you figure out how to do the same for your custom tDate and tFavorite structs. After you provide them, you should be able to initialize an object with:

var user = tUser()

Another option is to define your properties as Optional like: var name: String?. Optional is a separate discussion topic on its own.

I suggest reading the official Swift e-book for a basic understanding of initialization and overall the language when starting out. It's documented quite well in my humble opinion.

Hope it helps you out, and good luck!

Body:
I'm beginner in programming. I'm learning Swift and Java-Kotlin to develop apps.
Also I'm student in IT Engineering.

I have learnt in C Language modularity that means to have a library where declare the types and the actions and functions and I call these actions, functions and types in the main file declaring the files in the header.

I was trying to do something similar in Swift and Kotlin, to have a file where declare my custom types and call them in the different views-classes.

In Swift I know that is not necessary to import the file where the types are.

For instance, I have declared the following types in Swift

struct tUser {

    var userId: Int
    var name: String
    var birthday: tDate
    var location: String
    var province: String
    var email: String
    var userPassword: String
    var picture: Image
    var favorites: tFavorite
}

struct tDate {

    var day: Int
    var month: Int
    var year: Int
}

struct tFavorite {

    var identifyer: Int
}

If I would initialize the types in C I would do

tUser newUser;

newUser.userId = 001;
newUser.name = "John"

I'm trying to do the same in Swift and Kotlin but, in Swift I get error "Expressions are not allowed at the top level" also in Kotlin I have errors.

Perhaps the answer is that there is no sense to do this in a Object Oriented Language,

Can someone help me in this matter?

Thanks,

Body:
Glad to see a new person diving into Swift, welcome!

You can do what you are trying to do in Swift, but you have to be in a scope where it's allowed (e.g. a class or struct).

If you create a new Playground instead of an XCode project, you should be able to do it like you do in C.

If you want to use a project instead, the "New Project" template in XCode should give you a "ViewController.swift" file you can work on.

Just for starters, create a new "Example.swift" file in your project and paste your struct definitions there. After that, go back to your ViewController.swift file and see the function viewDidLoad. Inside there, try to initialize your objects like you did.

That should solve the scope problem. As for the initialization problem, you can't exactly create your objects like C without providing default values for your properties:

struct tUser {
    var userId: Int = 0
    var name: String = ""
    var birthday: tDate
    var location: String = ""
    var province: String = ""
    var email: String = ""
    var userPassword: String = ""
    var picture: Image
    var favorites: tFavorite
}

I'll let you figure out how to do the same for your custom tDate and tFavorite structs. After you provide them, you should be able to initialize an object with:

var user = tUser()

Another option is to define your properties as Optional like: var name: String?. Optional is a separate discussion topic on its own.

I suggest reading the official Swift e-book for a basic understanding of initialization and overall the language when starting out. It's documented quite well in my humble opinion.

Hope it helps you out, and good luck!


问:
Array of texture identifiers to OpenGL DrawElements/DrawArrays?
An OpenGL ES sequence like this can be used to render multiple objects in one pass:

```<code>glVertexPointer(...params..., vertex_Array );
glTexCoordPointer(...params..., texture_Coordinates_Array );
glBindTexture(...params..., one_single_texture_ID );
glDrawArrays( GL_TRIANGLES, number_Triangles );
</code>```

Here, the vertex array and texture coordinates array can refer to innumerable primitives that can be described in one step to OpenGL.

But do all these primitives' texture coordinates have to reference the one, single texture in the glBindTexture command?

It would be nice to pass in an array of texture identifiers:

```<code>glBindTexture(...params..., texture_identifier_array[] );
</code>```

Here, there would be a texture ID in the array for every primitive shape described in the preceding calls. So, each shape's texture coordinates would pertain to the texture identified in "texture_identifier_array[]".

I can see one option is to place all textures of interest one one large texture that can be referenced as a single entity in the drawing calls. On my platform, this creates an intermediate step with a large bitmap that might cause memory issues.

It would be best for me to be able to pass an array of texture identifiers to the OpenGL ES drawing calls. Can this be done?

答:
No, that's not possible. You could perhaps emulate it by using a texture array and giving your vertices a texture index. Then in the fragment shader you could look up the right texture with the index, but I doubt that ES supports texture arrays. And even then I don't know if this really works. Or if a texture atlas solution would be much more efficient.

If you want to render multiple versions of the same geometry (what I doubt), you're looking for instanced rendering, which also isn't supported by on ES devices, I think.

So the way to go at the moment will be a texture atlas (multiple textures in one) or just calling glDrawArrays multiple times.

Body:
An OpenGL ES sequence like this can be used to render multiple objects in one pass:

glVertexPointer(...params..., vertex_Array );
glTexCoordPointer(...params..., texture_Coordinates_Array );
glBindTexture(...params..., one_single_texture_ID );
glDrawArrays( GL_TRIANGLES, number_Triangles );

Here, the vertex array and texture coordinates array can refer to innumerable primitives that can be described in one step to OpenGL.

But do all these primitives' texture coordinates have to reference the one, single texture in the glBindTexture command?

It would be nice to pass in an array of texture identifiers:

glBindTexture(...params..., texture_identifier_array[] );

Here, there would be a texture ID in the array for every primitive shape described in the preceding calls. So, each shape's texture coordinates would pertain to the texture identified in "texture_identifier_array[]".

I can see one option is to place all textures of interest one one large texture that can be referenced as a single entity in the drawing calls. On my platform, this creates an intermediate step with a large bitmap that might cause memory issues.

It would be best for me to be able to pass an array of texture identifiers to the OpenGL ES drawing calls. Can this be done?


问:
How to show wpDataTables results inside popup using AJAX
I am using wpdatatables to display data.

I have added MySQL Query in backend, and that query has 2 dynamic parameter like

```<code>SELECT some fields
FROM tbl1 tb1
JOIN tbl2 tb2
    ON some conditions
JOIN tbl3 tb3
    ON some conditions
WHERE DATE(Date) BETWEEN '%VAR1%' AND '%VAR2%';
</code>```

wpdatatables Generate shortcode like [wpdatatable id=some_id] ,

I have create 2 date-picker for Start Date and End Date on Frontend.

Now I have to pass dynamic parameter like [wpdatatable id=some_id var1="strt_dt" var2="end_dt"]

So to get strt_dt and end_dt, I have call AJAX and pass parameters.

My problem is I am showing all this data inside popup.

I mean when user clicks on See Report Button
one popup will be open. Data also Displayed correctly. But it showing without wpdatatables Layout.
It is not Considering wpdatatables JS or CSS

Here is my AJAX Callback Function :

```<code> public function get_datatable_data() {
    echo do_shortcode('[wpdatatable id=some_id var1="'.$_POST['strt_dt'].'" var2="'.$_POST['end_dt'].'"]');
    wp_die();
}
</code>```

Here is Code in which I am appending data :

```<code>var params =  {"strt_dt":strt_dt,"end_dt":end_dt,action:"get_datatable_data"}
jQuery.post(ajaxurl,params,function(data){
    if(data){
        jQuery(".some class").empty().append(data);
    }else{
        jQuery(".some class").empty().append("No data Found");
    }
</code>```

答:
This would have been possible if you are using normal datatable where you can re-initalize datatable on ajax success by using following code.

```<code>$("#div").dataTable().fnDestroy()
$("#div").dataTable();
</code>```

But if you are using Plugin then there is no direct way to achive this, one possible solution is to create a normal page with datatable shortcode in it and then in you ajax callback you call that page in iframe.
for eg: you create page www.mysite.com/datatable - this page will have the actual shortcode

```<code>public function get_datatable_data() { ?>
   <iframe src="www.mysite.com/datatable" height="200px"></iframe>
<?php
    wp_die();
}
</code>```

this will allow datatable to get initalize in iframe.

Body:
I am using wpdatatables to display data.

I have added MySQL Query in backend, and that query has 2 dynamic parameter like

SELECT some fields
FROM tbl1 tb1
JOIN tbl2 tb2
    ON some conditions
JOIN tbl3 tb3
    ON some conditions
WHERE DATE(Date) BETWEEN '%VAR1%' AND '%VAR2%';

wpdatatables Generate shortcode like [wpdatatable id=some_id] ,

I have create 2 date-picker for Start Date and End Date on Frontend.

Now I have to pass dynamic parameter like [wpdatatable id=some_id var1="strt_dt" var2="end_dt"]

So to get strt_dt and end_dt, I have call AJAX and pass parameters.

My problem is I am showing all this data inside popup.

I mean when user clicks on See Report Button
one popup will be open. Data also Displayed correctly. But it showing without wpdatatables Layout.
It is not Considering wpdatatables JS or CSS

Here is my AJAX Callback Function :

 public function get_datatable_data() {
    echo do_shortcode('[wpdatatable id=some_id var1="'.$_POST['strt_dt'].'" var2="'.$_POST['end_dt'].'"]');
    wp_die();
}

Here is Code in which I am appending data :

var params =  {"strt_dt":strt_dt,"end_dt":end_dt,action:"get_datatable_data"}
jQuery.post(ajaxurl,params,function(data){
    if(data){
        jQuery(".some class").empty().append(data);
    }else{
        jQuery(".some class").empty().append("No data Found");
    }

Body:
This would have been possible if you are using normal datatable where you can re-initalize datatable on ajax success by using following code.

$("#div").dataTable().fnDestroy()
$("#div").dataTable();

But if you are using Plugin then there is no direct way to achive this, one possible solution is to create a normal page with datatable shortcode in it and then in you ajax callback you call that page in iframe.
for eg: you create page www.mysite.com/datatable - this page will have the actual shortcode

public function get_datatable_data() { ?>
   <iframe src="www.mysite.com/datatable" height="200px"></iframe>
<?php
    wp_die();
}

this will allow datatable to get initalize in iframe.


问:
Multiple HTTP Requests in Guards
I have the following routing config:

```<code>{
  path: '',
  canActivate: [AppGuard],
  children: [
    {
      path: 'login',
      loadChildren: ...
    }
  ]
}
</code>```

The guard (simplified):

```<code>canActivate(route, state) {
  return this.profileService.get().pipe(
    map(profile => {
      // I have to implement a not logged user
      if (!profile) {
        // No need to redirect
        if (alreadyOnLoginPage) {
          return true;
        } else {
          return this.router.createUrlTree(['/login']);
        }
      }
      // Some unnecessary logic here (redirection to the profile page)...
    })
  );
}
</code>```

Here we have two scenarios:

OK (1 request):

Go straight to the /login

Profile is fetched

No profile, you are on the login page already, so return true.

Not OK (2 requests):

Go to the /

Profile is fetched

No profile, you are not on the login page, so redirect to /login

Here guard is invoking one more time, so profile is fetched again.

No profile, you are on the login page already, so return true.

So, as you can see, two requests were invoked in the second scenario. I tried to multicast the service observable, but still have no success.

What should I do so only one request is invoked?

答:
In your  guard have a profile property in class, it will be there because its a injectable and singleton guard troughout app. </p>

<p>Change your guard to :- </p>

```<code>public profile;

canActivate(route, state) {
  const obs = this.profile ? of(this.profile): this.profileService.get();
  return obs.pipe(
    map(profile => {
      // I have to implement a not logged user
      if (!profile) {
        // No need to redirect
        if (alreadyOnLoginPage) {
          return true;
        } else {
          return this.router.createUrlTree(['/login']);
        }
      }
      // Some unnecessary logic here (redirection to the profile page)...
    })
  );
}
</code>```

Title: Multiple HTTP Requests in Guards

Body:
I have the following routing config:

{
  path: '',
  canActivate: [AppGuard],
  children: [
    {
      path: 'login',
      loadChildren: ...
    }
  ]
}

The guard (simplified):

canActivate(route, state) {
  return this.profileService.get().pipe(
    map(profile => {
      // I have to implement a not logged user
      if (!profile) {
        // No need to redirect
        if (alreadyOnLoginPage) {
          return true;
        } else {
          return this.router.createUrlTree(['/login']);
        }
      }
      // Some unnecessary logic here (redirection to the profile page)...
    })
  );
}

Here we have two scenarios:

OK (1 request):

Go straight to the /login

Profile is fetched

No profile, you are on the login page already, so return true.

Not OK (2 requests):

Go to the /

Profile is fetched

No profile, you are not on the login page, so redirect to /login

Here guard is invoking one more time, so profile is fetched again.

No profile, you are on the login page already, so return true.

So, as you can see, two requests were invoked in the second scenario. I tried to multicast the service observable, but still have no success.

What should I do so only one request is invoked?

Body:
In your  guard have a profile property in class, it will be there because its a injectable and singleton guard troughout app.

Change your guard to :-

public profile;

canActivate(route, state) {
  const obs = this.profile ? of(this.profile): this.profileService.get();
  return obs.pipe(
    map(profile => {
      // I have to implement a not logged user
      if (!profile) {
        // No need to redirect
        if (alreadyOnLoginPage) {
          return true;
        } else {
          return this.router.createUrlTree(['/login']);
        }
      }
      // Some unnecessary logic here (redirection to the profile page)...
    })
  );
}


问:
Checking "rules" in Java without lots of if statements
I'm creating a springboot banking API and in order to create a transaction a bunch of "rules" have to be checked.

e.g:

Current logged in user can't withdraw money from another user's savings account

Amount can't be higher/lower than certain number

etc.

This causes my createTransaction method to contain a lot of if statements (12!). This is what my code looks like in pseudo:

```<code>public ResponseEntity<String> createTransaction(Transaction body) {
    if (check rule 1) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("...");
    }
    if (check rule 2) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("...");
    }
    // etc...

    // Transaction complies to set rules
    return ResponseEntity.status(HttpStatus.CREATED).body("Transaction successful!");
}
</code>```

I can post my actual code if necessary but I think this paints the picture without having anyone to read 100 lines of code.

Because I have around 12 if statements checking these rules, my function is quite lengthy and difficult to read/maintain.
Googling for a solution didn't bring up results I was looking for. I've tried implementing exceptions but this didn't remove the amount of if statements. Maybe a switch could improve a bit, but I'm wondering if there's a clean OOP solution.

My question is: How can I clean this code up (OOP style)?

Thanks in advance.

答:
You should create a TransactionRule interface that allows you to implement specific transaction rules, and then use a stream to get the final result:

public interface TransactionRule {
  public boolean isAllowed(Transaction someTransaction);
}
```

<p>Example implementation 1:</p>

<pre class="lang-java prettyprint-override"><code>public class SufficientBudgetTransactionRule implements TransactionRule {
  public boolean isAllowed(Transaction someTransaction) {
    // Custom logic e.g.
    return someTransaction.wallet.value >= someTransaction.transaction.value;
  }
}
</code>```

Example implementation 2:

public class NotInFutureTransactionRule implements TransactionRule {
  public boolean isAllowed(Transaction someTransaction) {
    // Custom logic e.g.
    return someTransaction.transaction.datetime.isBefore(OffsetDateTime.now());
  }
}
```

<p>Then, you can store all the <code>TransactionRules</code> in a <code>List</code> and check whether they all validate like so:</p>

```private final List<TransactionRule> transactionRules; // Fill these of course

public boolean allTransactionRulesMatch(Transaction someTransaction) {
  return transactionRules.stream()
    .map(transactionRule -> transactionRule.isAllowed(someTransaction))
    .allMatch(result => result);
}
```

Body:
I'm creating a springboot banking API and in order to create a transaction a bunch of "rules" have to be checked.

e.g:

Current logged in user can't withdraw money from another user's savings account

Amount can't be higher/lower than certain number

etc.

This causes my createTransaction method to contain a lot of if statements (12!). This is what my code looks like in pseudo:

public ResponseEntity<String> createTransaction(Transaction body) {
    if (check rule 1) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("...");
    }
    if (check rule 2) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("...");
    }
    // etc...

    // Transaction complies to set rules
    return ResponseEntity.status(HttpStatus.CREATED).body("Transaction successful!");
}

I can post my actual code if necessary but I think this paints the picture without having anyone to read 100 lines of code.

Because I have around 12 if statements checking these rules, my function is quite lengthy and difficult to read/maintain.
Googling for a solution didn't bring up results I was looking for. I've tried implementing exceptions but this didn't remove the amount of if statements. Maybe a switch could improve a bit, but I'm wondering if there's a clean OOP solution.

My question is: How can I clean this code up (OOP style)?

Thanks in advance.

Body:
You should create a TransactionRule interface that allows you to implement specific transaction rules, and then use a stream to get the final result:

public interface TransactionRule {
  public boolean isAllowed(Transaction someTransaction);
}

Example implementation 1:

public class SufficientBudgetTransactionRule implements TransactionRule {
  public boolean isAllowed(Transaction someTransaction) {
    // Custom logic e.g.
    return someTransaction.wallet.value >= someTransaction.transaction.value;
  }
}

Example implementation 2:

public class NotInFutureTransactionRule implements TransactionRule {
  public boolean isAllowed(Transaction someTransaction) {
    // Custom logic e.g.
    return someTransaction.transaction.datetime.isBefore(OffsetDateTime.now());
  }
}

Then, you can store all the TransactionRules in a List and check whether they all validate like so:

private final List<TransactionRule> transactionRules; // Fill these of course

public boolean allTransactionRulesMatch(Transaction someTransaction) {
  return transactionRules.stream()
    .map(transactionRule -> transactionRule.isAllowed(someTransaction))
    .allMatch(result => result);
}


问:
How to ref to multiple components inside map
I need to set ref to each project inside map function. I'm forwardingRef from child to my parent and currently I'm getting only single Project. I need to set refs to array list and then work with it. I tried something like this:

```<code>    const projectSectionItem = useRef([])
    ref={projectSectionItem => projectSectionItem[index] = projectSectionItem}
</code>```

PARENT:

```<code>  const projectSectionItem = useRef<HTMLDivElement>(null)

<StyledSection ref={projectSection}>
    {data.map((i, index) => {
        return i.showOnHP === 1 ?
            <Element name={index.toString()} key={index}>
                <Project
                    url={`${URL}${i.button_image.image}`}
                    client={i.client_name}
                    project={i.project.en}
                    btn_color={"#000"}
                    btn_text={i.button_text}
                    href={`/cases/${i.slug}`}
                    ref={projectSectionItem}
                >
                </Project>
            </Element>
            : null
    })}
</code>```

CHILD:

```<code>export const Project = React.forwardRef<HTMLDivElement, ProjectProps>((props, ref) => {
    return (
        <StyledProject className={props.className} ref={ref}>
        ...
        </StyledProject>
    )
</code>```

})

答:
Since you should not use hooks (useRef) in a loop or conditionally, you can just use createRef like this:

```<code>const pressureRefs = data.filter(item => item.showOnHP).map(() => React.createRef<HTMLDivElement>())
<Project ... ref={refs[i]} />
</code>```

Body:
I need to set ref to each project inside map function. I'm forwardingRef from child to my parent and currently I'm getting only single Project. I need to set refs to array list and then work with it. I tried something like this:

    const projectSectionItem = useRef([])
    ref={projectSectionItem => projectSectionItem[index] = projectSectionItem}

PARENT:

  const projectSectionItem = useRef<HTMLDivElement>(null)

    )

})

Body:
Since you should not use hooks (useRef) in a loop or conditionally, you can just use createRef like this:

const pressureRefs = data.filter(item => item.showOnHP).map(() => React.createRef<HTMLDivElement>())
<Project ... ref={refs[i]} />


问:
touchesMoved get all the coordinates swiping fast
I want to get all the coordinates in touchesMoved. The problem I am facing is when you swipe fast on my view than touchesMoved is missing few coordinates from the swipe.

I have referred this question too. touchesMoved:withEvent

Any solution for this ?

答:
I don't think it is possible to get missing coordinates.
Because calling interval of touchesMoved is not frequent enough to catch all fast movements.
Maybe you can draw a path between coordinates you can catch.
That gives you a rough approximation of missing points.</p>


问:
How to read multi-value library with for loop in python
Assume that CSV file has this content:

```<code>Main1,Name1,Name2,Name3,Name4
Main2,NameA,NameB
Main3,Name11,Name12,Name13
</code>```

When I read it as library result is following:

```<code>{'Main1': ['Name1', 'Name2', 'Name3', 'Name4'],
 'Main2': ['NameA', 'NameB'],
 'Main3': ['Name11', 'Name12', 'Name13']}
</code>```

When I turn to particular item/value like a['Main3'][2] I'll get answer 'Name13'.
But the values ('Name's') are unknown number and I would like to read them all individually in e.g. for loop. If I read like this:

```<code>for rows in a:
    print(rows)
</code>```

I will get answer:

```<code>Main1
Main2
Main3
</code>```

But I would like to modify code something like:

```<code>for rows in a:
    print(rows)
    for values in rows:
        print(values)
</code>```

But result is erroneous. I expect to see something like this:

```<code>'Main1'
    'Name1'
    'Name2'
    'Name3'
    'Name4'
'Main2'
    'NameA'
    'NameB'
'Main3'
    'Name11'
    'Name12'
    'Name13'
</code>```

And I cannot figure out how to modify my code. Would you please help me? Thanks!

答:
As you can see a is a dictionary. so you want each key and the values,
So, Try this:

```<code>for k,v in a.items():
    print(k, *v, sep='\n')
</code>```

Body:
Assume that CSV file has this content:

Main1,Name1,Name2,Name3,Name4
Main2,NameA,NameB
Main3,Name11,Name12,Name13

When I read it as library result is following:

{'Main1': ['Name1', 'Name2', 'Name3', 'Name4'],
 'Main2': ['NameA', 'NameB'],
 'Main3': ['Name11', 'Name12', 'Name13']}

When I turn to particular item/value like a['Main3'][2] I'll get answer 'Name13'.
But the values ('Name's') are unknown number and I would like to read them all individually in e.g. for loop. If I read like this:

for rows in a:
    print(rows)

I will get answer:

Main1
Main2
Main3

But I would like to modify code something like:

for rows in a:
    print(rows)
    for values in rows:
        print(values)

But result is erroneous. I expect to see something like this:

'Main1'
    'Name1'
    'Name2'
    'Name3'
    'Name4'
'Main2'
    'NameA'
    'NameB'
'Main3'
    'Name11'
    'Name12'
    'Name13'

And I cannot figure out how to modify my code. Would you please help me? Thanks!

Body:
As you can see a is a dictionary. so you want each key and the values,
So, Try this:

for k,v in a.items():
    print(k, *v, sep='\n')


问:
Partial String Match in R Data Table
I am trying to match a string (or list of strings) from an R Shiny drop-down menu (multiple values selected) with data in a specific column of a data-table.

Details:

var_to_plot() is the list of strings (or single string if only one value is selected) which is selected on the dropdown menu in the R Shiny UI. It returns e.g. Var1

The data in the rows in the df$Relevant_Column that I want it to match looks like e.g:

Test1_Var1, Test2_Var1, Test2_Var2

I want to filter on both Var1 and Var2.

Selecting only 1 works when using Grepl, in code below, but not two, as I get the warning: "Warning in grep(var_to_plot(), df$Relevant_Column) :
argument 'pattern' has length > 1 and only the first element will be used"

I.e. it only filters on the first string in the list, not all of them.

So I tried using sqldf, but with no success as seen below.

I have  tried the following:

Using Grepl (returns warning):

df[grepl(var_to_plot(), df$Relevant_Column), ]

Using SQLDF (returns empty DF as for some reason it wont match from the var_to_plot())

df = sqldf("SELECT * FROM df WHERE Relevant_Column LIKE '%var_to_plot()%'")

答:
You'll likely want to concatenate the search terms into a valid regex, by separating them with a vertical bar.</p>

```<code>df <- data.frame(
  rowid = 1:4,
  Relevant_Column = c("Test1_Var1", "Test2_Var1", "Test2_Var2", "Text3_Var3")
)

var_to_plot <- c("Var1", "Var2")

## Base R.
df[grepl(paste(var_to_plot, collapse = "|"), df$Relevant_Column), ]

## Tidyverse.
library("stringr")
library("dplyr")
filter(df, str_detect(Relevant_Column, str_c(var_to_plot, collapse = "|")))

## data.table
library("data.table")
DT <- as.data.table(df)
DT[grepl(paste(var_to_plot, collapse = "|"), Relevant_Column)]
</code>```

Title: Partial String Match in R Data Table

Body:
You'll likely want to concatenate the search terms into a valid regex, by separating them with a vertical bar.

df <- data.frame(
  rowid = 1:4,
  Relevant_Column = c("Test1_Var1", "Test2_Var1", "Test2_Var2", "Text3_Var3")
)

var_to_plot <- c("Var1", "Var2")

## Base R.
df[grepl(paste(var_to_plot, collapse = "|"), df$Relevant_Column), ]

## Tidyverse.
library("stringr")
library("dplyr")
filter(df, str_detect(Relevant_Column, str_c(var_to_plot, collapse = "|")))

## data.table
library("data.table")
DT <- as.data.table(df)
DT[grepl(paste(var_to_plot, collapse = "|"), Relevant_Column)]