问:
Flutter one time choice radio buttons
How can i make one time choice custom radio button like in the picture

答:
```<code>import 'package:flutter/material.dart';
class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
  }
   class _HomeScreenState extends State<HomeScreen> {
       int _selection = 0;

      selectTime(int timeSelected) {
       setState(() {
       _selection = timeSelected;
          });
         }

         @override
  Widget build(BuildContext context) {
    return SafeArea(
    child: Scaffold(
     appBar: AppBar(
      title: Text("Home"),
       ),

       body: Container(
      padding: EdgeInsets.all(30),
      child: Column(
        children: <Widget>[
          Row(
            children: <Widget>[
              InkWell(
                onTap: () {
                  setState(() {
                    _selection = 1;
                  });
                },
                child: Stack(
                  children: <Widget>[
                    Container(
                      height: 40,
                      width: 150,
                      color: _selection == 1 ? Colors.green : Colors.white,
                    ),
                    Row(
                      children: <Widget>[
                        Radio(
                          focusColor: Colors.white,
                          groupValue: _selection,
                          onChanged: selectTime,
                          value: 1,
                        ),
                        Text(
                          "11:00 - 12:00",
                          style: TextStyle(fontWeight: FontWeight.bold),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              InkWell(
                onTap: () {
                  setState(() {
                    _selection = 2;
                  });
                },
                child: Stack(
                  children: <Widget>[
                    Container(
                      height: 40,
                      width: 150,
                      color: _selection == 2 ? Colors.green : Colors.white,
                    ),
                    Row(
                      children: <Widget>[
                        Radio(
                          focusColor: Colors.white,
                          groupValue: _selection,
                          onChanged: selectTime,
                          value: 2,
                        ),
                        Text(
                          "12:00 - 13:00",
                          style: TextStyle(fontWeight: FontWeight.bold),
                        ),
                      ],
                    ),
                  ],
                ),
              )
            ],
          ),
        ],
      )),
));
</code>```

<p>}
}</p>

Title: Flutter one time choice radio buttons

