问:
TypeError: '>' not supported between instances of 'NoneType' and 'int'
I am trying to disable a button when Click until a process finishes and then enable it again. Here's an outline of the steps:

user press button

button gets disabled

script starts to run

script ends to run

button is enabled

another element gets updated with script output

or I just perform dcc.loading on this case.

Here's my code:

```<code>import dash
import dash_html_components as html
from dash.dependencies import Input, Output
from Missing_relation_All import my_DB_func

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div([
    html.Button('Create Missing Relation Script', id='button', disabled=False),
    # other element
    html.Div(id='other-element'),
    # trigger div
    html.Div(id='trigger', children=0, style=dict(display='none'))
])

@app.callback(
    Output('button', 'disabled'),
    [Input('button', 'n_clicks'),
     Input('trigger', 'children')])
def trigger_function(n_clicks, trigger):
    context = dash.callback_context.triggered[0]['prop_id'].split('.')[0]
    context_value = dash.callback_context.triggered[0]['value']

    # if the button triggered the function
    if context == 'button':
        # if the function is triggered at app load, this will not disable the button
        # but if the function is triggered by clicking the button, this disables the button as expected
        if n_clicks > 0:
            return True
        else:
            return False
    # if the element function completed and triggered the function
    else:
        # if the function is triggered at app load, this will not disable the button
        # but if the function is triggered by the function finishing, this enables the button as expected
        return False

@app.callback(
    [Output('other-element', 'children'),
     Output('trigger', 'children')],
    [Input('button', 'n_clicks')])
def update_element(n_clicks):
    my_DB_func()
    return (
        'my element value',
        1  # update the trigger value
    )

if __name__ == '__main__':
    app.run_server(debug=True)
</code>```

So when I am trying to run the app I get this error:

```<code>TypeError: '>' not supported between instances of 'NoneType' and 'int'

File "C:\Users\haroo501\PycharmProjects\My_Check_Missing_Relation_Tool\newbuttontest.py", line 32, in trigger_function
if n_clicks > 0:
TypeError: '>' not supported between instances of 'NoneType' and 'int'

Traceback (most recent call last):
  File "C:\Users\haroo501\PycharmProjects\My_Check_Missing_Relation_Tool\newbuttontest.py", line 32, in trigger_function
    if n_clicks > 0:
TypeError: '>' not supported between instances of 'NoneType' and 'int'
</code>```

So what do I need to do after click the button make it Freeze or disabled till:

```<code>Process finished with exit code -1
</code>```

after finish the process or finish the script which is based on the def?

答:
I solved this like this way when Changed this part:

```<code>        if n_clicks > 0:
            return True
        else:
            return False
</code>```

to this:

```<code>        if n_clicks is None:
            raise dash.exceptions.PreventUpdate
        else:
            return True
</code>```

and this part:

```<code>@app.callback(
    [Output('other-element', 'children'),
     Output('trigger', 'children')],
    [Input('button', 'n_clicks')])
def update_element(n_clicks):
    my_DB_func()
    return (
        'my element value',
        1  # update the trigger value
    )
</code>```

to this:

```<code>def update_element(n_clicks):
    if n_clicks == True:
        my_DB_func()
    return (
        'my element value',
        1 # update the trigger value
    )
</code>```

as the final code will be something like this:

```<code>import dash
import dash_html_components as html
from dash.dependencies import Input, Output
from Missing_relation_All import my_DB_func
from dash.exceptions import PreventUpdate

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div([
    html.Button('Create Missing Relation Script', id='button', disabled=False),
    # other element
    html.Div(id='other-element'),
    # trigger div
    html.Div(id='trigger', children=0, style=dict(display='none'))
])

@app.callback(
    Output('button', 'disabled'),
    [Input('button', 'n_clicks'),
     Input('trigger', 'children')])
def trigger_function(n_clicks, trigger):
    context = dash.callback_context.triggered[0]['prop_id'].split('.')[0]
    context_value = dash.callback_context.triggered[0]['value']

    # if the button triggered the function
    if context == 'button':
        # if the function is triggered at app load, this will not disable the button
        # but if the function is triggered by clicking the button, this disables the button as expected
        if n_clicks is None:
            raise dash.exceptions.PreventUpdate
        else:
            return True
    # if the element function completed and triggered the function
    else:
        # if the function is triggered at app load, this will not disable the button
        # but if the function is triggered by the function finishing, this enables the button as expected
        return False

@app.callback(
    [Output('other-element','children'),
     Output('trigger','children')],
    [Input('button','n_clicks')])
def update_element(n_clicks):
    if n_clicks == True:
        my_DB_func()
    return (
        'my element value',
        1 # update the trigger value
    )

if __name__ == '__main__':
    app.run_server(debug=True)

</code>```

Body:
I am trying to disable a button when Click until a process finishes and then enable it again. Here's an outline of the steps:

user press button

button gets disabled

script starts to run

script ends to run

button is enabled

another element gets updated with script output

or I just perform dcc.loading on this case.

Here's my code:

import dash
import dash_html_components as html
from dash.dependencies import Input, Output
from Missing_relation_All import my_DB_func

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div([
    html.Button('Create Missing Relation Script', id='button', disabled=False),
    # other element
    html.Div(id='other-element'),
    # trigger div
    html.Div(id='trigger', children=0, style=dict(display='none'))
])

@app.callback(
    Output('button', 'disabled'),
    [Input('button', 'n_clicks'),
     Input('trigger', 'children')])
def trigger_function(n_clicks, trigger):
    context = dash.callback_context.triggered[0]['prop_id'].split('.')[0]
    context_value = dash.callback_context.triggered[0]['value']

    # if the button triggered the function
    if context == 'button':
        # if the function is triggered at app load, this will not disable the button
        # but if the function is triggered by clicking the button, this disables the button as expected
        if n_clicks > 0:
            return True
        else:
            return False
    # if the element function completed and triggered the function
    else:
        # if the function is triggered at app load, this will not disable the button
        # but if the function is triggered by the function finishing, this enables the button as expected
        return False

@app.callback(
    [Output('other-element', 'children'),
     Output('trigger', 'children')],
    [Input('button', 'n_clicks')])
def update_element(n_clicks):
    my_DB_func()
    return (
        'my element value',
        1  # update the trigger value
    )

if __name__ == '__main__':
    app.run_server(debug=True)

So when I am trying to run the app I get this error:

TypeError: '>' not supported between instances of 'NoneType' and 'int'

File "C:\Users\haroo501\PycharmProjects\My_Check_Missing_Relation_Tool\newbuttontest.py", line 32, in trigger_function
if n_clicks > 0:
TypeError: '>' not supported between instances of 'NoneType' and 'int'

Traceback (most recent call last):
  File "C:\Users\haroo501\PycharmProjects\My_Check_Missing_Relation_Tool\newbuttontest.py", line 32, in trigger_function
    if n_clicks > 0:
TypeError: '>' not supported between instances of 'NoneType' and 'int'

So what do I need to do after click the button make it Freeze or disabled till:

Process finished with exit code -1

after finish the process or finish the script which is based on the def?

Body:
I solved this like this way when Changed this part:

        if n_clicks > 0:
            return True
        else:
            return False

to this:

        if n_clicks is None:
            raise dash.exceptions.PreventUpdate
        else:
            return True

and this part:

@app.callback(
    [Output('other-element', 'children'),
     Output('trigger', 'children')],
    [Input('button', 'n_clicks')])
def update_element(n_clicks):
    my_DB_func()
    return (
        'my element value',
        1  # update the trigger value
    )

to this:

def update_element(n_clicks):
    if n_clicks == True:
        my_DB_func()
    return (
        'my element value',
        1 # update the trigger value
    )

as the final code will be something like this:

import dash
import dash_html_components as html
from dash.dependencies import Input, Output
from Missing_relation_All import my_DB_func
from dash.exceptions import PreventUpdate

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div([
    html.Button('Create Missing Relation Script', id='button', disabled=False),
    # other element
    html.Div(id='other-element'),
    # trigger div
    html.Div(id='trigger', children=0, style=dict(display='none'))
])

@app.callback(
    Output('button', 'disabled'),
    [Input('button', 'n_clicks'),
     Input('trigger', 'children')])
def trigger_function(n_clicks, trigger):
    context = dash.callback_context.triggered[0]['prop_id'].split('.')[0]
    context_value = dash.callback_context.triggered[0]['value']

    # if the button triggered the function
    if context == 'button':
        # if the function is triggered at app load, this will not disable the button
        # but if the function is triggered by clicking the button, this disables the button as expected
        if n_clicks is None:
            raise dash.exceptions.PreventUpdate
        else:
            return True
    # if the element function completed and triggered the function
    else:
        # if the function is triggered at app load, this will not disable the button
        # but if the function is triggered by the function finishing, this enables the button as expected
        return False

@app.callback(
    [Output('other-element','children'),
     Output('trigger','children')],
    [Input('button','n_clicks')])
def update_element(n_clicks):
    if n_clicks == True:
        my_DB_func()
    return (
        'my element value',
        1 # update the trigger value
    )

if __name__ == '__main__':
    app.run_server(debug=True)


来源: stackexchange

问:
I got a problem with Socket io when I deployed my application on Heroku
I created a chat room using socket.io within my express app and it's working fine in local host
when I deployed my application to heroku I get this error when I open the chat room

```<code>GET http://localhost:5000/socket.io/?EIO=3&transport=polling&t=N1PV-tt net::ERR_CONNECTION_REFUSED
</code>```

here is my index.js file

```<code>var express = require("express")
var cors = require("cors")
var bodyParser = require("body-parser")
var app = express()
var mongoose = require("mongoose")
//var http = require('http').createServer(app);
var io = require('socket.io')(http)
var port = process.env.PORT || 5000
var server = app.listen(port);
var io = require('socket.io').listen(server);
var http = require('http');

let users = [];
let messages = [];
let index = 0;

app.use(bodyParser.json())
app.use(cors())
app.use(bodyParser.urlencoded({ extended: false }))

const mongoURI = 'mongodb+srv://1920:1920@cluster0-qyzs9.mongodb.net/liebherr?retryWrites=true&w=majority'

mongoose.connect(mongoURI, { useNewUrlParser: true })
    .then(() => console.log("MongoDB Connected"))
    .catch(err => console.log(err))

var Users = require("./routes/Users")

app.use("/users", Users)

//Socket connection

io.on('connection', (socket) => {
    io.emit('noOfConnections', Object.keys(io.sockets.connected).length)

    socket.on('disconnect', () => {
        console.log(`a user has left the chat.`);
        io.emit('noOfConnections', Object.keys(io.sockets.connected).length)
    })

    socket.on('chat-message', (msg) => {
        socket.broadcast.emit('chat-message', msg)
    })
    socket.on('typing', (data) => {
        socket.broadcast.emit('typing', data)
    })
    socket.on('stoptyping', () => {
        socket.broadcast.emit('stoptyping')
    })
})

    // Static folder
    app.use(express.static(__dirname + '/public/'));
    app.get(/.*/);

</code>```

and here is package.json file

