问:
Calc() not working on flexbox width in firefox
I'm trying to use the css calc() function with variables to determine the width of a flexbox. This is working for me in chrome and safari but firefox doesn't seem to recognise the value at all.

This is how I wanted it to look in Chrome.

And this is how it shows up in Firefox.

Here's the example on codepen.

CSS:

```<code>:root {
    --card-width: 340px;
    --card-height: 150px;
    --card-padding: 20px;
}

html, body {
    background: #2e2e2e;
    width: 100vw;
    height: 100vh;
    padding: 0;
    margin: 0;
}

a {
    text-decoration: none;
}

.section {
        width: 100vw;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
    }

.card-holder {
    width: calc((var(--labelled-card-width, 340px) * 3) + ((var(--labelled-card-padding), 20px) * 2));
    height: calc((var(--labelled-card-height, 150px) * 2) + (var(--labelled-card-padding), 20px));
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    align-content: space-between;
}

.card {
    width: var(--labelled-card-width, 340px);
    height: var(--labelled-card-height, 150px);
    display: flex;
    justify-content: center;
    align-items: center;
    background: #fff;
    color: #000;
    transition: 0.1s;
}

.card i {
    margin-left: -25px;
    margin-right: 14px;
    font-size: 3.4rem;
}

.card h4 {
    text-transform: uppercase;
    font-size: 1rem;
    font-weight: 600;
    letter-spacing: 0.5px;
}
</code>```

HTML:

```<code><div class="section">

  <div class="card-holder">
      <a href="#" class="card">
          <i class="fa fa-check-circle"></i>
          <h4>Card<br>One</h4>
      </a>

      <a href="#" class="card">
          <i class="fa fa-check-circle"></i>
          <h4>Card<br>Two</h4>
      </a>

      <a href="#" class="card">
          <i class="fa fa-check-circle"></i>
          <h4>Card<br>Three</h4>
      </a>

      <a href="#" class="card">
          <i class="fa fa-check-circle"></i>
          <h4>Card<br>Four</h4>
      </a>
      <a href="#" class="card">
          <i class="fa fa-check-circle"></i>
          <h4>Card<br>Five</h4>
      </a>

      <a href="#" class="card">
          <i class="fa fa-check-circle"></i>
          <h4>Card<br>Six</h4>
      </a>

  </div>

</div>
</code>```

Is there a way to get around this problem or should I be doing this another way?

答:
Your var syntax isn't correct, somehow Chrome get away with it but Firefox didn't.

The default value should be within the parenthesis. You wrote it right for the width and height but not for the padding.

This is wrong:

```<code>.card-holder {
                                                 ∨                  ∨
    width: calc((var(--card-width, 340px) * 3) + ((var(--card-padding), 20px) * 2));

                                                   ∨                 ∨
    height: calc((var(--card-height, 150px) * 2) + (var(--card-padding), 20px));
}
</code>```

It should be:

```<code>.card-holder {
    width: calc((var(--card-width, 340px) * 3) + (var(--card-padding, 20px) * 2));
    height: calc((var(--card-height, 150px) * 2) + var(--card-padding, 20px));
}
</code>```

/* VARIABLES */

:root {
  /* CARDS */
  --card-width: 340px;
  --card-height: 150px;
  --card-padding: 20px;
}

/* GLOBAL */

html,
body {
  background: #2e2e2e;
  width: 100vw;
  height: 100vh;
  padding: 0;
  margin: 0;
}

a {
  text-decoration: none;
}

/* CARD HOLDER */