Body:
import 'package:flutter/material.dart';
class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
  }
   class _HomeScreenState extends State<HomeScreen> {
       int _selection = 0;

      selectTime(int timeSelected) {
       setState(() {
       _selection = timeSelected;
          });
         }

         @override
  Widget build(BuildContext context) {
    return SafeArea(
    child: Scaffold(
     appBar: AppBar(
      title: Text("Home"),
       ),

       body: Container(
      padding: EdgeInsets.all(30),
      child: Column(
        children: <Widget>[
          Row(
            children: <Widget>[
              InkWell(
                onTap: () {
                  setState(() {
                    _selection = 1;
                  });
                },
                child: Stack(
                  children: <Widget>[
                    Container(
                      height: 40,
                      width: 150,
                      color: _selection == 1 ? Colors.green : Colors.white,
                    ),
                    Row(
                      children: <Widget>[
                        Radio(
                          focusColor: Colors.white,
                          groupValue: _selection,
                          onChanged: selectTime,
                          value: 1,
                        ),
                        Text(
                          "11:00 - 12:00",
                          style: TextStyle(fontWeight: FontWeight.bold),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              InkWell(
                onTap: () {
                  setState(() {
                    _selection = 2;
                  });
                },
                child: Stack(
                  children: <Widget>[
                    Container(
                      height: 40,
                      width: 150,
                      color: _selection == 2 ? Colors.green : Colors.white,
                    ),
                    Row(
                      children: <Widget>[
                        Radio(
                          focusColor: Colors.white,
                          groupValue: _selection,
                          onChanged: selectTime,
                          value: 2,
                        ),
                        Text(
                          "12:00 - 13:00",
                          style: TextStyle(fontWeight: FontWeight.bold),
                        ),
                      ],
                    ),
                  ],
                ),
              )
            ],
          ),
        ],
      )),
));

}
}


来源: stackexchange

问:
class name not working in button tag in react js
i'm trying to add style to button using classNamein react js. but it didn't work. it shows default style like below. can anyone help with this?

here is my code.

home.js

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

export class Home extends React.Component{
    constructor(props){
        super();
        this.age=props.age;

    }
    onMakeOlder(){
        this.age +=3;
        console.log(this.age);
    }
    render(){

        return (
            <div>
                <p>in a new component!</p>
                <p>your name is {this.props.name} , your age is {this.age}</p>

                <hr/>
                <button onClick={this.onMakeOlder.bind(this)} className="btn btn-primary">Make me older!</button>
            </div>
        );
    }
}

Home.propTypes={
    name: React.PropTypes.string,
    age: React.PropTypes.number
    /*user: React.PropTypes.object*/
};
</code>```

Edited

here is main page.

index.js

```<code>import React from "react";
import { render } from "react-dom";
import {Header} from "./components/Header";
import {Home} from "./components/Home";

class App extends React.Component {
    render() {
       /* var user={
            name:"Senarath",
            hobbies: ["games","sports"]
        };*/
        return (
         <div className="container">
            <div className="row">
                <div className="col-xs-10 col-xs-offset-1">
           <Header/>
        </div>
            </div>
                <div className="row">
                    <div className="col-xs-10 col-xs-offset-1">
                       <Home name={"Pasindu"} age={24}  />

                    </div>
                </div>
            </div>
        );
    }
}
render(<App/>,window.document.getElementById("app"));
</code>```

webpack.config.js

```<code>var webpack =require("webpack");
var path = require("path");

var DIST_DIR = path.resolve(__dirname, "dist");
var SRC_DIR = path.resolve(__dirname, "src");

var config = {
    entry: SRC_DIR + "/app/index.js",
    output: {
        path: DIST_DIR + "/app",
        filename: "bundle.js",
        publicPath: "/app/"
    },
    module: {
        loaders: [
            {
                test: /\.js?/,
                include: SRC_DIR,
                loader: "babel-loader",
                query: {
                    presets: ["react", "es2015", "stage-2"]
                }
            },
            {
                test: /\.css$/,
                loaders: ['style-loader', 'css-loader'],
            },
        ],
    }
};

module.exports = config;
</code>```

here is the error i get.

答:
You can easily grab the button via type. ClassName did not work for me, too.
The "type"-solution works excellent for me:

HTML:

```<code> <button type="no-margin">Button</button>
</code>```

CSS:

```<code>button,
[type="no-margin"] {
  margin: 0;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
i'm trying to add style to button using classNamein react js. but it didn't work. it shows default style like below. can anyone help with this?

here is my code.

home.js

import React from "react";

export class Home extends React.Component{
    constructor(props){
        super();
        this.age=props.age;

    }
    onMakeOlder(){
        this.age +=3;
        console.log(this.age);
    }
    render(){

        return (

in a new component!

your name is {this.props.name} , your age is {this.age}

                <button onClick={this.onMakeOlder.bind(this)} className="btn btn-primary">Make me older!</button>

        );
    }
}

Home.propTypes={
    name: React.PropTypes.string,
    age: React.PropTypes.number
    /*user: React.PropTypes.object*/
};

Edited

here is main page.

index.js

import React from "react";
import { render } from "react-dom";
import {Header} from "./components/Header";
import {Home} from "./components/Home";

class App extends React.Component {
    render() {
       /* var user={
            name:"Senarath",
            hobbies: ["games","sports"]
        };*/
        return (

                       <Home name={"Pasindu"} age={24}  />

        );
    }
}
render(<App/>,window.document.getElementById("app"));

webpack.config.js

var webpack =require("webpack");
var path = require("path");

var DIST_DIR = path.resolve(__dirname, "dist");
var SRC_DIR = path.resolve(__dirname, "src");

var config = {
    entry: SRC_DIR + "/app/index.js",
    output: {
        path: DIST_DIR + "/app",
        filename: "bundle.js",
        publicPath: "/app/"
    },
    module: {
        loaders: [
            {
                test: /\.js?/,
                include: SRC_DIR,
                loader: "babel-loader",
                query: {
                    presets: ["react", "es2015", "stage-2"]
                }
            },
            {
                test: /\.css$/,
                loaders: ['style-loader', 'css-loader'],
            },
        ],
    }
};

module.exports = config;

here is the error i get.

Body:
You can easily grab the button via type. ClassName did not work for me, too.
The "type"-solution works excellent for me:

HTML:

 <button type="no-margin">Button</button>

CSS:

button,
[type="no-margin"] {
  margin: 0;
}


问:
Julia - read UInt32 from UInt8 Array
I have UInt8 data array which I got from TCPSocket.

I want to read UInt32s and UInt16s from different indices.

For example:

```<code>data = UInt8[0xFF, 0x00, 0x00, 0x00, 0xAA, 0x00]

// Something like this:
extracted_UInt32 = data.readUInt32(1) # [1-4]
extracted_UInt16 = data.readUInt16(5) # [5-6]
</code>```

It is exactly like Node.js's Buffer.readUInt16LE(offset): https://nodejs.org/api/buffer.html#buffer_buf_readint16le_offset

Thanks!

答:
You can read the data as a given type from the buffer:

```<code>julia> data = IOBuffer(UInt8[0xFF, 0x00, 0x00, 0x00, 0xAA, 0x00]);

julia> a = read(data, UInt32)
0x000000ff

julia> b = read(data, UInt16)
0x00aa
</code>```

You can probably do this from the TCP socket directly without materializing as a vector of bytes.

Title: Julia - read UInt32 from UInt8 Array

Body:
I have UInt8 data array which I got from TCPSocket.

I want to read UInt32s and UInt16s from different indices.

For example:

data = UInt8[0xFF, 0x00, 0x00, 0x00, 0xAA, 0x00]

// Something like this:
extracted_UInt32 = data.readUInt32(1) # [1-4]
extracted_UInt16 = data.readUInt16(5) # [5-6]

It is exactly like Node.js's Buffer.readUInt16LE(offset): https://nodejs.org/api/buffer.html#buffer_buf_readint16le_offset

Thanks!

Body:
You can read the data as a given type from the buffer:

julia> data = IOBuffer(UInt8[0xFF, 0x00, 0x00, 0x00, 0xAA, 0x00]);

julia> a = read(data, UInt32)
0x000000ff

julia> b = read(data, UInt16)
0x00aa

You can probably do this from the TCP socket directly without materializing as a vector of bytes.


问:
Getting flake8 returned a non none zero code : 1 in docker
I was following this article.
https://testdriven.io/blog/dockerizing-django-with-postgres-gunicorn-and-nginx/#production-dockerfile

In the Production Dockerfile section, the Dockerfile.prod file has these lines.

```<code># lint
RUN pip install --upgrade pip
RUN pip install flake8
COPY . /usr/src/app/
RUN flake8 --ignore=E501,F401 .
</code>```

When I run the below command,

```<code>docker-compose -f docker-compose.prod.yml up -d --build
</code>```

I'm getting the below error.

```<code>ERROR: Service 'web' failed to build: The command '/bin/sh -c flake8 --ignore=E501,F401' returned a non-zero code: 1
</code>```

I'm not much aware of flake8, When I commented the 'RUN flake8 --ignore=E501,F401 .' line from the Dockerfile.prod file everything worked.

Can anyone please tell me why I'm facing this issue and tell me a fix instead of removing that line from the Dockerfile. I'm not much aware of flak8 and I'm quite new to Docker too and your help will be much appreciated :)

Thanks.

答:
It might be a good idea to only let the code linting happen within your Django App folder. So if you followed the tutorial without alterations, you may want to replace this line:

```<code>RUN flake8 --ignore=E501,F401 .
</code>```

with your Django project code...

```<code>RUN flake8 --ignore=E501,F401 ./hello_django
</code>```

Otherwise, there's probably a lot of stuff that gets checked by flake8 that you don't want checked.

Body:
I was following this article.
https://testdriven.io/blog/dockerizing-django-with-postgres-gunicorn-and-nginx/#production-dockerfile

In the Production Dockerfile section, the Dockerfile.prod file has these lines.

# lint
RUN pip install --upgrade pip
RUN pip install flake8
COPY . /usr/src/app/
RUN flake8 --ignore=E501,F401 .

When I run the below command,

docker-compose -f docker-compose.prod.yml up -d --build

I'm getting the below error.

ERROR: Service 'web' failed to build: The command '/bin/sh -c flake8 --ignore=E501,F401' returned a non-zero code: 1

I'm not much aware of flake8, When I commented the 'RUN flake8 --ignore=E501,F401 .' line from the Dockerfile.prod file everything worked.

Can anyone please tell me why I'm facing this issue and tell me a fix instead of removing that line from the Dockerfile. I'm not much aware of flak8 and I'm quite new to Docker too and your help will be much appreciated :)

Thanks.

Body:
It might be a good idea to only let the code linting happen within your Django App folder. So if you followed the tutorial without alterations, you may want to replace this line:

RUN flake8 --ignore=E501,F401 .

with your Django project code...

RUN flake8 --ignore=E501,F401 ./hello_django

Otherwise, there's probably a lot of stuff that gets checked by flake8 that you don't want checked.


问:
How to add command line parameter to pytest command
I cannot find how to add named command line  parameter to pytest command, so I can execute tests with custom parameter available as a fixture.

pytest --my-parameter

```<code>def test_something(my_parameter):
    ...
</code>```

答:
In order to accomplish such behaviour the pytest_addoption shall be defined and new session level fixture in combination  with pytestconfig fixture shall be used</p>

```<code># conftest.py
import pytest

def pytest_addoption(parser):
    parser.addoption(
        "--my-parameter", action="store", default=None,
        help=("Parameter description")
    )

@pytest.fixture(scope='session')
def my_parameter(pytestconfig):
    """ Description of changes triggered by parameter. """
    param = pytestconfig.getoption("--my-parameter")
    if param is None:
        assert False, '--my-parameter parameter must be supplied in order to run test suite.'
    return param

# tests.py:
import pytest

def test_something(my_parameter):
    ...
</code>```

Body:
I cannot find how to add named command line  parameter to pytest command, so I can execute tests with custom parameter available as a fixture.

pytest --my-parameter

def test_something(my_parameter):
    ...

Body:
In order to accomplish such behaviour the pytest_addoption shall be defined and new session level fixture in combination  with pytestconfig fixture shall be used

# conftest.py
import pytest

def pytest_addoption(parser):
    parser.addoption(
        "--my-parameter", action="store", default=None,
        help=("Parameter description")
    )

@pytest.fixture(scope='session')
def my_parameter(pytestconfig):
    """ Description of changes triggered by parameter. """
    param = pytestconfig.getoption("--my-parameter")
    if param is None:
        assert False, '--my-parameter parameter must be supplied in order to run test suite.'
    return param

# tests.py:
import pytest

def test_something(my_parameter):
    ...


问:
How execute bat from mac? Is it possible to rewrite it to python or bash script?
I have a problem with .bat file. There is a .bat file that starts the server. But on a Mac OS system, this is impossible. Are there any options to rewrite it to python or bash so that it would be possible to start from MacBook?

This is .bat file:

```<code>echo start web server..
start cmd /k node webServer.js
echo start chrome..
start chrome.exe /k http://localhost:8080
</code>```

Thanks for helping!

答:
Here's a Python example that is cross-platform (unless you don't have node in PATH) and using only the standard library:

```<code># client.py

import subprocess
import webbrowser

if __name__ == '__main__':
    try:
        server_proc = subprocess.Popen(['node', 'webServer.js'])
        webbrowser.open('http://localhost:8080')
        server_proc.communicate()
    except KeyboardInterrupt:
        server_proc.terminate()
</code>```

Note, however, that webbrowser.open will open the browser that is set as default, so it could be Safari or whatever. If you want to specifically open Chrome, you will have to pass the full path to the executable (or modify your PATH env var). Example:

```<code># client.py

import os
import subprocess

if __name__ == '__main__':
    try:
        server_proc = subprocess.Popen(['node', 'webServer.js'])
        chrome_exe = os.path.join('/', 'Applications', 'Google Chrome.app', 'Contents', 'MacOS', 'Google Chrome')
        subprocess.Popen([chrome_exe, 'http://localhost:8080'])
        server_proc.communicate()
    except KeyboardInterrupt:
        server_proc.terminate()
</code>```

Body:
I have a problem with .bat file. There is a .bat file that starts the server. But on a Mac OS system, this is impossible. Are there any options to rewrite it to python or bash so that it would be possible to start from MacBook?

This is .bat file:

echo start web server..
start cmd /k node webServer.js
echo start chrome..
start chrome.exe /k http://localhost:8080

Thanks for helping!

Body:
Here's a Python example that is cross-platform (unless you don't have node in PATH) and using only the standard library:

# client.py

import subprocess
import webbrowser

if __name__ == '__main__':
    try:
        server_proc = subprocess.Popen(['node', 'webServer.js'])
        webbrowser.open('http://localhost:8080')
        server_proc.communicate()
    except KeyboardInterrupt:
        server_proc.terminate()

Note, however, that webbrowser.open will open the browser that is set as default, so it could be Safari or whatever. If you want to specifically open Chrome, you will have to pass the full path to the executable (or modify your PATH env var). Example:

# client.py

import os
import subprocess

if __name__ == '__main__':
    try:
        server_proc = subprocess.Popen(['node', 'webServer.js'])
        chrome_exe = os.path.join('/', 'Applications', 'Google Chrome.app', 'Contents', 'MacOS', 'Google Chrome')
        subprocess.Popen([chrome_exe, 'http://localhost:8080'])
        server_proc.communicate()
    except KeyboardInterrupt:
        server_proc.terminate()


问:
Blackberry trackball click, instead of responding to event, context menu is shown why?
I'm running into the following scenario on some devices: when the use clicks on field and expects an response, instead of properly responding to that click event, the device shows the context menu at the bottom center of the screen.

navigationUnclick and trackwheelUnclick

From what I've read, I can override navigationUnclick and trackwheelUnclick to prevent the menu from showing. I'm doing this as the screen level but reproducing the centered-menu scenario is difficult. Is this the correct approch?

Why does this happen? Is there any way to resolve this?

答: You could use CONSUME_CLICK style on all Fields in your MainScreen...</p>

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
How to know if my next call to printf() will exceed screen size
I am writing a program in C and my question is pretty straightforward: How to know if my next call to printf() will exceed screen size?

That is, sometimes when you use print, the text may not fit in one screen. E.g. I have 4-5 strings to print and I would like to create a function that prints the entire text or prints until the text is cut off due to the screen size.

答:
You can use snprintf to write into a string buffer and then write this buffer to the actual console output. Since it seems that you cannot control the number of characters you want to write, I suggest to use int snprintf( char* buffer, std::size_t buf_size, const char* format, ... ). It allows you to limit the number of characters to be written to avoid buffer overflows:

```<code>char buffer[80+1];  // maximum length of a complete line.
snprintf(buffer, sizeof(buffer), "my output: %d, %s", someInt, someString);
if (strlen(buffer) >= nrOfCharsLeftInLine) {
   buffer[nrOfCharsLeftInLine] = 0x0;
}
printf("%s",buffer);
</code>```

Body:
You can use snprintf to write into a string buffer and then write this buffer to the actual console output. Since it seems that you cannot control the number of characters you want to write, I suggest to use int snprintf( char* buffer, std::size_t buf_size, const char* format, ... ). It allows you to limit the number of characters to be written to avoid buffer overflows:

char buffer[80+1];  // maximum length of a complete line.
snprintf(buffer, sizeof(buffer), "my output: %d, %s", someInt, someString);
if (strlen(buffer) >= nrOfCharsLeftInLine) {
   buffer[nrOfCharsLeftInLine] = 0x0;
}
printf("%s",buffer);


问:
Authentication failed when using flask_pymongo
I'm sure that the MONGO_URI is correct because it works well in pymongo.
but when using flask_pymongo, it doesn't work...
here is my test code:

```<code>from flask import Flask
from flask_pymongo import PyMongo
app = Flask(__name__)

app.config['MONGO_URI'] ='mongodb://root:aaa2016@localhost:27017/mongo_test'
mongo = PyMongo(app, config_prefix='MONGO')

@app.route('/')
def hello_world():
    mongo.db.user.insert({'username': "aaa"})
    return 'Hello World!'

if __name__ == '__main__':
    app.run()
</code>```

run it and visit 127.0.0.1:5000, a response of 500 is given..

```<code>OperationFailure: Authentication failed.
127.0.0.1 - - [21/Jun/2016 20:40:25] "GET / HTTP/1.1" 500 -
</code>```

any help will be appreciated.

update:
here is the traceback:

```<code>File "C:\Python27\lib\site-packages\flask\app.py", line 2000, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Python27\lib\site-packages\flask\app.py", line 1991, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "C:\Python27\lib\site-packages\flask\app.py", line 1567, in       handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Python27\lib\site-packages\flask\app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line 1641, in  full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python27\lib\site-packages\flask\app.py", line 1544, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Python27\lib\site-packages\flask\app.py", line 1639, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line 1625, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "F:\PycharmProjects\flask_\flask_.py", line 12, in hello_world
mongo.db.user.insert({'username': "aaa"})
File "C:\Python27\lib\site-packages\pymongo\collection.py", line 2203, in insert
with self._socket_for_writes() as sock_info:
File "C:\Python27\lib\contextlib.py", line 17, in __enter__
return self.gen.next()
File "C:\Python27\lib\site-packages\pymongo\mongo_client.py", line 718, in _get_socket
with server.get_socket(self.__all_credentials) as sock_info:
File "C:\Python27\lib\contextlib.py", line 17, in __enter__
return self.gen.next()
File "C:\Python27\lib\site-packages\pymongo\server.py", line 152, in get_socket
with self.pool.get_socket(all_credentials, checkout) as sock_info:
File "C:\Python27\lib\contextlib.py", line 17, in __enter__
return self.gen.next()
File "C:\Python27\lib\site-packages\pymongo\pool.py", line 541, in get_socket
sock_info.check_auth(all_credentials)
File "C:\Python27\lib\site-packages\pymongo\pool.py", line 306, in  check_auth
auth.authenticate(credentials, self)
File "C:\Python27\lib\site-packages\pymongo\auth.py", line 436, in authenticate
auth_func(credentials, sock_info)
File "C:\Python27\lib\site-packages\pymongo\auth.py", line 416, in _authenticate_default
return _authenticate_scram_sha1(credentials, sock_info)
File "C:\Python27\lib\site-packages\pymongo\auth.py", line 188, in _authenticate_scram_sha1
res = sock_info.command(source, cmd)
File "C:\Python27\lib\site-packages\pymongo\pool.py", line 213, in command
read_concern)
File "C:\Python27\lib\site-packages\pymongo\network.py", line 99, in command
helpers._check_command_response(response_doc, None, allowable_errors)
File "C:\Python27\lib\site-packages\pymongo\helpers.py", line 196, in _check_command_response
raise OperationFailure(msg % errmsg, code, response)
OperationFailure: Authentication failed.
</code>```

答:
If you are using Flask-MongoEngine and setting mongo config  using app.config['MONGODB_*'] then, your uri will be generated from those variables e.g.

```<code>app.config['MONGODB_DB'] = 'project1'
app.config['MONGODB_HOST'] = '192.168.1.35'
app.config['MONGODB_PORT'] = 12345
app.config['MONGODB_USERNAME'] = 'webapp'
app.config['MONGODB_PASSWORD'] = 'pwd123'
</code>```

However, if you need to add some additional paramters (such query parameter authSource=admin) to uri then, you will have to pass mongo config through app.config['MONGODB_SETTINGS']

```<code>app.config['MONGODB_SETTINGS'] = {
    'connect': False,
    'host': 'mongodb://webapp:pwd123@192.168.1.35:12345/project1?authSource=admin'
}
</code>```

Body:
I'm sure that the MONGO_URI is correct because it works well in pymongo.
but when using flask_pymongo, it doesn't work...
here is my test code:

from flask import Flask
from flask_pymongo import PyMongo
app = Flask(__name__)

app.config['MONGO_URI'] ='mongodb://root:aaa2016@localhost:27017/mongo_test'
mongo = PyMongo(app, config_prefix='MONGO')

@app.route('/')
def hello_world():
    mongo.db.user.insert({'username': "aaa"})
    return 'Hello World!'

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

run it and visit 127.0.0.1:5000, a response of 500 is given..

OperationFailure: Authentication failed.
127.0.0.1 - - [21/Jun/2016 20:40:25] "GET / HTTP/1.1" 500 -

any help will be appreciated.

update:
here is the traceback:

File "C:\Python27\lib\site-packages\flask\app.py", line 2000, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Python27\lib\site-packages\flask\app.py", line 1991, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "C:\Python27\lib\site-packages\flask\app.py", line 1567, in       handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Python27\lib\site-packages\flask\app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line 1641, in  full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python27\lib\site-packages\flask\app.py", line 1544, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Python27\lib\site-packages\flask\app.py", line 1639, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line 1625, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "F:\PycharmProjects\flask_\flask_.py", line 12, in hello_world
mongo.db.user.insert({'username': "aaa"})
File "C:\Python27\lib\site-packages\pymongo\collection.py", line 2203, in insert
with self._socket_for_writes() as sock_info:
File "C:\Python27\lib\contextlib.py", line 17, in __enter__
return self.gen.next()
File "C:\Python27\lib\site-packages\pymongo\mongo_client.py", line 718, in _get_socket
with server.get_socket(self.__all_credentials) as sock_info:
File "C:\Python27\lib\contextlib.py", line 17, in __enter__
return self.gen.next()
File "C:\Python27\lib\site-packages\pymongo\server.py", line 152, in get_socket
with self.pool.get_socket(all_credentials, checkout) as sock_info:
File "C:\Python27\lib\contextlib.py", line 17, in __enter__
return self.gen.next()
File "C:\Python27\lib\site-packages\pymongo\pool.py", line 541, in get_socket
sock_info.check_auth(all_credentials)
File "C:\Python27\lib\site-packages\pymongo\pool.py", line 306, in  check_auth
auth.authenticate(credentials, self)
File "C:\Python27\lib\site-packages\pymongo\auth.py", line 436, in authenticate
auth_func(credentials, sock_info)
File "C:\Python27\lib\site-packages\pymongo\auth.py", line 416, in _authenticate_default
return _authenticate_scram_sha1(credentials, sock_info)
File "C:\Python27\lib\site-packages\pymongo\auth.py", line 188, in _authenticate_scram_sha1
res = sock_info.command(source, cmd)
File "C:\Python27\lib\site-packages\pymongo\pool.py", line 213, in command
read_concern)
File "C:\Python27\lib\site-packages\pymongo\network.py", line 99, in command
helpers._check_command_response(response_doc, None, allowable_errors)
File "C:\Python27\lib\site-packages\pymongo\helpers.py", line 196, in _check_command_response
raise OperationFailure(msg % errmsg, code, response)
OperationFailure: Authentication failed.

Body:
If you are using Flask-MongoEngine and setting mongo config  using app.config['MONGODB_*'] then, your uri will be generated from those variables e.g.

app.config['MONGODB_DB'] = 'project1'
app.config['MONGODB_HOST'] = '192.168.1.35'
app.config['MONGODB_PORT'] = 12345
app.config['MONGODB_USERNAME'] = 'webapp'
app.config['MONGODB_PASSWORD'] = 'pwd123'

However, if you need to add some additional paramters (such query parameter authSource=admin) to uri then, you will have to pass mongo config through app.config['MONGODB_SETTINGS']

app.config['MONGODB_SETTINGS'] = {
    'connect': False,
    'host': 'mongodb://webapp:pwd123@192.168.1.35:12345/project1?authSource=admin'
}


问:
How to change background image in js file but not hard coding url
I cannot figure out why I can't change background images when I use onmouseover events. My goal is when I put mouse over first pic, then this pic will show up on the top of page, when I move my mouse to another pic, then this new pic will show up on the top instead, then when I move mouse to the third pic, the third pic will show up on the top. Here I attached my html code and js code. Please help me.

function upDate(previewPic){
    // document.getElementById("image").style.backgroundColor = "green";
    document.getElementById("image").style.backgroundColor = "url(previewPic.src)";
    document.getElementById("image").innerHTML = previewPic.alt + ".  this is onmouseover events";
}

function unDo(){
    document.getElementById("image").style.backgroundColor = "#8e68ff";
    document.getElementById("image").innerHTML = "Hover over an image below to display here.";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id = "image">
    Hover over an image below to display here.
</div>

<img class = "preview"
     alt = "Styling with a Bandana"
     src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon.jpg"
     onmouseover = "upDate(this)"
     onmouseout = "unDo()">

<img class = "preview"
     alt = "With My Boy"
     src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon2.JPG"
     onmouseover = "upDate(this)"
     onmouseout = "unDo()">

<img class = "preview"
     src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon3.jpg"
     alt = "Young Puppy"
     onmouseover = "upDate(this)"
     onmouseout = "unDo()"></code>```

答:
'previewPic.src' seems to be a variable that has been used as a string. You should replace this piece of code

```<code>document.getElementById("image").style.backgroundColor = "url(previewPic.src)";
</code>```

with

```<code>document.getElementById("image").style. backgroundImage = "url('"+previewPic.src+"')";
</code>```

Body:
I cannot figure out why I can't change background images when I use onmouseover events. My goal is when I put mouse over first pic, then this pic will show up on the top of page, when I move my mouse to another pic, then this new pic will show up on the top instead, then when I move mouse to the third pic, the third pic will show up on the top. Here I attached my html code and js code. Please help me.

function upDate(previewPic){
    // document.getElementById("image").style.backgroundColor = "green";
    document.getElementById("image").style.backgroundColor = "url(previewPic.src)";
    document.getElementById("image").innerHTML = previewPic.alt + ".  this is onmouseover events";
}

function unDo(){
    document.getElementById("image").style.backgroundColor = "#8e68ff";
    document.getElementById("image").innerHTML = "Hover over an image below to display here.";
}

    Hover over an image below to display here.

Body:
'previewPic.src' seems to be a variable that has been used as a string. You should replace this piece of code

document.getElementById("image").style.backgroundColor = "url(previewPic.src)";

with

document.getElementById("image").style. backgroundImage = "url('"+previewPic.src+"')";


问:
Apollo-client State management cache is not updating automatically after save and delete operation
I am using apollo-client for graphql calls along with I added state management with in the package apollo-client. In graphql module, assigned InMemoryCache to cache variable and client variable is exported.Client variable is imported in component so data is available in client.cache.data after default get call executed but I want to update client cache after save and delete graphql operations success callbacks

Here is my graphql.module.ts:

```<code>    import {NgModule} from '@angular/core';
    import {ApolloModule, APOLLO_OPTIONS} from 'apollo-angular';
    import { ApolloClient } from 'apollo-client';
    import {InMemoryCache} from 'apollo-cache-inmemory';
    import { HttpLink } from 'apollo-link-http';

    const cache = new InMemoryCache();
    const link = new HttpLink({
        uri:'https://api.graph.cool/simple/v1/ciyz901en4j590185wkmexyex'
    });

    export var client = new ApolloClient({
      cache,
      link
    });
 @NgModule({
 })
</code>```

and my service call implementation

```<code>client
      .query({
        query: gql`
        {
          fORoomTypes()
          {
            nodes
            {
              roomTypeId
              roomType
              ratSingle
              ratDouble
              ratExtra
              statu
            }
          }
        }
      `,
      })
      .then(result => {
        callback(result);
      });
</code>```

after callback  client.cache.data contain data, I want to call this data with cache queries and I want to  update cache automatically
this is my save service implementation

```<code>  const post = gql`
      mutation
      {
        saveRtype(rt:
          {
            rty:
            {
              rt:"Club room"
              rat:4000
              cchub:4500
              ext:800
              statu:1
            }
            traCheck:1
          }
          )
      }
    `
    client.mutate({
      mutation: post
    }).then((data) => {
      callback(data)
    });
</code>```

答:
I've only used apollo client with React but hopefully can shed light on how it works. For this to happen "automatically", you either need to call refetchQueries to refetch fORoomTypes after the mutation, or manually update the cache. I noticed your responses do not return an id property, so how would it know which one to update? If there is an identifier that isn't called "id", then register it following this documentation.

Here is the link to documentation in general for what you want

https://www.apollographql.com/docs/angular/features/cache-updates/

Body:
I am using apollo-client for graphql calls along with I added state management with in the package apollo-client. In graphql module, assigned InMemoryCache to cache variable and client variable is exported.Client variable is imported in component so data is available in client.cache.data after default get call executed but I want to update client cache after save and delete graphql operations success callbacks

Here is my graphql.module.ts:

    import {NgModule} from '@angular/core';
    import {ApolloModule, APOLLO_OPTIONS} from 'apollo-angular';
    import { ApolloClient } from 'apollo-client';
    import {InMemoryCache} from 'apollo-cache-inmemory';
    import { HttpLink } from 'apollo-link-http';

    const cache = new InMemoryCache();
    const link = new HttpLink({
        uri:'https://api.graph.cool/simple/v1/ciyz901en4j590185wkmexyex'
    });

    export var client = new ApolloClient({
      cache,
      link
    });
 @NgModule({
 })

and my service call implementation

client
      .query({
        query: gql`
        {
          fORoomTypes()
          {
            nodes
            {
              roomTypeId
              roomType
              ratSingle
              ratDouble
              ratExtra
              statu
            }
          }
        }
      `,
      })
      .then(result => {
        callback(result);
      });

after callback  client.cache.data contain data, I want to call this data with cache queries and I want to  update cache automatically
this is my save service implementation

  const post = gql`
      mutation
      {
        saveRtype(rt:
          {
            rty:
            {
              rt:"Club room"
              rat:4000
              cchub:4500
              ext:800
              statu:1
            }
            traCheck:1
          }
          )
      }
    `
    client.mutate({
      mutation: post
    }).then((data) => {
      callback(data)
    });


问:
Using MultiDataTrigger to test for 0 and a boolean in TextBox which has StringFormat in XAML
I have a TextBox bound to a decimal value which I want to format to not display decimal values if they are zero. At the same time I want to change the Background to a color if the property value is zero and another boolean property is true.

I have managed to achieve both but not together. If I remove the StringFormat from the Text Binding below the Background works perfectly but a value of, for example, 10 is displayed as 10.00, which I don't want. With the StringFormat the Background is not set and the TextBox is empty when 0 and suppresses decimals if they are zero, as required (empty string for zero is acceptable). So I assume it has to do with the empty string. I did try to test for an empty string with Path=Text.IsEmpty and value="True" as suggested in another post but that gives a design time error that Property IsEmpty is not found on type String.

This is what I have so far:

```<code>    <TextBox x:Name="FactorValueTextBox" Text="{Binding Value, StringFormat={}{0:# ###.##}}" IsReadOnly="{Binding CommodityGradingFactor.Total}" GotKeyboardFocus="GradeFactorGotKeyboardFocus">
    <TextBox.Style>
        <Style TargetType="TextBox">
            <Style.Triggers>
                <MultiDataTrigger>
                    <MultiDataTrigger.Conditions>
                        <Condition Binding="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Text}" Value="0"/>
                        <Condition Binding="{Binding CommodityGradingFactor.Manditory}" Value="True"/>
                    </MultiDataTrigger.Conditions>
                    <Setter Property="Background" Value="LightPink"/>
                </MultiDataTrigger>
                <MultiTrigger>
                    <MultiTrigger.Conditions>
                        <Condition Property="IsMouseOver" Value="True"/>
                        <Condition Property="IsReadOnly" Value="False"/>
                    </MultiTrigger.Conditions>
                    <Setter Property="FontSize" Value="15"/>
                    <Setter Property="FontWeight" Value="Bold"/>
                </MultiTrigger>
            </Style.Triggers>
        </Style>
    </TextBox.Style>
</TextBox>
</code>```

For completeness the GotKeyboardFocus() function simply selects the current value when the user tabs into the TextBox:

```<code>private void GradeFactorGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    if (e.KeyboardDevice.IsKeyDown(Key.Tab))
        ((TextBox)sender).SelectAll();
}
</code>```

答:
Instead of binding the condition to the property Text

```<code><Condition Binding="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Text}" Value="0"/>
</code>```

Why not binding it to the property Value

```<code><Condition Binding="{Binding Value}" Value="0"/>
</code>```

Note:

Depending on your use case, you may want to implement INotifyPropertyChanged  on your Value property, avoid naming your backfield property as "value" since it is a Contextual keywords
 for INotifyPropertyChanged case.

Body:
I have a TextBox bound to a decimal value which I want to format to not display decimal values if they are zero. At the same time I want to change the Background to a color if the property value is zero and another boolean property is true.

I have managed to achieve both but not together. If I remove the StringFormat from the Text Binding below the Background works perfectly but a value of, for example, 10 is displayed as 10.00, which I don't want. With the StringFormat the Background is not set and the TextBox is empty when 0 and suppresses decimals if they are zero, as required (empty string for zero is acceptable). So I assume it has to do with the empty string. I did try to test for an empty string with Path=Text.IsEmpty and value="True" as suggested in another post but that gives a design time error that Property IsEmpty is not found on type String.

This is what I have so far:

    <TextBox x:Name="FactorValueTextBox" Text="{Binding Value, StringFormat={}{0:# ###.##}}" IsReadOnly="{Binding CommodityGradingFactor.Total}" GotKeyboardFocus="GradeFactorGotKeyboardFocus">
    <TextBox.Style>

        </Style>
    </TextBox.Style>
</TextBox>

For completeness the GotKeyboardFocus() function simply selects the current value when the user tabs into the TextBox:

private void GradeFactorGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    if (e.KeyboardDevice.IsKeyDown(Key.Tab))
        ((TextBox)sender).SelectAll();
}

Body:
Instead of binding the condition to the property Text

<Condition Binding="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Text}" Value="0"/>

Why not binding it to the property Value

<Condition Binding="{Binding Value}" Value="0"/>

Note:

Depending on your use case, you may want to implement INotifyPropertyChanged  on your Value property, avoid naming your backfield property as "value" since it is a Contextual keywords
 for INotifyPropertyChanged case.


问:
Can I determine `IsDevelopment` from `IWebJobsBuilder`
Very much an XY problem, but I'm interested in the underlying answer too.
See bottom for XY context.

I'm in a .NET Core 3 AzureFunctions (v3) App project.
This code makes my question fairly clear, I think:

namespace MyProj.Functions
{
    internal class CustomStartup : IWebJobsStartup
    {
        public void Configure(IWebJobsBuilder builder)
        {
            var isDevelopment = true; //Can I correctly populate this, such that it's true only for local Dev?
            if(isDevelopment)
            {
                // Do stuff I wouldn't want to do in Prod, or on CI...
            }
        }
    }
}
```

XY Context:

I have set up Swagger/Swashbuckle for my Function, and ideally I want it to auto-open the swagger page when I start the Function, locally.

On an API project this is trivial to do in Project Properties, but a Functions csproj doesn't have the option to start a web page "onDebug"; that whole page of project Properties is greyed out.

The above is the context in which I'm calling builder.AddSwashBuckle(Assembly.GetExecutingAssembly()); and I've added a call to  Diagnostics.Process to start a webpage during Startup. This works just fine for me.
I've currently got that behind a [Conditional("DEBUG")] flag, but I'd like it to be more constrained if possible. Definitely open to other solutions, but I haven't been able to find any so ...

答:
While I am not completely sure that it is possible in azure functions I think that setting the ASPNETCORE_ENVIRONMENT application setting as described in https://learn.microsoft.com/en-us/azure/azure-functions/functions-how-to-use-azure-function-app-settings should allow you to get whether the environment is set as production or development by injecting a IHostEnvironment dependency and checking

```<code>.IsDevelopment()
</code>```

on the injected dependency.

Body:
Very much an XY problem, but I'm interested in the underlying answer too.
See bottom for XY context.

I'm in a .NET Core 3 AzureFunctions (v3) App project.
This code makes my question fairly clear, I think:

namespace MyProj.Functions
{
    internal class CustomStartup : IWebJobsStartup
    {
        public void Configure(IWebJobsBuilder builder)
        {
            var isDevelopment = true; //Can I correctly populate this, such that it's true only for local Dev?
            if(isDevelopment)
            {
                // Do stuff I wouldn't want to do in Prod, or on CI...
            }
        }
    }
}

XY Context:

I have set up Swagger/Swashbuckle for my Function, and ideally I want it to auto-open the swagger page when I start the Function, locally.

On an API project this is trivial to do in Project Properties, but a Functions csproj doesn't have the option to start a web page "onDebug"; that whole page of project Properties is greyed out.

The above is the context in which I'm calling builder.AddSwashBuckle(Assembly.GetExecutingAssembly()); and I've added a call to  Diagnostics.Process to start a webpage during Startup. This works just fine for me.
I've currently got that behind a [Conditional("DEBUG")] flag, but I'd like it to be more constrained if possible. Definitely open to other solutions, but I haven't been able to find any so ...

Body:
While I am not completely sure that it is possible in azure functions I think that setting the ASPNETCORE_ENVIRONMENT application setting as described in https://learn.microsoft.com/en-us/azure/azure-functions/functions-how-to-use-azure-function-app-settings should allow you to get whether the environment is set as production or development by injecting a IHostEnvironment dependency and checking

.IsDevelopment()

on the injected dependency.


问:
MSSQL Sql tuning advisor - in mysql
In Microsoft SQL Server; there is a 'SQL Tuning Advisor' where you can feed it a query and it will analyze it and offer you suggestions on indexing. Is there something like this for mysql that I can use from phpmyadmin?</p>

答:
MySQL has a query profiler, see this article: http://dev.mysql.com/tech-resources/articles/using-new-query-profiler.html

And dbForge has graphical front end for that, see: http://www.devart.com/dbforge/mysql/studio/features.html#profiler

I don't think there's any tool that will suggest indexes unless you count the code monkeys at SO.

Title: MSSQL Sql tuning advisor - in mysql


问:
MS-ACCESS / SQL - How to apply where clause in multiple conditions
```<code>SELECT Stock.*
FROM Stock
WHERE (
(
(Stock.ComputerPartNumber) In (SELECT [ComputerPartNumber] FROM [Stock] As Tmp GROUP BY [ComputerPartNumber] HAVING Count(*)=2)
)
AND
(
(Stock.EquipmentName)="EquipmentA" Or (Stock.EquipmentName)="EquipmentB")
)
OR (
(
(Stock.ComputerPartNumber) In (SELECT [ComputerPartNumber] FROM [Stock] As Tmp GROUP BY [ComputerPartNumber] HAVING Count(*)=1)
)
AND (
(Stock.EquipmentName)="EquipmentA" Or (Stock.EquipmentName)="EquipmentB"
)
);
</code>```

I am using the above SQL to achieve below 3 items:-

Find out all of the ComputerPartNumber which used by EquipmentA and/or EquipmentB only

Filter out the query result if the ComputerPartNumber used by equipment other than EquipmentA and EquipmentB.

If the ComputerPartNumber is used by both EquipmentA and EquipmentC, filter out the result also.

However the item 3 cannot be filtered out successfully. What should I do in order to achieve the item3?
Table and Query snapshots are attached. Thanks in advance!

Table

Query

答:
You can use not exists:

```<code>select s.*
from stock as s
where not exists (select 1
                  from stock as s2
                  where s2.ComputerPartNumber = s.ComputerPartNumber and
                        s2.EquipmentName not in ("EquipmentA", "EquipmentB")
                 );
</code>```

Body:
SELECT Stock.*
FROM Stock
WHERE (
(
(Stock.ComputerPartNumber) In (SELECT [ComputerPartNumber] FROM [Stock] As Tmp GROUP BY [ComputerPartNumber] HAVING Count(*)=2)
)
AND
(
(Stock.EquipmentName)="EquipmentA" Or (Stock.EquipmentName)="EquipmentB")
)
OR (
(
(Stock.ComputerPartNumber) In (SELECT [ComputerPartNumber] FROM [Stock] As Tmp GROUP BY [ComputerPartNumber] HAVING Count(*)=1)
)
AND (
(Stock.EquipmentName)="EquipmentA" Or (Stock.EquipmentName)="EquipmentB"
)
);

I am using the above SQL to achieve below 3 items:-

Find out all of the ComputerPartNumber which used by EquipmentA and/or EquipmentB only

Filter out the query result if the ComputerPartNumber used by equipment other than EquipmentA and EquipmentB.

If the ComputerPartNumber is used by both EquipmentA and EquipmentC, filter out the result also.

However the item 3 cannot be filtered out successfully. What should I do in order to achieve the item3?
Table and Query snapshots are attached. Thanks in advance!

Table

Query

Body:
You can use not exists:

select s.*
from stock as s
where not exists (select 1
                  from stock as s2
                  where s2.ComputerPartNumber = s.ComputerPartNumber and
                        s2.EquipmentName not in ("EquipmentA", "EquipmentB")
                 );


问:
Function call inside OpenMP for loop
I have the following for loop, which contains a private function call inside of it:

for (i = 0; i < N; ++i)
    dates[i] = to_time_t(&string_dates[i][0]);
```

<p><code>to_time_t</code> simply converts a string (<code>e.g.: "18/03/2007"</code>) into a timestamp, and it does so with the help of <code>mktime()</code>, which is really slow. In fact, that for loop alone takes the most time out of any other code in the program. To remedy this, I am trying to apply OpenMP to the loop, like this:</p>

<pre class="lang-cpp prettyprint-override"><code>#pragma omp parallel for private(i)
for (i = 0; i < N; ++i)
    dates[i] = to_time_t(&string_dates[i][0]);
</code>```

My OpenMP knowledge is limited, but I'm assuming that each element of the dates array is never accessed by two threads simultaneously since i is private. The same should apply to string_dates. But when I run this code, performance is actually worse, so I must be doing something wrong, I just don't see it. Any help is appreciated!

Edit: I should have included the to_time_t code from the start.

time_t to_time_t(const string * date) {
    struct std::tm tm = {0};

    istringstream ss_tm(*date);
    ss_tm >> get_time(&tm, "%m/%d/%Y");

    return mktime(&tm);
}
```

答:
The problem is in mktime() which has a process-wide side effect. From the manual page:

Calling mktime() also sets the external variable tzname with information about the current timezone.

mktime() calls internally tzset(). The latter is serialised via a mutex lock, but what really slows it down in the multithreaded case is the constant cache trashing. When a call to tzset() by a thread running on a particular CPU core writes to tzname, this invalidates the caches of all the other cores, forcing threads that run on those cores to access higher cache levels or even the main memory the next time there is a call to mktime().

You need to find or write an equivalent of mktime() that doesn't modify global state. Or just stick to sequential execution for that part of the code. It is perfectly fine to call mktime() simultaneously in multiple sequential processes (e.g., in a pure MPI application).

Title: Function call inside OpenMP for loop

Body:
I have the following for loop, which contains a private function call inside of it:

for (i = 0; i < N; ++i)
    dates[i] = to_time_t(&string_dates[i][0]);

to_time_t simply converts a string (e.g.: "18/03/2007") into a timestamp, and it does so with the help of mktime(), which is really slow. In fact, that for loop alone takes the most time out of any other code in the program. To remedy this, I am trying to apply OpenMP to the loop, like this:

#pragma omp parallel for private(i)
for (i = 0; i < N; ++i)
    dates[i] = to_time_t(&string_dates[i][0]);

My OpenMP knowledge is limited, but I'm assuming that each element of the dates array is never accessed by two threads simultaneously since i is private. The same should apply to string_dates. But when I run this code, performance is actually worse, so I must be doing something wrong, I just don't see it. Any help is appreciated!

Edit: I should have included the to_time_t code from the start.

time_t to_time_t(const string * date) {
    struct std::tm tm = {0};

    istringstream ss_tm(*date);
    ss_tm >> get_time(&tm, "%m/%d/%Y");

    return mktime(&tm);
}


问:
Get rid of the timestamp in Eclipse console
Is there a way to get rid of the timestamp in Eclipse console?

I am recording screencasts and don't want to show the date/time within my videos.

答:
no, there isn't any way to do that.However, you can try to hide it somewhat by dragging the console to top-right.The timestamp is still there but in order to see it, you have to swipe right.

as shown,

if it is still visible, you can decrease the size of console.

Still, this is not the exact solution to your question.
I hope this might helps a little.


问:
Issue with a loop which checks members in a Discord server
I'm pretty new to Python so this is very confusing to me. I'm trying to check all members in a list, where for every member it checks whether it is person A/person B or neither, and then does a certain thing based on whether it is that person or not. For some reason, when the first person checked is the same as the person it checks for, it says that all the following people are that person too.
The code is used to get rid of all members in a discord server except a few (for resetting after a minigame).

```<code>async def serverreset(ctx):
for member in ctx.message.guild.members:
    print(member)
    if member == "person1#1234" or "person2#2345":
        print(f"Unable to ban {member.display_name}")
    else:
        await member.ban(reason="Reset", delete_message_days=7)
        print(f"Banned {member.display_name}")
</code>```

Result of running the program:

```<code>person1#1234
Unable to ban person1
person2#2345
Unable to ban person2
accountthatshouldbebanned#5678
Unable to ban accountthatshouldbebanned
</code>```

答:
What's happening there is the string representation (i.e. when being printed or put into a string) of a member object is the user's name + discriminator. But when you're using the member object in a statement, it doesn't convert it to a string.

There are a couple ways you can go about it:

if str(member) in ["person1#1234", "person2#2345"]:
    print(f"Unable to ban {member.display_name}")
else:
    # other code
```

<p>And that would be checking the member as a string. The alternative would be doing it via ID (which is more "failsafe", as IDs never change, but users are able to change their name and discriminator).</p>

<pre class="lang-py prettyprint-override"><code>if member.id in [112233445566778899, 223344556677889900]:
    print(f"Unable to ban {member.display_name}")
else:
    # other code
</code>```

Another thing to note is that when a bot edits roles, attempts to change a username, or kick/ban someone and that person has higher priveleges than the bot (i.e. the server owner), then it'll throw a Forbidden error, as it isn't high enough in the hierarchy to perform the action.

One last thing is in your if statement, you're checking member == "person#1234" or "person2#2345", which in plain english makes perfect sense. However, when the interpreter evaluates statements, it does them separately:

if member == "person1#1234"

OR

if "person2#2345"

Due to that second part, it will always evaluate to being True, and will only ever be False if the object is None, but because a string isn't None, it'll be True.

Hoping that made some sense.

References:

Guild.ban()

Member.id

discord.Member - Check out the str(x) to see what it returns when converted to a str

Python conditional statements

Body:
I'm pretty new to Python so this is very confusing to me. I'm trying to check all members in a list, where for every member it checks whether it is person A/person B or neither, and then does a certain thing based on whether it is that person or not. For some reason, when the first person checked is the same as the person it checks for, it says that all the following people are that person too.
The code is used to get rid of all members in a discord server except a few (for resetting after a minigame).

async def serverreset(ctx):
for member in ctx.message.guild.members:
    print(member)
    if member == "person1#1234" or "person2#2345":
        print(f"Unable to ban {member.display_name}")
    else:
        await member.ban(reason="Reset", delete_message_days=7)
        print(f"Banned {member.display_name}")

Result of running the program:

person1#1234
Unable to ban person1
person2#2345
Unable to ban person2
accountthatshouldbebanned#5678
Unable to ban accountthatshouldbebanned

Body:
What's happening there is the string representation (i.e. when being printed or put into a string) of a member object is the user's name + discriminator. But when you're using the member object in a statement, it doesn't convert it to a string.

There are a couple ways you can go about it:

if str(member) in ["person1#1234", "person2#2345"]:
    print(f"Unable to ban {member.display_name}")
else:
    # other code

And that would be checking the member as a string. The alternative would be doing it via ID (which is more "failsafe", as IDs never change, but users are able to change their name and discriminator).

if member.id in [112233445566778899, 223344556677889900]:
    print(f"Unable to ban {member.display_name}")
else:
    # other code

Another thing to note is that when a bot edits roles, attempts to change a username, or kick/ban someone and that person has higher priveleges than the bot (i.e. the server owner), then it'll throw a Forbidden error, as it isn't high enough in the hierarchy to perform the action.

One last thing is in your if statement, you're checking member == "person#1234" or "person2#2345", which in plain english makes perfect sense. However, when the interpreter evaluates statements, it does them separately:

if member == "person1#1234"

OR

if "person2#2345"

Due to that second part, it will always evaluate to being True, and will only ever be False if the object is None, but because a string isn't None, it'll be True.

Hoping that made some sense.

References:

Guild.ban()

Member.id

discord.Member - Check out the str(x) to see what it returns when converted to a str

Python conditional statements


问:
How to call function from other local file Node.js?
I tried like this from main.js

```<code>// Modules to control application life and create native browser window
const {app, BrowserWindow} = require('electron')
const parser = require('./parser.js');
parser.parseHash(url)
</code>```

But got error that: parser.parseHash is not function

```<code>// parser.js file
function parseHash(url) {
    ...
}
</code>```

答:
You need to export the function like this:</p>

```<code>// parser.js file
function parseHash(url) {
    ...
}

module.exports = {
    parseHash: parseHash
}
</code>```

Body:
I tried like this from main.js

// Modules to control application life and create native browser window
const {app, BrowserWindow} = require('electron')
const parser = require('./parser.js');
parser.parseHash(url)

But got error that: parser.parseHash is not function

// parser.js file
function parseHash(url) {
    ...
}

Body:
You need to export the function like this:

// parser.js file
function parseHash(url) {
    ...
}

module.exports = {
    parseHash: parseHash
}


问:
How to improve the performance of 'for loop' to integrate some objects in JS
I have three for loop as below to integrate their objects.

The problem is the length of 'cars' array is 20,000.

So it should runs every 20,000 times for finding same id between company.user and cars.

But the id of cars is unique.

Can I reduce this repeat number in JS?
I want to reduce the taking time.

Thank you for reading it.

p.s. I uploaded same question adding the concrete logic inside of for loop.

```<code>for (let i = 0; i < company.length; i += 1) {
  for (let j = 0; j < company[i].user.length; j += 1) {
    for (let k = 0; k < cars.length; k += 1) {
      if (company[i].user[j].id === cars[k].id) {
        company[i].user[j] = {
          ...company[i].user[j],
          ...cars[k]
        }
      }
    }
  }
}
</code>```

答:
If there is only 1 match then use break after you found that item. Imagine you find that item at index 1 for example, then the loop would still continue and do 19998 loops. Because of the information that you know there is only 1 possible match you can break it there.

```<code>    if (company[i].user[j].id === cars[k].id) {
      company[i].user[j] = {
        ...company[i].user[j],
        ...cars[k]
      }
      break;
    }
</code>```

Body:
I have three for loop as below to integrate their objects.

The problem is the length of 'cars' array is 20,000.

So it should runs every 20,000 times for finding same id between company.user and cars.

But the id of cars is unique.

Can I reduce this repeat number in JS?
I want to reduce the taking time.

Thank you for reading it.

p.s. I uploaded same question adding the concrete logic inside of for loop.

for (let i = 0; i < company.length; i += 1) {
  for (let j = 0; j < company[i].user.length; j += 1) {
    for (let k = 0; k < cars.length; k += 1) {
      if (company[i].user[j].id === cars[k].id) {
        company[i].user[j] = {
          ...company[i].user[j],
          ...cars[k]
        }
      }
    }
  }
}

Body:
If there is only 1 match then use break after you found that item. Imagine you find that item at index 1 for example, then the loop would still continue and do 19998 loops. Because of the information that you know there is only 1 possible match you can break it there.

    if (company[i].user[j].id === cars[k].id) {
      company[i].user[j] = {
        ...company[i].user[j],
        ...cars[k]
      }
      break;
    }


问:
Does IBM Waston personality insight API support simplied Chinese?
I'm trying to use personality insight API by IBM to get personality and value scores from social media posts in simplified Chinese language.

I find that they do support the Chinese language in the API document, but I get the error when I try to hit API.

Error info is:

```<code>{
    "code": 400,
    "sub_code": "C00001",
    "error": "The language you requested, zh-cn, is not supported. Languages
              supported: en,es,ja,ar,ko."
}
</code>```

Can anyone figure this out, what's wrong? Am I using API in wrong way?

答:
The entry for supported languages in the service documentation shows

```<code>Table 2. Specifying request and response languages
Language             Argument   Supported by Content-Language   Supported by Accept-Language

Simplified Chinese    zh-cn          No                             Yes
</code>```

ie. Chinese isn't supported for input text, but it is supported as the output report. So you can specify Spanish as the language of the text that you want to analyse, and request the analysis report back in Chinese.

Body:
I'm trying to use personality insight API by IBM to get personality and value scores from social media posts in simplified Chinese language.

I find that they do support the Chinese language in the API document, but I get the error when I try to hit API.

Error info is:

{
    "code": 400,
    "sub_code": "C00001",
    "error": "The language you requested, zh-cn, is not supported. Languages
              supported: en,es,ja,ar,ko."
}

Can anyone figure this out, what's wrong? Am I using API in wrong way?

Body:
The entry for supported languages in the service documentation shows

Table 2. Specifying request and response languages
Language             Argument   Supported by Content-Language   Supported by Accept-Language

Simplified Chinese    zh-cn          No                             Yes

ie. Chinese isn't supported for input text, but it is supported as the output report. So you can specify Spanish as the language of the text that you want to analyse, and request the analysis report back in Chinese.


问:
Angular Dynamic Form with Dynamic Event Binding With Dynamic Function
Hi I am new to angular and i need to make something that renders a form using JSON and that JSON also has all the events and functions too.
This is my Html Component

```<code>    <div *ngFor="let form of forms; index as i ">
    <div *ngIf="form.type == 'input'">
        <input  type="text" value="{{ form.value }}" ("{{form.event}}") = "{{form.function}}"/>

    </div>
</div>
</code>```

This is my TS file,

```<code>    @Component({
      selector: 'app-form',
      templateUrl: './form.component.html',
      styleUrls: ['./form.component.scss']
    })
    export class FormComponent implements OnInit {

      forms: any
      constructor() { }

  ngOnInit(): void {
      this.forms = [
        {
          'type' : 'input',
          'value' : '123',
          'event' : 'click',
          'function' : 'show',
        },

      ]

  }
   show(a,b){
    console.log('hello');
  }

}
</code>```

I can not find a way to generate the HTML with the events and function from my JSON Array.

答:
it's not possible do in this way. Angular transpile and minifie the code, so you don't know the name of the functions

The way is that your form was

```<code>this.forms = [
        {
          'type' : 'input',
          'value' : '123',
          'event' : 'click',
          'function' : this.show,
        },
</code>```

See that "function" is the function "this.show"

And your inputs can be like

```<code><div *ngIf="form.type == 'input'">
        <input  type="text" [ngValue]="form.value"
          (click)="form.event=='click' && form.function($event)"
          (blur)="form.event=='blur' && form.function($event)"
          (focus)="form.event=='focus' && form.function($event)"
        />
</div>
</code>```

See that whe you use (event)="condition && function()", if the condition is false don't execute the function

Body:
Hi I am new to angular and i need to make something that renders a form using JSON and that JSON also has all the events and functions too.
This is my Html Component

        <input  type="text" value="{{ form.value }}" ("{{form.event}}") = "{{form.function}}"/>

This is my TS file,

    @Component({
      selector: 'app-form',
      templateUrl: './form.component.html',
      styleUrls: ['./form.component.scss']
    })
    export class FormComponent implements OnInit {

      forms: any
      constructor() { }

  ngOnInit(): void {
      this.forms = [
        {
          'type' : 'input',
          'value' : '123',
          'event' : 'click',
          'function' : 'show',
        },

      ]

  }
   show(a,b){
    console.log('hello');
  }

}

I can not find a way to generate the HTML with the events and function from my JSON Array.

Body:
it's not possible do in this way. Angular transpile and minifie the code, so you don't know the name of the functions

The way is that your form was

this.forms = [
        {
          'type' : 'input',
          'value' : '123',
          'event' : 'click',
          'function' : this.show,
        },

See that "function" is the function "this.show"

And your inputs can be like

<div *ngIf="form.type == 'input'">
        <input  type="text" [ngValue]="form.value"
          (click)="form.event=='click' && form.function($event)"
          (blur)="form.event=='blur' && form.function($event)"
          (focus)="form.event=='focus' && form.function($event)"
        />
</div>

See that whe you use (event)="condition && function()", if the condition is false don't execute the function


答:
Are you exporting parseHash function in parser.js file?</p>

```<code>module.exports  = {
parseHash,
}
</code>```

Title: How to call function from other local file Node.js?

Body:
Are you exporting parseHash function in parser.js file?

module.exports  = {
parseHash,
}


问:
mysql changing column to row heading
I have a table that holds data like

```<code>   key        val
    Product    Oranges
    Customer   Alan Sherry
    Product    Apples
    Area       Isles
    Customer   John C
</code>```

etc

and I want to change it to more like

```<code>Product     customer      Area
Oranges     Alan Sherry   Isles
Appleas     John C
</code>```

how would I do that

thanks

答:
This could be hard to do using purely sql. You could use a cursor and look for product, customer, area (in a specific order, maybe?) and set variables for those 3 items until you come to product each time, then you flush the variables you've set into one row in the new table you've created using and insert statement and start reading again.

The statements inside the cursor will depend on the specifics on the data in the key val table.

Title: mysql changing column to row heading

Body:
I have a table that holds data like

   key        val
    Product    Oranges
    Customer   Alan Sherry
    Product    Apples
    Area       Isles
    Customer   John C

etc

and I want to change it to more like

Product     customer      Area
Oranges     Alan Sherry   Isles
Appleas     John C

how would I do that

thanks


问:
how to convert a binary string 128bit to decimal string in c++?
```<code>void convertBinaryToDecimal(std::string BinarySrc, std::string& DecimalDest)
{

}
</code>```

I need to convert a string binary length 128 bit to string Decimal

答:
Rather than providing solution directly I think I can give you a small hint.

Take the long binary number, and split it in half (or quarters, or whatever.)

Keep track of which of these is the upper range and which of these is the lower range of the binary number.

Calculate what the true value of lower range and upper range and add them together afterwards.

Body:
void convertBinaryToDecimal(std::string BinarySrc, std::string& DecimalDest)
{

}

I need to convert a string binary length 128 bit to string Decimal


答:
```<code>document.getElementById("image").style.backgroundColor = "#8e68ff";
</code>```

Above code is not valid first of all, you need to provide a unique id to your HTML element like -

```<code><img class = "preview"
 id="preview1"
 src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon3.jpg"
 alt = "Young Puppy"
 onmouseover = "upDate(this)"
 onmouseout = "unDo()">
</code>```

Now you can access this HTML image element using the id and change its src like this -

```<code>document.getElementById("preview1").src = "hackanm.gif";
</code>```

If you are using multiple image elements, please note that you have to use different ids for them.

Title: How to change background image in js file but not hard coding url

Body:
I cannot figure out why I can't change background images when I use onmouseover events. My goal is when I put mouse over first pic, then this pic will show up on the top of page, when I move my mouse to another pic, then this new pic will show up on the top instead, then when I move mouse to the third pic, the third pic will show up on the top. Here I attached my html code and js code. Please help me.

function upDate(previewPic){
    // document.getElementById("image").style.backgroundColor = "green";
    document.getElementById("image").style.backgroundColor = "url(previewPic.src)";
    document.getElementById("image").innerHTML = previewPic.alt + ".  this is onmouseover events";
}

function unDo(){
    document.getElementById("image").style.backgroundColor = "#8e68ff";
    document.getElementById("image").innerHTML = "Hover over an image below to display here.";
}

    Hover over an image below to display here.

Body:
document.getElementById("image").style.backgroundColor = "#8e68ff";

Above code is not valid first of all, you need to provide a unique id to your HTML element like -

<img class = "preview"
 id="preview1"
 src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon3.jpg"
 alt = "Young Puppy"
 onmouseover = "upDate(this)"
 onmouseout = "unDo()">

Now you can access this HTML image element using the id and change its src like this -

document.getElementById("preview1").src = "hackanm.gif";

If you are using multiple image elements, please note that you have to use different ids for them.


问:
Spark INLINE Vs. LATERAL VIEW EXPLODE differences?
In Spark, for the following use case, I'd like to understand what are the main differences between using the INLINE and EXPLODE ... I'm not sure if there are any performance implications or if one method is preferred over the other one or if there are any other uses cases where one is appropriate and the other is not...

The use case is to select 2 fields from a complex data type (array of structs), my instinct was to use INLINE since it explodes an array of structs

For example:

```<code>WITH sample AS (
 SELECT 1 AS id,
        array(NAMED_STRUCT('name', 'frank',
                           'age', 40,
                           'state', 'Texas'
                           ),
              NAMED_STRUCT('name', 'maria',
                           'age', 51,
                           'state', 'Georgia'
                           )
              )
            AS array_of_structs
),

inline_data AS (
SELECT id,
        INLINE(array_of_structs)
FROM sample
)

SELECT id,
        name AS person_name,
        age AS person_age
FROM inline_data
</code>```

And using LATERAL VIEW EXPLODE:

```<code>WITH sample AS (
 SELECT 1 AS id,
        array(NAMED_STRUCT('name', 'frank',
                           'age', 40,
                           'state', 'Texas'
                           ),
              NAMED_STRUCT('name', 'maria',
                           'age', 51,
                           'state', 'Georgia'
                           )
              )
            AS array_of_structs
)

SELECT  id,
        person.name,
        person.age
FROM sample
LATERAL VIEW EXPLODE(array_of_structs) exploded_people as person
</code>```

The documentation clearly states what each one of these do but I'd like to better understand when to pick one over the other one.

答:
EXPLODE UDTF will generate rows of struct (single column of type struct), and to get person name you need to use person.name:

```<code>WITH sample AS (
 SELECT 1 AS id,
        array(NAMED_STRUCT('name', 'frank',
                           'age', 40,
                           'state', 'Texas'
                           ),
              NAMED_STRUCT('name', 'maria',
                           'age', 51,
                           'state', 'Georgia'
                           )
              )
            AS array_of_structs
)

SELECT  id,
        person.name,
        person.age
FROM sample
LATERAL VIEW explode(array_of_structs) exploded_people as person
</code>```

Result:

```<code>id,name,age
1,frank,40
1,maria,51
</code>```

And INLINE UDTF will generate a row-set with N columns (N = number of top level elements in the struct), so you do not need to use dot notation person.name because name and other struct elements are already extracted by INLINE:

```<code>WITH sample AS (
 SELECT 1 AS id,
        array(NAMED_STRUCT('name', 'frank',
                           'age', 40,
                           'state', 'Texas'
                           ),
              NAMED_STRUCT('name', 'maria',
                           'age', 51,
                           'state', 'Georgia'
                           )
              )
            AS array_of_structs
)

SELECT  id,
        name,
        age
FROM sample
LATERAL VIEW inline(array_of_structs) exploded_people as name, age, state
</code>```

Result:

```<code>id,name,age
1,frank,40
1,maria,51
</code>```

Both INLINE and EXPLODE are UDTFs and require LATERAL VIEW in Hive. In Spark it works fine without lateral view. The only difference is that EXPLODE returns dataset of array elements(struct in your case) and INLINE is used to get struct elements already extracted. You need to define all struct elements in case of INLINE like this: LATERAL VIEW inline(array_of_structs) exploded_people as name, age, state

From performance perspective both INLINE and EXPLODE work the same, you can use EXPLAIN command to check the plan. Extraction of struct elements in the UDTF or after UDTF does not affect performance.

INLINE requires to describe all struct elements (in Hive) and EXPLODE does not, so, explode may be more convenient if you do not need to extract all struct elements of if you do not need to extract elements at all. INLINE is convenient when you need to extract all or most of struct elements.

Your first code example works only in Spark. In Hive 2.1.1 it throws an exception because lateral view required.

In Spark this will work also:

```<code>inline_data AS (
SELECT id,
        EXPLODE(array_of_structs) as person
FROM sample
)
</code>```

And to get age column you need to use person.age

Body:
In Spark, for the following use case, I'd like to understand what are the main differences between using the INLINE and EXPLODE ... I'm not sure if there are any performance implications or if one method is preferred over the other one or if there are any other uses cases where one is appropriate and the other is not...

The use case is to select 2 fields from a complex data type (array of structs), my instinct was to use INLINE since it explodes an array of structs

For example:

WITH sample AS (
 SELECT 1 AS id,
        array(NAMED_STRUCT('name', 'frank',
                           'age', 40,
                           'state', 'Texas'
                           ),
              NAMED_STRUCT('name', 'maria',
                           'age', 51,
                           'state', 'Georgia'
                           )
              )
            AS array_of_structs
),

inline_data AS (
SELECT id,
        INLINE(array_of_structs)
FROM sample
)

SELECT id,
        name AS person_name,
        age AS person_age
FROM inline_data

And using LATERAL VIEW EXPLODE:

WITH sample AS (
 SELECT 1 AS id,
        array(NAMED_STRUCT('name', 'frank',
                           'age', 40,
                           'state', 'Texas'
                           ),
              NAMED_STRUCT('name', 'maria',
                           'age', 51,
                           'state', 'Georgia'
                           )
              )
            AS array_of_structs
)

SELECT  id,
        person.name,
        person.age
FROM sample
LATERAL VIEW EXPLODE(array_of_structs) exploded_people as person

The documentation clearly states what each one of these do but I'd like to better understand when to pick one over the other one.

Body:
EXPLODE UDTF will generate rows of struct (single column of type struct), and to get person name you need to use person.name:

WITH sample AS (
 SELECT 1 AS id,
        array(NAMED_STRUCT('name', 'frank',
                           'age', 40,
                           'state', 'Texas'
                           ),
              NAMED_STRUCT('name', 'maria',
                           'age', 51,
                           'state', 'Georgia'
                           )
              )
            AS array_of_structs
)

SELECT  id,
        person.name,
        person.age
FROM sample
LATERAL VIEW explode(array_of_structs) exploded_people as person

Result:

id,name,age
1,frank,40
1,maria,51

And INLINE UDTF will generate a row-set with N columns (N = number of top level elements in the struct), so you do not need to use dot notation person.name because name and other struct elements are already extracted by INLINE:

WITH sample AS (
 SELECT 1 AS id,
        array(NAMED_STRUCT('name', 'frank',
                           'age', 40,
                           'state', 'Texas'
                           ),
              NAMED_STRUCT('name', 'maria',
                           'age', 51,
                           'state', 'Georgia'
                           )
              )
            AS array_of_structs
)

SELECT  id,
        name,
        age
FROM sample
LATERAL VIEW inline(array_of_structs) exploded_people as name, age, state

Result:

id,name,age
1,frank,40
1,maria,51

Both INLINE and EXPLODE are UDTFs and require LATERAL VIEW in Hive. In Spark it works fine without lateral view. The only difference is that EXPLODE returns dataset of array elements(struct in your case) and INLINE is used to get struct elements already extracted. You need to define all struct elements in case of INLINE like this: LATERAL VIEW inline(array_of_structs) exploded_people as name, age, state

From performance perspective both INLINE and EXPLODE work the same, you can use EXPLAIN command to check the plan. Extraction of struct elements in the UDTF or after UDTF does not affect performance.

INLINE requires to describe all struct elements (in Hive) and EXPLODE does not, so, explode may be more convenient if you do not need to extract all struct elements of if you do not need to extract elements at all. INLINE is convenient when you need to extract all or most of struct elements.

Your first code example works only in Spark. In Hive 2.1.1 it throws an exception because lateral view required.

In Spark this will work also:

inline_data AS (
SELECT id,
        EXPLODE(array_of_structs) as person
FROM sample
)

And to get age column you need to use person.age


问:
Invert a Eigen::VectorXd and assign to another Eigen::VectorXd
so I stumbled upon this compilation issue with Eigen. I'm using Eigen 3.3.4 and compiling on Linux with gcc 8.4.0.
Basically I have a defined class inheriting from Eigen::VectorXd which looks like this

```<code>class dVector : public Eigen::VectorXd {
   public:
    dVector() : Eigen::VectorXd() { setZero(); }
    dVector(int n) : Eigen::VectorXd(n) { setZero(); }
    dVector(const Eigen::VectorXd& v) : Eigen::VectorXd(v) {}
    dVector(const dVector& v) : Eigen::VectorXd(v) {}
    dVector& operator=(const Eigen::VectorXd& v) {
        Eigen::VectorXd::operator=(v);
        return *this;
    }
    dVector& operator=(const dVector& v) {
        Eigen::VectorXd::operator=(v);
        return *this;
    }
   ...
};
</code>```

And then in my code I use it like this:

```<code>static dVector a(100);
// do something with a
dVector b = -a; // <--- won't compile
dVector b = dVector(-a); <---- compiles
</code>```

The second last line doesn't compile, giving your usual Eigen error message:

```<code>error: no viable conversion from 'const Eigen::MatrixBase<Eigen::Matrix<double, -1, 1, 0, -1, 1>>::NegativeReturnType'
 (aka 'const CwiseUnaryOp<scalar_opposite_op<double>,
 const Eigen::Matrix<double, -1, 1, 0, -1, 1> >') to 'dVector'
</code>```

Now the reason why I am really intrigued is that this doesn't compile on Linux, but it compiles on Windows, using MSVC.

I don't really understand why this doesn't compile, my suspicion is that it has something to do with implicit conversions or what the operation -a actually returns; maybe it's not a dVector but an operation tree. Haven't yet fully grasped what is happening behind the scenes in Eigen.

So then two questions:

Why doesn't dVector b = -a; compile ?

What different thing does the MSVC compiler do that allows it to accept whatever it is that gcc refuses?

答:
operator-(dVector) doesn't exist but Eigen::VectorXd is a public base of dVector and therefore Eigen::operator-(Eigen::VectorXd) is chosen for -a.

This operator does not return an Eigen::VectorXd but a wrapper type convertible
to Eigen::VectorXd. This wrapper type is not convertible to dVector as it is needed to be converted to Eigen::VectorXd first.

If you try dVector b = Eigen::VectorXd(-a) it would work, for the same reason dVector b = dVector(-a) works.

Solution:
I would not recommend publicly inherit from Eigen::VectorXd use composition instead.

Solution2:
Implement operator-(dVector). Now the compiler will choose this operator instead.

Solution3:
Implement operator=(Eigen::VectorXd). The return type of Eigen::operator-(Eigen::VectorXd) is convertible to Eigen::VectorXd and can therefore be assigned to dVector.

MSVC either has a bug or a language extension to make this compile.

Body:
so I stumbled upon this compilation issue with Eigen. I'm using Eigen 3.3.4 and compiling on Linux with gcc 8.4.0.
Basically I have a defined class inheriting from Eigen::VectorXd which looks like this

class dVector : public Eigen::VectorXd {
   public:
    dVector() : Eigen::VectorXd() { setZero(); }
    dVector(int n) : Eigen::VectorXd(n) { setZero(); }
    dVector(const Eigen::VectorXd& v) : Eigen::VectorXd(v) {}
    dVector(const dVector& v) : Eigen::VectorXd(v) {}
    dVector& operator=(const Eigen::VectorXd& v) {
        Eigen::VectorXd::operator=(v);
        return *this;
    }
    dVector& operator=(const dVector& v) {
        Eigen::VectorXd::operator=(v);
        return *this;
    }
   ...
};

And then in my code I use it like this:

static dVector a(100);
// do something with a
dVector b = -a; // <--- won't compile
dVector b = dVector(-a); <---- compiles

The second last line doesn't compile, giving your usual Eigen error message:

error: no viable conversion from 'const Eigen::MatrixBase<Eigen::Matrix<double, -1, 1, 0, -1, 1>>::NegativeReturnType'
 (aka 'const CwiseUnaryOp<scalar_opposite_op<double>,
 const Eigen::Matrix<double, -1, 1, 0, -1, 1> >') to 'dVector'

Now the reason why I am really intrigued is that this doesn't compile on Linux, but it compiles on Windows, using MSVC.

I don't really understand why this doesn't compile, my suspicion is that it has something to do with implicit conversions or what the operation -a actually returns; maybe it's not a dVector but an operation tree. Haven't yet fully grasped what is happening behind the scenes in Eigen.

So then two questions:

Why doesn't dVector b = -a; compile ?

What different thing does the MSVC compiler do that allows it to accept whatever it is that gcc refuses?


问:
Convert Newtosoft JObject directly to BsonDocument
Try to convert JObject to BsonDocument using this example https://www.newtonsoft.com/json/help/html/WriteJTokenToBson.htm (BsonWriter obsolete, so I use BsonDataWriter)

```<code>var jObject = JObject.Parse("{\"name\":\"value\"}");

using var writer = new BsonDataWriter(new MemoryStream());
jObject.WriteTo(writer);

var bsonData = writer.ToBsonDocument();

Console.WriteLine(bsonData.ToJson());
</code>```

output:

```<code>{ "CloseOutput" : true, "AutoCompleteOnClose" : true, "Formatting" : 0, "DateFormatHandling" : 0, "DateTimeZoneHandling" : 3, "StringEscapeHandling" : 0, "FloatFormatHandling" : 0, "DateFormatString" : null
, "Culture" : { "Name" : "", "UseUserOverride" : false }, "DateTimeKindHandling" : 1 }

</code>```

Expected output is:

```<code>{"name": "value"}
</code>```

How can I fix it?

UPD: I have a JObject, and I want to convert it directly to BSONDocument, avoid serialization to string and string parsing

答:
If you have the json string already, you can simply create a bson document out of it </p>

```<code>var document= BsonDocument.Parse("{\"name\":\"value\"}");
</code>```

<p>If you strictly have a JObject, you can Serialize the JObject and then parse the result to a BSONDocument </p>

```<code>var document = BsonDocument.Parse(Newtonsoft.Json.JsonConvert.SerializeObject(jObject));
</code>```

Body:
Try to convert JObject to BsonDocument using this example https://www.newtonsoft.com/json/help/html/WriteJTokenToBson.htm (BsonWriter obsolete, so I use BsonDataWriter)

var jObject = JObject.Parse("{\"name\":\"value\"}");

using var writer = new BsonDataWriter(new MemoryStream());
jObject.WriteTo(writer);

var bsonData = writer.ToBsonDocument();

Console.WriteLine(bsonData.ToJson());

output:

{ "CloseOutput" : true, "AutoCompleteOnClose" : true, "Formatting" : 0, "DateFormatHandling" : 0, "DateTimeZoneHandling" : 3, "StringEscapeHandling" : 0, "FloatFormatHandling" : 0, "DateFormatString" : null
, "Culture" : { "Name" : "", "UseUserOverride" : false }, "DateTimeKindHandling" : 1 }

Expected output is:

{"name": "value"}

How can I fix it?

UPD: I have a JObject, and I want to convert it directly to BSONDocument, avoid serialization to string and string parsing

Body:
If you have the json string already, you can simply create a bson document out of it

var document= BsonDocument.Parse("{\"name\":\"value\"}");

If you strictly have a JObject, you can Serialize the JObject and then parse the result to a BSONDocument

var document = BsonDocument.Parse(Newtonsoft.Json.JsonConvert.SerializeObject(jObject));


问:
Julia - read UInt32 from UInt8 Array
I have UInt8 data array which I got from TCPSocket.

I want to read UInt32s and UInt16s from different indices.

For example:

```<code>data = UInt8[0xFF, 0x00, 0x00, 0x00, 0xAA, 0x00]

// Something like this:
extracted_UInt32 = data.readUInt32(1) # [1-4]
extracted_UInt16 = data.readUInt16(5) # [5-6]
</code>```

It is exactly like Node.js's Buffer.readUInt16LE(offset): https://nodejs.org/api/buffer.html#buffer_buf_readint16le_offset

Thanks!

答:
Also I have found reinterpret can be used:</p>

```<code>data = UInt8[0xFF, 0x00, 0x00, 0x00, 0xAA, 0x00]

a = reinterpret(UInt32, data[1:4])
b = reinterpret(UInt16, data[5:6])
</code>```

Title: Julia - read UInt32 from UInt8 Array

Body:
I have UInt8 data array which I got from TCPSocket.

I want to read UInt32s and UInt16s from different indices.

For example:

data = UInt8[0xFF, 0x00, 0x00, 0x00, 0xAA, 0x00]

// Something like this:
extracted_UInt32 = data.readUInt32(1) # [1-4]
extracted_UInt16 = data.readUInt16(5) # [5-6]

It is exactly like Node.js's Buffer.readUInt16LE(offset): https://nodejs.org/api/buffer.html#buffer_buf_readint16le_offset

Thanks!

Body:
Also I have found reinterpret can be used:

data = UInt8[0xFF, 0x00, 0x00, 0x00, 0xAA, 0x00]

a = reinterpret(UInt32, data[1:4])
b = reinterpret(UInt16, data[5:6])


问:
Optimizing MySQL query for the Tatoeba project
I've downloaded the Tatoeba project databases and I'm trying to query them but queries with a subquery are taking way too long.

```<code>-- 800.000 rows approx.
CREATE TABLE `sentences` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `language` char(3) DEFAULT NULL,
  `text` mediumtext,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=912551 DEFAULT CHARSET=utf8

-- 1.5 million rows approx.
CREATE TABLE `links` (
  `sentenceId` int(10) unsigned NOT NULL,
  `translatedId` int(10) unsigned NOT NULL,
  PRIMARY KEY (`sentenceId`,`translatedId`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8
</code>```

Basically the links table joins two sentences in the sentences table together (the original sentence and one  translation). A sentence can have zero or more translations. So I have an id of a sentence I want to work with and want to grab ALL the translations available.

This query gets me what I want but takes almost 18 seconds to complete.

```<code>SELECT * FROM `sentences` WHERE `id` IN (SELECT `translatedId` FROM `links` WHERE `sentenceId` = 157967);
</code>```

Running both queries by themselves just takes an instant.

What am I doing wrong?

答:
Try this(using an EXISTS clause):

```<code>SELECT *
    FROM `sentences` a
 WHERE EXISTS (SELECT 1 FROM `links` b WHERE `sentenceId` = 157967 AND b.`translatedId`=a.`id`);
</code>```

If the translatedId is unique in the links you can go for a inner join as given below

```<code>SELECT a.*
    FROM `sentences` a INNER JOIN `links` b
      ON b.`translatedId`=a.`id`
</code>```

Body:
I've downloaded the Tatoeba project databases and I'm trying to query them but queries with a subquery are taking way too long.

-- 800.000 rows approx.
CREATE TABLE `sentences` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `language` char(3) DEFAULT NULL,
  `text` mediumtext,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=912551 DEFAULT CHARSET=utf8

-- 1.5 million rows approx.
CREATE TABLE `links` (
  `sentenceId` int(10) unsigned NOT NULL,
  `translatedId` int(10) unsigned NOT NULL,
  PRIMARY KEY (`sentenceId`,`translatedId`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8

Basically the links table joins two sentences in the sentences table together (the original sentence and one  translation). A sentence can have zero or more translations. So I have an id of a sentence I want to work with and want to grab ALL the translations available.

This query gets me what I want but takes almost 18 seconds to complete.

SELECT * FROM `sentences` WHERE `id` IN (SELECT `translatedId` FROM `links` WHERE `sentenceId` = 157967);

Running both queries by themselves just takes an instant.

What am I doing wrong?

Body:
Try this(using an EXISTS clause):

SELECT *
    FROM `sentences` a
 WHERE EXISTS (SELECT 1 FROM `links` b WHERE `sentenceId` = 157967 AND b.`translatedId`=a.`id`);

If the translatedId is unique in the links you can go for a inner join as given below

SELECT a.*
    FROM `sentences` a INNER JOIN `links` b
      ON b.`translatedId`=a.`id`