问:
general programming logic
I have a general question - regarding testing of values, I have run into this issue multiple time and I end up with some unsightly long code to accomplish something that logically seems simple.

the issue - I have one or multiple values I want to test against other values....SUCH THAT my code ends up looking like this (conceptually)

```<code>IF (A > B
AND A < C
AND A < D
AND A < E)
THEN print "Yes"
</code>```

LOGICALLY I can express this as IF A > b,c,d,e etc.

If I also need to check other values in that list - you can see that the conditional statement to test against could become significantly larger and messier than the code the condition is intended to yield...

there MUST be a way problematically OR mathematically to express this common instance.

I know each language has 'syntax' specific ways to to this but .. I'll take suggestions and try em.

答:
In SQL there is often (I don't know if all dialects supoprt it) a BETWEEN operator. It takes an upper and lower value so you would have to do something like this (works in Oracle 10g):

```<code>select 1
from dual
where 1 between 0 and (select min(x) from (select 2 x from dual
                                           union
                                           select 3 x from dual
                                           union
                                          select 4 x from dual)) ;
</code>```

Obviosuly, this is very contrived, as I had to union multiple select from duals to make up the list to select the MIN from.

REwritten using your variables

```<code>select A
from some_table
where A between B and (select min(x) from (select C x from somewhere
                                           union
                                           select D x from somewhere
                                           union
                                          select E x from somewhere)) ;
</code>```

Title: general programming logic

Body:
I have a general question - regarding testing of values, I have run into this issue multiple time and I end up with some unsightly long code to accomplish something that logically seems simple.

the issue - I have one or multiple values I want to test against other values....SUCH THAT my code ends up looking like this (conceptually)

IF (A > B
AND A < C
AND A < D
AND A < E)
THEN print "Yes"

LOGICALLY I can express this as IF A > b,c,d,e etc.

If I also need to check other values in that list - you can see that the conditional statement to test against could become significantly larger and messier than the code the condition is intended to yield...

there MUST be a way problematically OR mathematically to express this common instance.

I know each language has 'syntax' specific ways to to this but .. I'll take suggestions and try em.

Body:
In SQL there is often (I don't know if all dialects supoprt it) a BETWEEN operator. It takes an upper and lower value so you would have to do something like this (works in Oracle 10g):

select 1
from dual
where 1 between 0 and (select min(x) from (select 2 x from dual
                                           union
                                           select 3 x from dual
                                           union
                                          select 4 x from dual)) ;

Obviosuly, this is very contrived, as I had to union multiple select from duals to make up the list to select the MIN from.

REwritten using your variables

select A
from some_table
where A between B and (select min(x) from (select C x from somewhere
                                           union
                                           select D x from somewhere
                                           union
                                          select E x from somewhere)) ;


来源: stackexchange

问:
Sorting Jsonb inner node in PostgreSQL
I have a details::Jsonb column in which data is stores as follows:

```<code>{"competitor_weight": {"weight": "", "data_source": "1"}}
{"competitor_weight": {"weight": "", "data_source": "1"}}
{"competitor_weight": {"weight": "5", "data_source": "1"}}
{"competitor_weight": {"weight": "25", "data_source": "0"}}
{"competitor_weight": {"weight": "20", "data_source": "1"}}
{"competitor_weight": {"weight": "20", "data_source": "1"}}
{"competitor_weight": {"weight": "15", "data_source": "1"}}
{"competitor_weight": {"weight": "15", "data_source": "1"}}
</code>```

I want to sort it as per the 'weight' node to generate result :

```<code>  Weight
    25
    20
    20
    15
    15
    5
</code>```

I have done like

```<code>select details -> 'competitor_weight' ->> 'weight' as weight
from sample_table
order by COALESCE(details -> 'competitor_weight' ->> 'weight', '0') DESC
</code>```

But the result comes as:

```<code>Weight
 5
25
20
20
15
15
</code>```

答:
You need to cast it to a number, currently your sorting is done on the ASCII strings. For that you also need to deal with the empty strings by converting them to null. You can get rid of the coalesce if you use nulls last to put the null values to the end

```<code>select details -> 'competitor_weight' ->> 'weight' as weight
from sample_table
order by nullif(details -> 'competitor_weight' ->> 'weight','')::int DESC nulls last
</code>```

ContentLicense: CC BY-SA 4.0

Title: Sorting Jsonb inner node in PostgreSQL

Body:
I have a details::Jsonb column in which data is stores as follows:

{"competitor_weight": {"weight": "", "data_source": "1"}}
{"competitor_weight": {"weight": "", "data_source": "1"}}
{"competitor_weight": {"weight": "5", "data_source": "1"}}
{"competitor_weight": {"weight": "25", "data_source": "0"}}
{"competitor_weight": {"weight": "20", "data_source": "1"}}
{"competitor_weight": {"weight": "20", "data_source": "1"}}
{"competitor_weight": {"weight": "15", "data_source": "1"}}
{"competitor_weight": {"weight": "15", "data_source": "1"}}

I want to sort it as per the 'weight' node to generate result :

  Weight
    25
    20
    20
    15
    15
    5

I have done like

select details -> 'competitor_weight' ->> 'weight' as weight
from sample_table
order by COALESCE(details -> 'competitor_weight' ->> 'weight', '0') DESC

But the result comes as:

Weight
 5
25
20
20
15
15

Body:
You need to cast it to a number, currently your sorting is done on the ASCII strings. For that you also need to deal with the empty strings by converting them to null. You can get rid of the coalesce if you use nulls last to put the null values to the end

select details -> 'competitor_weight' ->> 'weight' as weight
from sample_table
order by nullif(details -> 'competitor_weight' ->> 'weight','')::int DESC nulls last


问:
Update/set state dynamically in reactjs
I am new to reactjs and used to load/update data through javascript/jquery.

In my example I've got 3 buttons. Whenever I click one one button, I would like to update the text above. Right now, I am using same state for the counter. Can't you somehow get the current divs ID - and update the state inside it?

I could just change the state to 3 different states.
But the reason why I am not doing this is if I ever want to load something dynamically they probably have the same state?

jsfiddle:
https://jsfiddle.net/t9am76fs/1/

```<code>constructor(props) {
    super(props);

    this.state = {
        count: 0,
    };
}
incrementCounter = (value) => {
    this.setState({ count: this.state.count + value })
};

render() {
    return (
        <div>
            <div id='div1'>
                  <p>You clicked {this.state.count} times</p>
                  <button onClick={() => this.incrementCounter(1)}>+1</button>
            </div>

            <div id='div2'>
                  <p>You clicked {this.state.count} times</p>
                  <button onClick={() => this.incrementCounter(1)}>+1</button>
            </div>

            <div id='div3'>
                  <p>You clicked {this.state.count} times</p>
                  <button onClick={() => this.incrementCounter(1)}>+1</button>
            </div>
        </div>
    );
}
</code>```

Thanks

答:
You can also do it by giving the input names and accessing these via the event.target.name and use that to update state depending on the given name.

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

        this.state = {
            count: [0,0,0]
        };
    }
    incrementCounter = (event) => {
        const updatedCount = [...this.state.count] // Create a shallwo copy
        updatedCount[Number(event.target.name)]++
        this.setState({ count: updatedCount })
    };

    render() {
    const [count1, count2, count3] = this.state.count;
        return (

You clicked {count1} times

                      <button name='0' onClick={this.incrementCounter}>+1</button>

You clicked {count2} times

                      <button name='1' onClick={this.incrementCounter}>+1</button>

You clicked {count3} times

                      <button name='2' onClick={this.incrementCounter}>+1</button>

        );
    }
}

ReactDOM.render(<Counter />, document.querySelector("#app")); ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div></code>```

Title: Update/set state dynamically in reactjs

Body:
I am new to reactjs and used to load/update data through javascript/jquery.

In my example I've got 3 buttons. Whenever I click one one button, I would like to update the text above. Right now, I am using same state for the counter. Can't you somehow get the current divs ID - and update the state inside it?

I could just change the state to 3 different states.
But the reason why I am not doing this is if I ever want to load something dynamically they probably have the same state?

jsfiddle:
https://jsfiddle.net/t9am76fs/1/

constructor(props) {
    super(props);

    this.state = {
        count: 0,
    };
}
incrementCounter = (value) => {
    this.setState({ count: this.state.count + value })
};

render() {
    return (

You clicked {this.state.count} times

                  <button onClick={() => this.incrementCounter(1)}>+1</button>

You clicked {this.state.count} times

                  <button onClick={() => this.incrementCounter(1)}>+1</button>

You clicked {this.state.count} times

                  <button onClick={() => this.incrementCounter(1)}>+1</button>

    );
}

Thanks

Body:
You can also do it by giving the input names and accessing these via the event.target.name and use that to update state depending on the given name.

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

        this.state = {
            count: [0,0,0]
        };
    }
    incrementCounter = (event) => {
        const updatedCount = [...this.state.count] // Create a shallwo copy
        updatedCount[Number(event.target.name)]++
        this.setState({ count: updatedCount })
    };

    render() {
    const [count1, count2, count3] = this.state.count;
        return (
            <div>
                <div id='div1'>
                      <p>You clicked {count1} times</p>
                      <button name='0' onClick={this.incrementCounter}>+1</button>
                </div>

                <div id='div2'>
                      <p>You clicked {count2} times</p>
                      <button name='1' onClick={this.incrementCounter}>+1</button>
                </div>

                <div id='div3'>
                      <p>You clicked {count3} times</p>
                      <button name='2' onClick={this.incrementCounter}>+1</button>
                </div>
            </div>
        );
    }
}

ReactDOM.render(<Counter />, document.querySelector("#app"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>


问:
Is there a better way to check if a file is older than X?
I am currently using this code:

```<code>(Now - dctFile.LastWriteTime).TotalMinutes > DeleteAgeInDays * 1440
</code>```

Is there a more precise way? I know I could use .TotalMillisecondsand multiply by 86400000, but it seems inefficient.

答:
You could use the .AddDays method...

```<code>If dtcFile.LastWriteTime.AddDays(DeleteAgeInDays) < Date.Now Then
</code>```

That should be good enough for the precision you require... but if you wanted it to just check based on the date (and not the time as well)...

```<code>If dtcFile.LastWriteTime.AddDays(DeleteAgeInDays).Date < Date.Today Then
</code>```

Body:
I am currently using this code:

(Now - dctFile.LastWriteTime).TotalMinutes > DeleteAgeInDays * 1440

Is there a more precise way? I know I could use .TotalMillisecondsand multiply by 86400000, but it seems inefficient.

Body:
You could use the .AddDays method...

If dtcFile.LastWriteTime.AddDays(DeleteAgeInDays) < Date.Now Then

That should be good enough for the precision you require... but if you wanted it to just check based on the date (and not the time as well)...

If dtcFile.LastWriteTime.AddDays(DeleteAgeInDays).Date < Date.Today Then


问:
gradle is not building and project is also not opening in android View
i had cloned the project from the Github but the file is not working even the project is not opening in the Android View and i gradle files are not building. is there anyone who can help me resolving this issue? Here is the screenshot
 of errors</p>

答:
Hi you have enabled the offline mode of gradle sync in android studio.
you can toggle from here as in attached screenshot.

After that just sync the project and make sure your internet is working fine.
Happy Coding!


问:
Plotly: How to edit unified hoverlabel?
I am generating a graph with two different contour lines. When I hover the mouse over the graph it compares a menu with the values of the two contours as in the image:

I obtained this result with this code:

```<code># IMPORT
import plotly.graph_objs as go
import plotly.offline as pyo
import numpy as np

