问:
How do I fix my variables on my code as it does not appear
So when I ran this code below, I noticed that my variables myName and myAge didn't function at all. An I getting something wrong here?

This program says hello and asks for my name.

print ('Hello world!')

print ('What is your name?') # ask for their name

myName = input('Michael')

print ('It is good to meet you, ' + myName)

print('The length of your name is:')

print (len(myName))

print ('What is your age?') # ask for their age

myAge = input('16')

print('You will be " + str(int(myAge) + 1) + ' in a year.')
```

答:
A Basic Logical mistake, while taking input following  is Syntax
Input Syntax

```<code>input("MessageYouWantToAsk")
</code>```

Code Should be as follows

```<code>print ('Hello world!')
myName = input('What is your name?') # Ask for the name
print ('It is good to meet you, ' + myName) # prints the name and greets
print('The length of your name is:')
print (len(myName)) # Prints the length of that name

myAge = input('What is your Age?')   # What is the input of the age

print('You will be ' + str(int(myAge) + 1) + ' in a year.') # prints the next year age
</code>```

Keep in mind, whenever you open a ' string, you should disclose it with the same ' string closure.

Its a novice mistake to programming in python.

Body:
A Basic Logical mistake, while taking input following  is Syntax
Input Syntax

input("MessageYouWantToAsk")

Code Should be as follows

print ('Hello world!')
myName = input('What is your name?') # Ask for the name
print ('It is good to meet you, ' + myName) # prints the name and greets
print('The length of your name is:')
print (len(myName)) # Prints the length of that name

myAge = input('What is your Age?')   # What is the input of the age

print('You will be ' + str(int(myAge) + 1) + ' in a year.') # prints the next year age

Keep in mind, whenever you open a ' string, you should disclose it with the same ' string closure.

Its a novice mistake to programming in python.


来源: stackexchange

问:
Visual Studio Code: "Open with Live Server" and "Open with Default Browser" showing different web page
I was working on an html file using Live Server in Visual Studio Code. After I finished, When I opened it with the chrome, I found out all the elements are enlarged. I found out that "Open with Live Server" and "Open with Default Browser" option does not show the same element dimensions.

What I see using "Live Server"

What I see when I open it with default browser (chrome)

Why is this happening?
Is there any way to fix this dimension problem without having to write

答:
This goes back to linking to files (Like css,images or etc).

For example, we examine behavior in a css file:

```<code>.navbar-brand {
    background: url('../images/logo.svg');
}
</code>```

when using live server everything is fine. but default browser (without live server) not found logo.svg file.

I think you better check this subject.

ContentLicense: CC BY-SA 4.0

Body:
This goes back to linking to files (Like css,images or etc).

For example, we examine behavior in a css file:

.navbar-brand {
    background: url('../images/logo.svg');
}

when using live server everything is fine. but default browser (without live server) not found logo.svg file.

I think you better check this subject.


问:
Create Private Mirror of http://nodejs.org/dist
I'd like to create a proxy or local mirror of nodejs.org to increase speed and support build repeatability.

Sonatype Nexus fails as nodejs.org/dist isn't quite NPM

Wget fails, but I'm not sure why

wget --mirror --convert-links --adjust-extension --page-requisites --no-parent http://nodejs.org/dist

Please let me know if you have any suggestions

答: If you want to install npm too (maybe for use in a private network) you can use a little script that I’ve written: gist

ContentLicense: CC BY-SA 3.0


问:
Dash, how to callback depending on which button is being clicked?
I have a function that dynamically creates a set of buttons:

def generate_team_button(team_shortName):
    return dbc.Button(
                str(team_shortName),
                className="btn btn-primary",
                id=str(team_shortName),
                style={
                "margin-right": "10px",
                "margin-bottom": '10px',
                },
                n_clicks=0,

            )
```

<p>These buttons are displayed by looping through a set of items</p>

<pre class="lang-py prettyprint-override"><code>import dash
import dash_core_components as dcc
import dash_html_components as html

import dash_bootstrap_components as dbc

from dash.dependencies import Input
from dash.dependencies import Output
from dash.dependencies import State

import pandas as pd

data = {'teams': ['team1', 'team2', 'team3', 'team4']}
df_teams = pd.DataFrame(data)

app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])

app.layout = html.Div(
    [

        dbc.Row([
                dbc.Col(
                    children=[generate_team_button(i) for i in df_teams['teams']]
                ),

        ]),

        dbc.Row([
                dbc.Col(
                    id='section',
                    #WANT TO UPDATE THIS SECTION BASED ON WHICH BUTTON IS BEEING CLICKED

                ),

        ]),
    ]
),
</code>```

What I want to do is to update id=section based on which button is being pressed. To do that I need a @app.callback like below. But what I get is a tuple with how many times each button has been pressed.

@app.callback(
    [
        Output('league-table', 'value'),
    ],
    [
        Input(str(i), 'n_clicks') for i in df_teams['teams']
    ]

)

def update_league_table(*args):
    print(args)
    return f'{args}'

```

How can I update a section based on which button has been clicked?

答:
This information is available via the callback_context object. Here is a small example,

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

n_buttons = 5
# Create example app.
app = dash.Dash(prevent_initial_callbacks=True)
app.layout = html.Div([html.Button("Button {}".format(i), id=str(i)) for i in range(n_buttons)] + [html.Div(id="log")])

@app.callback(Output("log", "children"), [Input(str(i), "n_clicks") for i in range(n_buttons)])
def func(*args):
    trigger = callback_context.triggered[0]
    return "You clicked button {}".format(trigger["prop_id"].split(".")[0])

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

For additional details, see the documentation on advanced callbacks.

Body:
I have a function that dynamically creates a set of buttons:

def generate_team_button(team_shortName):
    return dbc.Button(
                str(team_shortName),
                className="btn btn-primary",
                id=str(team_shortName),
                style={
                "margin-right": "10px",
                "margin-bottom": '10px',
                },
                n_clicks=0,

            )

These buttons are displayed by looping through a set of items

import dash
import dash_core_components as dcc
import dash_html_components as html

import dash_bootstrap_components as dbc

from dash.dependencies import Input
from dash.dependencies import Output
from dash.dependencies import State

import pandas as pd

data = {'teams': ['team1', 'team2', 'team3', 'team4']}
df_teams = pd.DataFrame(data)

app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])

app.layout = html.Div(
    [

        dbc.Row([
                dbc.Col(
                    children=[generate_team_button(i) for i in df_teams['teams']]
                ),

        ]),

        dbc.Row([
                dbc.Col(
                    id='section',
                    #WANT TO UPDATE THIS SECTION BASED ON WHICH BUTTON IS BEEING CLICKED

                ),

        ]),
    ]
),

What I want to do is to update id=section based on which button is being pressed. To do that I need a @app.callback like below. But what I get is a tuple with how many times each button has been pressed.

@app.callback(
    [
        Output('league-table', 'value'),
    ],
    [
        Input(str(i), 'n_clicks') for i in df_teams['teams']
    ]

)

def update_league_table(*args):
    print(args)
    return f'{args}'

How can I update a section based on which button has been clicked?

Body:
This information is available via the callback_context object. Here is a small example,

import dash
import dash_html_components as html
from dash.dependencies import Output, Input
from dash import callback_context

n_buttons = 5
# Create example app.
app = dash.Dash(prevent_initial_callbacks=True)
app.layout = html.Div([html.Button("Button {}".format(i), id=str(i)) for i in range(n_buttons)] + [html.Div(id="log")])

@app.callback(Output("log", "children"), [Input(str(i), "n_clicks") for i in range(n_buttons)])
def func(*args):
    trigger = callback_context.triggered[0]
    return "You clicked button {}".format(trigger["prop_id"].split(".")[0])

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

For additional details, see the documentation on advanced callbacks.


问:
python string operation. sticked words separation
I have a pretty challenging problem here I need your help.

the problem is this:

I have a string for example "abcde"

Now, I want to separate this string into any possible ordered combinations as a list of strings.
for example,

```<code>my_function('abcde')

output =
[
 ['a', 'b', 'c', 'd', 'e'],
 ['a', 'b', 'c', 'de'],
 ['a', 'b', 'cde'],
 ['a', 'bced'],
 ['a', 'b', 'cd', 'e'],
 ['a', 'bc', 'd', 'e'],
 ['a', 'bc', 'de'],
 ['a', 'bcd', 'e'],
 ['a', 'bcde'],
 ['ab', 'c', 'd', 'e'],
 ['ab', 'c', 'de'],
 ['ab', 'cd', 'e'],
 ['ab', 'cde'],
 ['abc','d','e'],
 ['abc', 'de'],
 ['abcd', 'e'],
 ['abcde']
]
</code>```

It is not quite the permutation since the order matters.

答:
You could do this:

```<code>import itertools

def get_slices(values):
    slices_len = len(values) - 1

    for is_slice in itertools.product([True, False], repeat=slices_len):
        start_index = 0
        slices = []

        for slice_index, is_index_slice in enumerate(is_slice, 1):
            if is_index_slice:
                index_slice = values[start_index:slice_index]
                start_index = slice_index

                slices.append(index_slice)

        slices.append(values[start_index:])

        yield slices
</code>```

Most important part of this code is the itertools.product call at the beginning, this generates all possible types of slices. A slice definition here corresponds to a bunch of bools representing whether two adjacent elements at all indices of pairs in values (there are slices_len of these) are joined or not.