.section {
  width: 100vw;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.card-holder {
  width: calc((var(--card-width, 340px) * 3) + (var(--card-padding, 20px) * 2));
  height: calc((var(--card-height, 150px) * 2) + var(--card-padding, 20px));
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-content: space-between;
}

/* CARD */

.card {
  width: var(--card-width, 340px);
  height: var(--card-height, 150px);
  display: flex;
  justify-content: center;
  align-items: center;
  background: #fff;
  color: #000;
  transition: 0.1s;
}

.card i {
  margin-left: -25px;
  margin-right: 14px;
  font-size: 3.4rem;
}

.card h4 {
  text-transform: uppercase;
  font-size: 1rem;
  font-weight: 600;
  letter-spacing: 0.5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Font Awesome -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" crossorigin="anonymous">

<div class="section">
  <div class="card-holder">

      <i class="fa fa-check-circle"></i>
      <h4>Card<br>One</h4>

      <i class="fa fa-check-circle"></i>
      <h4>Card<br>Two</h4>

      <i class="fa fa-check-circle"></i>
      <h4>Card<br>Three</h4>

      <i class="fa fa-check-circle"></i>
      <h4>Card<br>Four</h4>

      <i class="fa fa-check-circle"></i>
      <h4>Card<br>Five</h4>

      <i class="fa fa-check-circle"></i>
      <h4>Card<br>Six</h4>

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

Body:
I'm trying to use the css calc() function with variables to determine the width of a flexbox. This is working for me in chrome and safari but firefox doesn't seem to recognise the value at all.

This is how I wanted it to look in Chrome.

And this is how it shows up in Firefox.

Here's the example on codepen.

CSS:

:root {
    --card-width: 340px;
    --card-height: 150px;
    --card-padding: 20px;
}

html, body {
    background: #2e2e2e;
    width: 100vw;
    height: 100vh;
    padding: 0;
    margin: 0;
}

a {
    text-decoration: none;
}

.section {
        width: 100vw;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
    }

.card-holder {
    width: calc((var(--labelled-card-width, 340px) * 3) + ((var(--labelled-card-padding), 20px) * 2));
    height: calc((var(--labelled-card-height, 150px) * 2) + (var(--labelled-card-padding), 20px));
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    align-content: space-between;
}

.card {
    width: var(--labelled-card-width, 340px);
    height: var(--labelled-card-height, 150px);
    display: flex;
    justify-content: center;
    align-items: center;
    background: #fff;
    color: #000;
    transition: 0.1s;
}

.card i {
    margin-left: -25px;
    margin-right: 14px;
    font-size: 3.4rem;
}

.card h4 {
    text-transform: uppercase;
    font-size: 1rem;
    font-weight: 600;
    letter-spacing: 0.5px;
}

HTML:

Card
One

Card
Two

Card
Three

Card
Four

Card
Five

Card
Six

Is there a way to get around this problem or should I be doing this another way?

Body:
Your var syntax isn't correct, somehow Chrome get away with it but Firefox didn't.

The default value should be within the parenthesis. You wrote it right for the width and height but not for the padding.

This is wrong:

.card-holder {
                                                 ∨                  ∨
    width: calc((var(--card-width, 340px) * 3) + ((var(--card-padding), 20px) * 2));

                                                   ∨                 ∨
    height: calc((var(--card-height, 150px) * 2) + (var(--card-padding), 20px));
}

It should be:

.card-holder {
    width: calc((var(--card-width, 340px) * 3) + (var(--card-padding, 20px) * 2));
    height: calc((var(--card-height, 150px) * 2) + var(--card-padding, 20px));
}

/* VARIABLES */

:root {
  /* CARDS */
  --card-width: 340px;
  --card-height: 150px;
  --card-padding: 20px;
}

/* GLOBAL */

html,
body {
  background: #2e2e2e;
  width: 100vw;
  height: 100vh;
  padding: 0;
  margin: 0;
}

a {
  text-decoration: none;
}

/* CARD HOLDER */

.section {
  width: 100vw;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.card-holder {
  width: calc((var(--card-width, 340px) * 3) + (var(--card-padding, 20px) * 2));
  height: calc((var(--card-height, 150px) * 2) + var(--card-padding, 20px));
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-content: space-between;
}

/* CARD */

.card {
  width: var(--card-width, 340px);
  height: var(--card-height, 150px);
  display: flex;
  justify-content: center;
  align-items: center;
  background: #fff;
  color: #000;
  transition: 0.1s;
}

.card i {
  margin-left: -25px;
  margin-right: 14px;
  font-size: 3.4rem;
}

.card h4 {
  text-transform: uppercase;
  font-size: 1rem;
  font-weight: 600;
  letter-spacing: 0.5px;
}

<!-- Font Awesome -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" crossorigin="anonymous">

<div class="section">
  <div class="card-holder">
    <a href="#" class="card">
      <i class="fa fa-check-circle"></i>
      <h4>Card<br>One</h4>
    </a>
    <a href="#" class="card">
      <i class="fa fa-check-circle"></i>
      <h4>Card<br>Two</h4>
    </a>
    <a href="#" class="card">
      <i class="fa fa-check-circle"></i>
      <h4>Card<br>Three</h4>
    </a>
    <a href="#" class="card">
      <i class="fa fa-check-circle"></i>
      <h4>Card<br>Four</h4>
    </a>
    <a href="#" class="card">
      <i class="fa fa-check-circle"></i>
      <h4>Card<br>Five</h4>
    </a>
    <a href="#" class="card">
      <i class="fa fa-check-circle"></i>
      <h4>Card<br>Six</h4>
    </a>
  </div>
</div>


来源: stackexchange

问:
Route [blog.all_article] not defined
I want to go from home.blade.php to all_article.blade.php, but they tell me that such a route was not found. What am I doing wrong. Thanks in advance for your help.

blog/home.blade

```<code> <a href="{{route('blog.all_article')}}" class="btn btn-primary pull-right"><i class="fa fa-plus-square-o"></i> Add</a>
</code>```

BlogController

```<code>public function articlesAll_blade(){
   return view('blog.all_article',[
     'articles' => Article::orderBy('created_at', 'desc')->paginate(10),
      'footers' => System::all(),
   ]);
}
</code>```

web.php

```<code> Route::get('/', 'BlogController@articlesAll', function () {
     return view('blog.home');
 });

 Route::get('/all_article', 'BlogController@articlesAll_blade', function () {
     return view('blog.all_article');
 });
</code>```

ContentLicense: CC BY-SA 4.0

Title: Route [blog.all_article] not defined

Body:
I want to go from home.blade.php to all_article.blade.php, but they tell me that such a route was not found. What am I doing wrong. Thanks in advance for your help.

blog/home.blade

  Add

BlogController

public function articlesAll_blade(){
   return view('blog.all_article',[
     'articles' => Article::orderBy('created_at', 'desc')->paginate(10),
      'footers' => System::all(),
   ]);
}

web.php

 Route::get('/', 'BlogController@articlesAll', function () {
     return view('blog.home');
 });

 Route::get('/all_article', 'BlogController@articlesAll_blade', function () {
     return view('blog.all_article');
 });

Body: Route::get('/all_article','BlogController@articlesAll_blade')->name('blog.all_article');


问:
Efficient way to broadcast/iterate over dictionary values
I am trying use dictionary values in a calculation such as this:

```<code>mydict = dict(zip(['key1', 'key2', 'key3'],
                  [1, 2, 3]))
print(mydict)

newvals = (mydict.values() + 3) ** 2
print(newvals)
</code>```

{'key1': 1, 'key2': 2, 'key3': 3}
TypeError: unsupported operand type(s) for +: 'dict_values' and 'int'
```

<p>Or if I do,</p>

<pre class="lang-py prettyprint-override"><code>import numpy as np
newvals = (np.array(mydict.values()) + 3) ** 2
print(newvals)
</code>```

```<code>TypeError: unsupported operand type(s) for +: 'dict_values' and 'int'
</code>```

It appears I have to convert the dictionary values to a list first, or iterate with a list comprehension.

newvals = (np.array(list(mydict.values())) + 3) ** 2
print(newvals)
```

```[16 25 36]
```

<p>Or I can do</p>

<pre class="lang-py prettyprint-override"><code>newvals = np.array([(val + 3) ** 2 for val in mydict.values()])
print(newvals)
</code>```

[16 25 36]
```

Is there an easier or more efficient way to do this?
Or is there an inbuilt method for dictionaries that I can employ so that I don't have to use a list comprehension or for loop?

Thank you.

答:
When we talk about avoiding loops in numpy, what we actually mean is avoiding Python level loops.  We still have to loop through the array elements, but we do it in fast compiled code.  That code only works on numpy ndarrays.  Furthermore, loops through arrays are worse than loops though lists.

If we start with lists, we have to first convert it to ndarray, e.g. arr = np.array([1,2,3]).  That array conversion takes time, enough so that often it is faster to do a list comprehension.

numpy does not have any code to work directly with Python dicts.  values() makes a generator-like object.  np.array(...) requires a list like object:

```<code>In [140]: np.array(list(mydict.values()))
Out[140]: array([1, 2, 3])
In [141]: (np.array(list(mydict.values())) +3)**2
Out[141]: array([16, 25, 36])
</code>```

fromiter can work from the values object:

```<code>In [142]: np.fromiter(mydict.values(), int)
Out[142]: array([1, 2, 3])
</code>```

np.fromiter may be faster than np.array, but I won't guarantee it.

I suspect that the list comprehension is faster, especially for this small example:

```<code>In [143]: [(x+3)**2 for x in mydict.values()]
Out[143]: [16, 25, 36]
</code>```

We could do some time testing, but for this small sample it probably won't be that useful.

Dictionaries are useful for a lot of things, but fast numeric calculations is not one them.

Body:
I am trying use dictionary values in a calculation such as this:

mydict = dict(zip(['key1', 'key2', 'key3'],
                  [1, 2, 3]))
print(mydict)

newvals = (mydict.values() + 3) ** 2
print(newvals)

{'key1': 1, 'key2': 2, 'key3': 3}
TypeError: unsupported operand type(s) for +: 'dict_values' and 'int'

Or if I do,

import numpy as np
newvals = (np.array(mydict.values()) + 3) ** 2
print(newvals)

TypeError: unsupported operand type(s) for +: 'dict_values' and 'int'

It appears I have to convert the dictionary values to a list first, or iterate with a list comprehension.

newvals = (np.array(list(mydict.values())) + 3) ** 2
print(newvals)

[16 25 36]

Or I can do

newvals = np.array([(val + 3) ** 2 for val in mydict.values()])
print(newvals)

[16 25 36]

Is there an easier or more efficient way to do this?
Or is there an inbuilt method for dictionaries that I can employ so that I don't have to use a list comprehension or for loop?

Thank you.

Body:
When we talk about avoiding loops in numpy, what we actually mean is avoiding Python level loops.  We still have to loop through the array elements, but we do it in fast compiled code.  That code only works on numpy ndarrays.  Furthermore, loops through arrays are worse than loops though lists.

If we start with lists, we have to first convert it to ndarray, e.g. arr = np.array([1,2,3]).  That array conversion takes time, enough so that often it is faster to do a list comprehension.

numpy does not have any code to work directly with Python dicts.  values() makes a generator-like object.  np.array(...) requires a list like object:

In [140]: np.array(list(mydict.values()))
Out[140]: array([1, 2, 3])
In [141]: (np.array(list(mydict.values())) +3)**2
Out[141]: array([16, 25, 36])

fromiter can work from the values object:

In [142]: np.fromiter(mydict.values(), int)
Out[142]: array([1, 2, 3])

np.fromiter may be faster than np.array, but I won't guarantee it.

I suspect that the list comprehension is faster, especially for this small example:

In [143]: [(x+3)**2 for x in mydict.values()]
Out[143]: [16, 25, 36]

We could do some time testing, but for this small sample it probably won't be that useful.

Dictionaries are useful for a lot of things, but fast numeric calculations is not one them.


问:
How to write filtered csv date to new file python
I looked through the suggestions and honestly, they couldn't help me enough not to continue with posting this.

I'm trying to organize data in a csv file to a new file. I can print out the results, I just can't write them to a new file. What I have so far is something that writes, but not the desired results. (fieldnames is in there because I changed from DictWriter to just writer as per dict and str issues)

```<code>import csv
import pandas as pd

with open('TastyTrades.csv', 'r') as trade_history:
    trade_reader = pd.read_csv('TastyTrades.csv')
    df = trade_reader.loc[trade_reader['Action'].isin(['BUY_TO_OPEN', 'SELL_TO_OPEN']) & (trade_reader['Instrument Type'] == 'Equity Option')]

    with open('new_taste.csv', 'w') as open_trades:
        fieldnames = ['Date', 'Type', 'Action', 'Symbol', 'Instrument Type', 'Description', 'Value', 'Quantity',
                      'Average Price', 'Commissions', 'Fees', 'Multiplier', 'Underlying Symbol', 'Expiration Date',
                      'Strike Price', 'Call or Put']
        csv_writer = csv.writer(open_trades, delimiter='\t')

        for line in trade_reader:
            csv_writer.writerow(line)

</code>```

The results I am getting brings back the header with each row making up each header name.

```<code>D   a   t   e

T   y   p   e

A   c   t   i   o   n

S   y   m   b   o   l

I   n   s   t   r   u   m   e   n   t       T   y   p   e

D   e   s   c   r   i   p   t   i   o   n

V   a   l   u   e
</code>```

What I'm trying to get is the following without it being indexed. (I'm running this as a print(df) in pycharm just as a show)

```<code>                         Date   Type  ... Strike Price Call or Put
0    2020-02-14T15:49:12-0500  Trade  ...        127.0        CALL
1    2020-02-14T15:49:11-0500  Trade  ...        107.0         PUT
2    2020-02-14T15:49:11-0500  Trade  ...        128.0        CALL
3    2020-02-14T15:49:11-0500  Trade  ...        106.0         PUT
8    2020-02-14T12:19:30-0500  Trade  ...          2.5        CALL
</code>```

答:
This will work friend          </p>

```<code>df.to_csv(r'C:/your/file/path.csv')
</code>```

Body:
I looked through the suggestions and honestly, they couldn't help me enough not to continue with posting this.

I'm trying to organize data in a csv file to a new file. I can print out the results, I just can't write them to a new file. What I have so far is something that writes, but not the desired results. (fieldnames is in there because I changed from DictWriter to just writer as per dict and str issues)

import csv
import pandas as pd

with open('TastyTrades.csv', 'r') as trade_history:
    trade_reader = pd.read_csv('TastyTrades.csv')
    df = trade_reader.loc[trade_reader['Action'].isin(['BUY_TO_OPEN', 'SELL_TO_OPEN']) & (trade_reader['Instrument Type'] == 'Equity Option')]

    with open('new_taste.csv', 'w') as open_trades:
        fieldnames = ['Date', 'Type', 'Action', 'Symbol', 'Instrument Type', 'Description', 'Value', 'Quantity',
                      'Average Price', 'Commissions', 'Fees', 'Multiplier', 'Underlying Symbol', 'Expiration Date',
                      'Strike Price', 'Call or Put']
        csv_writer = csv.writer(open_trades, delimiter='\t')

        for line in trade_reader:
            csv_writer.writerow(line)

The results I am getting brings back the header with each row making up each header name.

D   a   t   e

T   y   p   e

A   c   t   i   o   n

S   y   m   b   o   l

I   n   s   t   r   u   m   e   n   t       T   y   p   e

D   e   s   c   r   i   p   t   i   o   n

V   a   l   u   e

What I'm trying to get is the following without it being indexed. (I'm running this as a print(df) in pycharm just as a show)

                         Date   Type  ... Strike Price Call or Put
0    2020-02-14T15:49:12-0500  Trade  ...        127.0        CALL
1    2020-02-14T15:49:11-0500  Trade  ...        107.0         PUT
2    2020-02-14T15:49:11-0500  Trade  ...        128.0        CALL
3    2020-02-14T15:49:11-0500  Trade  ...        106.0         PUT
8    2020-02-14T12:19:30-0500  Trade  ...          2.5        CALL

Body:
This will work friend

df.to_csv(r'C:/your/file/path.csv')


问:
How do I call a Python function with parameters from an HTML page (alongside Django)?
I'm in the process of writing a Django app, but I've hit a slight roadblock.

You see, I have the backend return an HTML page, and that works just fine. What I am having trouble with though is going the other way around. I am trying to call a function on the backend once the user clicks a button. Now, I've already searched to see if anyone else has asked this question before, but all the posts that came up had a different scenario linked to them. All of them were for GET requests, but I need to be able to POST some data instead.

Does anyone know how I can do this?

答:
You'll want to get started with Django forms:

https://docs.djangoproject.com/en/3.0/topics/forms/

Forms accept a POST, and there are lots of handy parts for sanitizing the data.


问:
Unmarshalling String XML with JAXB not working and returning just null values
I'm trying to unmarshall a String XML to a POJO Object without success. This is the code i am using

```<code>MyObject myobject = JAXB.unmarshal(new StringReader(myxmlstring), MyObject.class);
</code>```

The Xml is structured and object is structured as followed:

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:SomePerson xmlns:ns2="http://to/something">
    <SomePerson>
        <person>
            <name>joe</name>
        </person>
    </SomePerson>
</ns2:SomePerson>
</code>```

this is my Object:

```<code>@XmlRootElement(name="SomePerson")
@XmlAccessorType(XmlAccessType.FIELD)
public class MyObject {

    @XmlElement(name = "name")
    private String name;

    //getter and setters
}
</code>```

答:
Suggest you to do something like this ::

```<code>        final DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        final InputSource is = new InputSource();
        is.setCharacterStream(new StringReader("<root><node1></node1></root>")); // put your xml string here

        final Document doc = db.parse(is);

        final XMLInputFactory xif = XMLInputFactory.newFactory();
        final DOMSource domSource = new DOMSource(document);
        final XMLStreamReader xsr = xif.createXMLStreamReader(domSource);
        final XMLReaderWithoutNamespace xr = new XMLReaderWithoutNamespace(xsr);
        final Unmarshaller unmarshaller = JAXBContext
                .newInstance("POJO LOCATION").createUnmarshaller();
        return (POJOClass) unmarshaller.unmarshal(xr);
</code>```

Let me know if this helps

Body:
I'm trying to unmarshall a String XML to a POJO Object without success. This is the code i am using

MyObject myobject = JAXB.unmarshal(new StringReader(myxmlstring), MyObject.class);

The Xml is structured and object is structured as followed:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:SomePerson xmlns:ns2="http://to/something">
    <SomePerson>
        <person>
            <name>joe</name>
        </person>
    </SomePerson>
</ns2:SomePerson>

this is my Object:

@XmlRootElement(name="SomePerson")
@XmlAccessorType(XmlAccessType.FIELD)
public class MyObject {

    @XmlElement(name = "name")
    private String name;

    //getter and setters
}

Body:
Suggest you to do something like this ::

        final DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        final InputSource is = new InputSource();
        is.setCharacterStream(new StringReader("<root><node1></node1></root>")); // put your xml string here

        final Document doc = db.parse(is);

        final XMLInputFactory xif = XMLInputFactory.newFactory();
        final DOMSource domSource = new DOMSource(document);
        final XMLStreamReader xsr = xif.createXMLStreamReader(domSource);
        final XMLReaderWithoutNamespace xr = new XMLReaderWithoutNamespace(xsr);
        final Unmarshaller unmarshaller = JAXBContext
                .newInstance("POJO LOCATION").createUnmarshaller();
        return (POJOClass) unmarshaller.unmarshal(xr);

Let me know if this helps


问:
How to override the default browser selection in Windows 7 when opening webppages with Python
I have a program written with Python 3.7.4 on Windows that opens web pages in a browser.  It displays the default browser and gives the user the chance to change which browser they want to use to open programs with.

The default browser is detected when the program is initialised using this technique:

```<code>from winreg import HKEY_CURRENT_USER, OpenKey, QueryValueEx

import webbroswer

reg_path = r'Software\Microsoft\Windows\Shell\Associations\UrlAssociations\https\UserChoice'
chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
firefox_path = 'C:/Program Files (x86)/Mozilla Firefox/firefox.exe %s'

with OpenKey(HKEY_CURRENT_USER, reg_path) as key:
    print(QueryValueEx(key, 'ProgId'))
    thedefaultbrowser = (QueryValueEx(key, 'ProgId'))
    thedefaultbrowser = (thedefaultbrowser[0])
    thedefaultbrowser = (thedefaultbrowser[0:2])
    if thedefaultbrowser == "Fi":
        browser_path = firefox_path
    if thedefaultbrowser == "Ch":
        browser_path = chrome_path
</code>```

And links are opened like this, as part of an infinite loop that happens later in the program:

```<code>while True:

    # [lots of GUI code that isn't relevant]

    event = input()

    if event == 'pleasegetmealinknao':
        x=open("C:/folder/atextfilewithalinkinit.txt", "r")
        the_url1 = x.read()
        webbrowser.get(browser_path).open(the_url1)
        x.close()
</code>```

In the same loop, input can be accepted from the user to change the browser type:

```<code>    elif event == "Firefox":
        browser_path = firefox_path
        continue
    elif event == "Chrome":
        browser_path = chrome_path
        continue
</code>```

So I can open a webpage with this just fine.  I can then change the browser type just fine, and then open another webpage in the newly user-selected browser, but - only in Windows 10.

In Windows 7, Firefox co-operates beautifully, and so does Chrome but only if Chrome is set as the default browser before the program runs.  However if Firefox is set as the default browser before the program is started, as soon as I switch to Chrome and then try to open anything in Chrome, the program gets very upset and stops running.  No crash, no error message or traceback, it just freezes completely and needs to be hard-restarted.  Sometimes I can rescue the program from its frozen state by closing the new browser window that was just opened, but this of course defeats the purpose of the program.

HOWEVER - if I scrap all this fancy business and just accept whatever the default browser is, like this:

```<code>    if event == 'pleasegetmealinknao':
        x=open("C:/folder/atextfilewithalinkinit.txt", "r")
        the_url1 = x.read()
        webbrowser.open(the_url1)
        x.close()
</code>```

Then the chosen link will open happily in whatever the system default browser is, whether it be Firefox, Chrome, Internet Explorer, or anything else.

So why is this happening and how can I fix?  Or do I just have to bury my dream of selectable browsers?

My guess is that this might have something to do with Chrome detecting that it is not the default browser and asking the user to change the default browser setting, that would make sense.  However then the question is, how do I make the Python program ignore whatever this behaviour is.  A popup related to this doesn't always appear.

EDIT: further testing and sometimes the Windows 7 pattern of behaviour also happens in Windows 10... but seemingly not all the time.  This makes me think even more that it's browser-related rather than strictly OS related and has a lot to do with Chrome asking for default status, but I'm still no closer to working out what to do about it.

答: I cannot test this issue as I do not have Windows 7. If the issue is that Chrome is checking whether it is the default browser, you can suppress that via the command line switch chrome.exe --no-default-browser-check $link. However, I do not think you can do this using the python webbrowser module. Instead, you would need to use subprocess or a terminal interacting module which is compatible with windows eg: pbs, and then call the webbrowser via the terminal. https://pypi.org/project/pbs/

Body:
I have a program written with Python 3.7.4 on Windows that opens web pages in a browser.  It displays the default browser and gives the user the chance to change which browser they want to use to open programs with.

The default browser is detected when the program is initialised using this technique:

from winreg import HKEY_CURRENT_USER, OpenKey, QueryValueEx

import webbroswer

reg_path = r'Software\Microsoft\Windows\Shell\Associations\UrlAssociations\https\UserChoice'
chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
firefox_path = 'C:/Program Files (x86)/Mozilla Firefox/firefox.exe %s'

with OpenKey(HKEY_CURRENT_USER, reg_path) as key:
    print(QueryValueEx(key, 'ProgId'))
    thedefaultbrowser = (QueryValueEx(key, 'ProgId'))
    thedefaultbrowser = (thedefaultbrowser[0])
    thedefaultbrowser = (thedefaultbrowser[0:2])
    if thedefaultbrowser == "Fi":
        browser_path = firefox_path
    if thedefaultbrowser == "Ch":
        browser_path = chrome_path

And links are opened like this, as part of an infinite loop that happens later in the program:

while True:

    # [lots of GUI code that isn't relevant]

    event = input()

    if event == 'pleasegetmealinknao':
        x=open("C:/folder/atextfilewithalinkinit.txt", "r")
        the_url1 = x.read()
        webbrowser.get(browser_path).open(the_url1)
        x.close()

In the same loop, input can be accepted from the user to change the browser type:

    elif event == "Firefox":
        browser_path = firefox_path
        continue
    elif event == "Chrome":
        browser_path = chrome_path
        continue

So I can open a webpage with this just fine.  I can then change the browser type just fine, and then open another webpage in the newly user-selected browser, but - only in Windows 10.

In Windows 7, Firefox co-operates beautifully, and so does Chrome but only if Chrome is set as the default browser before the program runs.  However if Firefox is set as the default browser before the program is started, as soon as I switch to Chrome and then try to open anything in Chrome, the program gets very upset and stops running.  No crash, no error message or traceback, it just freezes completely and needs to be hard-restarted.  Sometimes I can rescue the program from its frozen state by closing the new browser window that was just opened, but this of course defeats the purpose of the program.

HOWEVER - if I scrap all this fancy business and just accept whatever the default browser is, like this:

    if event == 'pleasegetmealinknao':
        x=open("C:/folder/atextfilewithalinkinit.txt", "r")
        the_url1 = x.read()
        webbrowser.open(the_url1)
        x.close()

Then the chosen link will open happily in whatever the system default browser is, whether it be Firefox, Chrome, Internet Explorer, or anything else.

So why is this happening and how can I fix?  Or do I just have to bury my dream of selectable browsers?

My guess is that this might have something to do with Chrome detecting that it is not the default browser and asking the user to change the default browser setting, that would make sense.  However then the question is, how do I make the Python program ignore whatever this behaviour is.  A popup related to this doesn't always appear.

EDIT: further testing and sometimes the Windows 7 pattern of behaviour also happens in Windows 10... but seemingly not all the time.  This makes me think even more that it's browser-related rather than strictly OS related and has a lot to do with Chrome asking for default status, but I'm still no closer to working out what to do about it.


问:
How to check whether the object with duplicate LocalDateTime property already exist inside the ObservableArray?
I wrote a method addAppointmentSaveButtonClicked that creates an object like this:

```<code>        Appointment newAppointment = new Appointment(appointmentId, chosenCustomerId, appointmentType, startDateTime, endDateTime, customerName);
</code>```

Then it adds that object to observableArrayList like this:

```<code>        MainScreenController.appointmentDisplayList.add(newAppointment);
</code>```

Now when I want to create a new Appointment or Edit existing one, I want to check whether there is already one with the same starting time in appointmentDisplayList array.

StartDateTime is LocalDateTime variable that is chosen from a combobox menu and always formatted like this:2020-02-15 10:30:00 in 30 minute intervals and there is no problems with milliseconds or anything like that.

What I have done so far:

I created following method that iterates through appointmentDisplayList like this:

```<code>    public static boolean existingAppointment(LocalDateTime ldt) {
    for (Appointment app : appointmentDisplayList) {
        if (app.getStart() == ldt) {
            System.out.println("True");
            return true;
        }
    }
    System.out.println("False");
    return false;
}
</code>```

Then whenever save button is clicked, I put in object creation code inside the IF code block like this:

```<code>if(!existingAppointment(startDateTime)) {
        AppointmentMethods.addAppointment(appointmentType, chosenCustomerId, utcStartTime, utcEndTime);
        appointmentId = AppointmentMethods.getAppointment(chosenCustomerId, utcStartTime).getAppointmentId();

        Appointment newAppointment = new Appointment(appointmentId, chosenCustomerId, appointmentType, startDateTime, endDateTime, customerName);
        MainScreenController.appointmentDisplayList.add(newAppointment);}
</code>```

Now the problem I am having with my code is that every single time and date I choose for my new appointent, this if block always comes as false, and duplicate appointments are added to my ArrayList.

I hope any experienced coder can help me figure out what I am doing wrong here? Thank you in advance!

答:
For objects, == tests if they are the same object. Assuming it has been set up well, .equals() tests if they have the same value. For a good discussion of setting up .equals, see nice overview of overriding equals, including visualization of this issue

That is why you needed app.getStart().equals(ldt) to compare the date values, to see if both objects represented the same date. app.getStart() == ldt was checking if they were the same object, which is not what you wanted.

Body:
I wrote a method addAppointmentSaveButtonClicked that creates an object like this:

        Appointment newAppointment = new Appointment(appointmentId, chosenCustomerId, appointmentType, startDateTime, endDateTime, customerName);

Then it adds that object to observableArrayList like this:

        MainScreenController.appointmentDisplayList.add(newAppointment);

Now when I want to create a new Appointment or Edit existing one, I want to check whether there is already one with the same starting time in appointmentDisplayList array.

StartDateTime is LocalDateTime variable that is chosen from a combobox menu and always formatted like this:2020-02-15 10:30:00 in 30 minute intervals and there is no problems with milliseconds or anything like that.

What I have done so far:

I created following method that iterates through appointmentDisplayList like this:

    public static boolean existingAppointment(LocalDateTime ldt) {
    for (Appointment app : appointmentDisplayList) {
        if (app.getStart() == ldt) {
            System.out.println("True");
            return true;
        }
    }
    System.out.println("False");
    return false;
}

Then whenever save button is clicked, I put in object creation code inside the IF code block like this:

if(!existingAppointment(startDateTime)) {
        AppointmentMethods.addAppointment(appointmentType, chosenCustomerId, utcStartTime, utcEndTime);
        appointmentId = AppointmentMethods.getAppointment(chosenCustomerId, utcStartTime).getAppointmentId();

        Appointment newAppointment = new Appointment(appointmentId, chosenCustomerId, appointmentType, startDateTime, endDateTime, customerName);
        MainScreenController.appointmentDisplayList.add(newAppointment);}

Now the problem I am having with my code is that every single time and date I choose for my new appointent, this if block always comes as false, and duplicate appointments are added to my ArrayList.

I hope any experienced coder can help me figure out what I am doing wrong here? Thank you in advance!


问:
React TS - How to pass props from a parent component to a deeply nested child
Currently, I have created some different form elements. I'm trying to create them in a diverse way so I can piece them together to create different formats for a form.

Here are a few of my form elements:

```<code>// Field Component
interface IField extends ILabel {}

export const Field: React.FunctionComponent<IField> = props => {
  return (
    <div>
      <Label {...props} />
      {props.children}
    </div>
  );
};

// Label Component
interface ILabel {
  htmlFor: string;
  label: string;
  required?: boolean;
}

export const Label: React.FunctionComponent<ILabel> = props => {
  return (
    <label htmlFor={props.htmlFor}>
      {props.label}
      // Some required icon would go where I've added the <span />.
      {props.required && <span />}
    </label>
  );
};

// Input Wrapper Component
export const InputWrapper: React.FunctionComponent = props => {
  return <div>{props.children}</div>;
};

// Input Component
interface IInput {
  type: string;
  id: string;
  name: string;
  value?: string;
  placeholder?: string;
  required?: boolean;
}

export const Input: React.FunctionComponent<IInput> = props => {
  return (
    <input
      type={props.type}
      id={props.id}
      name={props.name}
      value={props.value}
      placeholder={props.placeholder}
      required={props.required}
    />
  );
};
</code>```

And here's how I implement the component:

```<code><Field htmlFor="name" label="Name:" required>
  <InputWrapper>
    <Input
      id="name"
      type="text"
      name="name"
      placeholder="Enter your name..."
    />
  </InputWrapper>
</Field>
</code>```

I would like to be able to set the required prop on the Field component and it will also get passed down to my Input component, no matter how deeply nested it becomes. How is this possible?

I'm also providing a CodeSandBox demo.

Thanks for any help in advance!

答:
When using props.children and that it is impossible to know the exact hierarchy of the nested components, or that it may vary for different use-cases, it can be hard to try to pass the props from parent to children.

Context provide a way to share data and react on changes, for a tree of components.

Your codesandbox adapted to the explained solution

  https://codesandbox.io/s/react-stackoverflow-60241936-fvkdo

In your case, you would need to create a Context for your Field component to "share" the required field and define a default value.

interface IFieldContext {
  required?: boolean;
}

export const FieldContext = React.createContext<IFieldContext>({
  required: false // default value when the prop is not provided
});
```

<p>Then using <code>FieldContext.Provider</code> in the <code>Field</code> component you can assign the "shared" values for the nested components.</p>

<pre class="lang-js prettyprint-override"><code>export const Field: React.FunctionComponent<IField> = props => {
  return (
    <FieldContext.Provider value={{ required: props.required }}>
      <Label {...props} />
      {props.children}
    </FieldContext.Provider>
  );
};
</code>```

Finally, in the Input component, use FieldContext.Consumer to access the "shared" values and retrieve the required prop assigned on the Field component. You will then be able to remove the required field from the IInput interface since it now comes from the Context and not from props anymore.

interface IInput {
  type: string;
  id: string;
  name: string;
  value?: string;
  placeholder?: string;
}

export const Input: React.FunctionComponent<IInput> = props => {
  return (
    <FieldContext.Consumer>
      {context => (
        <input
          type={props.type}
          id={props.id}
          name={props.name}
          value={props.value}
          placeholder={props.placeholder}
          required={context.required} // access context prop
        />
      )}
    </FieldContext.Consumer>
  );
};
```

<p>And "voila", you can use the <code>required</code> prop on the <code>Field</code> component and it will be applied on your nested <code>Input</code> component, no matter how deep the <code>Input</code> is nested... fancy stuff </p>

<pre class="lang-js prettyprint-override"><code>export const App: React.FunctionComponent = () => {
  return (
    <Field htmlFor="name" label="Name:" required>
      <InputWrapper>
        <Input
          id="name"
          type="text"
          name="name"
          placeholder="Enter your name..."
        />
      </InputWrapper>
    </Field>
  );
};
</code>```

Body:
Currently, I have created some different form elements. I'm trying to create them in a diverse way so I can piece them together to create different formats for a form.

Here are a few of my form elements:

// Field Component
interface IField extends ILabel {}

export const Field: React.FunctionComponent<IField> = props => {
  return (

      {props.children}

  );
};

// Label Component
interface ILabel {
  htmlFor: string;
  label: string;
  required?: boolean;
}

export const Label: React.FunctionComponent<ILabel> = props => {
  return (

      {props.label}
      // Some required icon would go where I've added the .
      {props.required && }

  );
};

// Input Wrapper Component
export const InputWrapper: React.FunctionComponent = props => {
  return
{props.children}
;
};

// Input Component
interface IInput {
  type: string;
  id: string;
  name: string;
  value?: string;
  placeholder?: string;
  required?: boolean;
}

export const Input: React.FunctionComponent<IInput> = props => {
  return (
    <input
      type={props.type}
      id={props.id}
      name={props.name}
      value={props.value}
      placeholder={props.placeholder}
      required={props.required}
    />
  );
};

And here's how I implement the component:

<Field htmlFor="name" label="Name:" required>
  <InputWrapper>
    <Input
      id="name"
      type="text"
      name="name"
      placeholder="Enter your name..."
    />
  </InputWrapper>
</Field>

I would like to be able to set the required prop on the Field component and it will also get passed down to my Input component, no matter how deeply nested it becomes. How is this possible?

I'm also providing a CodeSandBox demo.

Thanks for any help in advance!

Body:
When using props.children and that it is impossible to know the exact hierarchy of the nested components, or that it may vary for different use-cases, it can be hard to try to pass the props from parent to children.

Context provide a way to share data and react on changes, for a tree of components.

Your codesandbox adapted to the explained solution

  https://codesandbox.io/s/react-stackoverflow-60241936-fvkdo

In your case, you would need to create a Context for your Field component to "share" the required field and define a default value.

interface IFieldContext {
  required?: boolean;
}

export const FieldContext = React.createContext<IFieldContext>({
  required: false // default value when the prop is not provided
});

Then using FieldContext.Provider in the Field component you can assign the "shared" values for the nested components.

export const Field: React.FunctionComponent<IField> = props => {
  return (
    <FieldContext.Provider value={{ required: props.required }}>
      <Label {...props} />
      {props.children}
    </FieldContext.Provider>
  );
};

Finally, in the Input component, use FieldContext.Consumer to access the "shared" values and retrieve the required prop assigned on the Field component. You will then be able to remove the required field from the IInput interface since it now comes from the Context and not from props anymore.

interface IInput {
  type: string;
  id: string;
  name: string;
  value?: string;
  placeholder?: string;
}

export const Input: React.FunctionComponent<IInput> = props => {
  return (
    <FieldContext.Consumer>
      {context => (
        <input
          type={props.type}
          id={props.id}
          name={props.name}
          value={props.value}
          placeholder={props.placeholder}
          required={context.required} // access context prop
        />
      )}
    </FieldContext.Consumer>
  );
};

And "voila", you can use the required prop on the Field component and it will be applied on your nested Input component, no matter how deep the Input is nested... fancy stuff

export const App: React.FunctionComponent = () => {
  return (
    <Field htmlFor="name" label="Name:" required>
      <InputWrapper>
        <Input
          id="name"
          type="text"
          name="name"
          placeholder="Enter your name..."
        />
      </InputWrapper>
    </Field>
  );
};


问:
Create a file system corruption on a embedded device
I'm working on a project where we are using a file system (NAND Flash) on our device.

We noteiced that sometimes, when we have a power shut down or we are resseting the software (by debugger).

The file system is corrupted after restart.

Now we try to do several improvements, like adding journaling or garbage collection.

But my main question is now, how could I create a filesystem corruption by my own, to test if the new mechanism is working.

Currently it is very hard to reproduce the failure state and I want to find a clear way to reproduce the failure state.

Has anyone some hints?

答:
I'm going to answer the question you want answered, not the question you asked.

As @Clifford said, what you need in order to test your new mechanism is not to introduce corruption, but rather to introduce a condition similar to a power failure.

How to achieve that depends on how you do your testing and development.

If your filesystem interacts directly with the NAND firmware, and you can't run it against a simulator, you have to go all the way and have your test suit actually automate power outages from software (there are software-controlled switches to do that).

If your filesystem can run on any block device, then you can do the following:

Create a btrfs filesystem on your test machine.

Create a large file on the btrfs filesystem.

mkfs your filesystem on the large file and mount it.

Issue a lot of operations against the mounted filesystem.

While the operations are running, take a btrfs snapshot.

Unmount your filesystem.

Unmount brtfs and mount the snapshot.

Remount your filesystem onto the snapshot of the loopback file.

Test that the filesystem is consistent.

Obviously, it doesn't have to be brtfs, any filesystem with snapshot support will do.


答:
Any particular reason you're not using CSS Grid for this?

Instead of using flexbox, you could simply do:

```<code>display: grid;
grid-template-columns: repeat(3, max-content);
grid-gap: 1em;
</code>```

I've modified your example here: JSFiddle Please see the comments for lines I've modified.

Title: Calc() not working on flexbox width in firefox

Body:
Any particular reason you're not using CSS Grid for this?

Instead of using flexbox, you could simply do:

display: grid;
grid-template-columns: repeat(3, max-content);
grid-gap: 1em;

I've modified your example here: JSFiddle Please see the comments for lines I've modified.


问:
Couldn't understand this SWIFT Fucntion
Hope you are doing well. Would anyone please explain this code to me? I am still not getting how we got 120 here. When the parameters were passed to the function, where was it saved? How did it determine max and min before calculating?

Would be really appreciated if anyone could explain it for me please..

答:
You're getting 120 because you're asking the tuple for the sum value twice. The tuple passed back is (min: Int, max: Int, sum: Int).  In this case, sum is also index number 2 (min is index zero, max is index one). So in this case statistics.sum == statistics.2

If you want to access min or max you can access them using statistics.min or statistics.max respectively.  You can also use statistics.0 or statistics.1 if you prefer (I recommend using the labels though).

Final thought: I would change your initial assignment of max and min inside the function to read as follows:

```<code>guard var max = scores.first, var min = scores.first else {
   return (0, 0, 0)
}
</code>```

This will protect against the user accidentally passing an empty array.

Title: Couldn't understand this SWIFT Fucntion

Body:
You're getting 120 because you're asking the tuple for the sum value twice. The tuple passed back is (min: Int, max: Int, sum: Int).  In this case, sum is also index number 2 (min is index zero, max is index one). So in this case statistics.sum == statistics.2

If you want to access min or max you can access them using statistics.min or statistics.max respectively.  You can also use statistics.0 or statistics.1 if you prefer (I recommend using the labels though).

Final thought: I would change your initial assignment of max and min inside the function to read as follows:

guard var max = scores.first, var min = scores.first else {
   return (0, 0, 0)
}

This will protect against the user accidentally passing an empty array.


问:
Check for IP validity
How do I check the validity of an IP address in a shell script, that is within the range 0.0.0.0 to 255.255.255.255?

答:
Alternate version that still does a thorough validation (meaning that it requires both a properly formatted IP address AND that each quadrant is within the range of allowed values aka 0-255). Works fine on GNU bash 4.4.20 (Linux Mint 19.3); no promises elsewhere but will prolly be fine as long as you have bash 4.

The initial format check regex is borrowed from the shannonman / Mitch Frazier answer above; the rest is my own.

```<code>    function isValidIpAddr() {
        # return code only version
        local ipaddr="$1";
        [[ ! $ipaddr =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]] && return 1;
        for quad in $(echo "${ipaddr//./ }"); do
            (( $quad >= 0 && $quad <= 255 )) && continue;
            return 1;
        done
    }
    function validateIpAddr() {
        # return code + output version
        local ipaddr="$1";
        local errmsg="ERROR: $1 is not a valid IP address";
        [[ ! $ipaddr =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]] && echo "$errmsg" && return 1;
        for quad in $(echo "${ipaddr//./ }"); do
            (( $quad >= 0 && $quad <= 255 )) && continue;
            echo "$errmsg";
            return 1;
        done
        echo "SUCCESS: $1 is a valid IP address";
    }

    $ isValidIpAddr '192.168.0.1'
    $ echo "$?"
    0

    $ isValidIpAddr '192.168.0.256'
    $ echo "$?"
    1

    $ validateIpAddr '12.1.10.191'
    SUCCESS: 12.1.10.191 is a valid IP address

    $ validateIpAddr '1.1.1.127'
    SUCCESS: 1.1.1.127 is a valid IP address

    $ validateIpAddr '1.1.1.1337'
    ERROR: 1.1.1.1337 is not a valid IP address
</code>```

ContentLicense: CC BY-SA 3.0

Title: Check for IP validity

Body:
Alternate version that still does a thorough validation (meaning that it requires both a properly formatted IP address AND that each quadrant is within the range of allowed values aka 0-255). Works fine on GNU bash 4.4.20 (Linux Mint 19.3); no promises elsewhere but will prolly be fine as long as you have bash 4.

The initial format check regex is borrowed from the shannonman / Mitch Frazier answer above; the rest is my own.

    function isValidIpAddr() {
        # return code only version
        local ipaddr="$1";
        [[ ! $ipaddr =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]] && return 1;
        for quad in $(echo "${ipaddr//./ }"); do
            (( $quad >= 0 && $quad <= 255 )) && continue;
            return 1;
        done
    }
    function validateIpAddr() {
        # return code + output version
        local ipaddr="$1";
        local errmsg="ERROR: $1 is not a valid IP address";
        [[ ! $ipaddr =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]] && echo "$errmsg" && return 1;
        for quad in $(echo "${ipaddr//./ }"); do
            (( $quad >= 0 && $quad <= 255 )) && continue;
            echo "$errmsg";
            return 1;
        done
        echo "SUCCESS: $1 is a valid IP address";
    }

    $ isValidIpAddr '192.168.0.1'
    $ echo "$?"
    0

    $ isValidIpAddr '192.168.0.256'
    $ echo "$?"
    1

    $ validateIpAddr '12.1.10.191'
    SUCCESS: 12.1.10.191 is a valid IP address

    $ validateIpAddr '1.1.1.127'
    SUCCESS: 1.1.1.127 is a valid IP address

    $ validateIpAddr '1.1.1.1337'
    ERROR: 1.1.1.1337 is not a valid IP address


问:
Laravel routing for deleting one record
I'm new to Laravel (but not developing) and am following along in the free Laravel 6 from Scratch course at Laracasts. I can't afford to subscribe to Laracasts so I can't ask questions there.

I've been following along as the instructor build an app that listed a bunch of articles, displayed a single article, created and saved a new article, and edited an existing article and saved it back to the database. Now I'm trying to delete an individual record but I can't quite get it right.

On the page where I display a single record, I give the user the option of editing the record or of deleting the record via two separate links. The Edit process works fine: it displays the record, allows me to change it (assuming I pass the validations), and then saves it to the database correctly.

The delete process fails. Since I am already displaying the record to the user and have presumably satisfied themselves that it IS the record they want to delete, I want to simply go to the destroy() method of my controller. But I'm obviously doing it wrong. I think the code in the controller is correct so it may be the routes that are messed up. The course doesn't show you how to do a delete and of the videos and stack overflow articles I've seen use different techniques, none of which I fully understand. I'm hoping someone can tell me what I'm doing wrong. There can't be more than 1 or 2 lines that are wrong....

Here's the message I get when I click on the Delete button when I am displaying Article #6:

```<code>Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The GET method is not supported for this route. Supported methods: POST.
http://localhost:8000/articles/6/delete
</code>```

Here's my routing:

```<code>Route::get('/articles', 'ArticlesController@index');
Route::post('/articles', 'ArticlesController@store');
Route::get('/articles/create', 'ArticlesController@create');
Route::get('/articles/{article}', 'ArticlesController@show');
Route::get('/articles/{article}/edit', 'ArticlesController@edit');
Route::put('/articles/{article}', 'ArticlesController@update');
Route::post('/articles/{article}/delete', 'ArticlesController@destroy');
</code>```

Here's the page that displays the article and let's the user click Edit or Delete links:

```<code>@extends ('layout');

@section ('content');

<div id="wrapper">
<div id="page" class="container">
    <div id="content">
        <div class="title">
            <h2>{{ $article->title }}</h2>
            <span class="byline">{{ $article->author}}</span></div>
        <p><img src="{{ $article->photopath}}" alt="" class="image image-full" /> </p>
        <p>{{ $article->body }}
        <p><a class="article-link" href="/articles/{{ $article->id }}/edit">Edit This Article</a>
        <a class="article-link" href="/articles/{{ $article->id }}/delete">Delete This Article</a></p>
    </div>
</div>
</div>
@endsection
</code>```

Lastly, here's my ArticlesController:

```<code><?php

namespace App\Http\Controllers;

use App\Article;
use Illuminate\Http\Request;

class ArticlesController extends Controller
{
public function index()
{
    $articles = Article::latest()->paginate(2);
    return view ('articles.index', ['articles' => $articles]);
}

public function show(Article $article)
{
    return view('articles.show', ['article' => $article]);
}

public function create()
{
    return view('articles.create');
}

public function store()
{
    //Stores a NEW article
    Article::create($this->validateArticle());
    return redirect('/articles');
}

public function edit(Article $article)
{
    return view('articles.edit', ['article' => $article]);
}

public function update(Article $article)
{
    //Updates an EXISTING article
    $article->update($this->validateArticle());
    return redirect('/articles/'.$article->id);
}

public function validateArticle()
{
    return request()->validate([
        'title' => ['required', 'min:5', 'max:20'],
        'author' => ['required', 'min:5', 'max:30'],
        'photopath' => ['required', 'min:10', 'max:100'],
        'excerpt' => ['required', 'min:10', 'max:50'],
        'body' => ['required', 'min:50', 'max:500']
    ]);
}

public function delete(Article $article)
{
    return view('articles.delete', ['article' => $article]);
}

public function destroy(Article $article)
{
    $article = Article::find($article->id);
    $article->delete();
    return redirect('/articles');
}
}
</code>```

答:
```<code>        Route::post('/articles/{id}/delete', 'ArticlesController@destroy')->name('article.destroy');

        public function destroy($id)
        {
            $article = Article::find($id);
            $article->delete();
            return redirect('/articles');
        }

<a class="article-link" href="{{ route('article.destroy',$article->id) }}">Delete This Article</a></p>

 <form id="delete-form-{{ $article->id }}" action="{{ route('article.destroy',$article->id) }}" method="POST" style="display: none;">
     @csrf
     @method('DELETE')
 </form>
</code>```

Title: Laravel routing for deleting one record

Body:
I'm new to Laravel (but not developing) and am following along in the free Laravel 6 from Scratch course at Laracasts. I can't afford to subscribe to Laracasts so I can't ask questions there.

I've been following along as the instructor build an app that listed a bunch of articles, displayed a single article, created and saved a new article, and edited an existing article and saved it back to the database. Now I'm trying to delete an individual record but I can't quite get it right.

On the page where I display a single record, I give the user the option of editing the record or of deleting the record via two separate links. The Edit process works fine: it displays the record, allows me to change it (assuming I pass the validations), and then saves it to the database correctly.

The delete process fails. Since I am already displaying the record to the user and have presumably satisfied themselves that it IS the record they want to delete, I want to simply go to the destroy() method of my controller. But I'm obviously doing it wrong. I think the code in the controller is correct so it may be the routes that are messed up. The course doesn't show you how to do a delete and of the videos and stack overflow articles I've seen use different techniques, none of which I fully understand. I'm hoping someone can tell me what I'm doing wrong. There can't be more than 1 or 2 lines that are wrong....

Here's the message I get when I click on the Delete button when I am displaying Article #6:

Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The GET method is not supported for this route. Supported methods: POST.
http://localhost:8000/articles/6/delete

Here's my routing:

Route::get('/articles', 'ArticlesController@index');
Route::post('/articles', 'ArticlesController@store');
Route::get('/articles/create', 'ArticlesController@create');
Route::get('/articles/{article}', 'ArticlesController@show');
Route::get('/articles/{article}/edit', 'ArticlesController@edit');
Route::put('/articles/{article}', 'ArticlesController@update');
Route::post('/articles/{article}/delete', 'ArticlesController@destroy');

Here's the page that displays the article and let's the user click Edit or Delete links:

@extends ('layout');

@section ('content');

{{ $article->title }}

            {{ $article->author}}

photopath}}" alt="" class="image image-full" />

{{ $article->body }}

id }}/edit">Edit This Article
        id }}/delete">Delete This Article