# CONSTANTS SET UP
N = 11
x_min = 0
x_max = 10
y_min = 0
y_max = 10
fontsize = 18

# COLORS SET UP
blue = '#6683f3'
orange = '#ff9266'
black = '#212121'

# DEFINE THE MESH GRID
x = np.linspace(x_min, x_max, N)
y = np.linspace(y_min, y_max, N)
XX, YY = np.meshgrid(x, y)

# CALCULATE Z1 AND Z2
Z1 = XX + YY
Z2 = XX - YY

# DEFINE THE TRACES LIST
data = [go.Contour(z = Z1,
                   transpose = True,
                   name = 'Z1',
                   zmin = np.min(Z1),
                   zmax = np.max(Z1) + 1,
                   hovertemplate = 'Z1 = %{z: .0f}<extra></extra>',
                   contours_coloring = 'lines',
                   showscale = False,
                   showlegend = True,
                   colorscale = [[0, orange], [1, orange]],
                   line_width = 4,
                   ncontours = 20,
                   contours = dict(showlabels = True,
                                   labelformat = '.0f',
                                   labelfont = dict(size = 18))),
        go.Contour(z = Z2,
                   transpose = True,
                   name = 'Z2',
                   zmin = np.min(Z2),
                   zmax = np.max(Z2) + 1,
                   hovertemplate = 'Z2 = %{z: .0f}<extra></extra>',
                   contours_coloring = 'lines',
                   showscale = False,
                   showlegend = True,
                   colorscale = [[0, blue], [1, blue]],
                   line_width = 4,
                   ncontours = 20,
                   contours = dict(showlabels = True,
                                   labelformat = '.0f',
                                   labelfont = dict(size = fontsize)))]

# DEFINE THE LAYOUT
layout = go.Layout(plot_bgcolor = black,
                   hovermode = 'x')

# DEFINE THE FIGURE
figure = go.Figure(data = data,
                   layout = layout)

# IMPROVE LEGEND AND HOVERLABEL ASPECT
figure.update_layout(legend = dict(itemsizing = 'constant',
                                   font = dict(size = fontsize)),
                     hoverlabel = dict(font_size = fontsize))

# PLOT THE FIGURE
pyo.plot(figure)
</code>```

In the layout definition section, if I replace hovermode = 'x' with hovermode = 'x unified' I get this result:

I would like to remove from this menu the first line that contains the information on the x. I honestly don't know where to start, I tried to consult the plotly documentation but I did not get any clue.

What I would get (image manually edited):

A possible alternative would be to improve the appearance of the menu that appears in the first image:

adding a unique background for the two contours

adding a colored line for each contour

Version info:

```<code>Python  4.7.0
dash    1.12.0
plotly  4.7.0
</code>```

答:
If this is your desired output:

Then just include:

```<code>figure.update_traces(hoverinfo = 'name+z')
</code>```

And, for both go.Contour, drop the hovertemplate parts:

```<code> #hovertemplate = 'Z1 = %{z: .0f}<extra></extra>',
 .
 .
 #hovertemplate = 'Z2 = %{z: .0f}<extra></extra>',
</code>```

Plot:

Some important details:

It seems that figure.update_traces(hoverinfo = 'name+z') or similar setups will have noe effect if a hovertemplate has been defined in go.Contour(). At least that is what I've found to be the case. Please let me know if you make any other discoveries after testing this!

Complete code:

```<code># IMPORT
import plotly.graph_objs as go
import plotly.offline as pyo
import numpy as np

# CONSTANTS SET UP
N = 11
x_min = 0
x_max = 10
y_min = 0
y_max = 10
fontsize = 18

# COLORS SET UP
blue = '#6683f3'
orange = '#ff9266'
black = '#212121'

# DEFINE THE MESH GRID
x = np.linspace(x_min, x_max, N)
y = np.linspace(y_min, y_max, N)
XX, YY = np.meshgrid(x, y)

# CALCULATE Z1 AND Z2
Z1 = XX + YY
Z2 = XX - YY

# DEFINE THE TRACES LIST
data = [go.Contour(z = Z1,
                   transpose = True,
                   name = 'Z1',
                   zmin = np.min(Z1),
                   zmax = np.max(Z1) + 1,
                   #hovertemplate = 'Z1 = %{z: .0f}<extra></extra>',
                   contours_coloring = 'lines',
                   showscale = False,
                   showlegend = True,
                   colorscale = [[0, orange], [1, orange]],
                   line_width = 4,
                   ncontours = 20,
                   contours = dict(showlabels = True,
                                   labelformat = '.0f',
                                   labelfont = dict(size = 18))),
        go.Contour(z = Z2,
                   transpose = True,
                   name = 'Z2',
                   zmin = np.min(Z2),
                   zmax = np.max(Z2) + 1,
                  # hovertemplate = 'Z2 = %{z: .0f}<extra></extra>',
                   contours_coloring = 'lines',
                   showscale = False,
                   showlegend = True,
                   colorscale = [[0, blue], [1, blue]],
                   line_width = 4,
                   ncontours = 20,
                   contours = dict(showlabels = True,
                                   labelformat = '.0f',
                                   labelfont = dict(size = fontsize)))]

# DEFINE THE LAYOUT
layout = go.Layout(plot_bgcolor = black,
                   hovermode = 'x unified')

# DEFINE THE FIGURE
figure = go.Figure(data = data,
                   layout = layout)

figure.update_traces(hoverinfo = 'name+z')

figure.update_layout(legend = dict(itemsizing = 'constant',
                                   font = dict(size = fontsize)),
                     hoverlabel = dict(font_size = fontsize))

figure.show()
</code>```

Title: Plotly: How to edit unified hoverlabel?

Body:
I am generating a graph with two different contour lines. When I hover the mouse over the graph it compares a menu with the values of the two contours as in the image:

I obtained this result with this code:

# IMPORT
import plotly.graph_objs as go
import plotly.offline as pyo
import numpy as np

# CONSTANTS SET UP
N = 11
x_min = 0
x_max = 10
y_min = 0
y_max = 10
fontsize = 18

# COLORS SET UP
blue = '#6683f3'
orange = '#ff9266'
black = '#212121'

# DEFINE THE MESH GRID
x = np.linspace(x_min, x_max, N)
y = np.linspace(y_min, y_max, N)
XX, YY = np.meshgrid(x, y)

# CALCULATE Z1 AND Z2
Z1 = XX + YY
Z2 = XX - YY

# DEFINE THE TRACES LIST
data = [go.Contour(z = Z1,
                   transpose = True,
                   name = 'Z1',
                   zmin = np.min(Z1),
                   zmax = np.max(Z1) + 1,
                   hovertemplate = 'Z1 = %{z: .0f}<extra></extra>',
                   contours_coloring = 'lines',
                   showscale = False,
                   showlegend = True,
                   colorscale = [[0, orange], [1, orange]],
                   line_width = 4,
                   ncontours = 20,
                   contours = dict(showlabels = True,
                                   labelformat = '.0f',
                                   labelfont = dict(size = 18))),
        go.Contour(z = Z2,
                   transpose = True,
                   name = 'Z2',
                   zmin = np.min(Z2),
                   zmax = np.max(Z2) + 1,
                   hovertemplate = 'Z2 = %{z: .0f}<extra></extra>',
                   contours_coloring = 'lines',
                   showscale = False,
                   showlegend = True,
                   colorscale = [[0, blue], [1, blue]],
                   line_width = 4,
                   ncontours = 20,
                   contours = dict(showlabels = True,
                                   labelformat = '.0f',
                                   labelfont = dict(size = fontsize)))]

# DEFINE THE LAYOUT
layout = go.Layout(plot_bgcolor = black,
                   hovermode = 'x')

# DEFINE THE FIGURE
figure = go.Figure(data = data,
                   layout = layout)

# IMPROVE LEGEND AND HOVERLABEL ASPECT
figure.update_layout(legend = dict(itemsizing = 'constant',
                                   font = dict(size = fontsize)),
                     hoverlabel = dict(font_size = fontsize))

# PLOT THE FIGURE
pyo.plot(figure)

In the layout definition section, if I replace hovermode = 'x' with hovermode = 'x unified' I get this result:

I would like to remove from this menu the first line that contains the information on the x. I honestly don't know where to start, I tried to consult the plotly documentation but I did not get any clue.

What I would get (image manually edited):

A possible alternative would be to improve the appearance of the menu that appears in the first image:

adding a unique background for the two contours

adding a colored line for each contour

Version info:

Python  4.7.0
dash    1.12.0
plotly  4.7.0

Body:
If this is your desired output:

Then just include:

figure.update_traces(hoverinfo = 'name+z')

And, for both go.Contour, drop the hovertemplate parts:

 #hovertemplate = 'Z1 = %{z: .0f}<extra></extra>',
 .
 .
 #hovertemplate = 'Z2 = %{z: .0f}<extra></extra>',

Plot:

Some important details:

It seems that figure.update_traces(hoverinfo = 'name+z') or similar setups will have noe effect if a hovertemplate has been defined in go.Contour(). At least that is what I've found to be the case. Please let me know if you make any other discoveries after testing this!

Complete code:

# IMPORT
import plotly.graph_objs as go
import plotly.offline as pyo
import numpy as np

# CONSTANTS SET UP
N = 11
x_min = 0
x_max = 10
y_min = 0
y_max = 10
fontsize = 18

# COLORS SET UP
blue = '#6683f3'
orange = '#ff9266'
black = '#212121'

# DEFINE THE MESH GRID
x = np.linspace(x_min, x_max, N)
y = np.linspace(y_min, y_max, N)
XX, YY = np.meshgrid(x, y)

# CALCULATE Z1 AND Z2
Z1 = XX + YY
Z2 = XX - YY

# DEFINE THE TRACES LIST
data = [go.Contour(z = Z1,
                   transpose = True,
                   name = 'Z1',
                   zmin = np.min(Z1),
                   zmax = np.max(Z1) + 1,
                   #hovertemplate = 'Z1 = %{z: .0f}<extra></extra>',
                   contours_coloring = 'lines',
                   showscale = False,
                   showlegend = True,
                   colorscale = [[0, orange], [1, orange]],
                   line_width = 4,
                   ncontours = 20,
                   contours = dict(showlabels = True,
                                   labelformat = '.0f',
                                   labelfont = dict(size = 18))),
        go.Contour(z = Z2,
                   transpose = True,
                   name = 'Z2',
                   zmin = np.min(Z2),
                   zmax = np.max(Z2) + 1,
                  # hovertemplate = 'Z2 = %{z: .0f}<extra></extra>',
                   contours_coloring = 'lines',
                   showscale = False,
                   showlegend = True,
                   colorscale = [[0, blue], [1, blue]],
                   line_width = 4,
                   ncontours = 20,
                   contours = dict(showlabels = True,
                                   labelformat = '.0f',
                                   labelfont = dict(size = fontsize)))]

# DEFINE THE LAYOUT
layout = go.Layout(plot_bgcolor = black,
                   hovermode = 'x unified')

# DEFINE THE FIGURE
figure = go.Figure(data = data,
                   layout = layout)

figure.update_traces(hoverinfo = 'name+z')

figure.update_layout(legend = dict(itemsizing = 'constant',
                                   font = dict(size = fontsize)),
                     hoverlabel = dict(font_size = fontsize))

figure.show()


问:
Are arrays being transformed when using an enhanced for loop?
Does Java 5 or higher apply some of form of "boxing" to arrays? This question came to mind as the following code goes through an array as if it's an Iterable.</p>

```<code>for( String : args ){
// Do stuff
}
</code>```

答:
No.

Unlike primitives, arrays (and strings) are Objects.

ContentLicense: CC BY-SA 3.0

Body:
Does Java 5 or higher apply some of form of "boxing" to arrays? This question came to mind as the following code goes through an array as if it's an Iterable.

for( String : args ){
// Do stuff
}


问:
How to get x and y offset position of legendItemClick in highcharts react js?
Exactly I want is when click on each single legend items it will show dropdown on with there position.</p>

答:
Since you're using react, why not just find the offset x and y from the onClick of anywhere within the desired component.
Your question is incomplete because there's no attached code but what you need is an event listener.

To get one to show you the x and y offset of any component you click on, do this;

```<code>  componentWillUnmount() {
    window.removeEventListener('click', this.handleClick);
  }

  componentDidMount() {
    window.addEventListener('click', this.handleClick);
</code>```

Now, create a function called handleClick and pass in the event as an argument like:

```<code>handleClick = (e) => {
 console.log(e.offsetX,e.offsetY)
    }
  }