```<code>{
  "name": "express-demo",
  "version": "1.0.0",
  "description": "This is a full stack application",
  "engines": {
    "node": "13.1.0"
  },
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "dev": "nodemon index.js"
  },
  "author": "Farouk Turki",
  "license": "ISC",
  "dependencies": {
    "bcrypt": "^3.0.7",
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "jsonwebtoken": "^8.5.1",
    "mongodb": "^3.5.2",
    "mongoose": "^5.8.9",
    "nodemon": "^2.0.2",
    "socket.io": "^2.3.0"
  }
}
</code>```

Everything is working fine except the chatroom so I need to know why it's still using port 5000 in localhost

答:
From the front end (socket.io client) you are setting the hostname as localhost. But a front end code is not run server-side, it is in client side(your browser/or any thin client), it can access only the resources that are accessible over the internet(or the resources which is accessible by the browser itself).

So, in your case, the connection code will look something like:

```<code><script>
  const socket = io('http://<your-heroku-public-url-for-the-express-server>');
  // which typically is
  const socket = io('http://randomname.herokuapp.com');
</script>
</code>```

Given that http://randomname.herokuapp.com is the public url of your node js server.

ContentLicense: CC BY-SA 4.0

Body:
I created a chat room using socket.io within my express app and it's working fine in local host
when I deployed my application to heroku I get this error when I open the chat room

GET http://localhost:5000/socket.io/?EIO=3&transport=polling&t=N1PV-tt net::ERR_CONNECTION_REFUSED

here is my index.js file

var express = require("express")
var cors = require("cors")
var bodyParser = require("body-parser")
var app = express()
var mongoose = require("mongoose")
//var http = require('http').createServer(app);
var io = require('socket.io')(http)
var port = process.env.PORT || 5000
var server = app.listen(port);
var io = require('socket.io').listen(server);
var http = require('http');

let users = [];
let messages = [];
let index = 0;

app.use(bodyParser.json())
app.use(cors())
app.use(bodyParser.urlencoded({ extended: false }))

const mongoURI = 'mongodb+srv://1920:1920@cluster0-qyzs9.mongodb.net/liebherr?retryWrites=true&w=majority'

mongoose.connect(mongoURI, { useNewUrlParser: true })
    .then(() => console.log("MongoDB Connected"))
    .catch(err => console.log(err))

var Users = require("./routes/Users")

app.use("/users", Users)

//Socket connection

io.on('connection', (socket) => {
    io.emit('noOfConnections', Object.keys(io.sockets.connected).length)

    socket.on('disconnect', () => {
        console.log(`a user has left the chat.`);
        io.emit('noOfConnections', Object.keys(io.sockets.connected).length)
    })

    socket.on('chat-message', (msg) => {
        socket.broadcast.emit('chat-message', msg)
    })
    socket.on('typing', (data) => {
        socket.broadcast.emit('typing', data)
    })
    socket.on('stoptyping', () => {
        socket.broadcast.emit('stoptyping')
    })
})

    // Static folder
    app.use(express.static(__dirname + '/public/'));
    app.get(/.*/);

and here is package.json file

{
  "name": "express-demo",
  "version": "1.0.0",
  "description": "This is a full stack application",
  "engines": {
    "node": "13.1.0"
  },
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "dev": "nodemon index.js"
  },
  "author": "Farouk Turki",
  "license": "ISC",
  "dependencies": {
    "bcrypt": "^3.0.7",
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "jsonwebtoken": "^8.5.1",
    "mongodb": "^3.5.2",
    "mongoose": "^5.8.9",
    "nodemon": "^2.0.2",
    "socket.io": "^2.3.0"
  }
}

Everything is working fine except the chatroom so I need to know why it's still using port 5000 in localhost

Body:
From the front end (socket.io client) you are setting the hostname as localhost. But a front end code is not run server-side, it is in client side(your browser/or any thin client), it can access only the resources that are accessible over the internet(or the resources which is accessible by the browser itself).

So, in your case, the connection code will look something like:

<script>
  const socket = io('http://<your-heroku-public-url-for-the-express-server>');
  // which typically is
  const socket = io('http://randomname.herokuapp.com');
</script>

Given that http://randomname.herokuapp.com is the public url of your node js server.


问:
What does it mean to pre-increment $#array?
I've come across the following line of code.  It has issues:

it is intended to do the same as push

it ought to have used push

it's hard to read, understand

I've since changed it to use push

it does something I thought was illegal, but clearly isn't

here it is:

```<code>$array [++$#array] = 'data';
</code>```

My question is: what does it mean to pre-increment $#array?  I always considered $#array to be an attribute of an array, and not writable.

答:
perldata says:

"The length of an array is a scalar value. You may find the length of array @days by evaluating $#days , as in csh. However, this isn't the length of the array; it's the subscript of the last element, which is a different value since there is ordinarily a 0th element. Assigning to $#days  actually changes the length of the array. Shortening an array this way destroys intervening values. Lengthening an array that was previously shortened does not recover values that were in those elements."

Modifying $#array is useful in some cases, but in this case, clearly push is better.

OwnerDisplayName: Paul Beckingham

ContentLicense: CC BY-SA 2.5

Body:
I've come across the following line of code.  It has issues:

it is intended to do the same as push

it ought to have used push

it's hard to read, understand

I've since changed it to use push

it does something I thought was illegal, but clearly isn't

here it is:

$array [++$#array] = 'data';

My question is: what does it mean to pre-increment $#array?  I always considered $#array to be an attribute of an array, and not writable.

LastEditorDisplayName: brian d foy

OwnerDisplayName: ysth


问:
How to check if string contains chars which are not in a list?
I have a question. How do I check if a python string contains chars which are not in a given list?

Here is the list (set):

set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._")
```

答:
I always defer to regular expressions when validating strings.

To create a set, you enclose all characters in the set in [].
To check if a string contains any character not in a set, add ^ to the beginning.
To check if the string contains one or more members of a set, append +.

Given this information, a regular expression to check if a string contains any characters other than {a,b,c,d} would look like this:

[^abcd]+ (note that this is case sensitive)

To use regular expressions in python, import re. The re.search(pattern, string, flags=0) method will look through the entire string for the pattern you give.

More information on regular expressions in python can be found here. A simple regular expression tester can be found here.


问:
Split a list of JSON blobs delimited by commas (ignoring commas inside a JSON blob)
Here's a weird one. I'm given an ill-conceived input string that is a list of JSON blobs, separated commas. e.g.:

string input = "{<some JSON object>},{JSON_2},{JSON_3},...,{JSON_n}"
```

<p>And I have to convert this to an actual list of JSON strings (<code>List<string></code>).</p>

<p>For context, the unsanitary "input" list of JSONs is read in directly from a .txt file on disk, produced by some other software. I'm writing an "adapter" to allow this data to be consumed by another piece of software that knows how to interpret the individual JSON objects contained within the list. Ideally, the original software could have output one file per JSON object.</p>

<hr>

<p>The "obvious" solution (using <code>String.Split</code>):</p>

<pre class="lang-cs prettyprint-override"><code>List<string> split = input.Split(',').ToList();
</code>```

would of course fail to escape commas present within the JSON objects ({}) themselves

I was considering a manual approach - walking the string character-by-character and only splitting out a new element if the count of { is equal to the count of }. Something like:

List<string> JsonBlobs = new List<string>();
int start = 0, nestingLevel = 0;
for (int i = 0; i < input.Length; i++)
{
    if (input[i] == '{') nestingLevel++;
    else if (input[i] == '}') nestingLevel--;
    else if (input[i] == ',' && nestingLevel == 0)
    {
        JsonBlobs.Add(input.Substring(start, i - start));
        start = i + 1;
    }
}
```

<p><em>(The above likely contains bugs)</em></p>

<hr>

<p>I had also considered adding JSON array braces on either end of the string (<code>[]</code>) and letting a JSON serializer deserialize it as a JSON array, then re-serialize each of the array elements one at a time:</p>

<pre class="lang-cs prettyprint-override"><code>List<string> JsonBlobs = Newtonsoft.Json.Linq.JArray.Parse("[" + input + "]")
    .Select<Newtonsoft.Json.Linq.JToken, string>(token => token.ToString()).ToList();
</code>```

But this seems overly-expensive, and could potentially result in newly serialized JSON representations that are not exactly equal to the original string contents.

Any better suggestions?

I'd prefer to use some easily-understandable use of built-in libraries and/or LINQ if possible. Regex would be a last resort, although nifty regex solutions would also be interesting to see.

答:
Trying to parse this out using your own rules is fraught. You noticed the problem where JSON properties are comma-separated, but also bear in mind that JSON values can include strings, which could contain braces and commas, and even quote characters that have nothing to do with the JSON structure.

```<code>{"John's comment": "I was all like, \"no way!\" :-}"}
</code>```

To do it right, you're going to need to write a parser capable of handling all the JSON rules. You're likely to make mistakes, and unlikely to get much value out of the effort you put into it.

I would personally suggest the approach of adding brackets on either side of the string and deserializing the whole thing as a JSON array.

I'd also suggest questioning the requirement to convert the result to a list of strings: Was that requirement based on someone's assumption that producing a list of strings would be simpler than producing a list of JObjects or a list of some specific serialized type?

Body:
Here's a weird one. I'm given an ill-conceived input string that is a list of JSON blobs, separated commas. e.g.:

string input = "{<some JSON object>},{JSON_2},{JSON_3},...,{JSON_n}"

And I have to convert this to an actual list of JSON strings (List<string>).

For context, the unsanitary "input" list of JSONs is read in directly from a .txt file on disk, produced by some other software. I'm writing an "adapter" to allow this data to be consumed by another piece of software that knows how to interpret the individual JSON objects contained within the list. Ideally, the original software could have output one file per JSON object.

The "obvious" solution (using String.Split):

List<string> split = input.Split(',').ToList();

would of course fail to escape commas present within the JSON objects ({}) themselves

I was considering a manual approach - walking the string character-by-character and only splitting out a new element if the count of { is equal to the count of }. Something like:

List<string> JsonBlobs = new List<string>();
int start = 0, nestingLevel = 0;
for (int i = 0; i < input.Length; i++)
{
    if (input[i] == '{') nestingLevel++;
    else if (input[i] == '}') nestingLevel--;
    else if (input[i] == ',' && nestingLevel == 0)
    {
        JsonBlobs.Add(input.Substring(start, i - start));
        start = i + 1;
    }
}

(The above likely contains bugs)

I had also considered adding JSON array braces on either end of the string ([]) and letting a JSON serializer deserialize it as a JSON array, then re-serialize each of the array elements one at a time:

List<string> JsonBlobs = Newtonsoft.Json.Linq.JArray.Parse("[" + input + "]")
    .Select<Newtonsoft.Json.Linq.JToken, string>(token => token.ToString()).ToList();

But this seems overly-expensive, and could potentially result in newly serialized JSON representations that are not exactly equal to the original string contents.

Any better suggestions?

I'd prefer to use some easily-understandable use of built-in libraries and/or LINQ if possible. Regex would be a last resort, although nifty regex solutions would also be interesting to see.

Body:
Trying to parse this out using your own rules is fraught. You noticed the problem where JSON properties are comma-separated, but also bear in mind that JSON values can include strings, which could contain braces and commas, and even quote characters that have nothing to do with the JSON structure.

{"John's comment": "I was all like, \"no way!\" :-}"}

To do it right, you're going to need to write a parser capable of handling all the JSON rules. You're likely to make mistakes, and unlikely to get much value out of the effort you put into it.

I would personally suggest the approach of adding brackets on either side of the string and deserializing the whole thing as a JSON array.

I'd also suggest questioning the requirement to convert the result to a list of strings: Was that requirement based on someone's assumption that producing a list of strings would be simpler than producing a list of JObjects or a list of some specific serialized type?


问:
NLogger giving inconsistent data after each run
I have used NLog to log the entry and exits of functions in my code. But with different runs of the same Application I am getting different logs. It is a multi threaded application. And I am using async to log the information.

The following is my configuration:

```<code><?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <targets>
    <target name="asynclogger" xsi:type="AsyncWrapper" overflowAction="Grow" queueLimit="100000" batchSize="5000" timeToSleepBetweenBatches="1">
      <target name="logfile" xsi:type="File" fileName="D:\IALogs\${processname}_${processid}_${threadid}.ialog"  layout ="${longdate} ${processname} ${processid} ${threadid} ${mdlc:item=threadid} ${level} ${message}"/>
    </target>
  </targets>

  <rules>
    <logger name="*" minlevel="Info" writeTo="asynclogger" />
  </rules>
</nlog>
</code>```

The following is the logger code.

```<code>class Program
    {
        private static readonly NLog.Logger nLogger = NLog.LogManager.GetCurrentClassLogger();
        static void Main(string[] args)
        {
            Thread th1 = new Thread(() => print(5000000));
            th1.Start();

            Thread th2 = new Thread(() => print(5000000));

            th2.Start();

            th1.Join();
            th2.Join();

            print(10000);

            Console.WriteLine("Done!!!!");
            Console.ReadLine();
        }

        private static void print(int noOfItems)
        {
            for (int i = 1; i <= noOfItems; i++)
            {
                nLogger.Info("Printing i =" + i);
            }
        }
    }
</code>```

With Console.Readline() the logs are completely written,
if there is no Console.Readline() the logs are different each time and also
the third Print method call from the main thread doesn't log anything if there is no Console.Readline(). If Console.Readline() is present then the 3rd print statement logs all the information

答:
I guess your sentence "I am getting different logs" should be translated to "I am missing some logs".

When enabling async-operations for NLog targets, then it is important to flush, because writing happens on background threads. Must wait for these, before exiting the application:

```<code>NLog.LogManager.Flush()
</code>```

See also: NLog Tutorial - Remember to flush

Body:
I have used NLog to log the entry and exits of functions in my code. But with different runs of the same Application I am getting different logs. It is a multi threaded application. And I am using async to log the information.

The following is my configuration:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <targets>
    <target name="asynclogger" xsi:type="AsyncWrapper" overflowAction="Grow" queueLimit="100000" batchSize="5000" timeToSleepBetweenBatches="1">
      <target name="logfile" xsi:type="File" fileName="D:\IALogs\${processname}_${processid}_${threadid}.ialog"  layout ="${longdate} ${processname} ${processid} ${threadid} ${mdlc:item=threadid} ${level} ${message}"/>
    </target>
  </targets>

  <rules>
    <logger name="*" minlevel="Info" writeTo="asynclogger" />
  </rules>
</nlog>

The following is the logger code.

class Program
    {
        private static readonly NLog.Logger nLogger = NLog.LogManager.GetCurrentClassLogger();
        static void Main(string[] args)
        {
            Thread th1 = new Thread(() => print(5000000));
            th1.Start();

            Thread th2 = new Thread(() => print(5000000));

            th2.Start();

            th1.Join();
            th2.Join();

            print(10000);

            Console.WriteLine("Done!!!!");
            Console.ReadLine();
        }

        private static void print(int noOfItems)
        {
            for (int i = 1; i <= noOfItems; i++)
            {
                nLogger.Info("Printing i =" + i);
            }
        }
    }

With Console.Readline() the logs are completely written,
if there is no Console.Readline() the logs are different each time and also
the third Print method call from the main thread doesn't log anything if there is no Console.Readline(). If Console.Readline() is present then the 3rd print statement logs all the information

Body:
I guess your sentence "I am getting different logs" should be translated to "I am missing some logs".

When enabling async-operations for NLog targets, then it is important to flush, because writing happens on background threads. Must wait for these, before exiting the application:

NLog.LogManager.Flush()

See also: NLog Tutorial - Remember to flush


问:
alternative of time for a seed to a random number generator?
In Go what value can one use as an alternative of current time

for a seed to a random number generator?

This simple question came to me as I was following the Tour of Go

where they say the current time in their sandbox environment is fixed.

答:
If you want access to the math/rand convenience functions without the deterministic PRNG, you can create a new secure rand.Source yourself.

```<code>type cryptoSource [8]byte

func (s *cryptoSource) Int63() int64 {
    const mask = (1 << 63) - 1
    crand.Read(s[:])
    i := int64(binary.BigEndian.Uint64(s[:]))
    return i & mask
}

func (cryptoSource) Seed(int64) {}
</code>```

https://play.golang.org/p/sD4fOkE8LeD

Body:
If you want access to the math/rand convenience functions without the deterministic PRNG, you can create a new secure rand.Source yourself.

type cryptoSource [8]byte

func (s *cryptoSource) Int63() int64 {
    const mask = (1 << 63) - 1
    crand.Read(s[:])
    i := int64(binary.BigEndian.Uint64(s[:]))
    return i & mask
}

func (cryptoSource) Seed(int64) {}

https://play.golang.org/p/sD4fOkE8LeD


问:
Function was unable to start. Microsoft.Azure.DocumentDB.Core: PartitionKey value must be supplied for this operation.?
I have a simple azure function cosmos trigger set up, like so:

```<code>{
  "bindings": [
    {
      "type": "cosmosDBTrigger",
      "name": "documents",
      "direction": "in",
      "leaseCollectionName": "leases",
      "connectionStringSetting": "DbConnectionString",
      "databaseName": "mydb",
      "collectionName": "mycollection",
      "createLeaseCollectionIfNotExists": "true"
    }
  ],
  "scriptFile": "../dist/TestCosmosTrigger/index.js"
}
</code>```

When I run the function I get an error:

The listener for function 'Functions.FeedNotifier' was unable to
  start. Microsoft.Azure.Documents.ChangeFeedProcessor: Host was already
  initialized.

I did try to add a partitionKey field to th ebindings to no avail.

答:
Please update to the latest Microsoft.Azure.WebJobs.Extensions.CosmosDB dependency package.

This error either means you have a partitioned leases collection that is not partitioned by /id or you are using an old extension version.

Body:
I have a simple azure function cosmos trigger set up, like so:

{
  "bindings": [
    {
      "type": "cosmosDBTrigger",
      "name": "documents",
      "direction": "in",
      "leaseCollectionName": "leases",
      "connectionStringSetting": "DbConnectionString",
      "databaseName": "mydb",
      "collectionName": "mycollection",
      "createLeaseCollectionIfNotExists": "true"
    }
  ],
  "scriptFile": "../dist/TestCosmosTrigger/index.js"
}

When I run the function I get an error:

The listener for function 'Functions.FeedNotifier' was unable to
  start. Microsoft.Azure.Documents.ChangeFeedProcessor: Host was already
  initialized.

I did try to add a partitionKey field to th ebindings to no avail.


问:
How to keep persistent volumes in sync between clusters?
I'm trying to get an installation of Wordpress running in Kubernetes, as well as have an option of running the same configuration locally in minikube. I want to use the standard Docker image of Wordpress: https://hub.docker.com/_/wordpress/.

I'm having trouble with making sure that the plugins and templates are in sync though. The Docker container exposes a Volume at /var/www/html. Wordpress installation, as well as my plugins will live there.

Assuming I do the development on Minikube, along with the installation of plugins etc. How do handle the move between Persistent Volumes between my local cluster and the target cluster? Should I just reinstall Wordpress every time when the Pod is scaled?

答: In a real production scenario you would want to use a standard tool to backup and migrate persistent volumes between clusters. Valero is such a tool which enables you to achieve that.</p>


问:
Angular don't showing index page after restart nginx
I have a application in a vps server that have the backend in node.js and the frontend in Angular;

I restart the nginx and something problems starts. My api don't work more in https, only in http (before i can make request in https);

When i access in browser the link of my application i receive a message from my backend, as if i'm making a get in this route, but before than i restart the nginx when i access this link my frontend shows the login page...

My angular dist files is in public_html and my node app is in /nodeapp;

This is my nginx conf:

```<code>#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log;
    error_log error.log warn;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;
 server {
        listen 80;
        listen [::]:80 ipv6only=on;
        server_name knowhowexpressapp.com;
        location / {
    proxy_pass http://189.90.138.98:3333;
    proxy_http_version 1.1;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $host;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
}
</code>```

I try some things like:

```<code>pm2 restart server;
nginx -s reload
service nginx restart
</code>```

but my frontend is still not showing when i try to access the page.

答:
As we have been able to deduce together, the configuration of nginx started a redirect towards the backend incorrectly.

Our solution was to not use nginx and expose the port we needed on the server so that the angular application could reach it.

Of course we could also use nginx in this regard and redirect only one path to a specific port.

Body:
I have a application in a vps server that have the backend in node.js and the frontend in Angular;

I restart the nginx and something problems starts. My api don't work more in https, only in http (before i can make request in https);

When i access in browser the link of my application i receive a message from my backend, as if i'm making a get in this route, but before than i restart the nginx when i access this link my frontend shows the login page...

My angular dist files is in public_html and my node app is in /nodeapp;

This is my nginx conf:

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log;
    error_log error.log warn;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;
 server {
        listen 80;
        listen [::]:80 ipv6only=on;
        server_name knowhowexpressapp.com;
        location / {
    proxy_pass http://189.90.138.98:3333;
    proxy_http_version 1.1;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $host;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
}

I try some things like:

pm2 restart server;
nginx -s reload
service nginx restart

but my frontend is still not showing when i try to access the page.


问:
sql, big query: aggregate all entries between two strings in a variable
I have to solve this problem within bigQuery. I have this column in my table:

```<code>event            | time
_________________|____________________
start            | 1
end              | 2
random_event_X   | 3
start            | 4
error_X          | 5
error_Y          | 6
end              | 7
start            | 8
error_F          | 9
start            | 10
random_event_Y   | 11
error_z          | 12
end              | 13
</code>```

I would like to, from the end event record everything until start appear and then count it. Everything can happen between start and end and outside of it. If there is an end, there is a start, but if there is a start, there is not necessarily an end.

The desire output would be like:

```<code>string_agg                            | count
"start, end"                          |  1
"start, error_X, error_Y, end"        |  1
"start, random_event_Y error_Z, end"  |  1
</code>```

So everything between each start and end if start has an end. So without the random_event_X at time 3, the start at time 8 or the error_F at time 9.

I was not able to find the solution and have struggle understanding how to approach this problem. Any help or advice is welcome.

答:
Below is for BigQuery Standard SQL    </p>

```<code>#standardSQL
SELECT agg_events, COUNT(1) cnt
FROM (
  SELECT STRING_AGG(event ORDER BY time) agg_events, COUNTIF(event IN ('start', 'end')) flag
  FROM (
    SELECT *, COUNTIF(event = 'start') OVER(PARTITION BY grp1 ORDER BY time) grp2
    FROM (
      SELECT *, COUNTIF(event = 'end') OVER(ORDER BY time DESC) grp1
      FROM `project.dataset.table`
    )
  )
  GROUP BY grp1, grp2
)
WHERE flag = 2
GROUP BY agg_events
</code>```

<p>If to apply to sample data from your question - result is    </p>

```<code>Row agg_events                          cnt
1   start,random_event_Y,error_z,end    1
2   start,error_X,error_Y,end           1
3   start,end                           1
</code>```

Body:
I have to solve this problem within bigQuery. I have this column in my table:

event            | time
_________________|____________________
start            | 1
end              | 2
random_event_X   | 3
start            | 4
error_X          | 5
error_Y          | 6
end              | 7
start            | 8
error_F          | 9
start            | 10
random_event_Y   | 11
error_z          | 12
end              | 13

I would like to, from the end event record everything until start appear and then count it. Everything can happen between start and end and outside of it. If there is an end, there is a start, but if there is a start, there is not necessarily an end.

The desire output would be like:

string_agg                            | count
"start, end"                          |  1
"start, error_X, error_Y, end"        |  1
"start, random_event_Y error_Z, end"  |  1

So everything between each start and end if start has an end. So without the random_event_X at time 3, the start at time 8 or the error_F at time 9.

I was not able to find the solution and have struggle understanding how to approach this problem. Any help or advice is welcome.

Body:
Below is for BigQuery Standard SQL

#standardSQL
SELECT agg_events, COUNT(1) cnt
FROM (
  SELECT STRING_AGG(event ORDER BY time) agg_events, COUNTIF(event IN ('start', 'end')) flag
  FROM (
    SELECT *, COUNTIF(event = 'start') OVER(PARTITION BY grp1 ORDER BY time) grp2
    FROM (
      SELECT *, COUNTIF(event = 'end') OVER(ORDER BY time DESC) grp1
      FROM `project.dataset.table`
    )
  )
  GROUP BY grp1, grp2
)
WHERE flag = 2
GROUP BY agg_events

If to apply to sample data from your question - result is

Row agg_events                          cnt
1   start,random_event_Y,error_z,end    1
2   start,error_X,error_Y,end           1
3   start,end                           1


问:
How to add an onClick function to a dynamically-filled div?
I have bootstrap navbar with dropdown:

```<code><ul class="navbar-nav mr-auto">
  <li class="nav-item dropdown">
   <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria haspopup="true" aria-expanded="false">GANRES</a>
   <div class="dropdown-menu"></div>
  </li>
</ul>
</code>```

And I have function that fills them with genres with the TMDb API:

```<code>async function getGenres() {
    let url = "https://api.themoviedb.org/3/genre/movie/list?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-US";
    let response = await fetch(url);
    let genres = await response.json();
    let navbar = document.getElementsByClassName("nav-item dropdown");
    navbar.innerHTML += `<div class="dropdown-menu">`;
    let nav = document.getElementsByClassName("dropdown-menu");
    for (let i = 0; i < genres.genres.length; i++) {
        nav[0].innerHTML += `<a class="dropdown-item" href="#">` + genres.genres[i].name + `</a>`;
    }

//This part should add separately to each element, but it does not work
//Here is error: Cannot set property 'click' of undefined at getGenres

    for (let i = 0; i < genres.genres.length; i++) {
    document.getElementsByClassName("dropdown-menu")[i].click = function () {
        getmovies("discover/movie?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-us&sort_by=popularity.desc&include_adult=false&include_video=false&page=1&with_genres=" + genres.genres[i].id);
    };
};
}
</code>```

The items themselves are created normally.GenresThe onClick function just doesn't work.

I tried to load this function as onload in body, but it didn't work

答:
Thank @KiaiFighter. Here is the final code:</p>

```<code>async function getGenres() {
        let url = "https://api.themoviedb.org/3/genre/movie/list?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-US";
        let response = await fetch(url);
        let genres = await response.json();

        const navbar = document.getElementsByClassName("nav-item dropdown");

        let nav = document.createElement("div");
        nav.className = "dropdown-menu";

        for (let i = 0; i < genres.genres.length; i++) {
            let a_tag = document.createElement("a");
            let link = document.createTextNode(genres.genres[i].name);
            a_tag.appendChild(link);
            a_tag.className = "dropdown-item";
            a_tag.href = "#";
            nav.appendChild(a_tag);
        }
        navbar[0].appendChild(nav);
        console.log("nav", nav);

        const items = document.getElementsByClassName("dropdown-item");
        for (let i = 0; i < genres.genres.length; i++) {
            items[i].addEventListener("click", () => {
                getMovies("discover/movie?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-us&sort_by=popularity.desc&include_adult=false&include_video=false&page=1&with_genres=" + genres.genres[i].id);
            });
        }

        console.log("navbar", navbar);
    }
</code>```

Body:
I have bootstrap navbar with dropdown:

   GANRES

And I have function that fills them with genres with the TMDb API:

async function getGenres() {
    let url = "https://api.themoviedb.org/3/genre/movie/list?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-US";
    let response = await fetch(url);
    let genres = await response.json();
    let navbar = document.getElementsByClassName("nav-item dropdown");
    navbar.innerHTML += `<div class="dropdown-menu">`;
    let nav = document.getElementsByClassName("dropdown-menu");
    for (let i = 0; i < genres.genres.length; i++) {
        nav[0].innerHTML += `<a class="dropdown-item" href="#">` + genres.genres[i].name + `</a>`;
    }

//This part should add separately to each element, but it does not work
//Here is error: Cannot set property 'click' of undefined at getGenres

    for (let i = 0; i < genres.genres.length; i++) {
    document.getElementsByClassName("dropdown-menu")[i].click = function () {
        getmovies("discover/movie?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-us&sort_by=popularity.desc&include_adult=false&include_video=false&page=1&with_genres=" + genres.genres[i].id);
    };
};
}

The items themselves are created normally.GenresThe onClick function just doesn't work.

I tried to load this function as onload in body, but it didn't work

Body:
Thank @KiaiFighter. Here is the final code:

async function getGenres() {
        let url = "https://api.themoviedb.org/3/genre/movie/list?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-US";
        let response = await fetch(url);
        let genres = await response.json();

        const navbar = document.getElementsByClassName("nav-item dropdown");

        let nav = document.createElement("div");
        nav.className = "dropdown-menu";

        for (let i = 0; i < genres.genres.length; i++) {
            let a_tag = document.createElement("a");
            let link = document.createTextNode(genres.genres[i].name);
            a_tag.appendChild(link);
            a_tag.className = "dropdown-item";
            a_tag.href = "#";
            nav.appendChild(a_tag);
        }
        navbar[0].appendChild(nav);
        console.log("nav", nav);

        const items = document.getElementsByClassName("dropdown-item");
        for (let i = 0; i < genres.genres.length; i++) {
            items[i].addEventListener("click", () => {
                getMovies("discover/movie?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-us&sort_by=popularity.desc&include_adult=false&include_video=false&page=1&with_genres=" + genres.genres[i].id);
            });
        }

        console.log("navbar", navbar);
    }


问:
Backup/Restore a dockerized PostgreSQL database
I'm trying to backup/restore a PostgreSQL database as is explained on the Docker website, but the data is not restored.

The volumes used by the database image are:

```<code>VOLUME  ["/etc/postgresql", "/var/log/postgresql", "/var/lib/postgresql"]
</code>```

and the CMD is:

```<code>CMD ["/usr/lib/postgresql/9.3/bin/postgres", "-D", "/var/lib/postgresql/9.3/main", "-c", "config_file=/etc/postgresql/9.3/main/postgresql.conf"]
</code>```

I create the DB container with this command:

```<code>docker run -it --name "$DB_CONTAINER_NAME" -d "$DB_IMAGE_NAME"
</code>```

Then I connect another container to insert some data manually:

```<code>docker run -it --rm --link "$DB_CONTAINER_NAME":db "$DB_IMAGE_NAME" sh -c 'exec bash'
psql -d test -h $DB_PORT_5432_TCP_ADDR
# insert some data in the db
<CTRL-D>
<CTRL-D>
</code>```

The tar archive is then created:

```<code>$ sudo docker run --volumes-from "$DB_CONTAINER_NAME" --rm -v $(pwd):/backup ubuntu tar cvf /backup/backup.tar /etc/postgresql /var/log/postgresql /var/lib/postgresql
</code>```

Now I remove the container used for the db and create another one, with the same name, and try to restore the data inserted before:

```<code>$ sudo docker run --volumes-from "$DB_CONTAINER_NAME" --rm -v $(pwd):/backup ubuntu tar xvf /backup/backup.tar
</code>```

But the tables are empty, why is the data not properly restored ?

答:
dksnap (https://github.com/kelda/dksnap) automates the process of running pg_dumpall and loading the dump via /docker-entrypoint-initdb.d.

It shows you a list of running containers, and you pick which one you want to backup. The resulting artifact is a regular Docker image, so you can then docker run it, or share it by pushing it to a Docker registry.

(disclaimer: I'm a maintainer on the project)

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to backup/restore a PostgreSQL database as is explained on the Docker website, but the data is not restored.

The volumes used by the database image are:

VOLUME  ["/etc/postgresql", "/var/log/postgresql", "/var/lib/postgresql"]

and the CMD is:

CMD ["/usr/lib/postgresql/9.3/bin/postgres", "-D", "/var/lib/postgresql/9.3/main", "-c", "config_file=/etc/postgresql/9.3/main/postgresql.conf"]

I create the DB container with this command:

docker run -it --name "$DB_CONTAINER_NAME" -d "$DB_IMAGE_NAME"

Then I connect another container to insert some data manually:

docker run -it --rm --link "$DB_CONTAINER_NAME":db "$DB_IMAGE_NAME" sh -c 'exec bash'
psql -d test -h $DB_PORT_5432_TCP_ADDR
# insert some data in the db
<CTRL-D>
<CTRL-D>

The tar archive is then created:

$ sudo docker run --volumes-from "$DB_CONTAINER_NAME" --rm -v $(pwd):/backup ubuntu tar cvf /backup/backup.tar /etc/postgresql /var/log/postgresql /var/lib/postgresql

Now I remove the container used for the db and create another one, with the same name, and try to restore the data inserted before:

$ sudo docker run --volumes-from "$DB_CONTAINER_NAME" --rm -v $(pwd):/backup ubuntu tar xvf /backup/backup.tar

But the tables are empty, why is the data not properly restored ?


问:
Column-specific processing in an sklearn pipeline
I have a situation where I need to do some column-specific processing in a pipeline, but because transformers return numpy arrays rather than pandas dataframes, I don't have column names to do my feature engineering.

Here's a simple, reproducible example where I have a function called engineer_feature that I want to use to create new data. I need to use it during/after the pipeline because it depends on one column becoming imputed, and I would like it to be able to be performed during k-fold cross-validation.

```<code>import numpy as np
import pandas as pd

from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import FunctionTransformer, OneHotEncoder, StandardScaler

df = pd.DataFrame({"Type": ["Beta", "Beta", "Alpha", "Charlie", "Beta", "Charlie"], "A": [1, 2, 3, np.nan, 22, 4], "B": [5, 7, 12, 21, 12, 10]})

def engineer_feature(df):
    df["C"] = df["A"] / df["B"]
    return df

categorical_transformer = Pipeline([
    ("one_hot", OneHotEncoder())
])

numeric_transformer = Pipeline([
    ("imputer", SimpleImputer()),
    ("engineer", FunctionTransformer(engineer_feature)),
    ("scaler", StandardScaler())
])

preprocessor = ColumnTransformer([
    ("categorical", categorical_transformer, ["Type"]),
    ("numeric", numeric_transformer, ["A", "B"])
])

preprocessor.fit_transform(df)
</code>```

Which yields this error:

```<code>IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
</code>```

Which makes sense because engineer_feature is trying to index columns as if though they are dataframes when they are just numpy arrays.

What's a strategy for getting around this? I don't want to hardcode column indices to access them via numpy, especially since my real dataframe has many more columns.

答:
Thanks to the discussion and answers given by Nick and Sergey (specifically that I do know what columns of my dataframe I'm passing into engineer_feature), I've come up with a solution that is acceptable to me; though if anyone has a better idea, please chime in.

```<code>import numpy as np
import pandas as pd

from functools import partial
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import FunctionTransformer, OneHotEncoder, StandardScaler

df = pd.DataFrame({"Type": ["Beta", "Beta", "Alpha", "Charlie", "Beta", "Charlie"], "A": [1, 2, 3, np.nan, 22, 4], "B": [5, 7, 12, 21, 12, 10]})

def engineer_feature(columns, X):
    df = pd.DataFrame(X, columns=columns)
    df["C"] = df["A"] / df["B"]
    return df

categorical_transformer = Pipeline([
    ("one_hot", OneHotEncoder())
])

def numeric_transformer(columns):
    transformer = Pipeline([
        ("imputer", SimpleImputer()),
        ("engineer", FunctionTransformer(partial(engineer_feature, columns))),
        ("scaler", StandardScaler())
    ])

    return ("numeric", transformer, columns)

preprocessor = ColumnTransformer([
    ("categorical", categorical_transformer, ["Type"]),
    numeric_transformer(["A", "B"])
])

preprocessor.fit_transform(df)
</code>```

It's worth nothing this depends on both columns A and B to have at least one value each so that SimpleImputer does not drop the column.

Body:
I have a situation where I need to do some column-specific processing in a pipeline, but because transformers return numpy arrays rather than pandas dataframes, I don't have column names to do my feature engineering.

Here's a simple, reproducible example where I have a function called engineer_feature that I want to use to create new data. I need to use it during/after the pipeline because it depends on one column becoming imputed, and I would like it to be able to be performed during k-fold cross-validation.

import numpy as np
import pandas as pd

from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import FunctionTransformer, OneHotEncoder, StandardScaler

df = pd.DataFrame({"Type": ["Beta", "Beta", "Alpha", "Charlie", "Beta", "Charlie"], "A": [1, 2, 3, np.nan, 22, 4], "B": [5, 7, 12, 21, 12, 10]})

def engineer_feature(df):
    df["C"] = df["A"] / df["B"]
    return df

categorical_transformer = Pipeline([
    ("one_hot", OneHotEncoder())
])

numeric_transformer = Pipeline([
    ("imputer", SimpleImputer()),
    ("engineer", FunctionTransformer(engineer_feature)),
    ("scaler", StandardScaler())
])

preprocessor = ColumnTransformer([
    ("categorical", categorical_transformer, ["Type"]),
    ("numeric", numeric_transformer, ["A", "B"])
])

preprocessor.fit_transform(df)

Which yields this error:

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

Which makes sense because engineer_feature is trying to index columns as if though they are dataframes when they are just numpy arrays.

What's a strategy for getting around this? I don't want to hardcode column indices to access them via numpy, especially since my real dataframe has many more columns.

Body:
Thanks to the discussion and answers given by Nick and Sergey (specifically that I do know what columns of my dataframe I'm passing into engineer_feature), I've come up with a solution that is acceptable to me; though if anyone has a better idea, please chime in.

import numpy as np
import pandas as pd

from functools import partial
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import FunctionTransformer, OneHotEncoder, StandardScaler

df = pd.DataFrame({"Type": ["Beta", "Beta", "Alpha", "Charlie", "Beta", "Charlie"], "A": [1, 2, 3, np.nan, 22, 4], "B": [5, 7, 12, 21, 12, 10]})

def engineer_feature(columns, X):
    df = pd.DataFrame(X, columns=columns)
    df["C"] = df["A"] / df["B"]
    return df

categorical_transformer = Pipeline([
    ("one_hot", OneHotEncoder())
])

def numeric_transformer(columns):
    transformer = Pipeline([
        ("imputer", SimpleImputer()),
        ("engineer", FunctionTransformer(partial(engineer_feature, columns))),
        ("scaler", StandardScaler())
    ])

    return ("numeric", transformer, columns)

preprocessor = ColumnTransformer([
    ("categorical", categorical_transformer, ["Type"]),
    numeric_transformer(["A", "B"])
])

preprocessor.fit_transform(df)

It's worth nothing this depends on both columns A and B to have at least one value each so that SimpleImputer does not drop the column.


问:
create-react-app is showing all my code in production, how to hide it?

In my chrome sources tab, I am able to view all my files by exact folder location. How can I hide them?

These weren't the problem in my previous project, which were made without using create-react-app.

答:
Make this change in package.json file and you are good to go.

```<code>scripts: {
  "build": "GENERATE_SOURCEMAP=false react-scripts build"
}
</code>```

Body:
Make this change in package.json file and you are good to go.

scripts: {
  "build": "GENERATE_SOURCEMAP=false react-scripts build"
}


问:
HDFS String data to timestamp in hive table
Hi  I have a data in HDFS as a string '2015-03-26T00:00:00+00:00' ..if i want to load this data into Hive table (column as timestamp).i am not able to load and i am getting null values.

if i specify column as string i am getting the  data into hive table
but if i specify column as timestamp i am not able to load the data and i am getting all NULL values in that column.

Eg: HDFS - '2015-03-26T00:00:00+00:00'

 hive table- create table t1(my_date string)
i can get output as - '2015-03-26T00:00:00+00:00'

if i specify create table t1(my_date as timestamp)--i can see all null values

Can any one help me on this

答:
You have to use a staging table. In the staging table load as String and in the final table use UDF as below to convert the string value to Timestamp

from_unixtime(unix_timestamp(column_name, 'dd-MM-yyyy HH:mm'))


问:
Powershell ISE variable highlighter
Is there any add-ons for Powershell ISE where you can highlight any occurrence of the variable or any word? Something like Sublime Text has? </p>

答: The ISE was not highlighting any keywords/syntaxes, for me the issue was with the file extension,  the PS script file extension was inadvertently set to .ps, when I renamed it to have .ps1 extension, all the syntax highlighting revived.  Hope this helps others.

Title: Powershell ISE variable highlighter


问:
Http - Tunnel connection failed: 403 Forbidden error with Python web scraping
I am trying to web scrape a http website and I am getting below error when I am trying to read the website.

```<code>HTTPSConnectionPool(host='proxyvipecc.nb.xxxx.com', port=83): Max retries exceeded with url: http://campanulaceae.myspecies.info/ (Caused by ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 403 Forbidden',)))
</code>```

Below is the code I have written with similar website. I tried using urllib and user-agent and still the same issue.

```<code>url = "http://campanulaceae.myspecies.info/"

response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'})
soup = BeautifulSoup(response.text, 'html.parser')

</code>```

Can anyone help me with the issue. Thanks in advance

答:
you should try to add proxy while requesting url.

```<code>proxyDict = {
          'http'  : "add http proxy",
          'https' : "add https proxy"
        }

requests.get(url, proxies=proxyDict)
</code>```

you can find more information here

Body:
I am trying to web scrape a http website and I am getting below error when I am trying to read the website.

HTTPSConnectionPool(host='proxyvipecc.nb.xxxx.com', port=83): Max retries exceeded with url: http://campanulaceae.myspecies.info/ (Caused by ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 403 Forbidden',)))

Below is the code I have written with similar website. I tried using urllib and user-agent and still the same issue.

url = "http://campanulaceae.myspecies.info/"

response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'})
soup = BeautifulSoup(response.text, 'html.parser')

Can anyone help me with the issue. Thanks in advance

Body:
you should try to add proxy while requesting url.

proxyDict = {
          'http'  : "add http proxy",
          'https' : "add https proxy"
        }

requests.get(url, proxies=proxyDict)

you can find more information here


问:
Scale Html List based on resolution
I have a
 containing a series of elements, they are formatted with CSS so they form a half donut chart.
I want to make this mobile-friendly so the content scales along with the screen.

I have tried to used media queries to change the width, and height of the elements and also the border-radius size with no success.

    body {
      font: normal 16px/1.5 'Roboto', sans-serif;
      padding: 130px 0 0 0;
      background: #f1f1f1;
    }

    /* RESET STYLES
    –––––––––––––––––––––––––––––––––––––––––––––––––– */

    .chart-skills {
      margin: 0 auto;
      padding: 0;
      list-style-type: none;
    overflow: hidden;
    }

    .chart-skills *,
    .chart-skills::before {
      box-sizing: border-box;
    }

    /* CHART-SKILLS STYLES
    –––––––––––––––––––––––––––––––––––––––––––––––––– */

    .chart-skills {
      position: relative;
      width: 800px;
      height: 400px;
    }

    .chart-skills::before,
    .chart-skills::after {
      position: absolute;
    }

    .chart-skills::before {
      content: '';
      width: inherit;
      height: inherit;
      border: 45px solid rgba(211, 211, 211, .3);
      border-bottom: none;
      border-top-left-radius: 400px;
      border-top-right-radius: 400px;
    }

    .chart-skills::after {
      content: 'Low to High Risk';
      left: 50%;
      bottom: 10px;
      transform: translateX(-50%);
      font-size: 1.1rem;
      font-weight: bold;
      color: #009933;
    }

    .chart-skills li {
      position: absolute;
      top: 100%;
      left: 0;
      width: inherit;
      height: inherit;
      border: 45px solid;
      border-top: none;
      border-bottom-left-radius: 400px;
      border-bottom-right-radius: 400px;
      transform-origin: 50% 0;
    animation-fill-mode: forwards;
    animation-duration: .1s;
    animation-timing-function: linear;
    transform-style: preserve-3d;
    backface-visibility: hidden;
    }

    .chart-skills li:nth-child(1) {
      z-index: 19;
      border-color: #00FF00;
      animation-name: rotate-1;

    }

    .chart-skills li:nth-child(2) {
      z-index: 18;
      border-color: #24FF00;
      animation-name: rotate-2;
      animation-delay: .1s;

    }

    .chart-skills li:nth-child(3) {
      z-index: 17;
      border-color: #47FF00;
      animation-name: rotate-3;
      animation-delay: .2s;
    }

    .chart-skills li:nth-child(4) {
      z-index: 16;
      border-color: #58FF00;
      animation-name: rotate-4;
      animation-delay: .3s;

    }

    .chart-skills li:nth-child(5) {
      z-index: 15;
      border-color: #6AFF00;
      animation-name: rotate-5;
      animation-delay: .4s;
    }

    .chart-skills li:nth-child(6) {
      z-index: 14;
      border-color: #8DFF00;
      animation-name: rotate-6;
      animation-delay: .6s;

    }

    .chart-skills li:nth-child(7) {
      z-index: 13;
      border-color: #B0FF00;
      animation-name: rotate-7;
      animation-delay: .7s;

    }

    .chart-skills li:nth-child(8) {
      z-index: 12;
      border-color: #D4FF00;
      animation-name: rotate-8;
      animation-delay: .8s;

    }

    .chart-skills li:nth-child(9) {
      z-index: 11;
      border-color: #F7FF00;
      animation-name: rotate-9;
      animation-delay: .9s;

    }

    .chart-skills li:nth-child(10) {
      z-index: 10;
      border-color: #FFF600;
      animation-name: rotate-10;
      animation-delay: 1s;

    }

    .chart-skills li:nth-child(11) {
      z-index: 9;
      border-color: #FFE400;
      animation-name: rotate-11;
      animation-delay: 1.1s;

    }

    .chart-skills li:nth-child(12) {
      z-index: 8;
      border-color: #FFD300;
      animation-name: rotate-12;
      animation-delay: 1.2s;

    }

    .chart-skills li:nth-child(13) {
      z-index: 7;
      border-color: #FFAF00;
      animation-name: rotate-13;
      animation-delay: 1.3s;

    }

    .chart-skills li:nth-child(14) {
      z-index: 6;
      border-color: #FF8C00;
      animation-name: rotate-14;
      animation-delay: 1.4s;

    }

    .chart-skills li:nth-child(15) {
      z-index: 5;
      border-color: #FF6900;
      animation-name: rotate-15;
      animation-delay: 1.5s;

    }

    .chart-skills li:nth-child(16) {
      z-index: 4;
      border-color: #FF4600;
      animation-name: rotate-16;
      animation-delay: 1.6s;
    }

    .chart-skills li:nth-child(17) {
      z-index: 3;
      border-color: #FF2300;
      animation-name: rotate-17;
      animation-delay: 1.7s;
    }
    .chart-skills li:nth-child(18) {
      z-index: 2;
      border-color: #FF1100;
      animation-name: rotate-18;
      animation-delay: 1.8s;
    }

    .chart-skills li:nth-child(19) {
      z-index: 1;
      border-color: #FF0000;
      animation-name: rotate-19;
      animation-delay: 1.9s;
    }

    /*----------------------------------------------------------------------------------------------------------------------------------*/
    @keyframes rotate-1{
      100% {
        transform: rotate(9.5deg);
      }
    }

    @keyframes rotate-2{
      0% {
        transform: rotate(9.5deg);
      }
      100% {
        transform: rotate(19deg);
      }
    }

    @keyframes rotate-3{
      0% {
        transform: rotate(19deg);
      }
      100% {
        transform: rotate(28.5deg);
      }
    }

    @keyframes rotate-4{
      0% {
        transform: rotate(28.5deg);
      }
      100% {
        transform: rotate(38deg);
      }
    }
    @keyframes rotate-5{
      0% {
        transform: rotate(38deg);
      }
      100% {
        transform: rotate(47.5deg);
      }
    }

    @keyframes rotate-6{
      0% {
        transform: rotate(47.5deg);
      }
      100% {
        transform: rotate(57deg);
      }
    }

    @keyframes rotate-7{
      0% {
        transform: rotate(57deg);
      }
      100% {
        transform: rotate(66.5deg);
      }
    }

    @keyframes rotate-8{
      0% {
        transform: rotate(66.5deg);
      }
      100% {
        transform: rotate(76deg);
      }
    }

    @keyframes rotate-9{
      0% {
        transform: rotate(76deg);
      }
      100% {
        transform: rotate(85.5deg);
      }
    }

    @keyframes rotate-10{
      0% {
        transform: rotate(85.5deg);
      }
      100% {
        transform: rotate(95deg);
      }
    }

    @keyframes rotate-11{
      0% {
        transform: rotate(95deg);
      }
      100% {
        transform: rotate(104.5deg);
      }
    }

    @keyframes rotate-12{
      0% {
        transform: rotate(104.5deg);
      }
      100% {
        transform: rotate(114deg);
      }
    }

    @keyframes rotate-13{
      0% {
        transform: rotate(114deg);
      }
      100% {
        transform: rotate(123.5deg);
      }
    }

    @keyframes rotate-14{
      0% {
        transform: rotate(123.5deg);
      }
      100% {
        transform: rotate(133deg);
      }
    }

    @keyframes rotate-15{
      0% {
        transform: rotate(133deg);
      }
      100% {
        transform: rotate(142.5deg);
      }
    }

    @keyframes rotate-16{
      0% {
        transform: rotate(142.5deg);
      }
      100% {
        transform: rotate(152deg);
      }
    }

    @keyframes rotate-17{
      0% {
        transform: rotate(152deg);
      }
      100% {
        transform: rotate(161.5deg);
      }
    }

    @keyframes rotate-18{
      0% {
        transform: rotate(161.5deg);
      }
      100% {
        transform: rotate(171deg);
      }
    }

    @keyframes rotate-19{
      0% {
        transform: rotate(171deg);
      }
      100% {
        transform: rotate(180deg);
      }
    }

    .chart-skills span {
      position: absolute;
      font-size: .85rem;
    }

    /*-------------------------------------------------------------------------------------------------------------------*/
    .chart-skills li:nth-child(1) span {
      top: 20px;
      left: 10px;
      transform: rotate(-9.5deg);
    }

    .chart-skills li:nth-child(2) span {
      top: -5px;
      left: 2px;
      transform: rotate(-19deg);
    }

    .chart-skills li:nth-child(3) span {
      top: 10px;
      left: 0px;
      transform: rotate(-28.5deg);
    }

    .chart-skills li:nth-child(4) span {
      top: 60px;
      left: 10px;
      transform: rotate(-38deg);
    }

    .chart-skills li:nth-child(5) span {
      top: 45px;
      left: 0px;
      transform: rotate(-47.5deg);
    }

    .chart-skills li:nth-child(6) span {
      top: 50px;
      left:  0px;
      transform: rotate(-57deg);
    }

    .chart-skills li:nth-child(7) span {
      top: 55px;
      left: -5px;
      transform: rotate(-66.5deg);
    }

    .chart-skills li:nth-child(8) span {
      top: 5px;
      left: -10px;
      transform: rotate(-76deg);
    }

    .chart-skills li:nth-child(9) span {
      top: 105px;
      left: 5px;
      transform: rotate(-85.5deg);
    }

    .chart-skills li:nth-child(10) span {
      top: 15px;
      left: -35px;
      transform: rotate(-95deg);
    }

    .chart-skills li:nth-child(11) span {
      top: -25px;
      left: -25px;
      transform: rotate(-104.5deg);
    }

    .chart-skills li:nth-child(12) span {
      top: -40px;
      left: -10px;
      transform: rotate(-114deg);
    }

    .chart-skills li:nth-child(13) span {
      top: -75px;
      left: 10px;
      transform: rotate(-123.5deg);
    }

    .chart-skills li:nth-child(14) span {
      top: 35px;
      left: -5px;
      transform: rotate(-133deg);
    }
    .chart-skills li:nth-child(15) span {
      top: -25px;
      left: -5px;
      transform: rotate(-142.5deg);
    }

    .chart-skills li:nth-child(16) span {
      top: -15px;
      left: 10px;
      transform: rotate(-152deg);
    }

    .chart-skills li:nth-child(17) span {
      top: -10px;
      left: 10px;
      transform: rotate(-161.5deg);
    }

    .chart-skills li:nth-child(18) span {
      top: 0px;
      left: 10px;
      transform: rotate(-171deg);
    }

    .chart-skills li:nth-child(19) span {
      top: 10px;
      left: 10px;
      transform: rotate(-180deg);
    }
    @keyframes fade-in {
      0%,
      90% {
        opacity: 0;
      }
      100% {
        opacity: 1;
      }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <ul class="chart-skills">
      <li><span>US savings bonds</span></li>
      <li><span>Savings accounts, money market accounts and CDs</span></li>
      <li><span>US Treasury bills, notes and bonds</span></li>
      <li><span>Annuities</span></li>
      <li><span>Money market funds</span></li>
      <li><span>Municipal bonds</span></li>
      <li><span>Corporate bonds</span></li>
      <li><span>High-yield</span></li>
      <li><span>REITs and MLPs</span></li>
      <li><span>Rental real estate</span></li>
      <li><span>Preferred stock</span></li>
      <li><span>Index funds</span></li>
      <li><span>Mutual funds</span></li>
      <li><span>Large-cap stocks</span></li>
      <li><span>Mid-cap stocks</span></li>
      <li><span>Small-cap stocks</span></li>
      <li><span>Commodities</span></li>
      <li><span>Options</span></li>
      <li><span>Futures</span></li>
    </ul></code>```

答:
The only viable option I see for this is to make this object as an inline SVG element and just scale it. The problem is that it won't be really responsive, it would just scale in terms of size, making the font size really small for smaller screens.

The problem here is the rotation of the elements, because if you reduce the size of the container it gets completely out of place and you'd have to use a lot of conditions for it to work even remotely close to what is desired.

You could make the image as a vector, export the code and just manipulate the text items. After that you just add width: 100%; height: auto to the svg element and it fits its parent element.

The problem here is that it has way too many elements to be readable in a cell phone. You should consider using an alternative layout for smaller screens.

Title: Scale Html List based on resolution

Body:
I have a
 containing a series of elements, they are formatted with CSS so they form a half donut chart.
I want to make this mobile-friendly so the content scales along with the screen.

I have tried to used media queries to change the width, and height of the elements and also the border-radius size with no success.

    body {
      font: normal 16px/1.5 'Roboto', sans-serif;
      padding: 130px 0 0 0;
      background: #f1f1f1;
    }

    /* RESET STYLES
    –––––––––––––––––––––––––––––––––––––––––––––––––– */

    .chart-skills {
      margin: 0 auto;
      padding: 0;
      list-style-type: none;
    overflow: hidden;
    }

    .chart-skills *,
    .chart-skills::before {
      box-sizing: border-box;
    }

    /* CHART-SKILLS STYLES
    –––––––––––––––––––––––––––––––––––––––––––––––––– */

    .chart-skills {
      position: relative;
      width: 800px;
      height: 400px;
    }

    .chart-skills::before,
    .chart-skills::after {
      position: absolute;
    }

    .chart-skills::before {
      content: '';
      width: inherit;
      height: inherit;
      border: 45px solid rgba(211, 211, 211, .3);
      border-bottom: none;
      border-top-left-radius: 400px;
      border-top-right-radius: 400px;
    }

    .chart-skills::after {
      content: 'Low to High Risk';
      left: 50%;
      bottom: 10px;
      transform: translateX(-50%);
      font-size: 1.1rem;
      font-weight: bold;
      color: #009933;
    }

    .chart-skills li {
      position: absolute;
      top: 100%;
      left: 0;
      width: inherit;
      height: inherit;
      border: 45px solid;
      border-top: none;
      border-bottom-left-radius: 400px;
      border-bottom-right-radius: 400px;
      transform-origin: 50% 0;
    animation-fill-mode: forwards;
    animation-duration: .1s;
    animation-timing-function: linear;
    transform-style: preserve-3d;
    backface-visibility: hidden;
    }

    .chart-skills li:nth-child(1) {
      z-index: 19;
      border-color: #00FF00;
      animation-name: rotate-1;

    }

    .chart-skills li:nth-child(2) {
      z-index: 18;
      border-color: #24FF00;
      animation-name: rotate-2;
      animation-delay: .1s;

    }

    .chart-skills li:nth-child(3) {
      z-index: 17;
      border-color: #47FF00;
      animation-name: rotate-3;
      animation-delay: .2s;
    }

    .chart-skills li:nth-child(4) {
      z-index: 16;
      border-color: #58FF00;
      animation-name: rotate-4;
      animation-delay: .3s;

    }

    .chart-skills li:nth-child(5) {
      z-index: 15;
      border-color: #6AFF00;
      animation-name: rotate-5;
      animation-delay: .4s;
    }

    .chart-skills li:nth-child(6) {
      z-index: 14;
      border-color: #8DFF00;
      animation-name: rotate-6;
      animation-delay: .6s;

    }

    .chart-skills li:nth-child(7) {
      z-index: 13;
      border-color: #B0FF00;
      animation-name: rotate-7;
      animation-delay: .7s;

    }

    .chart-skills li:nth-child(8) {
      z-index: 12;
      border-color: #D4FF00;
      animation-name: rotate-8;
      animation-delay: .8s;

    }

    .chart-skills li:nth-child(9) {
      z-index: 11;
      border-color: #F7FF00;
      animation-name: rotate-9;
      animation-delay: .9s;

    }

    .chart-skills li:nth-child(10) {
      z-index: 10;
      border-color: #FFF600;
      animation-name: rotate-10;
      animation-delay: 1s;

    }

    .chart-skills li:nth-child(11) {
      z-index: 9;
      border-color: #FFE400;
      animation-name: rotate-11;
      animation-delay: 1.1s;

    }

    .chart-skills li:nth-child(12) {
      z-index: 8;
      border-color: #FFD300;
      animation-name: rotate-12;
      animation-delay: 1.2s;

    }

    .chart-skills li:nth-child(13) {
      z-index: 7;
      border-color: #FFAF00;
      animation-name: rotate-13;
      animation-delay: 1.3s;

    }

    .chart-skills li:nth-child(14) {
      z-index: 6;
      border-color: #FF8C00;
      animation-name: rotate-14;
      animation-delay: 1.4s;

    }

    .chart-skills li:nth-child(15) {
      z-index: 5;
      border-color: #FF6900;
      animation-name: rotate-15;
      animation-delay: 1.5s;

    }

    .chart-skills li:nth-child(16) {
      z-index: 4;
      border-color: #FF4600;
      animation-name: rotate-16;
      animation-delay: 1.6s;
    }

    .chart-skills li:nth-child(17) {
      z-index: 3;
      border-color: #FF2300;
      animation-name: rotate-17;
      animation-delay: 1.7s;
    }
    .chart-skills li:nth-child(18) {
      z-index: 2;
      border-color: #FF1100;
      animation-name: rotate-18;
      animation-delay: 1.8s;
    }

    .chart-skills li:nth-child(19) {
      z-index: 1;
      border-color: #FF0000;
      animation-name: rotate-19;
      animation-delay: 1.9s;
    }

    /*----------------------------------------------------------------------------------------------------------------------------------*/
    @keyframes rotate-1{
      100% {
        transform: rotate(9.5deg);
      }
    }

    @keyframes rotate-2{
      0% {
        transform: rotate(9.5deg);
      }
      100% {
        transform: rotate(19deg);
      }
    }

    @keyframes rotate-3{
      0% {
        transform: rotate(19deg);
      }
      100% {
        transform: rotate(28.5deg);
      }
    }

    @keyframes rotate-4{
      0% {
        transform: rotate(28.5deg);
      }
      100% {
        transform: rotate(38deg);
      }
    }
    @keyframes rotate-5{
      0% {
        transform: rotate(38deg);
      }
      100% {
        transform: rotate(47.5deg);
      }
    }

    @keyframes rotate-6{
      0% {
        transform: rotate(47.5deg);
      }
      100% {
        transform: rotate(57deg);
      }
    }

    @keyframes rotate-7{
      0% {
        transform: rotate(57deg);
      }
      100% {
        transform: rotate(66.5deg);
      }
    }

    @keyframes rotate-8{
      0% {
        transform: rotate(66.5deg);
      }
      100% {
        transform: rotate(76deg);
      }
    }

    @keyframes rotate-9{
      0% {
        transform: rotate(76deg);
      }
      100% {
        transform: rotate(85.5deg);
      }
    }

    @keyframes rotate-10{
      0% {
        transform: rotate(85.5deg);
      }
      100% {
        transform: rotate(95deg);
      }
    }

    @keyframes rotate-11{
      0% {
        transform: rotate(95deg);
      }
      100% {
        transform: rotate(104.5deg);
      }
    }

    @keyframes rotate-12{
      0% {
        transform: rotate(104.5deg);
      }
      100% {
        transform: rotate(114deg);
      }
    }

    @keyframes rotate-13{
      0% {
        transform: rotate(114deg);
      }
      100% {
        transform: rotate(123.5deg);
      }
    }

    @keyframes rotate-14{
      0% {
        transform: rotate(123.5deg);
      }
      100% {
        transform: rotate(133deg);
      }
    }

    @keyframes rotate-15{
      0% {
        transform: rotate(133deg);
      }
      100% {
        transform: rotate(142.5deg);
      }
    }

    @keyframes rotate-16{
      0% {
        transform: rotate(142.5deg);
      }
      100% {
        transform: rotate(152deg);
      }
    }

    @keyframes rotate-17{
      0% {
        transform: rotate(152deg);
      }
      100% {
        transform: rotate(161.5deg);
      }
    }

    @keyframes rotate-18{
      0% {
        transform: rotate(161.5deg);
      }
      100% {
        transform: rotate(171deg);
      }
    }

    @keyframes rotate-19{
      0% {
        transform: rotate(171deg);
      }
      100% {
        transform: rotate(180deg);
      }
    }

    .chart-skills span {
      position: absolute;
      font-size: .85rem;
    }

    /*-------------------------------------------------------------------------------------------------------------------*/
    .chart-skills li:nth-child(1) span {
      top: 20px;
      left: 10px;
      transform: rotate(-9.5deg);
    }

    .chart-skills li:nth-child(2) span {
      top: -5px;
      left: 2px;
      transform: rotate(-19deg);
    }

    .chart-skills li:nth-child(3) span {
      top: 10px;
      left: 0px;
      transform: rotate(-28.5deg);
    }

    .chart-skills li:nth-child(4) span {
      top: 60px;
      left: 10px;
      transform: rotate(-38deg);
    }

    .chart-skills li:nth-child(5) span {
      top: 45px;
      left: 0px;
      transform: rotate(-47.5deg);
    }

    .chart-skills li:nth-child(6) span {
      top: 50px;
      left:  0px;
      transform: rotate(-57deg);
    }

    .chart-skills li:nth-child(7) span {
      top: 55px;
      left: -5px;
      transform: rotate(-66.5deg);
    }

    .chart-skills li:nth-child(8) span {
      top: 5px;
      left: -10px;
      transform: rotate(-76deg);
    }

    .chart-skills li:nth-child(9) span {
      top: 105px;
      left: 5px;
      transform: rotate(-85.5deg);
    }

    .chart-skills li:nth-child(10) span {
      top: 15px;
      left: -35px;
      transform: rotate(-95deg);
    }

    .chart-skills li:nth-child(11) span {
      top: -25px;
      left: -25px;
      transform: rotate(-104.5deg);
    }

    .chart-skills li:nth-child(12) span {
      top: -40px;
      left: -10px;
      transform: rotate(-114deg);
    }

    .chart-skills li:nth-child(13) span {
      top: -75px;
      left: 10px;
      transform: rotate(-123.5deg);
    }

    .chart-skills li:nth-child(14) span {
      top: 35px;
      left: -5px;
      transform: rotate(-133deg);
    }
    .chart-skills li:nth-child(15) span {
      top: -25px;
      left: -5px;
      transform: rotate(-142.5deg);
    }

    .chart-skills li:nth-child(16) span {
      top: -15px;
      left: 10px;
      transform: rotate(-152deg);
    }

    .chart-skills li:nth-child(17) span {
      top: -10px;
      left: 10px;
      transform: rotate(-161.5deg);
    }

    .chart-skills li:nth-child(18) span {
      top: 0px;
      left: 10px;
      transform: rotate(-171deg);
    }

    .chart-skills li:nth-child(19) span {
      top: 10px;
      left: 10px;
      transform: rotate(-180deg);
    }
    @keyframes fade-in {
      0%,
      90% {
        opacity: 0;
      }
      100% {
        opacity: 1;
      }

US savings bonds

Savings accounts, money market accounts and CDs

US Treasury bills, notes and bonds

Annuities

Money market funds

Municipal bonds

Corporate bonds

High-yield

REITs and MLPs

Rental real estate

Preferred stock

Index funds

Mutual funds

Large-cap stocks

Mid-cap stocks

Small-cap stocks

Commodities

Options

Futures


问:
How to create a query with two joins to the same lookup table
I am hoping someone can point me in the correct direction, I am just an amateur playing with a hobby.

I have 2 tables, first table 'tbl_wheel_diameter' has just 'wheel_diameter' and 'id'

Second table 'tbl_tyres' has 'wheel_diameter_front','wheel_diameter_rear' and 'vehicleId'

I need to write a query that selects the front and rear diameter together.
This is something I tried.

```<code>SELECT  tbl_wheel_diameter.wheel_diameter_front,tbl_wheel_diameter.wheel_diameter_rear
FROM tbl_tyres
INNER JOIN tbl_wheel_diameter
     ON tbl_wheel_diameter.id = tbl_tyres.wheel_diameter
WHERE tbl_tyres.vehicleId = 2
</code>```

I have read that I should use left joins but I seem to get confused with how to write them?

答:
Add an alias for the table so you can include the same table twice. Here is an example using an alias of t1 and t2.</p>

```<code>SELECT  t1.wheel_diameter,t2.wheel_diameter
FROM tbl_tyres
INNER JOIN tbl_wheel_diameter t1
     ON t1.id = tbl_tyres.wheel_diameter_front
INNER JOIN tbl_wheel_diameter t2
     ON t2.id = tbl_tyres.wheel_diameter_rear
WHERE tbl_tyres.vehicleId = 1
</code>```

Body:
I am hoping someone can point me in the correct direction, I am just an amateur playing with a hobby.

I have 2 tables, first table 'tbl_wheel_diameter' has just 'wheel_diameter' and 'id'

Second table 'tbl_tyres' has 'wheel_diameter_front','wheel_diameter_rear' and 'vehicleId'

I need to write a query that selects the front and rear diameter together.
This is something I tried.

SELECT  tbl_wheel_diameter.wheel_diameter_front,tbl_wheel_diameter.wheel_diameter_rear
FROM tbl_tyres
INNER JOIN tbl_wheel_diameter
     ON tbl_wheel_diameter.id = tbl_tyres.wheel_diameter
WHERE tbl_tyres.vehicleId = 2

I have read that I should use left joins but I seem to get confused with how to write them?

Body:
Add an alias for the table so you can include the same table twice. Here is an example using an alias of t1 and t2.

SELECT  t1.wheel_diameter,t2.wheel_diameter
FROM tbl_tyres
INNER JOIN tbl_wheel_diameter t1
     ON t1.id = tbl_tyres.wheel_diameter_front
INNER JOIN tbl_wheel_diameter t2
     ON t2.id = tbl_tyres.wheel_diameter_rear
WHERE tbl_tyres.vehicleId = 1


问:
Why is more memory allocated than expected?
I'm playing around with BenchmarkDotNet and its MemoryDiagnoser feature.

Considering the following benchmark:

```<code>[Benchmark]
public void Dummy()
{
   var buffer = new byte[1];
}
</code>```

I expect it to allocate exactly 1 byte.

But the benchmark result shows that a total of 32 bytes were allocated. How come? I find this quite misleading.

```<code>| Method |     Mean |     Error |    StdDev |   Median | Ratio | Rank |  Gen 0 | Gen 1 | Gen 2 | Allocated |
|------- |---------:|----------:|----------:|---------:|------:|-----:|-------:|------:|------:|----------:|
|  Dummy | 4.486 ns | 0.1762 ns | 0.5196 ns | 4.650 ns |  1.00 |    1 | 0.0038 |     - |     - |      32 B |

                                                                                why not 1 byte? ^^^^
</code>```

答:
I am the author of MemoryDiagnoser and I've described how to read the results my blog: https://adamsitnik.com/the-new-Memory-Diagnoser/#how-to-read-the-results

CLR does some aligning. If you try to allocate new byte[1] array, it will allocate byte[8] array.

We need extra space for object header, method table pointer and length of the array. The overhead is 3x Pointer Size. 8 + 3x4 = 20 for 32bit and 8 + 3x8 = 32 for 64bit.

Body:
I'm playing around with BenchmarkDotNet and its MemoryDiagnoser feature.

Considering the following benchmark:

[Benchmark]
public void Dummy()
{
   var buffer = new byte[1];
}

I expect it to allocate exactly 1 byte.

But the benchmark result shows that a total of 32 bytes were allocated. How come? I find this quite misleading.

| Method |     Mean |     Error |    StdDev |   Median | Ratio | Rank |  Gen 0 | Gen 1 | Gen 2 | Allocated |
|------- |---------:|----------:|----------:|---------:|------:|-----:|-------:|------:|------:|----------:|
|  Dummy | 4.486 ns | 0.1762 ns | 0.5196 ns | 4.650 ns |  1.00 |    1 | 0.0038 |     - |     - |      32 B |

                                                                                why not 1 byte? ^^^^


问:
How to pass ifdef defines to a .f file
Hi is there any way to add `ifdef in .f files. I have a .f file which includes hierarchial compilation.

```<code>`ifdef ASIC

rtl/a.v

`else
rtl/b.v
endif
</code>```

this is my intention if ASIC is passed as define a.v needs to compile. else b.v. Does the above code works without adding any extra things?

答:
I'm not aware of any tool that does this on the command line. Either create the .f file dynamically as part of your build process, or use a Verilog file to do this instead. </p>

```<code>`ifdef ASIC

`include "rtl/a.v"

`else
`include "rtl/b.v"
`endif
</code>```

Title: How to pass ifdef defines to a .f file

Body:
Hi is there any way to add `ifdef in .f files. I have a .f file which includes hierarchial compilation.

`ifdef ASIC

rtl/a.v

`else
rtl/b.v
endif

this is my intention if ASIC is passed as define a.v needs to compile. else b.v. Does the above code works without adding any extra things?

Body:
I'm not aware of any tool that does this on the command line. Either create the .f file dynamically as part of your build process, or use a Verilog file to do this instead.

`ifdef ASIC

`include "rtl/a.v"

`else
`include "rtl/b.v"
`endif


问:
Tests and code-coverage with private methods with Angular and Jasmine/Karma
So, I got these methods on my button component.

```<code>export class SidebarButtonComponent implements OnInit {

  private subscribeToRouter(): void {
    this.router.events.subscribe(route => {
      if (route instanceof NavigationEnd) {
        this.isSelected(route.urlAfterRedirects);
      }
    });
  }

  private isSelected(route: string): void {
    if (this.checkRoute(route)) {
      this.selected = true;
    } else {
      this.selected = false;
    }
  }

  private checkRoute(route: string): boolean {
    return route.includes(this.link);
  }

}
</code>```

I know I can't access private methods on my specs files, but the code coverage from Angular says I don't cover it:

59.09% Statements 13/22 37.5% Branches 3/8 42.86% Functions 3/7 52.63% Lines 10/19

What's the best methods to test these private tests, or at least, ignore them in code coverage?

答:
Access modifiers in typescript are only used in compile time. You can't directly access them like this

```<code>component.privateMethod(); // not accessible
</code>```

But you can access them using any:

```<code>(component as any).privateMethod();
</code>```

This is a workaround to access the private methods, otherwise you can test them using the methods in which these private methods are called.

Body:
So, I got these methods on my button component.

export class SidebarButtonComponent implements OnInit {

  private subscribeToRouter(): void {
    this.router.events.subscribe(route => {
      if (route instanceof NavigationEnd) {
        this.isSelected(route.urlAfterRedirects);
      }
    });
  }

  private isSelected(route: string): void {
    if (this.checkRoute(route)) {
      this.selected = true;
    } else {
      this.selected = false;
    }
  }

  private checkRoute(route: string): boolean {
    return route.includes(this.link);
  }

}

I know I can't access private methods on my specs files, but the code coverage from Angular says I don't cover it:

59.09% Statements 13/22 37.5% Branches 3/8 42.86% Functions 3/7 52.63% Lines 10/19

What's the best methods to test these private tests, or at least, ignore them in code coverage?

Body:
Access modifiers in typescript are only used in compile time. You can't directly access them like this

component.privateMethod(); // not accessible

But you can access them using any:

(component as any).privateMethod();

This is a workaround to access the private methods, otherwise you can test them using the methods in which these private methods are called.


问:
Search a text on terminal output on Mac (not using Terminator)
I installed something via Terminal (iterm2) on Mac and it showed a whole bunch of commands while installing. I need to look for a specific word to decide my next step?

What should I do?

Note:

I don't want to search a file. I want to search a text on the terminal output.

I cant use Ctrl + Shift + F. It for Ubuntu, not for Mac.

I don't use Terminator.

答:
Damn it! Simply Ctrl + F works.

Edit: As @sojim2 pointed out in comments, it's CMD + F on mac.


问:
Android, icon been duplicate when i install my app on the device
I try to install the app that i develop on my device  (Htc desire) and i see that the icon of the app is duplicate

what i need to change to don't late that happen?

how could i delete one of the icon?

Thanks for helping!!

答:
for change icon of app..

```<code><application android:icon="@drawable/icon" android:label="@string/app_name">
</code>```

see this line in your menifest file.. and change "@drawable/your_icon_name" instead of "@drawable/icon"

Body:
for change icon of app..

<application android:icon="@drawable/icon" android:label="@string/app_name">

see this line in your menifest file.. and change "@drawable/your_icon_name" instead of "@drawable/icon"


问:
matlab, format table nicely, without cell arrays
Asking because I suspect there's an easy way I'm unaware of and couldn't google to satisfaction:
I want to format a cell array nicely and a table would be very convenient. How can I format the strings contained in a cell array to be formatted nicely without any ' and {''} pre/suffixes?

```<code>t={'a','b','c'}
cell2table(t,'VariableNames',{'1','2','3'})

ans =

  1×3 table

      1        2        3
    _____    _____    _____

    {'a'}    {'b'}    {'c'}
</code>```

答:
I hear ya. I don't like seeing those quotes either.

If you don't care about performance, you can just convert all the strings to categoricals for the purpose of display.

t = {'a','b','c'};
tbl = cell2table(t,'VariableNames',{'1','2','3'});
tbl_for_display = varfun(@(x) categorical(x), tbl)
```

<p>Produces:</p>

```tbl_for_display =
  1×3 table
    Fun_1    Fun_2    Fun_3
    _____    _____    _____
      a        b        c
```

<p>Here's the cleaner way to do it, with a helper function:</p>

<pre class="lang-matlab prettyprint-override"><code>function out = nice_table_for_display(tbl)
out = tbl;
for i = 1:width(tbl)
  if iscellstr(tbl{:,i}) || isstring(tbl{:,i})
    out.(out.Properties.VariableNames{i}) = categorical(tbl{:,i});
  end
end
end
</code>```

So you do:

```<code>>> nice_table_for_display(tbl)
ans =
  1×3 table
    1    2    3
    _    _    _
    a    b    c
</code>```

Or, if that's no good, you need to go all the way and write your own custom replacement for table.disp.

Body:
Asking because I suspect there's an easy way I'm unaware of and couldn't google to satisfaction:
I want to format a cell array nicely and a table would be very convenient. How can I format the strings contained in a cell array to be formatted nicely without any ' and {''} pre/suffixes?

t={'a','b','c'}
cell2table(t,'VariableNames',{'1','2','3'})

ans =

  1×3 table

      1        2        3
    _____    _____    _____

    {'a'}    {'b'}    {'c'}

Body:
I hear ya. I don't like seeing those quotes either.

If you don't care about performance, you can just convert all the strings to categoricals for the purpose of display.

t = {'a','b','c'};
tbl = cell2table(t,'VariableNames',{'1','2','3'});
tbl_for_display = varfun(@(x) categorical(x), tbl)

Produces:

tbl_for_display =
  1×3 table
    Fun_1    Fun_2    Fun_3
    _____    _____    _____
      a        b        c

Here's the cleaner way to do it, with a helper function:

function out = nice_table_for_display(tbl)
out = tbl;
for i = 1:width(tbl)
  if iscellstr(tbl{:,i}) || isstring(tbl{:,i})
    out.(out.Properties.VariableNames{i}) = categorical(tbl{:,i});
  end
end
end

So you do:

>> nice_table_for_display(tbl)
ans =
  1×3 table
    1    2    3
    _    _    _
    a    b    c

Or, if that's no good, you need to go all the way and write your own custom replacement for table.disp.