@endsection

Lastly, here's my ArticlesController:

<?php

namespace App\Http\Controllers;

use App\Article;
use Illuminate\Http\Request;

class ArticlesController extends Controller
{
public function index()
{
    $articles = Article::latest()->paginate(2);
    return view ('articles.index', ['articles' => $articles]);
}

public function show(Article $article)
{
    return view('articles.show', ['article' => $article]);
}

public function create()
{
    return view('articles.create');
}

public function store()
{
    //Stores a NEW article
    Article::create($this->validateArticle());
    return redirect('/articles');
}

public function edit(Article $article)
{
    return view('articles.edit', ['article' => $article]);
}

public function update(Article $article)
{
    //Updates an EXISTING article
    $article->update($this->validateArticle());
    return redirect('/articles/'.$article->id);
}

public function validateArticle()
{
    return request()->validate([
        'title' => ['required', 'min:5', 'max:20'],
        'author' => ['required', 'min:5', 'max:30'],
        'photopath' => ['required', 'min:10', 'max:100'],
        'excerpt' => ['required', 'min:10', 'max:50'],
        'body' => ['required', 'min:50', 'max:500']
    ]);
}

public function delete(Article $article)
{
    return view('articles.delete', ['article' => $article]);
}

public function destroy(Article $article)
{
    $article = Article::find($article->id);
    $article->delete();
    return redirect('/articles');
}
}