list(get_slices("abcde)) will return the list you requested. If you don't need all results immediately, and instead want to iterate through them, you don't need the surrounding list call.

If you want the reverse order, you can switch the [True, False] with [False, True].

Body:
I have a pretty challenging problem here I need your help.

the problem is this:

I have a string for example "abcde"

Now, I want to separate this string into any possible ordered combinations as a list of strings.
for example,

my_function('abcde')

output =
[
 ['a', 'b', 'c', 'd', 'e'],
 ['a', 'b', 'c', 'de'],
 ['a', 'b', 'cde'],
 ['a', 'bced'],
 ['a', 'b', 'cd', 'e'],
 ['a', 'bc', 'd', 'e'],
 ['a', 'bc', 'de'],
 ['a', 'bcd', 'e'],
 ['a', 'bcde'],
 ['ab', 'c', 'd', 'e'],
 ['ab', 'c', 'de'],
 ['ab', 'cd', 'e'],
 ['ab', 'cde'],
 ['abc','d','e'],
 ['abc', 'de'],
 ['abcd', 'e'],
 ['abcde']
]

It is not quite the permutation since the order matters.

Body:
You could do this:

import itertools

def get_slices(values):
    slices_len = len(values) - 1

    for is_slice in itertools.product([True, False], repeat=slices_len):
        start_index = 0
        slices = []

        for slice_index, is_index_slice in enumerate(is_slice, 1):
            if is_index_slice:
                index_slice = values[start_index:slice_index]
                start_index = slice_index

                slices.append(index_slice)

        slices.append(values[start_index:])

        yield slices

Most important part of this code is the itertools.product call at the beginning, this generates all possible types of slices. A slice definition here corresponds to a bunch of bools representing whether two adjacent elements at all indices of pairs in values (there are slices_len of these) are joined or not.

list(get_slices("abcde)) will return the list you requested. If you don't need all results immediately, and instead want to iterate through them, you don't need the surrounding list call.

If you want the reverse order, you can switch the [True, False] with [False, True].


问:
How do you design a gradient for a layer in iOS?
I have to follow through my designer's gradient layer as shown below and I'm running into a wall trying to replicate her design (below).

I have the following code to try to replicate the same shadow but it is too solid compared to her gradient. How do I reduce my layer to have a gradient look and feel?

```<code>backgroundView.layer.shadowColor = UIColor.Custom.darkBlue.cgColor
backgroundView.layer.shadowOpacity = 1.0
backgroundView.layer.shadowRadius = 10
</code>```

EDIT:
I implemented what I needed using @Frankenstein's solution below.

```<code>backgroundView.backgroundColor = UIColor.Custom.darkBlue
let gradient: CAGradientLayer = CAGradientLayer()
gradient.colors = [UIColor.black.cgColor, UIColor.Custom.darkBlue.cgColor]
gradient.frame = CGRect(x: backgroundView.frame.origin.x, y: backgroundView.frame.origin.y - 39, width: view.bounds.width, height: 40)
view.layer.addSublayer(gradient)
</code>```

With the expected result below. Thank you!

答:
You need to add a new CAGradientLayer and not set the shadow, here is an example:

let gradient: CAGradientLayer = CAGradientLayer()

gradient.colors = [UIColor.black.cgColor, UIColor.Custom.darkBlue.cgColor]
gradient.locations = [0.0 , 1.0]
gradient.startPoint = CGPoint(x: 0.0, y: 1.0)
gradient.endPoint = CGPoint(x: 1.0, y: 1.0)
gradient.frame = view.bounds
view.layer.addSublayer(gradient)
```

Body:
I have to follow through my designer's gradient layer as shown below and I'm running into a wall trying to replicate her design (below).

I have the following code to try to replicate the same shadow but it is too solid compared to her gradient. How do I reduce my layer to have a gradient look and feel?

backgroundView.layer.shadowColor = UIColor.Custom.darkBlue.cgColor
backgroundView.layer.shadowOpacity = 1.0
backgroundView.layer.shadowRadius = 10

EDIT:
I implemented what I needed using @Frankenstein's solution below.

backgroundView.backgroundColor = UIColor.Custom.darkBlue
let gradient: CAGradientLayer = CAGradientLayer()
gradient.colors = [UIColor.black.cgColor, UIColor.Custom.darkBlue.cgColor]
gradient.frame = CGRect(x: backgroundView.frame.origin.x, y: backgroundView.frame.origin.y - 39, width: view.bounds.width, height: 40)
view.layer.addSublayer(gradient)

With the expected result below. Thank you!


问:
Convert indefinitely running Runnable from java to kotlin
I have some code like this in java that monitors a certain file:

```<code>private Handler mHandler = new Handler();
private final Runnable monitor = new Runnable() {

    public void run() {
        // Do my stuff
        mHandler.postDelayed(monitor, 1000); // 1 second
    }
};
</code>```

This is my kotlin code:

```<code>private val mHandler = Handler()
val monitor: Runnable = Runnable {
    // do my stuff
    mHandler.postDelayed(whatToDoHere, 1000) // 1 second
}
</code>```

I dont understand what Runnable I should pass into mHandler.postDelayed. What is the right solution? Another interesting thing is that the kotlin to java convertor freezes when I feed this code.

答:
Lambda-expressions do not have this, but object expressions (anonymous classes) do. Then the corrected code would be:

```<code>private val mHandler = Handler()
val monitor: Runnable = object : Runnable{
 override fun run() {
                   //any action
                }
                //runnable

            }

 mHandler.postDelayed(monitor, 1000)
</code>```

Body:
I have some code like this in java that monitors a certain file:

private Handler mHandler = new Handler();
private final Runnable monitor = new Runnable() {

    public void run() {
        // Do my stuff
        mHandler.postDelayed(monitor, 1000); // 1 second
    }
};

This is my kotlin code:

private val mHandler = Handler()
val monitor: Runnable = Runnable {
    // do my stuff
    mHandler.postDelayed(whatToDoHere, 1000) // 1 second
}

I dont understand what Runnable I should pass into mHandler.postDelayed. What is the right solution? Another interesting thing is that the kotlin to java convertor freezes when I feed this code.

Body:
Lambda-expressions do not have this, but object expressions (anonymous classes) do. Then the corrected code would be:

private val mHandler = Handler()
val monitor: Runnable = object : Runnable{
 override fun run() {
                   //any action
                }
                //runnable

            }

 mHandler.postDelayed(monitor, 1000)


问:
Why is my mousedown event triggered on a mouseup event?
I've been working on the etch-a-sketch project of the Odin project, and I came across some weird behavior when implementing the mousedown and mouseup event listeners.

I've created a 50x50 grid of divs in a container div. The container div listens on mousedown events, upon which it calls the startDrawing function, filling the boxes that the user hovers over. It also listens on mousedown events, so that when the mouse is released, the stopDrawing function is called and the filling of boxes stops.

All of this works pretty much fine, but sometimes when I start drawing a line with the mouse left button held down, the box div becomes "grabbed". After this, while dragging the mouse with the left button still down, the boxes are not filled when hovering over them. Then when I release the mouse it starts drawing. It's as if the behavior is toggled after the accidental "grabbing", but on the next mousedown it starts acting normally again.

This is probably harder to explain than to see it for yourself, so below is my code as well as a link to a corresponding codepen.

I've tried googling to find out how I can remove this "grabbing" behavior, but I haven't really found anything, probably because I don't even know what keywords to search for.

Can somebody explain what's happening and provide some info on how I can fix this?

Etch-a-Sketch Codepen

const GRID_SIZE = 50;
for(let i = 0; i < GRID_SIZE * GRID_SIZE; i++){
    const container = document.getElementById('container');
    let div = document.createElement('div');
    div.classList.add('box');
    container.appendChild(div);
}

function fillBox(e){
    this.classList.add('filled');
}

function clearGrid(){
    const boxes = document.querySelectorAll('.box');
    boxes.forEach(box => box.classList.remove('filled'));
}

function startDrawing(){
    // console.log("start drawing");
    const boxes = document.querySelectorAll('.box');
    boxes.forEach(box => box.addEventListener('mouseover', fillBox));
}

function stopDrawing(){
    // console.log("stop drawing");
    const boxes = document.querySelectorAll('.box');
    boxes.forEach(box => box.removeEventListener('mouseover', fillBox));
}

const container = document.querySelector('#container');
container.addEventListener('mousedown', startDrawing);
container.addEventListener('mouseup', stopDrawing);

const button = document.querySelector('#clear-grid-btn');
button.onclick = clearGrid;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#container{
    width: 500px;
    display: grid;
    grid-template-columns: repeat(50, 10px);
    grid-template-rows: repeat(50, 10px);
    border: solid;
    border-color: black;
    margin:auto;
}

.box{
    width: 10px;
    height: 10px;
}

.box:hover{
    background-color: blue;
}

.filled{
    background-color: blue;
}

#clear-grid-btn{
    display:block;
    margin:auto;
    margin-top: 10px;
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="etch-a-sketch.css">

    <button id="clear-grid-btn">Clear grid</button>

```

答:
What happens here is that the default behavior of a mousedown + mousemove is to initiate a grab.

Certainly, at some point, the browser will select some content in the page and start grabbing it.

The solution to avoid this is to tell the browser that your code does handle the event and should thus not perform its usual behavior. You can do so by calling the Event::preventDefault() method:

const GRID_SIZE = 50;
for(let i = 0; i < GRID_SIZE * GRID_SIZE; i++){
    const container = document.getElementById('container');
    let div = document.createElement('div');
    div.classList.add('box');
    container.appendChild(div);
}

function fillBox(evt){
    evt.preventDefault(); // tell the browser we handle that event
    this.classList.add('filled');
}

function clearGrid(){
    const boxes = document.querySelectorAll('.box');
    boxes.forEach(box => box.classList.remove('filled'));
}

function startDrawing(evt){
    evt.preventDefault(); // tell the browser we handle that event
    // console.log("start drawing");
    const boxes = document.querySelectorAll('.box');
    boxes.forEach(box => box.addEventListener('mouseover', fillBox));
}

function stopDrawing(evt){
    evt.preventDefault(); // tell the browser we handle that event
    // console.log("stop drawing");
    const boxes = document.querySelectorAll('.box');
    boxes.forEach(box => box.removeEventListener('mouseover', fillBox));
}

const container = document.querySelector('#container');
container.addEventListener('mousedown', startDrawing);
container.addEventListener('mouseup', stopDrawing);

const button = document.querySelector('#clear-grid-btn');
button.onclick = clearGrid;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#container{
    width: 500px;
    display: grid;
    grid-template-columns: repeat(50, 10px);
    grid-template-rows: repeat(50, 10px);
    border: solid;
    border-color: black;
    margin:auto;
}

.box{
    width: 10px;
    height: 10px;
}

.box:hover{
    background-color: blue;
}

.filled{
    background-color: blue;
}

#clear-grid-btn{
    display:block;
    margin:auto;
    margin-top: 10px;
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="etch-a-sketch.css">

    <button id="clear-grid-btn">Clear grid</button>

```

Body:
I've been working on the etch-a-sketch project of the Odin project, and I came across some weird behavior when implementing the mousedown and mouseup event listeners.

I've created a 50x50 grid of divs in a container div. The container div listens on mousedown events, upon which it calls the startDrawing function, filling the boxes that the user hovers over. It also listens on mousedown events, so that when the mouse is released, the stopDrawing function is called and the filling of boxes stops.

All of this works pretty much fine, but sometimes when I start drawing a line with the mouse left button held down, the box div becomes "grabbed". After this, while dragging the mouse with the left button still down, the boxes are not filled when hovering over them. Then when I release the mouse it starts drawing. It's as if the behavior is toggled after the accidental "grabbing", but on the next mousedown it starts acting normally again.

This is probably harder to explain than to see it for yourself, so below is my code as well as a link to a corresponding codepen.

I've tried googling to find out how I can remove this "grabbing" behavior, but I haven't really found anything, probably because I don't even know what keywords to search for.

Can somebody explain what's happening and provide some info on how I can fix this?

Etch-a-Sketch Codepen

const GRID_SIZE = 50;
for(let i = 0; i < GRID_SIZE * GRID_SIZE; i++){
    const container = document.getElementById('container');
    let div = document.createElement('div');
    div.classList.add('box');
    container.appendChild(div);
}

function fillBox(e){
    this.classList.add('filled');
}

function clearGrid(){
    const boxes = document.querySelectorAll('.box');
    boxes.forEach(box => box.classList.remove('filled'));
}

function startDrawing(){
    // console.log("start drawing");
    const boxes = document.querySelectorAll('.box');
    boxes.forEach(box => box.addEventListener('mouseover', fillBox));
}

function stopDrawing(){
    // console.log("stop drawing");
    const boxes = document.querySelectorAll('.box');
    boxes.forEach(box => box.removeEventListener('mouseover', fillBox));
}

const container = document.querySelector('#container');
container.addEventListener('mousedown', startDrawing);
container.addEventListener('mouseup', stopDrawing);

const button = document.querySelector('#clear-grid-btn');
button.onclick = clearGrid;

#container{
    width: 500px;
    display: grid;
    grid-template-columns: repeat(50, 10px);
    grid-template-rows: repeat(50, 10px);
    border: solid;
    border-color: black;
    margin:auto;
}

.box{
    width: 10px;
    height: 10px;
}

.box:hover{
    background-color: blue;
}

.filled{
    background-color: blue;
}

#clear-grid-btn{
    display:block;
    margin:auto;
    margin-top: 10px;
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="etch-a-sketch.css">

    <button id="clear-grid-btn">Clear grid</button>

Body:
What happens here is that the default behavior of a mousedown + mousemove is to initiate a grab.

Certainly, at some point, the browser will select some content in the page and start grabbing it.

The solution to avoid this is to tell the browser that your code does handle the event and should thus not perform its usual behavior. You can do so by calling the Event::preventDefault() method:

const GRID_SIZE = 50;
for(let i = 0; i < GRID_SIZE * GRID_SIZE; i++){
    const container = document.getElementById('container');
    let div = document.createElement('div');
    div.classList.add('box');
    container.appendChild(div);
}

function fillBox(evt){
    evt.preventDefault(); // tell the browser we handle that event
    this.classList.add('filled');
}

function clearGrid(){
    const boxes = document.querySelectorAll('.box');
    boxes.forEach(box => box.classList.remove('filled'));
}

function startDrawing(evt){
    evt.preventDefault(); // tell the browser we handle that event
    // console.log("start drawing");
    const boxes = document.querySelectorAll('.box');
    boxes.forEach(box => box.addEventListener('mouseover', fillBox));
}

function stopDrawing(evt){
    evt.preventDefault(); // tell the browser we handle that event
    // console.log("stop drawing");
    const boxes = document.querySelectorAll('.box');
    boxes.forEach(box => box.removeEventListener('mouseover', fillBox));
}

const container = document.querySelector('#container');
container.addEventListener('mousedown', startDrawing);
container.addEventListener('mouseup', stopDrawing);

const button = document.querySelector('#clear-grid-btn');
button.onclick = clearGrid;

#container{
    width: 500px;
    display: grid;
    grid-template-columns: repeat(50, 10px);
    grid-template-rows: repeat(50, 10px);
    border: solid;
    border-color: black;
    margin:auto;
}

.box{
    width: 10px;
    height: 10px;
}

.box:hover{
    background-color: blue;
}

.filled{
    background-color: blue;
}

#clear-grid-btn{
    display:block;
    margin:auto;
    margin-top: 10px;
}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="etch-a-sketch.css">
</head>
<body>
    <div id="container"></div>
    <button id="clear-grid-btn">Clear grid</button>
</body>
<script src="etch-a-sketch.js"></script>
</html>


问:
Returning smart pointer from raw pointer
This is the way i am returning smart pointer from a raw pointer.

```<code>std::shared_ptr<Geometry> Clone() const
{
    Circle *sc = new Circle(*this);
    return std::shared_ptr< Geometry >(sc);
}
</code>```

Is it the correct way to return Smart pointer from raw pointer ?

答:
The term "correct" is quite vague. Ok, this code should work, if you ask of that. However there are more details you should take into consideration.

First, it is better to construct the object in the same expression where you construct the smart pointer:

```<code>std::shared_ptr<Geometry> Clone() const
{
    return std::shared_ptr< Geometry >(new Circle(*this));
}
</code>```

Why so? Imagine that you add one more line of code in between, and this code throws an exception... That is the benefit of smart pointers that they prevent you from memory leaks like that, and you loose this benefit in your initial version of code.

Next, I don't see the definition of the class Geometry, and it probably has a virtual destructor... But what if it doesn't? Which class would the shared_ptr destroy? The answer is: the class that shared_ptr knows. Ok, in your code there is a way for shared_ptr to get known that the actual class is class Circle (because of the shared_ptr constructor, that knows exactly the actual class of the underlying object), but it is very easy to make a mistake. One-liner solves this issue.

But there is one more (possible) improvement: std::make_shared:

```<code>std::shared_ptr<Geometry> Clone() const
{
    return std::make_shared< Circle >(*this);
}
</code>```

In this case you allocate memory only once, for both the object and the counter structure. That works better unless you employ std::weak_ptr. You should be very careful using both std::make_shared and std:weak_ptr: the actual memory deallocation of the shared counter (which is the same memory that is used for the object itself in case of std::make_shared) will be done only after the last weak_ptr is destroyed. That could cause some sort of a memory leak.

So the way you use it is correct, but there is not enough information to judge what is the best idiomatic way to do that.

Body:
This is the way i am returning smart pointer from a raw pointer.

std::shared_ptr<Geometry> Clone() const
{
    Circle *sc = new Circle(*this);
    return std::shared_ptr< Geometry >(sc);
}

Is it the correct way to return Smart pointer from raw pointer ?

Body:
The term "correct" is quite vague. Ok, this code should work, if you ask of that. However there are more details you should take into consideration.

First, it is better to construct the object in the same expression where you construct the smart pointer:

std::shared_ptr<Geometry> Clone() const
{
    return std::shared_ptr< Geometry >(new Circle(*this));
}

Why so? Imagine that you add one more line of code in between, and this code throws an exception... That is the benefit of smart pointers that they prevent you from memory leaks like that, and you loose this benefit in your initial version of code.

Next, I don't see the definition of the class Geometry, and it probably has a virtual destructor... But what if it doesn't? Which class would the shared_ptr destroy? The answer is: the class that shared_ptr knows. Ok, in your code there is a way for shared_ptr to get known that the actual class is class Circle (because of the shared_ptr constructor, that knows exactly the actual class of the underlying object), but it is very easy to make a mistake. One-liner solves this issue.

But there is one more (possible) improvement: std::make_shared:

std::shared_ptr<Geometry> Clone() const
{
    return std::make_shared< Circle >(*this);
}

In this case you allocate memory only once, for both the object and the counter structure. That works better unless you employ std::weak_ptr. You should be very careful using both std::make_shared and std:weak_ptr: the actual memory deallocation of the shared counter (which is the same memory that is used for the object itself in case of std::make_shared) will be done only after the last weak_ptr is destroyed. That could cause some sort of a memory leak.

So the way you use it is correct, but there is not enough information to judge what is the best idiomatic way to do that.


问:
Passing the serialized data to the controller in MVC through AJAX
I have a view :

```<code>@{
    ViewBag.Title = "Home Page";
}

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
    <link href="~/Scripts/datatable/DataTables-1.10.20/css/dataTables.jqueryui.min.css" rel="stylesheet" />
    @section Scripts{

        <script src="~/Scripts/datatable/DataTables-1.10.20/js/jquery.dataTables.min.js"></script>
        <script src="~/Scripts/datatable/DataTables-1.10.20/js/dataTables.jqueryui.min.js"></script>
        <script>
            $(document).ready(function () {
                $("#contenttable").DataTable({

                });

                $("#submitdata").click(function () {
                    var datatabledata = $("#datatble-form").serialize();
                    alert(datatabledata);
                    $.ajax({
                        url: "/Home/getData",
                        type: "POST",
                        data: { model: datatabledata },
                        success: function () {
                            alert('success');
                        },
                        error: function () {
                            alert('failure');
                        }
                    });
                });
            });
        </script>
    }
</head>

<body>
    <form id="datatble-form">
        <table>
            <tr>
                <td>Friend Name</td>
                <td><input name="FriendName" type="text" /></td>
            </tr>
            <tr>
                <td>Friend Age</td>
                <td><input name="FriendAge" type="text" /></td>
            </tr>
            <tr>
                <td>Position</td>
                <td><input name="Friendposition" type="text" /></td>
            </tr>
            <tr>
                <td>Office</td>
                <td><input name="Friendoffice" type="text" /></td>
            </tr>
        </table>

        <input id="submitdata" type="button" value="Submit" />
    </form>
</body>
</html>
</code>```

My controller is :

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using datatableViewTocontroller.Models;

namespace datatableViewTocontroller.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult getData(string model)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            MyClass myClass = jss.Deserialize<MyClass>(model);
            return RedirectToAction("index");
        }

}
</code>```

}

and My Model is :

```<code>namespace datatableViewTocontroller.Models
{
    public class MyClass
    {
        public string FriendName { get; set; }
        public string FriendAge { get; set; }
        public string Friendposition { get; set; }
        public string Friendoffice { get; set; }
    }
}
</code>```

Ok now I ellaborate my problem.
I have a form with the inputs for name, age, position and office and Iam trying to submit the data to the controller by serialize(). The form is getting serialized ( because it is displaying the values in the alert ) and controller call is also successfull like :

but while deserialzing I have got this error :
Invalid JSON primitive: FriendName.
like this :

How can I resolve this issue ? please help..

答:
Whatever you are getting in your action method of controller is not json data that's why you are getting the error while deserializing it.

Solution

You can update your getdata method instead of passing string in parameter you can pass your model class which will bind data automatically and you will no longer required deserializing the json.

[HttpPost]
public ActionResult getData(MyClass model)
{
  // Do whatever you want with model
  return RedirectToAction("index");
}```
</div>
</div>
</p>

<p>And also change your click method as below</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$("#submitdata").click(function () {
 $.post("/Home/getData",$("#datatble-form").serialize()).done(function(data){
   alert('success');
 }).catch(function(){
  alert('failure');
 });
});</code>```

Body:
I have a view :

@{
    ViewBag.Title = "Home Page";
}

    <title></title>
    <link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
    <link href="~/Scripts/datatable/DataTables-1.10.20/css/dataTables.jqueryui.min.css" rel="stylesheet" />
    @section Scripts{

    }

    <form id="datatble-form">

                Friend Name
                <input name="FriendName" type="text" />

                Friend Age
                <input name="FriendAge" type="text" />

                Position
                <input name="Friendposition" type="text" />

                Office
                <input name="Friendoffice" type="text" />

        <input id="submitdata" type="button" value="Submit" />
    </form>

My controller is :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using datatableViewTocontroller.Models;

namespace datatableViewTocontroller.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult getData(string model)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            MyClass myClass = jss.Deserialize<MyClass>(model);
            return RedirectToAction("index");
        }

}

}