</code>```

Finally, give the component an onClick attribute and pass in this.handleClick as the function to be run like:

```<code><div className="charts" onClick={this.handleClick}>
</div>
</code>```

N.B: You'd ideally do all of this within a stateful component.

Body:
Since you're using react, why not just find the offset x and y from the onClick of anywhere within the desired component.
Your question is incomplete because there's no attached code but what you need is an event listener.

To get one to show you the x and y offset of any component you click on, do this;

  componentWillUnmount() {
    window.removeEventListener('click', this.handleClick);
  }

  componentDidMount() {
    window.addEventListener('click', this.handleClick);

Now, create a function called handleClick and pass in the event as an argument like:

handleClick = (e) => {
 console.log(e.offsetX,e.offsetY)
    }
  }

Finally, give the component an onClick attribute and pass in this.handleClick as the function to be run like:

<div className="charts" onClick={this.handleClick}>
</div>

N.B: You'd ideally do all of this within a stateful component.


问:
How to Modify a javax.json.JsonObject Object?
I am coding a feature in which I read and write back json. However I can read the json elements from a file but can't edit the same loaded object. Here is my code which I am working on.

InputStream inp = new FileInputStream(jsonFilePath);
JsonReader reader = Json.createReader(inp);

JsonArray employeesArr = reader.readArray();
for (int i = 0; i < 2; i++) {
    JsonObject jObj = employeesArr.getJsonObject(i);
    JsonObject teammanager = jObj.getJsonObject("manager");

    Employee manager = new Employee();
    manager.name = teammanager.getString("name");
    manager.emailAddress = teammanager.getString("email");
    System.out.println("uploading File " + listOfFiles[i].getName());
    File file  = insertFile(...);
    JsonObject tmpJsonValue = Json.createObjectBuilder()
        .add("fileId", file.getId())
        .add("alternativeLink", file.getAlternateLink())
        .build();

    jObj.put("alternativeLink", tmpJsonValue.get("alternativeLink"));  <-- fails here
}
```

I get the following exception when I run it.

Exception in thread "main" java.lang.UnsupportedOperationException

at java.util.AbstractMap.put(AbstractMap.java:203)

at com.mongodb.okr.DriveQuickstart.uploadAllFiles(DriveQuickstart.java:196)

at com.mongodb.okr.App.main(App.java:28)

答:
As answered by Sotirios, you can use JsonObjectBuilders.
To insert value into JsonObject, you can use method:

```<code>private JsonObject insertValue(JsonObject source, String key, String value) {
    JsonObjectBuilder builder = Json.createObjectBuilder();
    builder.add(key, value);
    source.entrySet().
            forEach(e -> builder.add(e.getKey(), e.getValue()));
    return builder.build();
}
</code>```

To insert JsonObject into JsonObject, you can use method:

```<code>private JsonObject insertObject(JsonObject parent, JsonObject child, String childName) {
    JsonObjectBuilder child_builder = Json.createObjectBuilder();
    JsonObjectBuilder parent_builder = Json.createObjectBuilder();
    parent.entrySet().
            forEach(e -> parent_builder.add(e.getKey(), e.getValue()));
    child.entrySet().
            forEach(e -> child_builder.add(e.getKey(), e.getValue()));
    parent_builder.add(childName, child_builder);
    return parent_builder.build();
}
</code>```

Please note, if you change the child JsonObject after inserting it into another "parent" JsonObject, it will have no effect on the "parent" JsonObject.

Body:
I am coding a feature in which I read and write back json. However I can read the json elements from a file but can't edit the same loaded object. Here is my code which I am working on.

InputStream inp = new FileInputStream(jsonFilePath);
JsonReader reader = Json.createReader(inp);

JsonArray employeesArr = reader.readArray();
for (int i = 0; i < 2; i++) {
    JsonObject jObj = employeesArr.getJsonObject(i);
    JsonObject teammanager = jObj.getJsonObject("manager");

    Employee manager = new Employee();
    manager.name = teammanager.getString("name");
    manager.emailAddress = teammanager.getString("email");
    System.out.println("uploading File " + listOfFiles[i].getName());
    File file  = insertFile(...);
    JsonObject tmpJsonValue = Json.createObjectBuilder()
        .add("fileId", file.getId())
        .add("alternativeLink", file.getAlternateLink())
        .build();

    jObj.put("alternativeLink", tmpJsonValue.get("alternativeLink"));  <-- fails here
}

I get the following exception when I run it.

Exception in thread "main" java.lang.UnsupportedOperationException

at java.util.AbstractMap.put(AbstractMap.java:203)

at com.mongodb.okr.DriveQuickstart.uploadAllFiles(DriveQuickstart.java:196)

at com.mongodb.okr.App.main(App.java:28)

Body:
As answered by Sotirios, you can use JsonObjectBuilders.
To insert value into JsonObject, you can use method:

private JsonObject insertValue(JsonObject source, String key, String value) {
    JsonObjectBuilder builder = Json.createObjectBuilder();
    builder.add(key, value);
    source.entrySet().
            forEach(e -> builder.add(e.getKey(), e.getValue()));
    return builder.build();
}

To insert JsonObject into JsonObject, you can use method:

private JsonObject insertObject(JsonObject parent, JsonObject child, String childName) {
    JsonObjectBuilder child_builder = Json.createObjectBuilder();
    JsonObjectBuilder parent_builder = Json.createObjectBuilder();
    parent.entrySet().
            forEach(e -> parent_builder.add(e.getKey(), e.getValue()));
    child.entrySet().
            forEach(e -> child_builder.add(e.getKey(), e.getValue()));
    parent_builder.add(childName, child_builder);
    return parent_builder.build();
}

Please note, if you change the child JsonObject after inserting it into another "parent" JsonObject, it will have no effect on the "parent" JsonObject.


问:
CMD opens Windows Store when I type 'python'
Today when I tried to run simple code on Sublime Text 3, the following message appeared:

Python was not found but can be installed from the Microsoft Store: https://go.microsoft.com/fwlink?linkID=2082640

And when I type Python in CMD, it opens the Windows Store for me to download Python 3.7. This problem started today for no good reason. I didn't change or download anything about Python and already tried reinstalling Python, and the Path environment variable is correct.

答:
If the Python interpreter is already installed, then go to Apps & features from settings, select Python, and then select modify.

Again select modify and select Next:

Then this window will appear:

Select "add Python to environment variable" and click on the install button. Then again go to apps & features, click modify and click Repair.
Now go to CMD and type Python.
Problem solved.


答:
Hmmm.  Sounds like a but of recursive programming might do the trick.  I have no idea why you're trying to do this and your haven't provided a desired outcome, so I can't check my results, but something like this might work.

[Untested code]

```<code>doIt <- function(data, currentDepth=1, maxDepth=5) {
  data <- data %>%
    group_by(UF, UPA, V1008, V1014, V2007,
             V2008, V20081, V20082, V2003) %>%
    mutate(p201 = ifelse(n_p %in% 1:currentDepth & V2008 != 99 & V20081 != 99 & V20082 != 9999,
                         100*(n_p-1) + V2003,
                         NA)) %>%
    fill(p201, .direction = 'down')
    if (currentDepth == maxDepth) return(data)
    else return (doIt(data, currentDepth+1, maxDepth))
}

final_dataset <- doIt(dataset)
</code>```

I've tried to generalise your ifelse.  The function either calls itself again (if current depth < maxDepth) or returns its own result.

Title: Place a for loop in the middle of a pipe in R

Body:
I would like some help to make my code a bit leaner.

Here is a fraction of my original dataset:

library(tidyverse)
dataset <- data.frame(UPA = c(130033353, 130033353, 130033353, 130033353,
                              130033353, 230036930, 230036930, 230036930, 230036930, 230036930,
                              230124582, 230124582, 230124582, 230124582, 230124582, 240039107,
                              240039107, 240039107, 240039107, 240039107, 320022393, 320022393,
                              320022393, 320022393, 320022393, 330093898, 330093898, 330093898,
                              330093898, 330093898),
                      UF = c(13, 13, 13, 13, 13, 23, 23, 23,23, 23, 23, 23, 23, 23, 23, 24, 24,
                             24, 24, 24, 32, 32, 32, 32, 32, 33, 33, 33, 33, 33),
                      V1008 = c(1, 1, 1, 1, 1, 5, 5, 5, 5,5, 11, 11, 11, 11, 11,
                                8, 8, 8, 8, 8, 3, 3, 3, 3, 3, 9, 9, 9,9, 9),
                      V1014 = c(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
                                2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2),
                      V2008 = c(22, 23, 12, 28, 29, 13, 9, 9, 2, 22, 18, 5, 8,
                                16, 16, 12, 24, 2, 25, 28, 7, 7, 7, 15, 15, 6,
                                6, 18, 14, 14),
                      V20081 = c(1, 9, 6, 3, 5, 9, 7, 6, 9, 5, 2, 6, 1, 5, 9,
                                 10, 5, 4, 5, 1, 7, 7, 7, 5, 5, 8, 8, 4, 8, 8),
                      V20082 = c(1952, 1964, 1995, 1999, 2009, 1993, 1998, 2000,
                                 2003, 2011, 1967, 1990, 1993, 1996, 2001, 1947, 1996,
                                 1998, 1997, 2012, 2010, 2010, 2010, 2011, 2011, 1981, 1981, 1984,
                                 2006, 2006),
                      V2003 = c(1, 2, 6, 8, 10, 2, 9, 10, 12, 15, 2, 3,
                                5, 7, 11, 2, 6, 7, 7, 9, 3, 3, 3, 4, 4, 1, 1, 2, 4, 4),
                      V2007 = c(1, 2, 2, 1, 2, 2, 1, 1, 1, 1, 2, 1, 2, 1, 1, 2, 2, 1, 2,
                                2, 1, 1, 1, 1, 1, 2, 2, 1, 2, 2),
                      n_p = c(1, NA, NA, NA, NA, NA, NA, NA,
                              NA, NA, NA, NA, NA, NA, NA, NA,
                              NA, NA, NA, NA, NA, NA, NA, NA,
                              NA, 1, 2, 1, NA, NA),
                      id_dom = c(2499L, 2499L, 2499L, 2499L,
                                 2499L, 10962L, 10962L, 10962L, 10962L,
                                 10962L, 12618L, 12618L, 12618L, 12618L, 12618L, 13673L,
                                 13673L, 13673L, 13673L, 13673L, 25945L, 25945L, 25945L,
                                 25945L, 25945L, 28145L, 28145L, 28145L, 28145L, 28145L))