问:
How can I assign a name to a task in TPL
I'm going to use lots of tasks running on my application. Each bunch of tasks is running for some reason. I would like to name these tasks so when I watch the Parallel Tasks window, I could recognize them easily.

With another point of view, consider I'm using tasks at the framework level to populate a list. A developer that use my framework is also using tasks for her job. If she looks at the Parallel Tasks Window she will find some tasks having no idea about. I want to name tasks so she can distinguish the framework tasks from her tasks.

It would be very convenient if there was such API:

```<code>var task = new Task(action, "Growth calculation task")
</code>```

or maybe:

```<code>var task = Task.Factory.StartNew(action, "Populating the datagrid")
</code>```

or even while working with Parallel.ForEach

```<code>Parallel.ForEach(list, action, "Salary Calculation Task"
</code>```

Is it possible to name a task?

Is it possible to give Parallel.ForEach a naming structure (maybe using a lambda) so it creates tasks with that naming?

Is there such API somewhere that I'm missing?

I've also tried to use an inherited task to override it's ToString(). But unfortunately the Parallel Tasks window doesn't use ToString()!

```<code>class NamedTask : Task
{
    private string TaskName { get; set; }
    public NamedTask(Action action, string taskName):base(action)
    {
        TaskName = taskName;
    }

    public override string ToString()
    {
        return TaskName;
    }
}
</code>```