and My Model is :

namespace datatableViewTocontroller.Models
{
    public class MyClass
    {
        public string FriendName { get; set; }
        public string FriendAge { get; set; }
        public string Friendposition { get; set; }
        public string Friendoffice { get; set; }
    }
}

Ok now I ellaborate my problem.
I have a form with the inputs for name, age, position and office and Iam trying to submit the data to the controller by serialize(). The form is getting serialized ( because it is displaying the values in the alert ) and controller call is also successfull like :

but while deserialzing I have got this error :
Invalid JSON primitive: FriendName.
like this :

How can I resolve this issue ? please help..

Body:
Whatever you are getting in your action method of controller is not json data that's why you are getting the error while deserializing it.

Solution

You can update your getdata method instead of passing string in parameter you can pass your model class which will bind data automatically and you will no longer required deserializing the json.

[HttpPost]
public ActionResult getData(MyClass model)
{
  // Do whatever you want with model
  return RedirectToAction("index");
}

And also change your click method as below

$("#submitdata").click(function () {
 $.post("/Home/getData",$("#datatble-form").serialize()).done(function(data){
   alert('success');
 }).catch(function(){
  alert('failure');
 });
});


问:
How can I remove attributes from an html tag?
How can I use php to strip all/any attributes from a tag, say a paragraph tag?

 to