I want to update the value of the p201 variable according to n_p's value in an iterative way. n_p can go possibly from 1 to 5 (although not in dataset, I apologize for not being able to take a sample that contains all possible cases). In the first wave, I assign p201 to be equal to 100*(n_p-1) + V2003 if n_p == 1 and NA otherwise. After that, I go from 2 to 5 doing the same considering only rows in which p201 is still missing.

Here is the code:

final_df <- dataset %>%
  group_by(UF, UPA, V1008, V1014, V2007,
           V2008, V20081, V20082, V2003) %>%
  mutate(p201 = ifelse(n_p == 1 & V2008 != 99 &
                         V20081 != 99 & V20082 != 9999,
                       100*(n_p-1) + V2003, NA)) %>%
    fill(p201, .direction = 'down') %>%
    mutate(p201 = ifelse(n_p == 1,
                         p201,
                         ifelse(n_p == 2 & is.na(p201) & V2008 != 99 &
                                  V20081 != 99 & V20082 != 9999,
                                100*(n_p-1) + V2003,
                                NA))) %>%
    fill(p201, .direction = 'down') %>%
    mutate(p201 = ifelse(n_p %in% 1:2,
                         p201,
                         ifelse(n_p == 3 & is.na(p201) & V2008 != 99 &
                                  V20081 != 99 & V20082 != 9999,
                                100*(n_p-1) + V2003,
                                NA))) %>%
    fill(p201, .direction = 'down') %>%
    mutate(p201 = ifelse(n_p %in% 1:3,
                         p201,
                         ifelse(n_p == 4 & is.na(p201) & V2008 != 99 &
                                  V20081 != 99 & V20082 != 9999,
                                100*(n_p-1) + V2003,
                                NA))) %>%
    fill(p201, .direction = 'down') %>%
    mutate(p201 = ifelse(n_p %in% 1:4,
                         p201,
                         ifelse(n_p == 5 & is.na(p201) & V2008 != 99 &
                                  V20081 != 99 & V20082 != 9999,
                                100*(n_p-1) + V2003,
                                NA))) %>%
    ungroup() %>%
    mutate_at(c('UF', 'UPA', 'V1008', 'p201'), as.character) %>%
    mutate(idind = ifelse(is.na(p201),
                          NA,
                          paste0(V1014, UF, UPA, V1008, p201)))

I clearly could use something like a for loop  (or maybe something even better, using map?) to make the code a bit leaner, but I don't know how to insert a loop inside a pipe flow using tidyverse's syntax.

Can somebody help? My desired output is exactly the one resulting in final_df, but with cleaner code.

PS: Please do not mind that the result will generate a lot of NAs in p201 - the whole dataset is more complex and this probably wouldn't be true with it.

EDIT
I've figured out a solution by adapting Limey's answer - I didn't know about recursive functions.

Here it goes:

loop <- function(data,
                 interview = 2,
                 int_final = 5){
  data <- data %>%
    group_by(UF, UPA, V1008, V1014, V2007,
             V2008, V20081, V20082, V2003) %>%
    fill(p201, .direction = 'down') %>%
    mutate(p201 = ifelse(
      n_p %in% 1:(interview-1),
      p201,
      ifelse(
          n_p == interview  & is.na(p201) &
            V2008 != 99 &
            V20081 != 99 & V20082 != 9999,
          100 * (n_p - 1) + V2003,
          NA
        )
      ))

    if(interview == int_final){
      return(data)
      } else{
        return(loop(data, interview + 1, int_final))
        }
}

final_dataset <- dataset %>%
  group_by(UF, UPA, V1008, V1014, V2007,
           V2008, V20081, V20082, V2003) %>%
  mutate(p201 = ifelse(n_p == 1  & V2008 != 99 &
                         V20081 != 99 & V20082 != 9999,
                       100*(n_p-1) + V2003, NA)) %>%
  loop() %>%
  ungroup() %>%
  mutate_at(c('UF', 'UPA', 'V1008', 'p201'), as.character) %>%
  mutate(idind = ifelse(is.na(p201),
                        NA,
                        paste0(V1014, UF, UPA, V1008, p201)))

Body:
Hmmm.  Sounds like a but of recursive programming might do the trick.  I have no idea why you're trying to do this and your haven't provided a desired outcome, so I can't check my results, but something like this might work.

[Untested code]

doIt <- function(data, currentDepth=1, maxDepth=5) {
  data <- data %>%
    group_by(UF, UPA, V1008, V1014, V2007,
             V2008, V20081, V20082, V2003) %>%
    mutate(p201 = ifelse(n_p %in% 1:currentDepth & V2008 != 99 & V20081 != 99 & V20082 != 9999,
                         100*(n_p-1) + V2003,
                         NA)) %>%
    fill(p201, .direction = 'down')
    if (currentDepth == maxDepth) return(data)
    else return (doIt(data, currentDepth+1, maxDepth))
}

final_dataset <- doIt(dataset)

I've tried to generalise your ifelse.  The function either calls itself again (if current depth < maxDepth) or returns its own result.


问:
How to pass Scala Seq to a Java varargs
I have an existing Java method like this:

```<code>public static MyJavaClass javaFunc(String name, long... values) {
    ...
}
</code>```

and I need to call it from Scala with this:

```<code>val idList: Seq[Long] = Seq(1L, 2L, 3L)

MyJavaClass.javaFunc("hello", idList)
</code>```

but it ends up invoking the toString method on the idList parameter.  I've tried the following to no avail:

```<code>MyJavaClass.javaFunc("hello", idList:_*)
</code>```

which causes compile error:

```<code>no `: _*' annotation allowed here (such annotations are only allowed in arguments to *-parameters)
</code>```

How can I pass the argument?

答:
I can't reproduce this on Scala 2.10.4 and Java 8 but it seems like a bug.

You can avoid the : _* by adding these Java methods:

```<code>public static MyJavaClass javaFuncConverter(String name, long[] values) {
     return javaFunc(name, values);
}

public static MyJavaClass javaFuncConverter(String name, long value) {
     return javaFunc(name, value);
}
</code>```

In your Scala code you call it like this:

```<code>val idList: Seq[Long] = Seq(1L, 2L, 3L)

MyJavaClass.javaFuncConverter("hello", idList.toArray)
MyJavaClass.javaFuncConverter("hello", idList.head)
</code>```

Title: How to pass Scala Seq to a Java varargs

Body:
I have an existing Java method like this:

public static MyJavaClass javaFunc(String name, long... values) {
    ...
}

and I need to call it from Scala with this:

val idList: Seq[Long] = Seq(1L, 2L, 3L)

MyJavaClass.javaFunc("hello", idList)

but it ends up invoking the toString method on the idList parameter.  I've tried the following to no avail:

MyJavaClass.javaFunc("hello", idList:_*)

which causes compile error:

no `: _*' annotation allowed here (such annotations are only allowed in arguments to *-parameters)

How can I pass the argument?

Body:
I can't reproduce this on Scala 2.10.4 and Java 8 but it seems like a bug.

You can avoid the : _* by adding these Java methods:

public static MyJavaClass javaFuncConverter(String name, long[] values) {
     return javaFunc(name, values);
}

public static MyJavaClass javaFuncConverter(String name, long value) {
     return javaFunc(name, value);
}

In your Scala code you call it like this:

val idList: Seq[Long] = Seq(1L, 2L, 3L)

MyJavaClass.javaFuncConverter("hello", idList.toArray)
MyJavaClass.javaFuncConverter("hello", idList.head)


问:
Swift protocol error: 'weak' cannot be applied to non-class type
What's the difference between Protocols and class-bound Protocols, and which one we should use in Swift?

```<code>protocol A : class { ... }

protocol A { ... }
</code>```

We get an error when attempting to add a weak delegate when the Protocol is not defined as : class:

```<code>protocol A { ... }

weak var delegate: A
</code>```

Gives the error:

'weak' cannot be applied to non-class type

or

'weak' must not be applied to non-class-bound 'A'; consider adding a protocol conformance that has a class bound

答:
If you are using Swift 4 or later, use AnyObject:

```<code>protocol A : AnyObject { ... }
</code>```

Using class as before gives the warning and fix-it:

Using 'class' keyword to define a class-constrained protocol is deprecated; use 'AnyObject' instead

Replace 'class' with 'AnyObject'

Body:
What's the difference between Protocols and class-bound Protocols, and which one we should use in Swift?

protocol A : class { ... }

protocol A { ... }

We get an error when attempting to add a weak delegate when the Protocol is not defined as : class:

protocol A { ... }

weak var delegate: A

Gives the error:

'weak' cannot be applied to non-class type

or

'weak' must not be applied to non-class-bound 'A'; consider adding a protocol conformance that has a class bound

Body:
If you are using Swift 4 or later, use AnyObject:

protocol A : AnyObject { ... }

Using class as before gives the warning and fix-it:

Using 'class' keyword to define a class-constrained protocol is deprecated; use 'AnyObject' instead

Replace 'class' with 'AnyObject'


问:
How can I convert a utf8 to ISO-8859-1 in Dart?
I need to use iso-8859 type in flutter but the method iconv not supported, is there any other method ?</p>

答:
I'd convert it to a string and then convert the string to the ISO-8859-X code page that you want, which in this case is probably ISO-8859-6 Latin/Arabic.
The convert package (now) supports all the ISO-8859 code pages.

import "dart:convert" show utf8;
import "package:convert" show latinArabic;
...
  var utf8Bytes = ...;
  var string = utf8.decode(utf8Bytes);
  var latinArabicBytes = latinArabic.encode(string);
```
<p>You can create helper converter for that as:</p>
<pre class="lang-dart prettyprint-override"><code>  final utf8ToLatinArabicConverter = utf8.decoder.fuse(latinArabic.encoder);
  final utf8ToLatinARabic = utf8ToLatinArabicConverter.convert;
  ....
     var latinArabicBytes = utf8ToLatinArabic(utf8Bytes);
</code>```

Body:
I'd convert it to a string and then convert the string to the ISO-8859-X code page that you want, which in this case is probably ISO-8859-6 Latin/Arabic.
The convert package (now) supports all the ISO-8859 code pages.

import "dart:convert" show utf8;
import "package:convert" show latinArabic;
...
  var utf8Bytes = ...;
  var string = utf8.decode(utf8Bytes);
  var latinArabicBytes = latinArabic.encode(string);

You can create helper converter for that as:

  final utf8ToLatinArabicConverter = utf8.decoder.fuse(latinArabic.encoder);
  final utf8ToLatinARabic = utf8ToLatinArabicConverter.convert;
  ....
     var latinArabicBytes = utf8ToLatinArabic(utf8Bytes);


问:
uwsgi specify python binary
On our production server we are running Ubuntu 12.04, to make sure that our application is running in a predefined consistent environment we use Pythonbrew to compile a custom Python. I have created a user that is going to be running our API server, the user has his own Python 2.7.2 environment created with Pythonbrew, with the necessary packages installed using pip.

I've also installed uWSGI on the system, it's going to wrap the API application and make it available to Apache via mod_wsgi. The problem is that I can't get uWSGI to use the correct python binary. The current config looks like this:

```<code>[uwsgi]
socket = 127.0.0.1:3031
processes = 4
chdir = /home/app/
pythonpath = /home/app
gid = 1002
uid = 1002
module = api
callable = APP
enable-threads = true
</code>```

When I try to run this config on the terminal with:

```<code>uwsgi --ini app.ini
</code>```

It fails to import some module. This module is installed only in the Pythonbrew environment that the API user is using. The problem is that uWSGI is using the default python binary in /usr/bin.

One solution is to use a separate uWSGI installed using pip in the API user's environment, but I really want to use the system's uWSGI because it integrates better with the OS.

Is there any way to specify which Python binary uWSGI should use, other then by installing a separate one? If I have to install a separate instance of uWSGI, what is the best way to have it start on system boot?

Edit: just realised that it is probably not using the python binary, but just lining against it's library, so there is no way for me to use the default installation of wsgi, and the non-default python. But the question still remains, what is the best way to integrate a custom built uWSGI into the system.

答:
I had this problem on Ubuntu 18.04 (so a tad bit newer than when the question was asked) and remembered that the [uwsgi] section of the configuration file contains the long command line switches.

It appears that uwsgi in the version that is packaged for Ubuntu 18.04.4 defaults to using the python plugin, which means Python 2.x in this case.

And so I managed to configure my apps by setting them to use the python3 plugin:

```<code>[uwsgi]
plugin = python3
</code>```

This requires the uwsgi-plugin-python3 package to be installed. In case of Ubuntu 18.04 this defaulted to Python 3.6 and hence the above plugin line could also have been:

```<code>plugin = python36
</code>```

You can test if it works with a given plugin by running uwsgi from the command line like so:

```<code>uwsgi --plugin python3 -s :0
</code>```

Title: uwsgi specify python binary

Body:
On our production server we are running Ubuntu 12.04, to make sure that our application is running in a predefined consistent environment we use Pythonbrew to compile a custom Python. I have created a user that is going to be running our API server, the user has his own Python 2.7.2 environment created with Pythonbrew, with the necessary packages installed using pip.

I've also installed uWSGI on the system, it's going to wrap the API application and make it available to Apache via mod_wsgi. The problem is that I can't get uWSGI to use the correct python binary. The current config looks like this:

[uwsgi]
socket = 127.0.0.1:3031
processes = 4
chdir = /home/app/
pythonpath = /home/app
gid = 1002
uid = 1002
module = api
callable = APP
enable-threads = true

When I try to run this config on the terminal with:

uwsgi --ini app.ini

It fails to import some module. This module is installed only in the Pythonbrew environment that the API user is using. The problem is that uWSGI is using the default python binary in /usr/bin.

One solution is to use a separate uWSGI installed using pip in the API user's environment, but I really want to use the system's uWSGI because it integrates better with the OS.

Is there any way to specify which Python binary uWSGI should use, other then by installing a separate one? If I have to install a separate instance of uWSGI, what is the best way to have it start on system boot?

Edit: just realised that it is probably not using the python binary, but just lining against it's library, so there is no way for me to use the default installation of wsgi, and the non-default python. But the question still remains, what is the best way to integrate a custom built uWSGI into the system.

Body:
I had this problem on Ubuntu 18.04 (so a tad bit newer than when the question was asked) and remembered that the [uwsgi] section of the configuration file contains the long command line switches.

It appears that uwsgi in the version that is packaged for Ubuntu 18.04.4 defaults to using the python plugin, which means Python 2.x in this case.

And so I managed to configure my apps by setting them to use the python3 plugin:

[uwsgi]
plugin = python3

This requires the uwsgi-plugin-python3 package to be installed. In case of Ubuntu 18.04 this defaulted to Python 3.6 and hence the above plugin line could also have been:

plugin = python36

You can test if it works with a given plugin by running uwsgi from the command line like so:

uwsgi --plugin python3 -s :0


问:
How to write out HTML entity name ( , <, >, etc)
How would I write the entity name in HTML and not have it do its function? Example: I'm doing a tutorial and want to tell someone how to use the non-breaking space in their code (<code> </code>) So, how to actually write out "&" "n" "b" "s" "p" ";" but have it be fluid with no spaces?</p>

答:
JavaScript can be used to change the text of HTML element, below example adds non-blocking space entity character into span element.

```<code><p>A common character entity used in HTML is the non-breaking space: <span id="myid"></span></p>
  <script>
    document.getElementById("myid").textContent= " ";
  </script>
</code>```

Body: How would I write the entity name in HTML and not have it do its function? Example: I'm doing a tutorial and want to tell someone how to use the non-breaking space in their code ( ) So, how to actually write out "&" "n" "b" "s" "p" ";" but have it be fluid with no spaces?

Body:
JavaScript can be used to change the text of HTML element, below example adds non-blocking space entity character into span element.

<p>A common character entity used in HTML is the non-breaking space: <span id="myid"></span></p>
  <script>
    document.getElementById("myid").textContent= "&nbsp;";
  </script>


问:
Undefined token error when shader file saved in unicode
Why do i get undefined token error when the shader text file is saved in unicode , when i save it back in ansi the error goes away.</p>

```<code>#version 330 core
layout( location = 0 ) in vec2 aPos;
layout( location = 1) in vec2 aTexCoord;
void main()
{
   gl_Position = vec4(aPos , 0.0 , 1.0);
};
</code>```

答:
The OpenGL spec takes a char* as the array to compile the data. char's are usually a byte so they can take at most 256 values, which is ASCII.

If you give it a string that tries to encode a larger character representation (e.g UTF-16) it will interpret the data as if it was a char* which means the compiler is now reading the byte prefix in the larger representation as if it was its own, unique value.

This is of course undefined behaviour and likely to not work.

Body:
Why do i get undefined token error when the shader text file is saved in unicode , when i save it back in ansi the error goes away.

#version 330 core
layout( location = 0 ) in vec2 aPos;
layout( location = 1) in vec2 aTexCoord;
void main()
{
   gl_Position = vec4(aPos , 0.0 , 1.0);
};


问:
SPF issue: what causes softfail?
Whenever I use PHP to send emails to members of my site, the email ends up in the spam folder for most email providers like Gmail and Hotmail.

When I check the original source in Gmail, I see the following:

Delivered-To: mypersonalmail@gmail.com

  Received: by 10.236.41.34 with SMTP id g22cs272510yhb;

          Wed, 1 Jun 2011 05:38:27 -0700 (PDT)

  Received: by 10.236.77.102 with SMTP id c66mr7228248yhe.303.1306931907131;
          Wed, 01 Jun 2011 05:38:27 -0700 (PDT)

  Received-SPF: softfail (google.com: best guess record for domain of transitioning info@mywebserver.com does not designate  as permitted sender)

  Received: by 10.190.5.195 with POP3 id 3mf1156376yxt.72;
          Wed, 01 Jun 2011 05:38:27 -0700 (PDT)
  X-Gmail-Fetch-Info: info@mywebserver.com 14 mail.mywebserver.com 110 info@mywebserver.com

  Return-path:

  Envelope-to: info@mywebserver.com

  Received: from mybestsh by s01.next-web.nl with local (Exim 4.69)

      (envelope-from )

      id 1QRkgT-0000BF-3v

      for info@mywebserver.com; Wed, 01 Jun 2011 14:38:01 +0200

  To: info@mywebserver.com

  Subject: Your new password

  MIME-Version: 1.0

  From: MyServer

  Reply-To: MyServer

  X-Sender: MyServer

I have set up my SPF records as follows:

```<code>v=spf1 a mx ip4:xxx.xxx.xx.xx-all
</code>```

I am wondering what causes the softfail. Any ideas?

答:
I found a very good post about spf check here.
If you got your spf and other setting right and still getting email in spam folder wait for 3,4 hour as described in post

Google’s spam filters are very powerful. If you send too much spam to their server from an IP or IP block, they will block you for up to several hours at a time. You will receive spam, you will forward it. They will filter mail as spam that you don’t think is spam. No matter what, you will send email to Google that they think is spam, even if you disagree. By simply receiving more email than they appreciate in a given time frame, your forwarder will suddenly stop working for hours at a time (or worse).

Title: SPF issue: what causes softfail?

Body:
Whenever I use PHP to send emails to members of my site, the email ends up in the spam folder for most email providers like Gmail and Hotmail.

When I check the original source in Gmail, I see the following:

Delivered-To: mypersonalmail@gmail.com

  Received: by 10.236.41.34 with SMTP id g22cs272510yhb;

          Wed, 1 Jun 2011 05:38:27 -0700 (PDT)

  Received: by 10.236.77.102 with SMTP id c66mr7228248yhe.303.1306931907131;
          Wed, 01 Jun 2011 05:38:27 -0700 (PDT)

  Received-SPF: softfail (google.com: best guess record for domain of transitioning info@mywebserver.com does not designate  as permitted sender)

  Received: by 10.190.5.195 with POP3 id 3mf1156376yxt.72;
          Wed, 01 Jun 2011 05:38:27 -0700 (PDT)
  X-Gmail-Fetch-Info: info@mywebserver.com 14 mail.mywebserver.com 110 info@mywebserver.com

  Return-path:

  Envelope-to: info@mywebserver.com

  Received: from mybestsh by s01.next-web.nl with local (Exim 4.69)

      (envelope-from )

      id 1QRkgT-0000BF-3v

      for info@mywebserver.com; Wed, 01 Jun 2011 14:38:01 +0200

  To: info@mywebserver.com

  Subject: Your new password

  MIME-Version: 1.0

  From: MyServer

  Reply-To: MyServer

  X-Sender: MyServer

I have set up my SPF records as follows:

v=spf1 a mx ip4:xxx.xxx.xx.xx-all

I am wondering what causes the softfail. Any ideas?


问:
Getting the string in the middle of two other strings in Python
I need to find the string in between two other strings. How could I do this?

```<code>string = "vHELLOv"
</code>```

Finding "HELLO" which is in between of two lowercase "v"'s

Another example could be:

```<code>string = "/World/"
</code>```

Finding "World" in the middle of the two "/"s

答:
You can do it in various ways as

```<code> import re

 text = "vHELLOv" #or txt = "/World/"
 re.match(r"(v|\/)(\w*)(v|\/)", text).group(2)
 or
 re.search(r"(v|\/)(\w*)(v|\/)", text).group(2)
</code>```

This is the regex methods
You can do it also with string replace as

```<code>txt.replace(txt[0], "") if txt[0] == txt[-1] else txt
</code>```

Body:
I need to find the string in between two other strings. How could I do this?

string = "vHELLOv"

Finding "HELLO" which is in between of two lowercase "v"'s

Another example could be:

string = "/World/"

Finding "World" in the middle of the two "/"s

Body:
You can do it in various ways as

 import re

 text = "vHELLOv" #or txt = "/World/"
 re.match(r"(v|\/)(\w*)(v|\/)", text).group(2)
 or
 re.search(r"(v|\/)(\w*)(v|\/)", text).group(2)

This is the regex methods
You can do it also with string replace as

txt.replace(txt[0], "") if txt[0] == txt[-1] else txt


答:
No, arrays are always reference types. There's no need for boxing or unboxing, unless it's on the access for each element. For example:

```<code>int[] x = new int[10]; // The value of x is a reference

int y = x[0]; // No boxing
Integer z = x[1]; // Boxing conversion from x[1] (which is an int) to Integer
</code>```

Also note that although the enhanced for loop is available for both arrays and iterables, it's compiled differently for each.

See section 14.14.2 of the JLS for the two different translations of the enhanced for loop.

Title: Are arrays being transformed when using an enhanced for loop?