答:
Thanks to mike's answer I ended up with:

```<code>    public static class ExtensionMethods
    {
        private static readonly ConcurrentDictionary<WeakReference<Task>, object> TaskNames = new ConcurrentDictionary<WeakReference<Task>, object>();

        public static void _Tag(this Task pTask, object pTag)
        {
            if (pTask == null) return;
            var weakReference = ContainsTask(pTask) ?? new WeakReference<Task>(pTask);
            TaskNames[weakReference] = pTag;
        }
        public static void _Name(this Task pTask, string name)
        {
            _Tag(pTask, name);
        }

        public static object _Tag(this Task pTask)
        {
            var weakReference = ContainsTask(pTask);
            if (weakReference == null) return null;
            return TaskNames[weakReference];
        }
        public static object _Name(this Task pTask)
        {
            return (string)_Tag(pTask);
        }

        private static WeakReference<Task> ContainsTask(Task pTask)
        {
            foreach (var kvp in TaskNames.ToList())
            {
                WeakReference<Task> weakReference = kvp.Key;

                if (!weakReference.TryGetTarget(out var taskFromReference))
                {
                    TaskNames.TryRemove(weakReference, out _);
                    //TaskNames.TryRemove(out ); //Keep the dictionary clean.
                    continue;
                }

                if (pTask == taskFromReference)
                {
                    return weakReference;
                }
            }
            return null;
        }
    }
</code>```