答:
You might also look into html purifier. True, it's quite bloated, and might not fit your needs if it only conceirns this specific example, but it offers more or less 'bulletproof' purification of possible hostile html. Also you can choose to allow or disallow certain attributes (it's highly configurable).

http://htmlpurifier.org/


问:
Is there a verbose logging mode for pickle.dumps()?
Im trying to encode about 25000 images into a pickle file using the following code

```<code>f = open("dataset_encoding.pickle", "wb")
f.write(pickle.dumps(sampleDataset))
f.close()
</code>```

Python consumes a lot of time executing this function on my PC, is there a verbose logging option for pickle.dumps() so I can know that it is still running?

I couldn't find anything here

答:
As mentioned in the comments, I was trying to pickle a list of length 4. To reduce the memory usage per pickle file, I decided to save my list into 4 different pickles. Following is the code I used to print a ProgressBar while the pickling completes :

```<code>import pickle

def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):
"""
Call in a loop to create terminal progress bar
@params:
    iteration   - Required  : current iteration (Int)
    total      - Required  : total iterations (Int)
    prefix    - Optional  : prefix string (Str)
    suffix    - Optional  : suffix string (Str)
    decimals    - Optional  : positive number of decimals in percent complete (Int)
    length    - Optional  : character length of bar (Int)
    fill        - Optional  : bar fill character (Str)
    printEnd    - Optional  : end character (e.g. "\r", "\r\n") (Str)
"""
    percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
    filledLength = int(length * iteration // total)
    bar = fill * filledLength + '-' * (length - filledLength)
    print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = printEnd)
    if iteration == total:
        print()

def verbosePickle(data_list, filename, prefix_text):
    print("sampleDataset["+str(index)+"] Length :"+str(len(sample)))
    with open(filename, "wb") as f:
        pickle.dump(len(data_list), f)
        printProgressBar(0, len(data_list)-1, prefix = prefix_text, suffix = "Complete", length = 50)
        for data_index, data in enumerate(data_list):
            printProgressBar(data_index, len(data_list)-1, prefix = prefix_text, suffix = "Complete", length = 50)
            pickle.dump(data, f)

for index, sample in enumerate(sampleDataset):
    print("Saving Pickle Files")
    verbosePickle(sample, "sampleDataset"+index+".pickle", "Saving pickle "+index+" :")
</code>```

Standard Output :

Saving pickle 0 :
  |█████████████████████-----------------------------| 44.0% Complete

Body:
Im trying to encode about 25000 images into a pickle file using the following code

f = open("dataset_encoding.pickle", "wb")
f.write(pickle.dumps(sampleDataset))
f.close()

Python consumes a lot of time executing this function on my PC, is there a verbose logging option for pickle.dumps() so I can know that it is still running?

I couldn't find anything here

Body:
As mentioned in the comments, I was trying to pickle a list of length 4. To reduce the memory usage per pickle file, I decided to save my list into 4 different pickles. Following is the code I used to print a ProgressBar while the pickling completes :

import pickle

def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):
"""
Call in a loop to create terminal progress bar
@params:
    iteration   - Required  : current iteration (Int)
    total      - Required  : total iterations (Int)
    prefix    - Optional  : prefix string (Str)
    suffix    - Optional  : suffix string (Str)
    decimals    - Optional  : positive number of decimals in percent complete (Int)
    length    - Optional  : character length of bar (Int)
    fill        - Optional  : bar fill character (Str)
    printEnd    - Optional  : end character (e.g. "\r", "\r\n") (Str)
"""
    percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
    filledLength = int(length * iteration // total)
    bar = fill * filledLength + '-' * (length - filledLength)
    print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = printEnd)
    if iteration == total:
        print()