Body:
Does Java 5 or higher apply some of form of "boxing" to arrays? This question came to mind as the following code goes through an array as if it's an Iterable.

for( String : args ){
// Do stuff
}

Body:
No, arrays are always reference types. There's no need for boxing or unboxing, unless it's on the access for each element. For example:

int[] x = new int[10]; // The value of x is a reference

int y = x[0]; // No boxing
Integer z = x[1]; // Boxing conversion from x[1] (which is an int) to Integer

Also note that although the enhanced for loop is available for both arrays and iterables, it's compiled differently for each.

See section 14.14.2 of the JLS for the two different translations of the enhanced for loop.


问:
How to use the three steps of Jenkins Warnings Next Generation Plugin properly?
The Jenkins Warnings Next Generation Plugin's documentation for pipelines specifies three step variants:

publishIssues: Publish issues created by a static analysis scan

recordIssues: Record compiler warnings and static analysis results

scanForIssues: Scan files or the console log for warnings or issues

I've just tried this simple snippet out:

```<code>stage('QA checks') {
    steps {
        recordIssues([
            enabledForFailure: true,
            tools: [php()]
        ])
    }
}
</code>```

and got the result displayed on the build's page ("PHP Runtime: No warnings"). But then what is the sense of the other two steps?

What is a proper way of configuring the plugin? Should these three parts be used, like this?

```<code>stage('QA checks') {
    steps {
        scanForIssues([...])
        recordIssues([...])
        publishIssues([...])
    }
}
</code>```

答:
Came here for the same question. Figured it out from the docs. https://github.com/jenkinsci/warnings-ng-plugin/blob/master/doc/Documentation.md

In summary, the recordIssues command is intended to be used alone for simple usecases while the scanForIssues and publishIssues commands are intended to be used together for more complex usecases.

So your usage of recordIssues seems perfectly in line with the authors intent.

From the documentation:

Advanced Pipeline configuration

Sometimes publishing and reporting issues using a single step is not
  sufficient. E.g., if you build your product using several parallel
  steps and you want to combine the issues from all of these steps into
  a single result. Then you need to split scanning and aggregation. The
  plugin provides the following two steps:

scanForIssues: this step scans a report file or the console log with a particular parser and creates an intermediate
  AnnotatedReport
  object that contains the report. [...]

publishIssues: this step publishes a new report in your build that contains the aggregated results of several scanForIssues steps. [...]

Body:
The Jenkins Warnings Next Generation Plugin's documentation for pipelines specifies three step variants:

publishIssues: Publish issues created by a static analysis scan

recordIssues: Record compiler warnings and static analysis results

scanForIssues: Scan files or the console log for warnings or issues

I've just tried this simple snippet out:

stage('QA checks') {
    steps {
        recordIssues([
            enabledForFailure: true,
            tools: [php()]
        ])
    }
}

and got the result displayed on the build's page ("PHP Runtime: No warnings"). But then what is the sense of the other two steps?

What is a proper way of configuring the plugin? Should these three parts be used, like this?

stage('QA checks') {
    steps {
        scanForIssues([...])
        recordIssues([...])
        publishIssues([...])
    }
}


问:
general programming logic
I have a general question - regarding testing of values, I have run into this issue multiple time and I end up with some unsightly long code to accomplish something that logically seems simple.

the issue - I have one or multiple values I want to test against other values....SUCH THAT my code ends up looking like this (conceptually)

```<code>IF (A > B
AND A < C
AND A < D
AND A < E)
THEN print "Yes"
</code>```

LOGICALLY I can express this as IF A > b,c,d,e etc.

If I also need to check other values in that list - you can see that the conditional statement to test against could become significantly larger and messier than the code the condition is intended to yield...

there MUST be a way problematically OR mathematically to express this common instance.

I know each language has 'syntax' specific ways to to this but .. I'll take suggestions and try em.

答:
you want

IF A > b,c,d,e

so perhaps

```<code>if a > max(b,c,d,e)
</code>```

does that work out to what you want?

Title: general programming logic

Body:
I have a general question - regarding testing of values, I have run into this issue multiple time and I end up with some unsightly long code to accomplish something that logically seems simple.

the issue - I have one or multiple values I want to test against other values....SUCH THAT my code ends up looking like this (conceptually)

IF (A > B
AND A < C
AND A < D
AND A < E)
THEN print "Yes"

LOGICALLY I can express this as IF A > b,c,d,e etc.

If I also need to check other values in that list - you can see that the conditional statement to test against could become significantly larger and messier than the code the condition is intended to yield...

there MUST be a way problematically OR mathematically to express this common instance.

I know each language has 'syntax' specific ways to to this but .. I'll take suggestions and try em.

Body:
you want

IF A > b,c,d,e

so perhaps

if a > max(b,c,d,e)

does that work out to what you want?


问:
How to search in a JSONField for a key with spaces in Django with Postgres?
Suppose I've a JSONField namely "data" defined in one of my models.py in Django. The Contents of the field is somewhat similar to the following -

```<code>{
    "name": "John",
    "email": "johndoe@foo.bar",
    "last name": "Doe"
}
</code>```

I need to write a queries of the following form -

```<code>self.objects.filter(data__name="John")
</code>```

How do I write a similar query for the key "last name". I'm not able to proceed since that key has a space. Was thinking of getting the data and filtering it using python, But I think there would be more efficient way to get it done.

I've not real control over the data in the JSONField. So, I can't really change the name of the key.

答:
We can achieve it the following way -</p>

```<code>lookup = "data__last name"
self.objects.filter(**{lookup: "Doe"})
</code>```

Body:
Suppose I've a JSONField namely "data" defined in one of my models.py in Django. The Contents of the field is somewhat similar to the following -

{
    "name": "John",
    "email": "johndoe@foo.bar",
    "last name": "Doe"
}

I need to write a queries of the following form -

self.objects.filter(data__name="John")

How do I write a similar query for the key "last name". I'm not able to proceed since that key has a space. Was thinking of getting the data and filtering it using python, But I think there would be more efficient way to get it done.

I've not real control over the data in the JSONField. So, I can't really change the name of the key.

Body:
We can achieve it the following way -

lookup = "data__last name"
self.objects.filter(**{lookup: "Doe"})


问:
Codeigniter's Model with QueryBuilder JOIN query
Really new to working with CI4's Model and struggling to adapt my existing MySQL JOIN queries to work with the examples in its User Guide.

I have adapted part of my code like so:

```<code>    public function brand_name($brand_name_slug)
    {
        return $this->asArray()
                    ->where('availability', 'in stock')
                    ->where('sku !=', '')
                    ->where('brand_name_slug', $brand_name_slug)
                    ->groupBy('gtin')
                    ->orderBy('brand_name, subbrand_name, product, size, unit')
                    ->findAll();
    }
</code>```

It works fine. I have looked at examples, and figured out I can add the code ->table('shop a') and it still works, but I also need to to add the following JOIN statement:

```<code>JOIN (SELECT gtin, MIN(sale_price) AS sale_price FROM shop GROUP BY gtin) AS b ON a.gtin = b.gtin AND a.sale_price = b.sale_price
</code>```

As soon as I add ->join('shop b', 'a.gtin = b.gtin and a.sale_price = b.sale_price') I get a '404 - File Not Found' error.

When I look at all examples of CI4 joins and adapt my code to fit, my foreach($shop as $row) loop generates a 'Whoops...' error because they end with a getResult() or getResultArray - instead of findAll().

Which is the way forward, and do I need to change my foreach loop.

Full MySQL statement:

```<code>SELECT * FROM shop a JOIN (SELECT gtin, MIN(sale_price) AS sale_price FROM shop GROUP BY gtin) AS b ON a.gtin = b.gtin AND a.sale_price = b.sale_price WHERE availability = 'in stock' AND sku != '' AND brand_name_slug = $brand_name_slug GROUP BY gtin ORDER BY brand_name, subbrand_name, product, size
</code>```

答:
Query builders have their limits. That's why the query method exists. If you have a complex query I'd advise you to just use $this->query();.

It will make you lose less time and effort converting something you know already works. And in the top of that, while converting complex queries you usually end up using the query builder but with big part of your SQL in it.

In your model extending CodeIgniter\Model :

```<code>    $query = $this->db->query("SELECT * FROM shop a JOIN (SELECT gtin, MIN(sale_price) AS sale_price FROM shop GROUP BY gtin) AS b ON a.gtin = b.gtin AND a.sale_price = b.sale_price WHERE availability = 'in stock' AND sku != '' AND brand_name_slug = \$brand_name_slug GROUP BY gtin ORDER BY brand_name, subbrand_name, product, size");

    // your array result
    $result_array = $query->getResultArray();
    // your object result
    $result_object = $query->getResult();
</code>```

Body:
Really new to working with CI4's Model and struggling to adapt my existing MySQL JOIN queries to work with the examples in its User Guide.

I have adapted part of my code like so:

    public function brand_name($brand_name_slug)
    {
        return $this->asArray()
                    ->where('availability', 'in stock')
                    ->where('sku !=', '')
                    ->where('brand_name_slug', $brand_name_slug)
                    ->groupBy('gtin')
                    ->orderBy('brand_name, subbrand_name, product, size, unit')
                    ->findAll();
    }

It works fine. I have looked at examples, and figured out I can add the code ->table('shop a') and it still works, but I also need to to add the following JOIN statement:

JOIN (SELECT gtin, MIN(sale_price) AS sale_price FROM shop GROUP BY gtin) AS b ON a.gtin = b.gtin AND a.sale_price = b.sale_price

As soon as I add ->join('shop b', 'a.gtin = b.gtin and a.sale_price = b.sale_price') I get a '404 - File Not Found' error.

When I look at all examples of CI4 joins and adapt my code to fit, my foreach($shop as $row) loop generates a 'Whoops...' error because they end with a getResult() or getResultArray - instead of findAll().

Which is the way forward, and do I need to change my foreach loop.

Full MySQL statement:

SELECT * FROM shop a JOIN (SELECT gtin, MIN(sale_price) AS sale_price FROM shop GROUP BY gtin) AS b ON a.gtin = b.gtin AND a.sale_price = b.sale_price WHERE availability = 'in stock' AND sku != '' AND brand_name_slug = $brand_name_slug GROUP BY gtin ORDER BY brand_name, subbrand_name, product, size

Body:
Query builders have their limits. That's why the query method exists. If you have a complex query I'd advise you to just use $this->query();.

It will make you lose less time and effort converting something you know already works. And in the top of that, while converting complex queries you usually end up using the query builder but with big part of your SQL in it.

In your model extending CodeIgniter\Model :

    $query = $this->db->query("SELECT * FROM shop a JOIN (SELECT gtin, MIN(sale_price) AS sale_price FROM shop GROUP BY gtin) AS b ON a.gtin = b.gtin AND a.sale_price = b.sale_price WHERE availability = 'in stock' AND sku != '' AND brand_name_slug = \$brand_name_slug GROUP BY gtin ORDER BY brand_name, subbrand_name, product, size");

    // your array result
    $result_array = $query->getResultArray();
    // your object result
    $result_object = $query->getResult();


问:
Conan Add remote Task in Azure Pipelines : Failing when adding two remotes
I have a Azure DevOps pipeline in which I am adding two remotes. When using the JFrog Extension for  Azure Pipelines and the included conan upload task, this task will not use the configured remote, but always the last added. Is there any solution to this or what am I  missing?

I hope the following describes the setup well enough:

Service connections / repos:

Prerelease Repo

Service  connection with technical user to  add,update,delete pre released packages (typically branch based releases)

```<code> - task: ArtifactoryConan@1
   displayName: "Add conan develop remote"
   inputs:
     conanCommand: "Add Remote"
     remoteName: "develop"
     artifactoryService: "Artifactory_Develop"
     conanRepo: "develop"
     purgeExistingRemotes: false
     conanUserHome: "$(Pipeline.Workspace)"
</code>```

Release repo

Service connection with a restricted technical user to only add to a release repo, but not update or delete

```<code> - task: ArtifactoryConan@1
   displayName: "Add conan release remote"
   inputs:
     conanCommand: "Add Remote"
     remoteName: "release"
     artifactoryService: "Artifactory_Release"
     conanRepo: "release"
     purgeExistingRemotes: false
     conanUserHome: "$(Pipeline.Workspace)"
</code>```

Upload task

Based on branches, I would like to upload and publish my Conan artifacts to the dedicated repository, using the dedicated  service connection:

```<code>- task: ArtifactoryConan@1
        displayName: "Conan upload develop repo"
        condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/develop'), ne(variables['Build.Reason'], 'PullRequest'))
        inputs:
          conanCommand: "Upload"
          remoteName: "develop"
          patternOrReference: "$(conan_package_name)/$(conan_package_version)@$(project_name)/$(conan_channel)"
          extraArguments: "--all -c"
          buildName: "$(Build.DefinitionName)"
          buildNumber: "$(Build.BuildNumber)"
          conanUserHome: "$(Pipeline.Workspace)"
</code>```

Result

The conan upload task seems to be always using the last added remote?

```<code>2020-06-02T10:43:03.3661883Z ##[section]Starting: Conan upload develop repo
2020-06-02T10:43:03.3669805Z ==============================================================================
2020-06-02T10:43:03.3670263Z Task         : Artifactory Conan
2020-06-02T10:43:03.3670628Z Description  : This task runs a Conan command.
2020-06-02T10:43:03.3670974Z Version      : 1.9.4
2020-06-02T10:43:03.3671273Z Author       : JFrog
2020-06-02T10:43:03.3671597Z Help         : Run Conan command.
2020-06-02T10:43:03.3671999Z ==============================================================================
2020-06-02T10:43:03.8219651Z Running Conan build tool from: /usr/local/bin/conan
2020-06-02T10:43:03.8220128Z Conan User Home: /__w/1
2020-06-02T10:43:03.8245768Z Running Conan command at: /__w/1/s
2020-06-02T10:43:03.8257251Z [command]/usr/local/bin/conan upload --all -c HelloWorld/1.0@Hello/develop
2020-06-02T10:43:04.2091929Z Uploading to remote 'release':
2020-06-02T10:43:04.2165470Z
2020-06-02T10:43:04.2166636Z Uploading HelloWorld/1.0@Hello/develop to remote 'release'
</code>```

答:
After adding the "-r (--remote) option in the "extraArguments", the correct remote was used:</p>

```<code>- task: ArtifactoryConan@1
    displayName: "Conan upload develop repo"
    inputs:
      conanCommand: "Upload"
      remoteName: "MYREMOTE" # this is not working
      patternOrReference: "$(conan_package_name)/$(conan_package_version)@$(project_name)/$(conan_channel)"
      extraArguments: "--all -c -r MYREMOTE" # this is
      buildName: "$(Build.DefinitionName)"
      buildNumber: "$(Build.BuildNumber)"
      conanUserHome: "$(Pipeline.Workspace)"
</code>```

Body:
I have a Azure DevOps pipeline in which I am adding two remotes. When using the JFrog Extension for  Azure Pipelines and the included conan upload task, this task will not use the configured remote, but always the last added. Is there any solution to this or what am I  missing?

I hope the following describes the setup well enough:

Service connections / repos:

Prerelease Repo

Service  connection with technical user to  add,update,delete pre released packages (typically branch based releases)

 - task: ArtifactoryConan@1
   displayName: "Add conan develop remote"
   inputs:
     conanCommand: "Add Remote"
     remoteName: "develop"
     artifactoryService: "Artifactory_Develop"
     conanRepo: "develop"
     purgeExistingRemotes: false
     conanUserHome: "$(Pipeline.Workspace)"

Release repo

Service connection with a restricted technical user to only add to a release repo, but not update or delete

 - task: ArtifactoryConan@1
   displayName: "Add conan release remote"
   inputs:
     conanCommand: "Add Remote"
     remoteName: "release"
     artifactoryService: "Artifactory_Release"
     conanRepo: "release"
     purgeExistingRemotes: false
     conanUserHome: "$(Pipeline.Workspace)"

Upload task

Based on branches, I would like to upload and publish my Conan artifacts to the dedicated repository, using the dedicated  service connection:

- task: ArtifactoryConan@1
        displayName: "Conan upload develop repo"
        condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/develop'), ne(variables['Build.Reason'], 'PullRequest'))
        inputs:
          conanCommand: "Upload"
          remoteName: "develop"
          patternOrReference: "$(conan_package_name)/$(conan_package_version)@$(project_name)/$(conan_channel)"
          extraArguments: "--all -c"
          buildName: "$(Build.DefinitionName)"
          buildNumber: "$(Build.BuildNumber)"
          conanUserHome: "$(Pipeline.Workspace)"

Result

The conan upload task seems to be always using the last added remote?

2020-06-02T10:43:03.3661883Z ##[section]Starting: Conan upload develop repo
2020-06-02T10:43:03.3669805Z ==============================================================================
2020-06-02T10:43:03.3670263Z Task         : Artifactory Conan
2020-06-02T10:43:03.3670628Z Description  : This task runs a Conan command.
2020-06-02T10:43:03.3670974Z Version      : 1.9.4
2020-06-02T10:43:03.3671273Z Author       : JFrog
2020-06-02T10:43:03.3671597Z Help         : Run Conan command.
2020-06-02T10:43:03.3671999Z ==============================================================================
2020-06-02T10:43:03.8219651Z Running Conan build tool from: /usr/local/bin/conan
2020-06-02T10:43:03.8220128Z Conan User Home: /__w/1
2020-06-02T10:43:03.8245768Z Running Conan command at: /__w/1/s
2020-06-02T10:43:03.8257251Z [command]/usr/local/bin/conan upload --all -c HelloWorld/1.0@Hello/develop
2020-06-02T10:43:04.2091929Z Uploading to remote 'release':
2020-06-02T10:43:04.2165470Z
2020-06-02T10:43:04.2166636Z Uploading HelloWorld/1.0@Hello/develop to remote 'release'

Body:
After adding the "-r (--remote) option in the "extraArguments", the correct remote was used:

- task: ArtifactoryConan@1
    displayName: "Conan upload develop repo"
    inputs:
      conanCommand: "Upload"
      remoteName: "MYREMOTE" # this is not working
      patternOrReference: "$(conan_package_name)/$(conan_package_version)@$(project_name)/$(conan_channel)"
      extraArguments: "--all -c -r MYREMOTE" # this is
      buildName: "$(Build.DefinitionName)"
      buildNumber: "$(Build.BuildNumber)"
      conanUserHome: "$(Pipeline.Workspace)"


问:
Is It OK to Delete Original Repo After Migration to GitLab
I have Migrated a few of my Projects from BitBucket to Gitlab.
I just wanted to check the GitLab.com, with some projects and various features it provides.

I want to permanently migrate a few of my projects from BitBucket Repo to the GitLab.com.
I have done the import of projects to Gitlab.

But I have a few queries here:

I see the "Leave Project" link of the Repositories migrated from BitBucket, rather I don't see this "Leave Project" link on other repositories, which are directly created on GitLab. Which means, does GitLab is still connected with BitBucket for Repo?

What will happen if I delete the original BitBucket Repo? Will the new Project repository I have imported will work / or will not work?

I have read about the migration of projects from BitBucket to GitLab.com, but in those docs, it's not mentioned that it is OK to delete the original repo.

I need help on these questions so that I can move some of my projects fully on GitLab and remove the repositories (which I have migrated to GitLab already) from BitBucket.

Thank you.

答:
1. "Leave Project"

So it looks like when you import your Project from BitBucket to GitLab, it will create a Project for you on Gitlab

Leave a project
  Leave project will only display on the project’s dashboard when a project is part of a group (under a group namespace). If you choose to leave a project you will no longer be a project member, therefore, unable to contribute.

https://docs.gitlab.com/ee/user/project/#leave-a-project

To answer your question about GitLab still having links to the original repo: Nope, it clones the original Repo.

2. Deleting Original BitBucket Repo

Deleting the original repo will not have an effect on code already imported or code pushed after the import to your gitlab repository. The newly created Repository is a clone of the original one.

3. Documentation regarding Deleting Original

I too have looked and could not find anything of substance, but I can tell you that i have personally performed this process, and not just with BitBucket, but with GitLab as well, and have not had any issues in this regard.

Hope this helps!
Good Luck :)


问:
create a variable from multiple variables in R
I have a data set looks like, dat. I want to create one new variable (newVar) with values 1 through 4 using the Q1 through Q6 in R. Can anyone help how to do this, please?

```<code>newVar of 1: If any variable in Q1 through Q6 = "A"
newVar of 2: **If none of variables in Q1 through Q6 = "A", and** If any variable in Q59_1 through Q6= "B"
newVar of 3: **If none of variables in Q1 through Q6 = "A" or "B", and** If any variable in Q1 through Q6= "C"
newVar of 4: If none of variables in Q1 through Q6 = "A" or "B" or "C" , and**strong text** If any variable in Q1 through Q6= "D"

dat = data.frame(Q1 = c("A","D","B","A","D","C","B"),
                 Q2 = c("C","A","B","A","C","C","B"),
                 Q3 = c("B","D","D","A","B","C","A"),
                 Q4 = c("A","C","A","D","B","D","B"),
                 Q5 = c("C","D","D","A","A","C","B"),
                 Q6 = c("D","B","A","A","C","C","A"),
                 Q7 = c("5","1","2","2","4","0","3"),
                 Q8 = c("T","U","O","O","Z","W","Y"),
                 Q9 = c("X","T","V","P","I","U","Y"))
</code>```

Additional comment: I actually need all the conditions especially the bold parts (If none of variables in ...) such as
    NewVar 2: If none of variables in Q1 through Q6 = "A", and If any variable in Q59_1 through Q6= "B"
       3: If none of variables in Q1 through Q6 = "A" or "B", and If any variable in Q1 through Q6= "C"
       4: If none of variables in Q1 through Q6 = "A" or "B" or "C" , and If any variable in Q1 through Q6= "D"

答:
You can use match with LETTERS and min to test if any of the LETTERS is present.

```<code>dat$newVar <- apply(dat[1:6], 1, function(x) min(match(x, LETTERS[1:4])))
dat
#  Q1 Q2 Q3 Q4 Q5 Q6 Q7 Q8 Q9 newVar
#1  A  C  B  A  C  D  5  T  X      1
#2  D  A  D  C  D  B  1  U  T      1
#3  B  B  D  A  D  A  2  O  V      1
#4  A  A  A  D  A  A  2  O  P      1
#5  D  C  B  B  A  C  4  Z  I      1
#6  C  C  C  D  C  C  0  W  U      3
#7  B  B  A  B  B  A  3  Y  Y      1
</code>```

Body:
I have a data set looks like, dat. I want to create one new variable (newVar) with values 1 through 4 using the Q1 through Q6 in R. Can anyone help how to do this, please?