It is thread safe now and it also supports a name not just a tag.

Body:
I'm going to use lots of tasks running on my application. Each bunch of tasks is running for some reason. I would like to name these tasks so when I watch the Parallel Tasks window, I could recognize them easily.

With another point of view, consider I'm using tasks at the framework level to populate a list. A developer that use my framework is also using tasks for her job. If she looks at the Parallel Tasks Window she will find some tasks having no idea about. I want to name tasks so she can distinguish the framework tasks from her tasks.

It would be very convenient if there was such API:

var task = new Task(action, "Growth calculation task")

or maybe:

var task = Task.Factory.StartNew(action, "Populating the datagrid")

or even while working with Parallel.ForEach

Parallel.ForEach(list, action, "Salary Calculation Task"

Is it possible to name a task?

Is it possible to give Parallel.ForEach a naming structure (maybe using a lambda) so it creates tasks with that naming?

Is there such API somewhere that I'm missing?

I've also tried to use an inherited task to override it's ToString(). But unfortunately the Parallel Tasks window doesn't use ToString()!

class NamedTask : Task
{
    private string TaskName { get; set; }
    public NamedTask(Action action, string taskName):base(action)
    {
        TaskName = taskName;
    }

    public override string ToString()
    {
        return TaskName;
    }
}

Body:
Thanks to mike's answer I ended up with:

    public static class ExtensionMethods
    {
        private static readonly ConcurrentDictionary<WeakReference<Task>, object> TaskNames = new ConcurrentDictionary<WeakReference<Task>, object>();

        public static void _Tag(this Task pTask, object pTag)
        {
            if (pTask == null) return;
            var weakReference = ContainsTask(pTask) ?? new WeakReference<Task>(pTask);
            TaskNames[weakReference] = pTag;
        }
        public static void _Name(this Task pTask, string name)
        {
            _Tag(pTask, name);
        }

        public static object _Tag(this Task pTask)
        {
            var weakReference = ContainsTask(pTask);
            if (weakReference == null) return null;
            return TaskNames[weakReference];
        }
        public static object _Name(this Task pTask)
        {
            return (string)_Tag(pTask);
        }

        private static WeakReference<Task> ContainsTask(Task pTask)
        {
            foreach (var kvp in TaskNames.ToList())
            {
                WeakReference<Task> weakReference = kvp.Key;

                if (!weakReference.TryGetTarget(out var taskFromReference))
                {
                    TaskNames.TryRemove(weakReference, out _);
                    //TaskNames.TryRemove(out ); //Keep the dictionary clean.
                    continue;
                }

                if (pTask == taskFromReference)
                {
                    return weakReference;
                }
            }
            return null;
        }
    }

It is thread safe now and it also supports a name not just a tag.


问:
Continuous value supplied to discrete scale ggplot2
when I tried to plot a graph of decision boundary in R, I met some problem and it returned a error "Continuous value supplied to discrete scale". I think the problem happened in the scale_colur_manual but I don't know how to fix it. Below is the code attached.</p>

```<code>library(caTools)
set.seed(123)
split = sample.split(df$Purchased,SplitRatio = 0.75)
training_set = subset(df,split==TRUE)
test_set = subset(df,split==FALSE)

# Feature Scaling
training_set[,1:2] = scale(training_set[,1:2])
test_set[,1:2] = scale(test_set[,1:2])

# Fitting logistic regression to the training set
lr = glm(formula = Purchased ~ .,
         family = binomial,
         data = training_set)

 #Predicting the test set results
 prob_pred = predict(lr,type = 'response',newdata = test_set[-3])
 y_pred = ifelse(prob_pred > 0.5, 1, 0)

 #Making the Confusion Matrix
 cm = table(test_set[,3],y_pred)
 cm

 #Visualizing the training set results
 library(ggplot2)

 set = training_set

 X1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)

 X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01)

 grid_set = expand.grid(X1, X2)

 colnames(grid_set) = c('Age', 'EstimatedSalary')

 prob_set = predict(lr, type = 'response', newdata = grid_set)

 y_grid = ifelse(prob_set > 0.5, 1,0)

 ggplot(grid_set) +

       geom_tile(aes(x = Age, y = EstimatedSalary, fill = factor(y_grid)),

       show.legend = F) +

 geom_point(data = set, aes(x = Age, y = EstimatedSalary, color = Purchased),

         show.legend = F) +

 scale_fill_manual(values = c("orange", "springgreen3")) +

 scale_colour_manual(values = c("red3", "green4")) +

 scale_x_continuous(breaks = seq(floor(min(X1)), ceiling(max(X2)), by = 1)) +

 labs(title = "Logistic Regression (Training set)",

      ylab = "Estimated Salary", xlab = "Age")
</code>```

答:
Is your Purchased variable a factor? If not, it has to be. Try this:

```<code>grid_set %>%
   mutate(Purchased=factor(Purchased)) %>%
   ggplot() +
   geom_tile(aes(x = Age, y = EstimatedSalary, fill = factor(y_grid)),
       show.legend = F) + ... # add the rest of your commands.
</code>```

Body:
when I tried to plot a graph of decision boundary in R, I met some problem and it returned a error "Continuous value supplied to discrete scale". I think the problem happened in the scale_colur_manual but I don't know how to fix it. Below is the code attached.

library(caTools)
set.seed(123)
split = sample.split(df$Purchased,SplitRatio = 0.75)
training_set = subset(df,split==TRUE)
test_set = subset(df,split==FALSE)

# Feature Scaling
training_set[,1:2] = scale(training_set[,1:2])
test_set[,1:2] = scale(test_set[,1:2])

# Fitting logistic regression to the training set
lr = glm(formula = Purchased ~ .,
         family = binomial,
         data = training_set)

 #Predicting the test set results
 prob_pred = predict(lr,type = 'response',newdata = test_set[-3])
 y_pred = ifelse(prob_pred > 0.5, 1, 0)

 #Making the Confusion Matrix
 cm = table(test_set[,3],y_pred)
 cm

 #Visualizing the training set results
 library(ggplot2)

 set = training_set

 X1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)

 X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01)

 grid_set = expand.grid(X1, X2)

 colnames(grid_set) = c('Age', 'EstimatedSalary')

 prob_set = predict(lr, type = 'response', newdata = grid_set)

 y_grid = ifelse(prob_set > 0.5, 1,0)

 ggplot(grid_set) +

       geom_tile(aes(x = Age, y = EstimatedSalary, fill = factor(y_grid)),

       show.legend = F) +

 geom_point(data = set, aes(x = Age, y = EstimatedSalary, color = Purchased),

         show.legend = F) +

 scale_fill_manual(values = c("orange", "springgreen3")) +

 scale_colour_manual(values = c("red3", "green4")) +

 scale_x_continuous(breaks = seq(floor(min(X1)), ceiling(max(X2)), by = 1)) +

 labs(title = "Logistic Regression (Training set)",

      ylab = "Estimated Salary", xlab = "Age")

Body:
Is your Purchased variable a factor? If not, it has to be. Try this:

grid_set %>%
   mutate(Purchased=factor(Purchased)) %>%
   ggplot() +
   geom_tile(aes(x = Age, y = EstimatedSalary, fill = factor(y_grid)),
       show.legend = F) + ... # add the rest of your commands.


问:
Two variable in a plot Tradingview

I have two calculation result

```<code>x1 = if ((o1-c1)/c1)*100 > input
    1
</code>```

```<code>x2 = if ((o2-c2)/c2)*100 > input
    2
</code>```

I would like to have a plot with those two variables together like

```<code>plot (x1 & x2)
</code>```

So the result will be 12 or 1 or 2
but I can't find out how to replace the "&" to make it work?

答:
You'll need to swap your conditions in:</p>

```<code>//@version=4
study("")
// c1 = ((o1-c1)/c1)*100
// c2 = ((o2-c2)/c2)*100
c1 = close > open
c2 = close[2] > open[2] and close[1] > open[1]

x1 = c1 ? input(1) : 0
x2 = c2 ? input(2) : 0
x3 = (x2 != 0 ? x1 * 10 : x1) + x2
plot(x1, "x1", linewidth = 1)
plot(x2, "x2", linewidth = 2)
plot(x3, "x3", linewidth = 3)
</code>```

Title: Two variable in a plot Tradingview

Body:
I have two calculation result

x1 = if ((o1-c1)/c1)*100 > input
    1

x2 = if ((o2-c2)/c2)*100 > input
    2

I would like to have a plot with those two variables together like

plot (x1 & x2)

So the result will be 12 or 1 or 2
but I can't find out how to replace the "&" to make it work?

Body:
You'll need to swap your conditions in:

//@version=4
study("")
// c1 = ((o1-c1)/c1)*100
// c2 = ((o2-c2)/c2)*100
c1 = close > open
c2 = close[2] > open[2] and close[1] > open[1]

x1 = c1 ? input(1) : 0
x2 = c2 ? input(2) : 0
x3 = (x2 != 0 ? x1 * 10 : x1) + x2
plot(x1, "x1", linewidth = 1)
plot(x2, "x2", linewidth = 2)
plot(x3, "x3", linewidth = 3)


问:
How to force imagemagick to keep the original colorspace of an image
I have a problem using imagemagicks convert and keeping the colorspace.

I have a JPEG that is just black (this is an edge case). When I run identify on it this is the output:

black.jpg JPEG 1920x1080 1920x1080+0+0 8-bit sRGB 12787B 0.000u 0:00.000

I then add some text to the image:

convert black.jpg -pointsize 50 -fill WHITE -draw "text 100,100 'foobar'" test.jpg

Now running identify on the resulting test image shows:

test.jpg JPEG 1920x1080 1920x1080+0+0 8-bit Gray 256c 11316B 0.000u 0:00.000

I tried to add the -colorspace sRGB option but it did not help at all. No matter what I do, the colorspace is always converted from sRGB to Gray.

How can I tell imagemagick to leave the colorspace as it is in the original image?

ImageMagick 6.9.10-23 Q16 arm 20190101

答:
In Imagemagick, for most formats you can just add -type truecolor. For example:

```<code>convert black.jpg -pointsize 50 -fill WHITE -draw "text 100,100 'foobar'" -type truecolor test.jpg
</code>```

should do what you want.

Note for PNG you need to add PNG24: to preface the output as PNG24:test.png

Body:
In Imagemagick, for most formats you can just add -type truecolor. For example:

convert black.jpg -pointsize 50 -fill WHITE -draw "text 100,100 'foobar'" -type truecolor test.jpg

should do what you want.

Note for PNG you need to add PNG24: to preface the output as PNG24:test.png


问:
how do I display the correct output when no positve numbers are entered
I'm new to coding. Assignment is to calculate the average of all the positive numbers input and exit when a zero is input. If no positive numbers are input display a message average not possible.  </p>

<p>The following is what I have so far. I am stuck on the part about printing out the message "cannot calculate the average" when only a zero or negative numbers are input. </p>

```<code>public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int numbers = 0;
    int sumOfNumbers = 0;
    double averagePositive = 0;
    while (true) {
        System.out.println("Give a number: ");
        int number = Integer.valueOf(scanner.nextLine());
        if (number == 0)
            break;

        if (number > 0)
            sumOfNumbers = number + sumOfNumbers;

        if (number > 0)
            numbers = numbers + 1;

        if (number > 0)
            averagePositive = (double)sumOfNumbers / (double)numbers;
    }
    System.out.println(averagePositive);
}
</code>```

答:
I'd probably do it like this to keep it simple. Also in general, try not to cramp code together. Most formal project demand a certain degree of styling and usually spaces between operators and braces, etc... is required. In the long run it makes the code more readable and easier to maintain.

In your code there was no need to repeat the same if test for number > 0 multiple times, they could have all been bundled together. If the program was bigger and more complex I may have named the variable names with more qualification but for a short program like this, brief names were sufficient for clarity.

continue and break are important keywords to control loop behavior and can be used to increase brevity and clarity.  continue goes back to the top of the loop immediately and break exits the innermost loop immediately. Dividing a double by an int yields a double so I was able to eliminate a cast. And the += operator makes it a little easier to read the line.

Also in Java and C any if() or else clause that contains one line doesn't require braces and unless a program is nested in such a way that adding the braces anyway adds to the clarity, it is often clearer to omit the braces in that case. The if statement illustrates both ways in a single statement.

```<code>import java.util.Scanner;
public class avg
{
    static int count = 0;
    static double sum = 0;

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("\nEnter a sequence of positive numbers (0 to calculate average):\n");

        while (true) {
            System.out.print("Number? ");
            int n = scanner.nextInt();
            if (n < 0) {
                System.out.println("Negative numbers not allowed.");
                continue;
            } else if (n == 0)
                break;

            sum += (double)n;
            ++count;
        }

        System.out.println("Average of " + count + " numbers = " +
            (double)(sum / count) + "\n");

        System.exit(1);
    }
}
</code>```

Sample output:

```
    $ java avg

    Enter a sequence of positive numbers (0 to calculate average)

    Number? 1
    Number? 2
    Number? 3
    Number? 4
    Number? 5
    Number? -6
    Negative numbers not allowed.
    Number? 0

    Average of 5 numbers = 3.0
```

Body:
I'm new to coding. Assignment is to calculate the average of all the positive numbers input and exit when a zero is input. If no positive numbers are input display a message average not possible.

The following is what I have so far. I am stuck on the part about printing out the message "cannot calculate the average" when only a zero or negative numbers are input.

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int numbers = 0;
    int sumOfNumbers = 0;
    double averagePositive = 0;
    while (true) {
        System.out.println("Give a number: ");
        int number = Integer.valueOf(scanner.nextLine());
        if (number == 0)
            break;

        if (number > 0)
            sumOfNumbers = number + sumOfNumbers;

        if (number > 0)
            numbers = numbers + 1;

        if (number > 0)
            averagePositive = (double)sumOfNumbers / (double)numbers;
    }
    System.out.println(averagePositive);
}

Body:
I'd probably do it like this to keep it simple. Also in general, try not to cramp code together. Most formal project demand a certain degree of styling and usually spaces between operators and braces, etc... is required. In the long run it makes the code more readable and easier to maintain.

In your code there was no need to repeat the same if test for number > 0 multiple times, they could have all been bundled together. If the program was bigger and more complex I may have named the variable names with more qualification but for a short program like this, brief names were sufficient for clarity.

continue and break are important keywords to control loop behavior and can be used to increase brevity and clarity.  continue goes back to the top of the loop immediately and break exits the innermost loop immediately. Dividing a double by an int yields a double so I was able to eliminate a cast. And the += operator makes it a little easier to read the line.

Also in Java and C any if() or else clause that contains one line doesn't require braces and unless a program is nested in such a way that adding the braces anyway adds to the clarity, it is often clearer to omit the braces in that case. The if statement illustrates both ways in a single statement.

import java.util.Scanner;
public class avg
{
    static int count = 0;
    static double sum = 0;

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("\nEnter a sequence of positive numbers (0 to calculate average):\n");

        while (true) {
            System.out.print("Number? ");
            int n = scanner.nextInt();
            if (n < 0) {
                System.out.println("Negative numbers not allowed.");
                continue;
            } else if (n == 0)
                break;

            sum += (double)n;
            ++count;
        }

        System.out.println("Average of " + count + " numbers = " +
            (double)(sum / count) + "\n");

        System.exit(1);
    }
}

Sample output:

    $ java avg

    Enter a sequence of positive numbers (0 to calculate average)

    Number? 1
    Number? 2
    Number? 3
    Number? 4
    Number? 5
    Number? -6
    Negative numbers not allowed.
    Number? 0

    Average of 5 numbers = 3.0


问:
What is the trailing x
I noticed that their are a lot of technologies that uses X in their names like Directx and PhysX and X server ... is there a something common? Or is there any reason to choose X?

答:
According to Wikipedia, the X in DirectX 'stands in' for the various Direct APIs - Direct3D, DirectSound, DirectPlay etc.  Seems like a reasonable explanation.

PhysX probably plays on the whole DirectX 'thing' - but I expect it's named as such 'cause it sounds a bit like physics.

X Server serves X.  :p

Title: What is the trailing x


问:
Cannot connect to database because axios is in UI javascript file
I've just deployed a weather API app to Heroku and the whole UI is working fine - the only issue that I have is that I cannot fetch data from the database. I am importing a file named, 'data.js' of dummy data to the 'index.js' file which is node.js and contains my app's server. I've realized that the issue lies in my 'UI' javascript file, 'script.js' because I use, 'localhost:3000' in my axios get call. Below is a photo of what I am describing

How can I make it so that my UI javascript file can contain an axios call using localhost:3000 or process.env?

答:
A few options:

1) If the browser application and API are hosted by the same webserver, you can just use the absolute path of the API endpoint instead of the full URL.

2) You can inspect the hostname of the browser application (window.location.origin) to see if it's being hosted locally or remotely. And depending on the result, you can either set the endpoint to the localhost name or the remote hostname of the API on Heroku.

3) You could also implement specific builds for different environments to substitute the correct values (in your case, for local and production). Webpack, for instance, allows you to map environment variables to your source code, in which case you could use localhost for the development build and the remote hostname in the production build.


问:
How to get the actual URL of a browser copied image in JavaScript
Ok, so when we do a "Copy Image" on a image (not image location) in Firefox for example, the data is copied to the clipboard.  If we paste into an editable
 and output the HTML of that
, we can see that it is the actual URL of the image and not the base64 URL or some object URL.  If we paste that into Paint for example, we get the actual image.  Is the URL embedded somewhere inside the clipboard data?  If so, how would we retrieve it on paste?

Here is the code to call for the paste event:

```<code>let cd = (event.clipboardData || event.originalEvent.clipboardData);

for (item of cd.items) {
    if (item.type.indexOf("image") >= 0) {
            ..... get the URL value ....

        break;
    }
}
</code>```