def verbosePickle(data_list, filename, prefix_text):
    print("sampleDataset["+str(index)+"] Length :"+str(len(sample)))
    with open(filename, "wb") as f:
        pickle.dump(len(data_list), f)
        printProgressBar(0, len(data_list)-1, prefix = prefix_text, suffix = "Complete", length = 50)
        for data_index, data in enumerate(data_list):
            printProgressBar(data_index, len(data_list)-1, prefix = prefix_text, suffix = "Complete", length = 50)
            pickle.dump(data, f)

for index, sample in enumerate(sampleDataset):
    print("Saving Pickle Files")
    verbosePickle(sample, "sampleDataset"+index+".pickle", "Saving pickle "+index+" :")

Standard Output :

Saving pickle 0 :
  |█████████████████████-----------------------------| 44.0% Complete


问:
PostGIS Installation "could not open extension control file"
I've been scouring posts trying to figure out how to resolve this issue - could not open extension control file "/usr/local/share/postgresql/extension/postgis.control": No such file or directory

I'm installing PostgreSQL and PostGIS with apt-get install postgresql-12 postgis postgresql-12-postgis-3 into a Docker container running python:latest. I'd initially been running Alpine however it seemed there were a number of issues getting PostGIS installed successfully on Alpine distributions.

I've located the file with find /usr -name postgis.control under /usr/share/postgresql/12/extension/postgis.control. I've attempted to move this to the directory PostGIS expects, but I'm still seeing the same error.

It's been driving me totally mad!

Any help is appreciated, and happy to answer any questions that will help me find an answer.

答: I was never able to resolve this issue, so I ended up switching to the official postGIS docker image which worked flawlessly. Would recommend it to anyone else in a similar situation.</p>


问:
Snowflake Data Reader displays wrong number of warehouses
Context:
I am using trial version of  Enterprise Edition of Snowflake;

1) Created a database and table with some data and warehouse COMPUTE_WH
2) created reader account and shared table to that reader account and warehouse to use as data consumer : TEST_WH

when i see as an Account admin logged in as in step1; i see two warehouses; count but displays only one warehouse and the same when i login as data consumer dispays 2 warehouses and dispays "TEST_WH"

in sceanrio :
   1) I am provider of the data and data sharing to another reader account and created warehouse for the data consumer;
I want to track how much Provider account warehoused used and also how much data consumers are spending credits;

There are 2 issues here :
    - Why the data consumer account displays two warehouses but as per that account it is only 1 warehouse being created and used;
  - Data Provider account says two warehouses but does not display warehouse "test_wh" credits usage.
Has any observed this?

答:
It is not clear how you can create a warehouse and share it with the consumer account. The Consumer account admin needs to create a warehouse and use it for data processing requests.

Can you kindly update this space with the steps that you performed in sharing the warehouse from the provider account?

In general, the virtual warehouses created by the consumer ma consume credits, which will be charged to your provider account. If you wish to control the amount of credits consumed monthly by the virtual warehouses in the reader account you can use the resource monitor to configure.

Ref : https://docs.snowflake.com/en/user-guide/data-sharing-reader-config.html#task-4-create-resource-monitors-optional


问:
How I get y_true and y_pred values for loss function?
How do I get the y_true and y_pred values for this loss function I wrote :

```<code>def kullback_leibler_divergence(y_true, y_pred):
    y_true = K.clip(y_true, K.epsilon(), 1)
    y_pred = K.clip(y_pred, K.epsilon(), 1)
    return K.sum(y_true * K.log(y_true / y_pred), axis=-1)
</code>```

答:
I'm not sure if it helps but, in machine learning
y_true refers to the true values, the original labels.
y_pred are the predictions of your classifier thus y_pred = clf.predict(y_true)
The loss function essentially computes how far the predictions are from the 'true' labels.

Body:
How do I get the y_true and y_pred values for this loss function I wrote :

def kullback_leibler_divergence(y_true, y_pred):
    y_true = K.clip(y_true, K.epsilon(), 1)
    y_pred = K.clip(y_pred, K.epsilon(), 1)
    return K.sum(y_true * K.log(y_true / y_pred), axis=-1)


问:
"Compilation failed; see the compiler error output for details." error
"Compilation failed; see the compiler error output for details."

getting this error when compiling help me please?

```org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:compileDebugJavaWithJavac'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:103)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:73)
    at org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:59)
    at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:59)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:101)
    at org.gradle.api.internal.tasks.execution.FinalizeInputFilePropertiesTaskExecuter.execute(FinalizeInputFilePropertiesTaskExecuter.java:44)
    at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:88)
    at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:62)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:248)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:241)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:230)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:123)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:79)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:104)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:98)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:623)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:578)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:98)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.gradle.api.internal.tasks.compile.CompilationFailedException: Compilation failed; see the compiler error output for details.
    at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.execute(JdkJavaCompiler.java:50)
    at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.execute(JdkJavaCompiler.java:35)
    at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.delegateAndHandleErrors(NormalizingJavaCompiler.java:98)
    at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.execute(NormalizingJavaCompiler.java:51)
    at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.execute(NormalizingJavaCompiler.java:37)
    at org.gradle.api.internal.tasks.compile.CleaningJavaCompilerSupport.execute(CleaningJavaCompilerSupport.java:35)
    at org.gradle.api.internal.tasks.compile.CleaningJavaCompilerSupport.execute(CleaningJavaCompilerSupport.java:25)
    at org.gradle.api.internal.tasks.compile.incremental.IncrementalCompilationFinalizer.execute(IncrementalCompilationFinalizer.java:39)
    at org.gradle.api.internal.tasks.compile.incremental.IncrementalCompilationFinalizer.execute(IncrementalCompilationFinalizer.java:24)
    at org.gradle.api.tasks.compile.JavaCompile.performCompilation(JavaCompile.java:207)
    at org.gradle.api.tasks.compile.JavaCompile.compile(JavaCompile.java:133)
    at com.android.build.gradle.tasks.factory.AndroidJavaCompile.compile(AndroidJavaCompile.java:125)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
    at org.gradle.api.internal.project.taskfactory.IncrementalTaskAction.doExecute(IncrementalTaskAction.java:50)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:39)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:26)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:124)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:113)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:95)
    ... 33 more
```

build gradle

```<code>apply plugin: 'com.android.application'
android {
compileSdkVersion 27
defaultConfig {
    applicationId "com.yube.fasturl"
    minSdkVersion 15
    targetSdkVersion 27
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner
    "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-
    android.txt'), 'proguard-rules.pro'
    }
    }
    }

     dependencies {
     implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.1.0'
implementation 'com.android.support:design:27.1.0'
implementation 'com.github.florent37:materialtextfield:1.0.7'
implementation 'com.android.support.constraint:constraint-
layout:1.0.2'
//noinspection GradleCompatible
implementation 'com.google.android.gms:play-services-ads:15.0.0'
testImplementation 'junit:junit:4.12'
implementation 'com.android.support:recyclerview-v7:22.2.0'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation
'com.android.support.test.espresso:espresso-core:3.0.1'
implementation 'com.android.support:mediarouter-v7:27.1.0'
   }
</code>```

答: This may be the gradle version problem, there may be some difference between gradle version installed on machine and version used in project. I got simmilar problem when i have installed gradle version 5.0 and my project has 4.8, In this case use gradlew instead of gradle in command, problem resolved.

Body:
"Compilation failed; see the compiler error output for details."

getting this error when compiling help me please?

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:compileDebugJavaWithJavac'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:103)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:73)
    at org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:59)
    at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:59)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:101)
    at org.gradle.api.internal.tasks.execution.FinalizeInputFilePropertiesTaskExecuter.execute(FinalizeInputFilePropertiesTaskExecuter.java:44)
    at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:88)
    at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:62)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:248)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:241)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:230)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:123)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:79)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:104)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:98)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:623)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:578)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:98)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.gradle.api.internal.tasks.compile.CompilationFailedException: Compilation failed; see the compiler error output for details.
    at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.execute(JdkJavaCompiler.java:50)
    at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.execute(JdkJavaCompiler.java:35)
    at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.delegateAndHandleErrors(NormalizingJavaCompiler.java:98)
    at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.execute(NormalizingJavaCompiler.java:51)
    at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.execute(NormalizingJavaCompiler.java:37)
    at org.gradle.api.internal.tasks.compile.CleaningJavaCompilerSupport.execute(CleaningJavaCompilerSupport.java:35)
    at org.gradle.api.internal.tasks.compile.CleaningJavaCompilerSupport.execute(CleaningJavaCompilerSupport.java:25)
    at org.gradle.api.internal.tasks.compile.incremental.IncrementalCompilationFinalizer.execute(IncrementalCompilationFinalizer.java:39)
    at org.gradle.api.internal.tasks.compile.incremental.IncrementalCompilationFinalizer.execute(IncrementalCompilationFinalizer.java:24)
    at org.gradle.api.tasks.compile.JavaCompile.performCompilation(JavaCompile.java:207)
    at org.gradle.api.tasks.compile.JavaCompile.compile(JavaCompile.java:133)
    at com.android.build.gradle.tasks.factory.AndroidJavaCompile.compile(AndroidJavaCompile.java:125)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
    at org.gradle.api.internal.project.taskfactory.IncrementalTaskAction.doExecute(IncrementalTaskAction.java:50)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:39)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:26)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:124)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:113)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:95)
    ... 33 more