newVar of 1: If any variable in Q1 through Q6 = "A"
newVar of 2: **If none of variables in Q1 through Q6 = "A", and** If any variable in Q59_1 through Q6= "B"
newVar of 3: **If none of variables in Q1 through Q6 = "A" or "B", and** If any variable in Q1 through Q6= "C"
newVar of 4: If none of variables in Q1 through Q6 = "A" or "B" or "C" , and**strong text** If any variable in Q1 through Q6= "D"

dat = data.frame(Q1 = c("A","D","B","A","D","C","B"),
                 Q2 = c("C","A","B","A","C","C","B"),
                 Q3 = c("B","D","D","A","B","C","A"),
                 Q4 = c("A","C","A","D","B","D","B"),
                 Q5 = c("C","D","D","A","A","C","B"),
                 Q6 = c("D","B","A","A","C","C","A"),
                 Q7 = c("5","1","2","2","4","0","3"),
                 Q8 = c("T","U","O","O","Z","W","Y"),
                 Q9 = c("X","T","V","P","I","U","Y"))

Additional comment: I actually need all the conditions especially the bold parts (If none of variables in ...) such as
    NewVar 2: If none of variables in Q1 through Q6 = "A", and If any variable in Q59_1 through Q6= "B"
       3: If none of variables in Q1 through Q6 = "A" or "B", and If any variable in Q1 through Q6= "C"
       4: If none of variables in Q1 through Q6 = "A" or "B" or "C" , and If any variable in Q1 through Q6= "D"

Body:
You can use match with LETTERS and min to test if any of the LETTERS is present.

dat$newVar <- apply(dat[1:6], 1, function(x) min(match(x, LETTERS[1:4])))
dat
#  Q1 Q2 Q3 Q4 Q5 Q6 Q7 Q8 Q9 newVar
#1  A  C  B  A  C  D  5  T  X      1
#2  D  A  D  C  D  B  1  U  T      1
#3  B  B  D  A  D  A  2  O  V      1
#4  A  A  A  D  A  A  2  O  P      1
#5  D  C  B  B  A  C  4  Z  I      1
#6  C  C  C  D  C  C  0  W  U      3
#7  B  B  A  B  B  A  3  Y  Y      1


问:
Java recursively list the files from directory of specific pattern
I've below directory/file structure

```<code>ABC
  -- Apps
  -- Tests
     -- file1.xml
     -- file2.xml
  -- AggTests
  -- UnitTests
PQR
  -- Apps
  -- Tests
     -- file3.xml
     -- file4.xml
  -- AggTests
  -- UnitTests

</code>```

Here I just want to a List of Files from Tests directory. How can I achieve it in java, I found this is something helpful https://stackoverflow.com/a/24006711/1665592

Something below is listing down all XML files but I need it from specific directory called Tests?

```<code>try (Stream<Path> walk = Files.walk(Paths.get("C:\\projects"))) {

    List<String> fileList = walk.map(x -> x.toString())
            .filter(f -> f.endsWith(".xml")).collect(Collectors.toList());

    fileList.forEach(System.out::println);

} catch (IOException e) {
    e.printStackTrace();
}

</code>```

Ultimately, I need fileList = [file1.xml, file2.xml, file3.xml, file4.xml]

答:
```<code>public List<String> getAllFiles(String baseDirectory,String filesParentDirectory) throws IOException{
       return Files.walk(Paths.get(baseDirectory))
               .filter(Files::isRegularFile)
               .filter(x->(x.getParent().getFileName().toString().equals(filesParentDirectory)))
               .map(x->x.getFileName().toString()).collect(Collectors.toList());
    }
</code>```

Body:
I've below directory/file structure

ABC
  -- Apps
  -- Tests
     -- file1.xml
     -- file2.xml
  -- AggTests
  -- UnitTests
PQR
  -- Apps
  -- Tests
     -- file3.xml
     -- file4.xml
  -- AggTests
  -- UnitTests

Here I just want to a List of Files from Tests directory. How can I achieve it in java, I found this is something helpful https://stackoverflow.com/a/24006711/1665592

Something below is listing down all XML files but I need it from specific directory called Tests?

try (Stream<Path> walk = Files.walk(Paths.get("C:\\projects"))) {

    List<String> fileList = walk.map(x -> x.toString())
            .filter(f -> f.endsWith(".xml")).collect(Collectors.toList());

    fileList.forEach(System.out::println);

} catch (IOException e) {
    e.printStackTrace();
}

Ultimately, I need fileList = [file1.xml, file2.xml, file3.xml, file4.xml]


问:
How to get all form input values using blur event in `addEventListener`?
I am trying to get form values dynamically using addEventListener but I am just getting first input, not getting other inputs.

This is my current code:

$(document).ready(
  function() {
    const user_input = document.querySelector('input[type="text"], input[type="password"]');

    user_input.addEventListener(
      'blur',
      function(event) {
        var target = event.target;

        if (target.name == "first_name") {
          console.log('first name : ' + target.value);
        }

        if (target.name == "mid_name") {
          console.log('mid name : ' + target.value);
        }

        if (target.name == "last_name") {
          console.log('last name : ' + target.value);
        }

        if (target.name == "password") {
          console.log('password : ' + target.value);
        }
      }
    );
  }
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  first_name : <input type="text" name="first_name" value=""> <br>
  mid_name : <input type="text" name="mid_name" value=""> <br>
  last_name : <input type="text" name="last_name" value=""> <br>
  password : <input type="password" name="password" value=""> <br>
</form></code>```

Demo on JSFiddle

I can just get the fist name value; for the other inputs I am not getting anything. Any idea what I am doing wrong?

答:
Aside from the issue you are facing with querySelector() vs querySelectorAll() addressed by other answers, I suggest you use the native FormData() to get all your data from the form, here is a snippet:

https://developer.mozilla.org/en-US/docs/Web/API/FormData

document.getElementById('mybutton').addEventListener('click', function(e) {
  e.preventDefault();
  let myForm = document.getElementById('myForm');
  let formData = new FormData(myForm);
  for (let input of formData) {
    console.log(input);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>

    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>

    <form id="myForm">
      first_name : <input type="text" name="first_name" value=""> <br>
      mid_name  :  <input type="text" name="mid_name" value=""> <br>
      last_name  :  <input type="text" name="last_name" value=""> <br>
      password :  <input type="password" name="mid_name" value=""> <br>
      <button id="mybutton">
       get data
      </button>
    </form>

<script src="script.js"></script>
  </body>
</html></code>```

Body:
I am trying to get form values dynamically using addEventListener but I am just getting first input, not getting other inputs.

This is my current code:

$(document).ready(
  function() {
    const user_input = document.querySelector('input[type="text"], input[type="password"]');

    user_input.addEventListener(
      'blur',
      function(event) {
        var target = event.target;

        if (target.name == "first_name") {
          console.log('first name : ' + target.value);
        }

        if (target.name == "mid_name") {
          console.log('mid name : ' + target.value);
        }

        if (target.name == "last_name") {
          console.log('last name : ' + target.value);
        }

        if (target.name == "password") {
          console.log('password : ' + target.value);
        }
      }
    );
  }
);

<form>
  first_name : <input type="text" name="first_name" value="">

  mid_name : <input type="text" name="mid_name" value="">

  last_name : <input type="text" name="last_name" value="">

  password : <input type="password" name="password" value="">

</form>

Demo on JSFiddle

I can just get the fist name value; for the other inputs I am not getting anything. Any idea what I am doing wrong?

Body:
Aside from the issue you are facing with querySelector() vs querySelectorAll() addressed by other answers, I suggest you use the native FormData() to get all your data from the form, here is a snippet:

https://developer.mozilla.org/en-US/docs/Web/API/FormData

document.getElementById('mybutton').addEventListener('click', function(e) {
  e.preventDefault();
  let myForm = document.getElementById('myForm');
  let formData = new FormData(myForm);
  for (let input of formData) {
    console.log(input);
  }
});

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>

    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>

    <form id="myForm">
      first_name : <input type="text" name="first_name" value=""> <br>
      mid_name  :  <input type="text" name="mid_name" value=""> <br>
      last_name  :  <input type="text" name="last_name" value=""> <br>
      password :  <input type="password" name="mid_name" value=""> <br>
      <button id="mybutton">
       get data
      </button>
    </form>

<script src="script.js"></script>
  </body>
</html>


问:
How to find the support vectors for SVM?
I'm using the liblinear library to train a linear SVM on my data. I have access to the weights for each class of the trained model. But I need to figure out which training instances are acting as support vectors.

The liblinear library doesn't seem to provide these vectors as a model attribute. And I can't seem to figure out how I can find them manually. If I have the training data and I have the weights that define the hyperplane, how would I go about finding these support vectors?

答:
Let me assume we are talking about libsvm instead of sklearn svc.

The answer can be found in the LIBLINEAR FAQ. In short, you can't. You need to modify the source code.

Q: How could I know which training instances are support vectors?

Some LIBLINEAR solvers consider the primal problem, so support
vectors are not obtained during the training procedure. For dual
solvers, we output only the primal weight vector w, so support vectors
are not stored in the model. This is different from LIBSVM.

To know support vectors, you can modify the following loop in
solve_l2r_l1l2_svc() of linear.cpp to print out indices:

```<code>    for(i=0; i<l; i++)
    {
        v += alpha[i]*(alpha[i]*diag[GETI(i)] - 2);
        if(alpha[i] > 0)
            ++nSV;
    }
</code>```

Note that we group data in the same class together before calling this
subroutine. Thus the order of your training instances has been
changed. You can sort your data (e.g., positive instances before
negative ones) before using liblinear. Then indices will be the same.

Body:
Let me assume we are talking about libsvm instead of sklearn svc.

The answer can be found in the LIBLINEAR FAQ. In short, you can't. You need to modify the source code.

Q: How could I know which training instances are support vectors?

Some LIBLINEAR solvers consider the primal problem, so support
vectors are not obtained during the training procedure. For dual
solvers, we output only the primal weight vector w, so support vectors
are not stored in the model. This is different from LIBSVM.

To know support vectors, you can modify the following loop in
solve_l2r_l1l2_svc() of linear.cpp to print out indices:

    for(i=0; i<l; i++)
    {
        v += alpha[i]*(alpha[i]*diag[GETI(i)] - 2);
        if(alpha[i] > 0)
            ++nSV;
    }

Note that we group data in the same class together before calling this
subroutine. Thus the order of your training instances has been
changed. You can sort your data (e.g., positive instances before
negative ones) before using liblinear. Then indices will be the same.


问:
How to Prevent Keyboard appearing for EditText that is not enabled
My activity has an EditText which is supposedly not editable until user clicks on edit button for the screen.

I did edit.setEnabled(false) but still a keyboard appears for the user and values can be added to the EditText in the screen via the keyboard even though the screen might look a bit greyed out.  What else do I have to do to prevent editing of the EditText until user has specifically pushed an edit button.

Thanks,
Steve

答:
Attention that setEditable is depecrated.

You can use :

```<code>setInputType(EditorInfo.TYPE_CLASS_TEXT)
</code>```

To turn keyboard on.

```<code>setInputType(EditorInfo.TYPE_NULL)
</code>```

To turn keyboard off.

Body:
Attention that setEditable is depecrated.

You can use :

setInputType(EditorInfo.TYPE_CLASS_TEXT)

To turn keyboard on.

setInputType(EditorInfo.TYPE_NULL)

To turn keyboard off.