答:
You can access the markup data through the text/html data type using the getData method of your DataTransfer object.

Then you just need to parse that markup and search for the 's src.

target.onpaste = (e) => {
  const dT = e.clipboardData || window.clipboardData;
  const html = dT.getData('text/html') || "";
  const parsed = new DOMParser().parseFromString(html, 'text/html');
  const img = parsed.querySelector('img');
  if( !img ) { console.warn('no image here'); return; }
  const url = img.src;
  console.log(url);
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#target { border: 1px solid }</code>```

copy this image by right-click + "Copy Image"

Then paste here
```

Body:
Ok, so when we do a "Copy Image" on a image (not image location) in Firefox for example, the data is copied to the clipboard.  If we paste into an editable
 and output the HTML of that
, we can see that it is the actual URL of the image and not the base64 URL or some object URL.  If we paste that into Paint for example, we get the actual image.  Is the URL embedded somewhere inside the clipboard data?  If so, how would we retrieve it on paste?

Here is the code to call for the paste event:

let cd = (event.clipboardData || event.originalEvent.clipboardData);

for (item of cd.items) {
    if (item.type.indexOf("image") >= 0) {
            ..... get the URL value ....

        break;
    }
}

Body:
You can access the markup data through the text/html data type using the getData method of your DataTransfer object.

Then you just need to parse that markup and search for the <img>'s src.

target.onpaste = (e) => {
  const dT = e.clipboardData || window.clipboardData;
  const html = dT.getData('text/html') || "";
  const parsed = new DOMParser().parseFromString(html, 'text/html');
  const img = parsed.querySelector('img');
  if( !img ) { console.warn('no image here'); return; }
  const url = img.src;
  console.log(url);
};

#target { border: 1px solid }

<p><img id="img" src="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon.png">copy this image by right-click + "Copy Image"</p>
<div contenteditable id="target">Then paste here</div>


问:
How do i go to next page of google with sllenium in python
I made this little program but it's not working, basically what I want to do is, I want to scan all page 1 by 1 and if I get my desired website in the page I want to click on it,
but I'm stuck here on the next page

I tried with locating element by Link Text with this command
Next_btn = driver.find_element_by_link_text('Next').click() but nothing is working

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys

# create a new Firefox session
driver = webdriver.Firefox()

# Navigate to the application home page
driver.get("https://www.google.com")

# get the search textbox
search_field = driver.find_element_by_name('q')
search_field.clear()

# enter search keyword and submit
search_field.send_keys("Stranger things")
search_field.submit()

#goint to next page results
Next_btn = driver.find_element_by_xpath('//*[@id="pnnext"]/span[2]')
Next_btn.click()
</code>```

答:
Make Sure to use the WebDriverWait, so that the script will make sure the element is present before performing the operation.

Here is the tested code, which worked as expected.

Imports required:

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

Code:

```<code>url = "https://google.com"
driver.get(url)
# get the search textbox
search_field = driver.find_element_by_name('q')
search_field.clear()

# enter search keyword and submit
search_field.send_keys("Stranger things")
search_field.submit()

Next_Button = WebDriverWait(driver,10).until(EC.presence_of_element_located((By.LINK_TEXT, "Next")))
Next_Button.click()
</code>```

Body:
I made this little program but it's not working, basically what I want to do is, I want to scan all page 1 by 1 and if I get my desired website in the page I want to click on it,
but I'm stuck here on the next page

I tried with locating element by Link Text with this command
Next_btn = driver.find_element_by_link_text('Next').click() but nothing is working

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

# create a new Firefox session
driver = webdriver.Firefox()

# Navigate to the application home page
driver.get("https://www.google.com")

# get the search textbox
search_field = driver.find_element_by_name('q')
search_field.clear()

# enter search keyword and submit
search_field.send_keys("Stranger things")
search_field.submit()

#goint to next page results
Next_btn = driver.find_element_by_xpath('//*[@id="pnnext"]/span[2]')
Next_btn.click()

Body:
Make Sure to use the WebDriverWait, so that the script will make sure the element is present before performing the operation.

Here is the tested code, which worked as expected.

Imports required:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

Code:

url = "https://google.com"
driver.get(url)
# get the search textbox
search_field = driver.find_element_by_name('q')
search_field.clear()

# enter search keyword and submit
search_field.send_keys("Stranger things")
search_field.submit()

Next_Button = WebDriverWait(driver,10).until(EC.presence_of_element_located((By.LINK_TEXT, "Next")))
Next_Button.click()


问:
How do you set an 'active' class in React and CSS?
I have navigation in my React app. However I would like the colour of navigation to change if on that page.

Heres my code Ive added an active className to the items.

```<code>        <Link to='/'>
          <li className='menu-list-item menu-list-logo   active'>Gatsby's</li>
        </Link>
        <Link to='/drink'>
          <li className='menu-list-item active'>Drink</li>
        </Link>
        <Link to='/food'>
          <li className='menu-list-item active'>Food</li>
        </Link>
        <Link to='contact'>
          <li className='menu-list-item active'>Contact</li>
        </Link>
</code>```

The navigation links currently have a background of black. I want the colour to change to lets say red.
P.S I'm using standard CSS for styles.

答:
There is actually a property of activeClassName in NavLink of react router.

It goes like this

```<code>Import { NavLink } from 'react-router-dom`
...

<NavLink exact activeClassName="your_active_css_classname" className="normal_css">Link name </NavLink>
</code>```

Don't forget to add exact. Read more here: https://reacttraining.com/react-router/web/api/NavLink

Body:
I have navigation in my React app. However I would like the colour of navigation to change if on that page.

Heres my code Ive added an active className to the items.

        <Link to='/'>

Gatsby's

        </Link>
        <Link to='/drink'>

Drink

        </Link>
        <Link to='/food'>

Food

        </Link>
        <Link to='contact'>

Contact

        </Link>

The navigation links currently have a background of black. I want the colour to change to lets say red.
P.S I'm using standard CSS for styles.

Body:
There is actually a property of activeClassName in NavLink of react router.

It goes like this

Import { NavLink } from 'react-router-dom`
...

<NavLink exact activeClassName="your_active_css_classname" className="normal_css">Link name </NavLink>

Don't forget to add exact. Read more here: https://reacttraining.com/react-router/web/api/NavLink


问:
Highlight the closing tag of the currently selected opening tag
One thing I'm missing from SublimeText, is it's ability to highlight the currently selected elements closing tag.

For eg,

Because my cursor is in a div, it highlights every occurrence of the word div when it would be so much more useful, to rather highlight the closing div only.

Is this possible?

答:
Had the same problem as OP, and finally found the solution!!

As it turns out, the same issue was only occurring to me when editing .PHP files.

Placing my cursor on any tag will trigger auto highlighting for any occurring tags that matched. See image below:

To turn this behaviour off, add this into your settings.json in VS code:

```<code>"editor.occurrencesHighlight": false,
</code>```

To target specific languages, add this instead:

```<code> "[php]": {
    "editor.occurrencesHighlight": true,
 }
</code>```

Result:

Hope this helps :)

Body:
Had the same problem as OP, and finally found the solution!!

As it turns out, the same issue was only occurring to me when editing .PHP files.

Placing my cursor on any tag will trigger auto highlighting for any occurring tags that matched. See image below:

To turn this behaviour off, add this into your settings.json in VS code:

"editor.occurrencesHighlight": false,

To target specific languages, add this instead:

 "[php]": {
    "editor.occurrencesHighlight": true,
 }

Result:

Hope this helps :)


问:
Nativescript how to write HTML in typescript like document.write()
basically I want to generate a specific number of labels at different row/col positions based on user input but I cannot find anywhere that tells how to write to the .component.html document from the .component.ts document.  I basically want to use something like document.write() but for nativescript.</p>

答:
Use interpolation (denoted by {{...}}) to insert data from component in template:

Component:

```<code>export class AppComponent  {
  name = 'Angular';

  labels = [
    {
      id: '1',
      name: '',
    },
    {
      id: '2',
      name: '',
    },
    {
      id: '3',
      name: '',
    },
  ];

  public onKey(event: any) {
    for (const label of this.labels) {
      label.name = event.target.value;
    }
  }
}
</code>```

Template (HTML):

```<code><div class="divTable">
  <div class="divTableBody">
    <ng-container *ngFor="let label of labels">
      <div class="divTableRow">
        <div class="divTableCell">{{ label.id }}</div>
        <div class="divTableCell">{{ label.name }}</div>
      </div>
    </ng-container>
  </div>
</div>

<p>Type here:</p>
<input (keyup)="onKey($event)">
</code>```

Working example: Stackblitz

Body:
Use interpolation (denoted by {{...}}) to insert data from component in template:

Component:

export class AppComponent  {
  name = 'Angular';

  labels = [
    {
      id: '1',
      name: '',
    },
    {
      id: '2',
      name: '',
    },
    {
      id: '3',
      name: '',
    },
  ];

  public onKey(event: any) {
    for (const label of this.labels) {
      label.name = event.target.value;
    }
  }
}

Template (HTML):

<div class="divTable">
  <div class="divTableBody">
    <ng-container *ngFor="let label of labels">
      <div class="divTableRow">
        <div class="divTableCell">{{ label.id }}</div>
        <div class="divTableCell">{{ label.name }}</div>
      </div>
    </ng-container>
  </div>
</div>

<p>Type here:</p>
<input (keyup)="onKey($event)">

Working example: Stackblitz


问:
How can I define a typemap for SWIG, that converts a reference argument from C++ to C#
I have a C++ library which provides the following enum and function:

```<code>typedef enum en{
  a,
  b
}myEnum;

int myFunction( myEnum &varToSet )
{
  varToSet = 1;
  return 0;
}
</code>```

The function in the C# Wrapper should look something like this:

```<code>public static int myFunction( ref myEnum varToSet )
</code>```

I have tried to get this result by following typemap in the Swig interface file:

```<code>%typemap(cstype) myEnum & "ref myEnum"
%typemap(csin) myEnum & %{ref $csinput%}
</code>```

Swig changed the type from SWIGTYPE_p_myEnum to ref myEnum in Wrapper.cs, but not in WrapperPINVOKE.cs. What am I missing here?

答:
You need to add a typemap for imtype:</p>

```<code>%typemap(imtype) myEnum & "ref myEnum"
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a C++ library which provides the following enum and function:

typedef enum en{
  a,
  b
}myEnum;

int myFunction( myEnum &varToSet )
{
  varToSet = 1;
  return 0;
}

The function in the C# Wrapper should look something like this:

public static int myFunction( ref myEnum varToSet )

I have tried to get this result by following typemap in the Swig interface file:

%typemap(cstype) myEnum & "ref myEnum"
%typemap(csin) myEnum & %{ref $csinput%}

Swig changed the type from SWIGTYPE_p_myEnum to ref myEnum in Wrapper.cs, but not in WrapperPINVOKE.cs. What am I missing here?

Body:
You need to add a typemap for imtype:

%typemap(imtype) myEnum & "ref myEnum"