build gradle

apply plugin: 'com.android.application'
android {
compileSdkVersion 27
defaultConfig {
    applicationId "com.yube.fasturl"
    minSdkVersion 15
    targetSdkVersion 27
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner
    "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-
    android.txt'), 'proguard-rules.pro'
    }
    }
    }

     dependencies {
     implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.1.0'
implementation 'com.android.support:design:27.1.0'
implementation 'com.github.florent37:materialtextfield:1.0.7'
implementation 'com.android.support.constraint:constraint-
layout:1.0.2'
//noinspection GradleCompatible
implementation 'com.google.android.gms:play-services-ads:15.0.0'
testImplementation 'junit:junit:4.12'
implementation 'com.android.support:recyclerview-v7:22.2.0'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation
'com.android.support.test.espresso:espresso-core:3.0.1'
implementation 'com.android.support:mediarouter-v7:27.1.0'
   }


问:
how to call different tables in if and else part of the same database in iphone?
I have a database. It has two tables in it. I want to call one table in if condition. If if conditions fails i wanted to call the second table in the else part.

Can any one help by providing the sample code.

Thanks in advance

答:
This is super-simple:</p>

```<code>char *tableName = (somecondition) ? "someTable" : "someOtherTable";
</code>```

Body:
This is super-simple:

char *tableName = (somecondition) ? "someTable" : "someOtherTable";


问:
Getting unique count of each ticket along with No of days in each assignment queue in python pandas
I am creating small POC which will tell me how many days each ticket remains with each different team. (L1, L2 are team names)

答:
I assume that you have read your Excel files into a DataFrame and
Age of ticket in days column in it contains either empty strings
or a number (not NaN), just as on your picture.

Start from generating a temporary DataFrame:

```<code>wrk = df.groupby(['Ticket No', 'Assignment queue']).Status.count()\
    .unstack().fillna(0, downcast='infer')
wrk.columns.name = None
</code>```

The result, for your data sample is:

```<code>           L1  L2
Ticket No
INC001      1   3
INC002      3   1
INC003      4   0
INC004      1   3
</code>```

And to get the result, run:

```<code>result = wrk.add_prefix('No of days in ').add_suffix(' Queue')\
    .join(df.groupby('Ticket No')['Age of ticket in days'].last()
    .rename('Total number of days for resolution'))\
    .reset_index()
</code>```

The result is:

```<code>  Ticket No  No of days in L1 Queue  No of days in L2 Queue  Total number of days for resolution
0    INC001                       1                       3                                    4
1    INC002                       3                       1
2    INC003                       4                       0                                    4
3    INC004                       1                       3                                    4
</code>```

Edit

If Age of ticket in days column in the source DataFrame does contain
NaNs, a small correction is needed: Just add .fillna('') after last().

A remark concerning the source data (following your comment)

Note that each row states only the sequence of assignments for each
ticket, without actual dates when particular ticket has been assigned and
then passed to another team (or completed).

This is why:

I assumed that each row is something like "report at the end of
consecutive day".

The way how wrk is computed is actually to count in how many rows
the particular ticket was assigned to each team (assuming "1 row per
day" rule).

On the other hand, Age of ticket is given apparently without any
defined connection to the above rule. It should be equal to the
number of rows for particular ticket, but I don't know whether this
rule is observed in each case (for each ticket).

For your sample data there was no such discrepancies, but in other
rows the may occur.

Or maybe your DataFrame should contain in each row:

the "start date" - when this ticket was assigned to this team,

the "end date" - when this ticket was either assigned to some
other team or completed.

Then:

rows with the same start and end date should not be counted,

each row should "contribute" (to the team in question) the number
of days resulting from the difference between end and start date.

In this case the last column would be not needed.

Body:
I assume that you have read your Excel files into a DataFrame and
Age of ticket in days column in it contains either empty strings
or a number (not NaN), just as on your picture.

Start from generating a temporary DataFrame:

wrk = df.groupby(['Ticket No', 'Assignment queue']).Status.count()\
    .unstack().fillna(0, downcast='infer')
wrk.columns.name = None

The result, for your data sample is:

           L1  L2
Ticket No
INC001      1   3
INC002      3   1
INC003      4   0
INC004      1   3

And to get the result, run:

result = wrk.add_prefix('No of days in ').add_suffix(' Queue')\
    .join(df.groupby('Ticket No')['Age of ticket in days'].last()
    .rename('Total number of days for resolution'))\
    .reset_index()

The result is:

  Ticket No  No of days in L1 Queue  No of days in L2 Queue  Total number of days for resolution
0    INC001                       1                       3                                    4
1    INC002                       3                       1
2    INC003                       4                       0                                    4
3    INC004                       1                       3                                    4

Edit

If Age of ticket in days column in the source DataFrame does contain
NaNs, a small correction is needed: Just add .fillna('') after last().

A remark concerning the source data (following your comment)

Note that each row states only the sequence of assignments for each
ticket, without actual dates when particular ticket has been assigned and
then passed to another team (or completed).

This is why:

I assumed that each row is something like "report at the end of
consecutive day".

The way how wrk is computed is actually to count in how many rows
the particular ticket was assigned to each team (assuming "1 row per
day" rule).

On the other hand, Age of ticket is given apparently without any
defined connection to the above rule. It should be equal to the
number of rows for particular ticket, but I don't know whether this
rule is observed in each case (for each ticket).

For your sample data there was no such discrepancies, but in other
rows the may occur.

Or maybe your DataFrame should contain in each row:

the "start date" - when this ticket was assigned to this team,

the "end date" - when this ticket was either assigned to some
other team or completed.

Then:

rows with the same start and end date should not be counted,

each row should "contribute" (to the team in question) the number
of days resulting from the difference between end and start date.

In this case the last column would be not needed.


问:
Mocking es6 class constructor attribute with mocha/sinon
I have a small wrapper class which adds promises to some mysql functionality.

```<code>const mysql = require('mysql');

export default class MySQL {
    constructor(host, user, password, database, port = 3306) {
        this.conn = mysql.createConnection({
            host,
            port,
            user,
            password,
            database,
        });
    }

    query(sql, args) {
        return new Promise((resolve, reject) => {
            // eslint-disable-next-line consistent-return
            this.conn.query(sql, args, (err, rows) => {
                if (err) {
                    reject(err);
                    return;
                }
                resolve(rows);
            });
        });
    }

    close() {
        return new Promise((resolve, reject) => {
            this.conn.end((err) => {
                if (err) {
                    reject(err);
                    return;
                }
                resolve();
            });
        });
    }
}
</code>```

I am trying to write a unit test for this class but am completely stuck trying to mock this.conn.

I have tried various mixes of proxyquire, sinon, and both combined.  When I use proxyquire in a beforeEach hook:

```<code>beforeEach(function () {
    createConnectionStub = sinon.stub();
    MySQL = proxyquire('../../lib/utils/mysql', {
        mysql: {
            createConnection: createConnectionStub,
        },
    }).default;
});
</code>```

and try to set a stub to the conn object:

```<code>it('Returns query results', async function () {
            stubDb = new MySQL('host', 'user', 'password', 'database');
            stubDb.conn = sinon.stub();

            const results = await stubDb.query('SELECT * FROM whatever');
        });
</code>```

I keep getting TypeError: this.conn.query is not a function

what is the best way to setup a mock as the this.conn attributes so I can easily assert method calls against it?  Any help would be much appreciated

答:
I am an hour late. :)

But I have coded the example and provide alternative to test, so I continue to post this.

I agree, that you do not need proxyquire at all. I use sinon sandbox, stub and fake in example below.

// @file stackoverflow.js
const sinon = require('sinon');
const { expect } = require('chai');
const mysql = require('mysql');

// Change this to your mysql class definition.
const MySQL = require('./mysql.js');

describe('MySQL', function () {
  let sandbox;

  before(function () {
    sandbox = sinon.createSandbox();
  });

  after(function () {
    sandbox.restore();
  });

  it('constructor fn', function () {
    // Prepare stub.
    const stubMysql = sandbox.stub(mysql, 'createConnection');
    // This just to make sure whether conn is storing this true value.
    stubMysql.returns(true);

    const test = new MySQL('host', 'user', 'password', 'database');

    // Check whether call mysql.createConnection the right way.
    expect(test).to.be.an('object');
    expect(test).to.have.property('conn', true);
    expect(stubMysql.calledOnce).to.equal(true);
    expect(stubMysql.args[0]).to.have.lengthOf(1);
    expect(stubMysql.args[0][0]).to.have.property('host', 'host');
    expect(stubMysql.args[0][0]).to.have.property('user', 'user');
    expect(stubMysql.args[0][0]).to.have.property('password', 'password');
    expect(stubMysql.args[0][0]).to.have.property('database', 'database');
    expect(stubMysql.args[0][0]).to.have.property('port', 3306);
    // Restore stub.
    stubMysql.restore();
  });

  it('query fn', async function () {
    let fakeCounter = 0;
    // Create fake function.
    const fakeMysqlQuery = sinon.fake((arg1, arg2, arg3) => {
      // On first response: return fake row.
      if (fakeCounter === 0) {
        fakeCounter += 1;
        arg3(undefined, []);
      }
      // On second response: return error.
      if (fakeCounter > 0) {
        arg3(new Error('TESTQUERY'));
      }
    });
    // Prepare stub.
    const stubMysql = sandbox.stub(mysql, 'createConnection');
    stubMysql.returns({
      query: fakeMysqlQuery,
    });

    const test = new MySQL('host', 'user', 'password', 'database');

    expect(test).to.be.an('object');
    expect(test).to.have.property('conn');
    expect(test.conn).to.respondTo('query');
    expect(stubMysql.calledOnce).to.equal(true);
    expect(test).to.respondTo('query');

    // Test success query.
    const results = await test.query('SELECT * FROM whatever');

    expect(results).to.be.an('array');
    expect(results).to.have.lengthOf(0);
    expect(fakeMysqlQuery.calledOnce).to.equal(true);
    expect(fakeMysqlQuery.args[0]).to.have.lengthOf(3);
    expect(fakeMysqlQuery.args[0][0]).to.equal('SELECT * FROM whatever');
    expect(fakeMysqlQuery.args[0][1]).to.be.an('undefined');
    expect(fakeMysqlQuery.args[0][2]).to.be.an('function');
    expect(fakeCounter).to.equal(1);

    // Test rejection.
    try {
      await test.query('SELECT * FROM blablabla');
      expect.fail('should not reach here for mysql query test.');
    } catch (error) {
      expect(error).to.have.property('message', 'TESTQUERY');
      expect(fakeMysqlQuery.calledTwice).to.equal(true);
      expect(fakeMysqlQuery.args[1]).to.have.lengthOf(3);
      expect(fakeMysqlQuery.args[1][0]).to.equal('SELECT * FROM blablabla');
      expect(fakeMysqlQuery.args[1][1]).to.be.an('undefined');
      expect(fakeMysqlQuery.args[1][2]).to.be.an('function');
    }

    // Restore stub.
    stubMysql.restore();
  });

  it('close fn', async function () {
    let fakeCounter = 0;
    // Create fake function.
    const fakeMysqlEnd = sinon.fake((arg1) => {
      // On first response: return fake row.
      if (fakeCounter === 0) {
        fakeCounter += 1;
        arg1();
      }
      // On second response: return error.
      if (fakeCounter > 0) {
        arg1(new Error('TESTCLOSE'));
      }
    });
    // Prepare stub.
    const stubMysql = sandbox.stub(mysql, 'createConnection');
    stubMysql.returns({
      end: fakeMysqlEnd,
    });

    const test = new MySQL('host', 'user', 'password', 'database');

    expect(test).to.be.an('object');
    expect(test).to.have.property('conn');
    expect(test.conn).to.respondTo('end');
    expect(stubMysql.calledOnce).to.equal(true);
    expect(test).to.respondTo('close');

    // Test success close.
    await test.close();

    expect(fakeMysqlEnd.calledOnce).to.equal(true);
    expect(fakeMysqlEnd.args[0]).to.have.lengthOf(1);
    expect(fakeMysqlEnd.args[0][0]).to.be.an('function');
    expect(fakeCounter).to.equal(1);

    // Test failed close.
    try {
      await test.close();
      expect.fail('should not reach here for mysql end test.');
    } catch (error) {
      expect(error).to.have.property('message', 'TESTCLOSE');
      expect(fakeMysqlEnd.calledTwice).to.equal(true);
      expect(fakeMysqlEnd.args[1]).to.have.lengthOf(1);
      expect(fakeMysqlEnd.args[1][0]).to.be.an('function');
    }

    // Restore stub.
    stubMysql.restore();
  });
});

```

```$ npx mocha stackoverflow.js

  MySQL
    ✓ constructor fn
    ✓ query fn
    ✓ close fn

  3 passing (21ms)

$
```

Hope this helps.

Body:
I have a small wrapper class which adds promises to some mysql functionality.

const mysql = require('mysql');

export default class MySQL {
    constructor(host, user, password, database, port = 3306) {
        this.conn = mysql.createConnection({
            host,
            port,
            user,
            password,
            database,
        });
    }

    query(sql, args) {
        return new Promise((resolve, reject) => {
            // eslint-disable-next-line consistent-return
            this.conn.query(sql, args, (err, rows) => {
                if (err) {
                    reject(err);
                    return;
                }
                resolve(rows);
            });
        });
    }

    close() {
        return new Promise((resolve, reject) => {
            this.conn.end((err) => {
                if (err) {
                    reject(err);
                    return;
                }
                resolve();
            });
        });
    }
}

I am trying to write a unit test for this class but am completely stuck trying to mock this.conn.

I have tried various mixes of proxyquire, sinon, and both combined.  When I use proxyquire in a beforeEach hook:

beforeEach(function () {
    createConnectionStub = sinon.stub();
    MySQL = proxyquire('../../lib/utils/mysql', {
        mysql: {
            createConnection: createConnectionStub,
        },
    }).default;
});

and try to set a stub to the conn object:

it('Returns query results', async function () {
            stubDb = new MySQL('host', 'user', 'password', 'database');
            stubDb.conn = sinon.stub();

            const results = await stubDb.query('SELECT * FROM whatever');
        });

I keep getting TypeError: this.conn.query is not a function

what is the best way to setup a mock as the this.conn attributes so I can easily assert method calls against it?  Any help would be much appreciated

Body:
I am an hour late. :)

But I have coded the example and provide alternative to test, so I continue to post this.

I agree, that you do not need proxyquire at all. I use sinon sandbox, stub and fake in example below.

// @file stackoverflow.js
const sinon = require('sinon');
const { expect } = require('chai');
const mysql = require('mysql');

// Change this to your mysql class definition.
const MySQL = require('./mysql.js');

describe('MySQL', function () {
  let sandbox;

  before(function () {
    sandbox = sinon.createSandbox();
  });

  after(function () {
    sandbox.restore();
  });

  it('constructor fn', function () {
    // Prepare stub.
    const stubMysql = sandbox.stub(mysql, 'createConnection');
    // This just to make sure whether conn is storing this true value.
    stubMysql.returns(true);

    const test = new MySQL('host', 'user', 'password', 'database');

    // Check whether call mysql.createConnection the right way.
    expect(test).to.be.an('object');
    expect(test).to.have.property('conn', true);
    expect(stubMysql.calledOnce).to.equal(true);
    expect(stubMysql.args[0]).to.have.lengthOf(1);
    expect(stubMysql.args[0][0]).to.have.property('host', 'host');
    expect(stubMysql.args[0][0]).to.have.property('user', 'user');
    expect(stubMysql.args[0][0]).to.have.property('password', 'password');
    expect(stubMysql.args[0][0]).to.have.property('database', 'database');
    expect(stubMysql.args[0][0]).to.have.property('port', 3306);
    // Restore stub.
    stubMysql.restore();
  });

  it('query fn', async function () {
    let fakeCounter = 0;
    // Create fake function.
    const fakeMysqlQuery = sinon.fake((arg1, arg2, arg3) => {
      // On first response: return fake row.
      if (fakeCounter === 0) {
        fakeCounter += 1;
        arg3(undefined, []);
      }
      // On second response: return error.
      if (fakeCounter > 0) {
        arg3(new Error('TESTQUERY'));
      }
    });
    // Prepare stub.
    const stubMysql = sandbox.stub(mysql, 'createConnection');
    stubMysql.returns({
      query: fakeMysqlQuery,
    });

    const test = new MySQL('host', 'user', 'password', 'database');

    expect(test).to.be.an('object');
    expect(test).to.have.property('conn');
    expect(test.conn).to.respondTo('query');
    expect(stubMysql.calledOnce).to.equal(true);
    expect(test).to.respondTo('query');

    // Test success query.
    const results = await test.query('SELECT * FROM whatever');

    expect(results).to.be.an('array');
    expect(results).to.have.lengthOf(0);
    expect(fakeMysqlQuery.calledOnce).to.equal(true);
    expect(fakeMysqlQuery.args[0]).to.have.lengthOf(3);
    expect(fakeMysqlQuery.args[0][0]).to.equal('SELECT * FROM whatever');
    expect(fakeMysqlQuery.args[0][1]).to.be.an('undefined');
    expect(fakeMysqlQuery.args[0][2]).to.be.an('function');
    expect(fakeCounter).to.equal(1);

    // Test rejection.
    try {
      await test.query('SELECT * FROM blablabla');
      expect.fail('should not reach here for mysql query test.');
    } catch (error) {
      expect(error).to.have.property('message', 'TESTQUERY');
      expect(fakeMysqlQuery.calledTwice).to.equal(true);
      expect(fakeMysqlQuery.args[1]).to.have.lengthOf(3);
      expect(fakeMysqlQuery.args[1][0]).to.equal('SELECT * FROM blablabla');
      expect(fakeMysqlQuery.args[1][1]).to.be.an('undefined');
      expect(fakeMysqlQuery.args[1][2]).to.be.an('function');
    }

    // Restore stub.
    stubMysql.restore();
  });

  it('close fn', async function () {
    let fakeCounter = 0;
    // Create fake function.
    const fakeMysqlEnd = sinon.fake((arg1) => {
      // On first response: return fake row.
      if (fakeCounter === 0) {
        fakeCounter += 1;
        arg1();
      }
      // On second response: return error.
      if (fakeCounter > 0) {
        arg1(new Error('TESTCLOSE'));
      }
    });
    // Prepare stub.
    const stubMysql = sandbox.stub(mysql, 'createConnection');
    stubMysql.returns({
      end: fakeMysqlEnd,
    });

    const test = new MySQL('host', 'user', 'password', 'database');

    expect(test).to.be.an('object');
    expect(test).to.have.property('conn');
    expect(test.conn).to.respondTo('end');
    expect(stubMysql.calledOnce).to.equal(true);
    expect(test).to.respondTo('close');

    // Test success close.
    await test.close();

    expect(fakeMysqlEnd.calledOnce).to.equal(true);
    expect(fakeMysqlEnd.args[0]).to.have.lengthOf(1);
    expect(fakeMysqlEnd.args[0][0]).to.be.an('function');
    expect(fakeCounter).to.equal(1);

    // Test failed close.
    try {
      await test.close();
      expect.fail('should not reach here for mysql end test.');
    } catch (error) {
      expect(error).to.have.property('message', 'TESTCLOSE');
      expect(fakeMysqlEnd.calledTwice).to.equal(true);
      expect(fakeMysqlEnd.args[1]).to.have.lengthOf(1);
      expect(fakeMysqlEnd.args[1][0]).to.be.an('function');
    }

    // Restore stub.
    stubMysql.restore();
  });
});

$ npx mocha stackoverflow.js

  MySQL
    ✓ constructor fn
    ✓ query fn
    ✓ close fn

  3 passing (21ms)

$

Hope this helps.


问:
Property has not been defined and the schema does not allow additional properties
I'm getting the below error while trying to validate the schema - v7 draft. Appreciate your help in resolving this error.

I'm trying to build the schema based on the conditional enum value from header. The attribute 'salary' type needs to vary based on the condition choose in the header.

ERROR

Property 'salary' has not been defined and the schema does not allow additional properties.

JSON schema

```<code>{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "EmployeeHeader": {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "type": "object",
      "properties": {
        "empType": {
          "type": "string",
          "enum": [
            "FULLTIME",
            "CONTRACT"
          ]
        }
      },
      "required": [
        "empType"
      ]
    },
    "EmployeeDetail": {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "type": "array",
      "items": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "type": "object",
        "properties": {
          "workInfo": {
            "$schema": "http://json-schema.org/draft-07/schema#",
            "type": "object",
            "properties": {
              "jobtitle": {
                "type": "string",
                "minLength": 1,
                "maxLength": 200
              }
            },
            "required": [
              "jobtitle"
            ],
            "additionalProperties": false
          }
        },
        "required": [
          "workInfo"
        ],
        "additionalProperties": false
      },
      "minItems": 1
    }
  },
  "if": {
    "properties": {
      "EmployeeHeader": {
        "properties": {
          "empType": {
            "const": "FULLTIME"
          }
        }
      }
    }
  },
  "then": {
    "properties": {
      "EmployeeDetail": {
        "items": {
          "properties": {
            "workInfo": {
              "properties": {
                "salary": {
                  "type": "object",
                  "properties": {
                    "regular": {
                      "type": "number",
                      "minimum": 0,
                      "maximum": 1000000,
                      "exclusiveMaximum": false,
                      "multipleOf": 0.01
                    },
                    "bonus": {
                      "type": "number",
                      "minimum": 0,
                      "maximum": 1000000,
                      "exclusiveMaximum": false,
                      "multipleOf": 0.01
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  },
  "else": {
    "properties": {
      "EmployeeDetail": {
        "items": {
          "properties": {
            "workInfo": {
              "properties": {
                "salary": {
                  "type": "number",
                  "minimum": 0,
                  "maximum": 1000000,
                  "exclusiveMaximum": false,
                  "multipleOf": 0.01
                }
              }
            }
          }
        }
      }
    }
  },
  "required": [
    "EmployeeHeader",
    "EmployeeDetail"
  ],
  "additionalProperties": false
}

</code>```

SAMPLE PAYLOAD

```<code>{
  "EmployeeHeader": {
    "empType": "FULLTIME"
  },
  "EmployeeDetail": [
    {
      "workInfo": {
        "jobtitle": "Software Engineer",
        "salary": {
          "regular": 4000,
          "bonus": 5000
        }
      }
    }
  ]
}
</code>```

答:
Issue

The additionalProperties keyword only considers the properties and patternProperties defined in the immediate subschema where it appears. Since you define the “salary” property only within your then and else keywords, it is treated as an illegal additional property.

Solution

Already introduce the “salary” property in the subschema’s properties where the additionalProperties: false are defined as well. At least as simple boolean schema true.
In other circumstances, one could also include all common attributes that appear in both the then and else keywords to reduce duplication, but in your particular case that’s hardly an option.

Additional Note

Generally speaking, if/then/else should only be used for additional constraints (e.g. minimum/maximum/required) but not to introduce completely new properties especially when using patternProperties or additionalProperties.

Body:
I'm getting the below error while trying to validate the schema - v7 draft. Appreciate your help in resolving this error.

I'm trying to build the schema based on the conditional enum value from header. The attribute 'salary' type needs to vary based on the condition choose in the header.

ERROR

Property 'salary' has not been defined and the schema does not allow additional properties.

JSON schema

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "EmployeeHeader": {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "type": "object",
      "properties": {
        "empType": {
          "type": "string",
          "enum": [
            "FULLTIME",
            "CONTRACT"
          ]
        }
      },
      "required": [
        "empType"
      ]
    },
    "EmployeeDetail": {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "type": "array",
      "items": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "type": "object",
        "properties": {
          "workInfo": {
            "$schema": "http://json-schema.org/draft-07/schema#",
            "type": "object",
            "properties": {
              "jobtitle": {
                "type": "string",
                "minLength": 1,
                "maxLength": 200
              }
            },
            "required": [
              "jobtitle"
            ],
            "additionalProperties": false
          }
        },
        "required": [
          "workInfo"
        ],
        "additionalProperties": false
      },
      "minItems": 1
    }
  },
  "if": {
    "properties": {
      "EmployeeHeader": {
        "properties": {
          "empType": {
            "const": "FULLTIME"
          }
        }
      }
    }
  },
  "then": {
    "properties": {
      "EmployeeDetail": {
        "items": {
          "properties": {
            "workInfo": {
              "properties": {
                "salary": {
                  "type": "object",
                  "properties": {
                    "regular": {
                      "type": "number",
                      "minimum": 0,
                      "maximum": 1000000,
                      "exclusiveMaximum": false,
                      "multipleOf": 0.01
                    },
                    "bonus": {
                      "type": "number",
                      "minimum": 0,
                      "maximum": 1000000,
                      "exclusiveMaximum": false,
                      "multipleOf": 0.01
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  },
  "else": {
    "properties": {
      "EmployeeDetail": {
        "items": {
          "properties": {
            "workInfo": {
              "properties": {
                "salary": {
                  "type": "number",
                  "minimum": 0,
                  "maximum": 1000000,
                  "exclusiveMaximum": false,
                  "multipleOf": 0.01
                }
              }
            }
          }
        }
      }
    }
  },
  "required": [
    "EmployeeHeader",
    "EmployeeDetail"
  ],
  "additionalProperties": false
}

SAMPLE PAYLOAD

{
  "EmployeeHeader": {
    "empType": "FULLTIME"
  },
  "EmployeeDetail": [
    {
      "workInfo": {
        "jobtitle": "Software Engineer",
        "salary": {
          "regular": 4000,
          "bonus": 5000
        }
      }
    }
  ]
}


问:
QueryFilter() return array of structure in coldfusion2016. But it's should return query
Here I'm working with QueryFilter() function. I've go through this function usage & return type. The adobe docs said it's return query. But sample code return array of structure in coldfusion2016.  I've tried the same code in cf2018 but it's return the query only.

So I've tried with same code trycf.com. While I choose cf2016 in trycf there also return type in query only. But I don't know why my cf2016 return array of structure. My sample code.

```<code><cfscript>

    news = queryNew("id,type,title", "integer,varchar,varchar");
    queryAddRow(news,[{
        id: 1,
        type: "book",
        title: "Cloud Atlas"
    },{
        id: 2,
        type: "book",
        title: "Lord of The Rings"
    },{
        id: 3,
        type: "film",
        title: "Men in Black"
    }]);

    books = QueryFilter(news,function(_news) {
        return _news.type is 'book';
    });
    writeDump(books);

</cfscript>
</code>```

CF2016 Output in my local :

CF2018 Output :

Could you please any one know the root causes of this issue ?

答:
Yes the queryFilter() should return the Filtered query.We have the issue that return type as array of structure in before update11 in cf2016. So once I've update my cf2016 from update10 to update11. It's get resolved. Now my queryFilter() function return the query only.

So update11 resolved this problem in cf2016. Thank you.

Body:
Here I'm working with QueryFilter() function. I've go through this function usage & return type. The adobe docs said it's return query. But sample code return array of structure in coldfusion2016.  I've tried the same code in cf2018 but it's return the query only.

So I've tried with same code trycf.com. While I choose cf2016 in trycf there also return type in query only. But I don't know why my cf2016 return array of structure. My sample code.

<cfscript>

    news = queryNew("id,type,title", "integer,varchar,varchar");
    queryAddRow(news,[{
        id: 1,
        type: "book",
        title: "Cloud Atlas"
    },{
        id: 2,
        type: "book",
        title: "Lord of The Rings"
    },{
        id: 3,
        type: "film",
        title: "Men in Black"
    }]);

    books = QueryFilter(news,function(_news) {
        return _news.type is 'book';
    });
    writeDump(books);

</cfscript>

CF2016 Output in my local :

CF2018 Output :

Could you please any one know the root causes of this issue ?