问:
Pandas Week of the Month Business Day Stock Price Data
My question is different than the following:

Question1: Week of a month pandas
Quesiton2: Week number of the month

The above question deals with assuming 7 days in a week. It attempts to count the number of 7 days week there are. My data is composed of (business days) daily prices and there can be at times missing days of the week because the market was closed for holiday.

My question is how does one find the week of the month given a date. Note I highlighted "given a date" because this process is processed daily so any answers that looks ahead till the end of the month will likely not work.

My attempts has been the look ahead which isn't optimal:

```<code>def is_third_friday(s):
    d = datetime.datetime.strptime(s, '%Y-%m-%d')
    return d.weekday() == 5 and 15 <= d.day <= 21

dow = deepcopy(data['Close'] * np.nan).to_frame()
dow.columns = ['OpexFriday']
dow['next_date'] = pd.Series([str(i.date() + datetime.timedelta(days=1)) for i in dow.index]).values
dow['OpexFriday'] = pd.Series([is_third_friday(str(i)) for i in dow['next_date']]).values
dow['OpexWeek'] = (dow['OpexFriday'] * 1).replace(0, np.nan).fillna(method='bfill', limit=4).replace(np.nan, 0) == True
</code>```

I don't know how to provide some sample data but if  you go to "https://aroussi.com/post/python-yahoo-finance" page and use the authors yfinance package, you will be able to get some price data to work with.

The functions above will find the 3rd week of the month (all True). In addition, it will set the Friday of that week too.

Let me know if you see any problem with the question or if its a duplicate. I have searched a while for a solution.

答:
One way could be to use timedelta to change any date to the next Friday, then check if this following Friday is between 15 and 21.

```<code>from datetime import datetime, timedelta
def OpexWeek (s):
    d = datetime.strptime(s, '%Y-%m-%d')
    day = (d+timedelta(days=(4-d.weekday())%7)).day
    return (day>=15) & (day<=21)
</code>```

then you get

```<code>#for the example the second Friday of June 2020:
OpexWeek('2020-06-12')
False

# the Monday after is True because part of the OpexWeek
OpexWeek('2020-06-15')
True
</code>```

Note: one thing to know is that the Saturday and the Sunday before the OpexWeek are True, but because you said your data is business days, then it should not matter.

The pandas version to use on Series of datetime could be:

```<code>def OpexWeekPd (ser):
    return (ser+pd.to_timedelta((4-ser.dt.weekday)%7, unit='d')).dt.day.between(15,21)
</code>```

With a small example:

```<code>print (
    pd.DataFrame({'date':pd.bdate_range('2020-06-01', '2020-06-30').astype(str)})
      .assign(isOpexWeek=lambda x: x['date'].apply(OpexWeek),
              isIpexWeekPd=lambda x: OpexWeekPd(pd.to_datetime(x['date'])))
    )
          date  isOpexWeek  isIpexWeekPd
0   2020-06-01       False         False
1   2020-06-02       False         False
2   2020-06-03       False         False
3   2020-06-04       False         False
4   2020-06-05       False         False
5   2020-06-08       False         False
6   2020-06-09       False         False
7   2020-06-10       False         False
8   2020-06-11       False         False
9   2020-06-12       False         False
10  2020-06-15        True          True
11  2020-06-16        True          True
12  2020-06-17        True          True
13  2020-06-18        True          True
14  2020-06-19        True          True
15  2020-06-22       False         False
16  2020-06-23       False         False
17  2020-06-24       False         False
18  2020-06-25       False         False
19  2020-06-26       False         False
20  2020-06-29       False         False
21  2020-06-30       False         False
</code>```

Body:
My question is different than the following:

Question1: Week of a month pandas
Quesiton2: Week number of the month

The above question deals with assuming 7 days in a week. It attempts to count the number of 7 days week there are. My data is composed of (business days) daily prices and there can be at times missing days of the week because the market was closed for holiday.

My question is how does one find the week of the month given a date. Note I highlighted "given a date" because this process is processed daily so any answers that looks ahead till the end of the month will likely not work.

My attempts has been the look ahead which isn't optimal:

def is_third_friday(s):
    d = datetime.datetime.strptime(s, '%Y-%m-%d')
    return d.weekday() == 5 and 15 <= d.day <= 21

dow = deepcopy(data['Close'] * np.nan).to_frame()
dow.columns = ['OpexFriday']
dow['next_date'] = pd.Series([str(i.date() + datetime.timedelta(days=1)) for i in dow.index]).values
dow['OpexFriday'] = pd.Series([is_third_friday(str(i)) for i in dow['next_date']]).values
dow['OpexWeek'] = (dow['OpexFriday'] * 1).replace(0, np.nan).fillna(method='bfill', limit=4).replace(np.nan, 0) == True

I don't know how to provide some sample data but if  you go to "https://aroussi.com/post/python-yahoo-finance" page and use the authors yfinance package, you will be able to get some price data to work with.

The functions above will find the 3rd week of the month (all True). In addition, it will set the Friday of that week too.

Let me know if you see any problem with the question or if its a duplicate. I have searched a while for a solution.

Body:
One way could be to use timedelta to change any date to the next Friday, then check if this following Friday is between 15 and 21.

from datetime import datetime, timedelta
def OpexWeek (s):
    d = datetime.strptime(s, '%Y-%m-%d')
    day = (d+timedelta(days=(4-d.weekday())%7)).day
    return (day>=15) & (day<=21)

then you get

#for the example the second Friday of June 2020:
OpexWeek('2020-06-12')
False

# the Monday after is True because part of the OpexWeek
OpexWeek('2020-06-15')
True

Note: one thing to know is that the Saturday and the Sunday before the OpexWeek are True, but because you said your data is business days, then it should not matter.

The pandas version to use on Series of datetime could be:

def OpexWeekPd (ser):
    return (ser+pd.to_timedelta((4-ser.dt.weekday)%7, unit='d')).dt.day.between(15,21)

With a small example:

print (
    pd.DataFrame({'date':pd.bdate_range('2020-06-01', '2020-06-30').astype(str)})
      .assign(isOpexWeek=lambda x: x['date'].apply(OpexWeek),
              isIpexWeekPd=lambda x: OpexWeekPd(pd.to_datetime(x['date'])))
    )
          date  isOpexWeek  isIpexWeekPd
0   2020-06-01       False         False
1   2020-06-02       False         False
2   2020-06-03       False         False
3   2020-06-04       False         False
4   2020-06-05       False         False
5   2020-06-08       False         False
6   2020-06-09       False         False
7   2020-06-10       False         False
8   2020-06-11       False         False
9   2020-06-12       False         False
10  2020-06-15        True          True
11  2020-06-16        True          True
12  2020-06-17        True          True
13  2020-06-18        True          True
14  2020-06-19        True          True
15  2020-06-22       False         False
16  2020-06-23       False         False
17  2020-06-24       False         False
18  2020-06-25       False         False
19  2020-06-26       False         False
20  2020-06-29       False         False
21  2020-06-30       False         False


来源: stackexchange

问:
How to loop over multiple fields in Django template?
I have models that inherit from an abstract model like this:

```<code>class ImprovementAbstraction(models.Model):
    needsImprovement = models.BooleanField()
    hasFallacies = models.BooleanField()
    hasEmotionalDeficiency = models.BooleanField()
    isNecessaryToObtain = models.BooleanField()
    doesAReallyCauseB = models.BooleanField()
    areAllStepsPresent = models.BooleanField()
    isCauseSufficient = models.BooleanField()
    areAllClausesIdentified = models.BooleanField()
    isCausalityCertain = models.BooleanField()
    languageIsEnglish = models.BooleanField()
    isTautologyPresent = models.BooleanField()

    class Meta:
        abstract = True

class Assumption(MainAbstractModel, ImprovementAbstraction):
    need = models.ForeignKey(Need, on_delete=models.SET_NULL, null=True)
    assumption = models.CharField(max_length=500, default="", null=True)

    def __str__(self):
        return self.assumption
</code>```

In the template I would like to display all of the "ToImprovementAbstraction" Model fields associated with the Assumption model. Is there a way to loop over all the fields in the template, something like Assumption.ImprovementAbstractionFields.all() (made up code)?

答:
I use the built-in vars() method for that.

For example, you have an Assumption object:

```<code>assumptionObject = .models.Assumption.objects.get(pk=1)
</code>```

If you use vars() method with that query object like this:

```<code>vars(assumptionObject)
</code>```

it will return a dictionary containing all the field names and values as a Python dictionary.

If you only want the field names you can use it like this:

```<code>vars(assumptionObject).keys()
</code>```

EDIT: I should warn you that, if you use vars() on a query object, the returned dictionary will contain a django.db.models.base.ModelState object stored in a key called _state. If you're going to use the values in a for loop or something, you should put an exception for that.

ContentLicense: CC BY-SA 4.0

Body:
I have models that inherit from an abstract model like this:

class ImprovementAbstraction(models.Model):
    needsImprovement = models.BooleanField()
    hasFallacies = models.BooleanField()
    hasEmotionalDeficiency = models.BooleanField()
    isNecessaryToObtain = models.BooleanField()
    doesAReallyCauseB = models.BooleanField()
    areAllStepsPresent = models.BooleanField()
    isCauseSufficient = models.BooleanField()
    areAllClausesIdentified = models.BooleanField()
    isCausalityCertain = models.BooleanField()
    languageIsEnglish = models.BooleanField()
    isTautologyPresent = models.BooleanField()

    class Meta:
        abstract = True

class Assumption(MainAbstractModel, ImprovementAbstraction):
    need = models.ForeignKey(Need, on_delete=models.SET_NULL, null=True)
    assumption = models.CharField(max_length=500, default="", null=True)

    def __str__(self):
        return self.assumption

In the template I would like to display all of the "ToImprovementAbstraction" Model fields associated with the Assumption model. Is there a way to loop over all the fields in the template, something like Assumption.ImprovementAbstractionFields.all() (made up code)?

Body:
I use the built-in vars() method for that.

For example, you have an Assumption object:

assumptionObject = .models.Assumption.objects.get(pk=1)

If you use vars() method with that query object like this:

vars(assumptionObject)

it will return a dictionary containing all the field names and values as a Python dictionary.

If you only want the field names you can use it like this:

vars(assumptionObject).keys()

EDIT: I should warn you that, if you use vars() on a query object, the returned dictionary will contain a django.db.models.base.ModelState object stored in a key called _state. If you're going to use the values in a for loop or something, you should put an exception for that.


问:
How can I get environment variables from docker compose in Quasar Framework?
I have the next docker-compose configuration

```<code>version: '3'

services:
 frontend:
  image: frontend-image
  depends_on:
   - backend-image
  ports:
    - 8081:8081
  environment:
   - OAUTH_CLIENT="client"
   - OAUTH_CLIENT_KEY="Client111"
   - BACKEND_HOSTNAME="localhost"
   - BACKEND_PORT="8080"
</code>```

This is the frontend-image Dockerfile

```<code>FROM  quasarframework/quasar-org:1.0.0

WORKDIR /opt/app

COPY package.json /opt/app/package.json

RUN rm -r node_modules

RUN npm install

RUN npm -g install quasar-cli

COPY . /opt/app

EXPOSE 4000

EXPOSE 8081

CMD ["quasar", "dev"]
</code>```

But when I execute console.log(process.env) I'm only getting one property:

```<code>{NODE_ENV:"development"}
</code>```

Everything on the front end is working OK, my unique problem is with environment variables.
My objective is to set different environment variables for different environments.

Docker version

```<code>Client:
 Version:       17.12.0-ce
 API version:   1.35
 Go version:    go1.9.2
 Git commit:    c97c6d6
 Built: Wed Dec 27 20:11:19 2017
 OS/Arch:       linux/amd64

Server:
 Engine:
  Version:      17.12.0-ce
  API version:  1.35 (minimum version 1.12)
  Go version:   go1.9.2
  Git commit:   c97c6d6
  Built:        Wed Dec 27 20:09:53 2017
  OS/Arch:      linux/amd64
  Experimental: false
</code>```

Docker Compose Version

```<code>docker-compose version 1.18.0, build 8dd22a9
docker-py version: 2.6.1
CPython version: 2.7.13
OpenSSL version: OpenSSL 1.0.1t  3 May 2016
</code>```

答:
Quasar lets you pass custom environment variables through build.env property of quasar.conf.js.

Quasar App CLI v2+

{
    // ...
    build: {
        env: {
            OAUTH_CLIENT: process.env.OAUTH_CLIENT,
            OAUTH_CLIENT_KEY: process.env.OAUTH_CLIENT_KEY),
            BACKEND_HOSTNAME: process.env.BACKEND_HOSTNAME,
            BACKEND_PORT: parseInt(process.env.BACKEND_PORT),
        }
    }
}

```
<p>You now will be able to use your env variables inside your quasar application:</p>
<pre class="lang-js prettyprint-override"><code>console.log(process.env.APP_OAUTH_CLIENT);
// note, that
console.log(process.env);
// won't work as you might expect
</code>```

Quasar App CLI before v2

You can be as simple as:

{
    // ...
    build: {
        env: {
            OAUTH_CLIENT: JSON.stringify(process.env.OAUTH_CLIENT),
            OAUTH_CLIENT_KEY: JSON.stringify(process.env.OAUTH_CLIENT_KEY),
            BACKEND_HOSTNAME: JSON.stringify(process.env.BACKEND_HOSTNAME),
            BACKEND_PORT: process.env.BACKEND_PORT, // this will be integer at runtime!
        }
    }
}

```
<p>Or pass everything in bulk:</p>
<pre class="lang-js prettyprint-override"><code>{
    // ...
    build: {
        env: Object.fromEntries(Object.entries(process.env)
            /* Filter variables which you want to pass to quasar, for example only pass variables starting with APP_ */
            .filter(([ key, value ]) => /^APP_/.test(key))
            /* Enquote strings so that they remain strings when inlined to source code by quasar */
            .map(([ key, value ]) => [ key, JSON.stringify(value) ])
        )
    }
}
</code>```

You now will be able to use your env variables inside your quasar application:

console.log(process.env);
console.log(process.env.APP_OAUTH_CLIENT);
```
<p>A couple of notes, though</p>
<p>First, it is strongly advised to filter variables passed down to your quasar application, i.e. meaning to <strong>public scope</strong>.</p>
<p>vue-cli does a similar thing by default:</p>
<blockquote>
<p>Note that only <code>NODE_ENV</code>, <code>BASE_URL</code>, and variables that start with <code>VUE_APP_</code> will be statically embedded into the client bundle ... (from vue-cli guide).</p>
</blockquote>
<p>Quasar doesn't embed anything out of the box, but let you have full control over what and how to embed using it's <code>build.env</code> config property.</p>
<p>Second, note that when you pass <code>{ BACKEND_HOSTNAME: "localhost" }</code> variable and then use it like <code>var h = process.env.BACKEND_HOSTNAME;</code> quasar statically <strong>replaces</strong> it with <code>localhost</code> <strong>as is</strong>, not trying to somehow serialize the value, so it evaluates to <code>var h = localhost</code>, which is not a valid JS and you will probably receive a syntax error. Instead, if you want to be on a safe side, I'd recommend to serialize all env values to strings with <code>JSON.stringify</code> when passing to quasar config, so that <code>var h = process.env.BACKEND_HOSTNAME;</code> becomes <code>var h = "localhost"</code>.</p>
<p>I also find it useful to define a dedicated module to deal with env variables:</p>
<pre class="lang-js prettyprint-override"><code>export default {
    oauthClient: process.env.OAUTH_CLIENT,
    oauthClientKey: process.env.OAUTH_CLIENT_KEY,
    backendHostname: process.env.BACKEND_HOSTNAME,
    backendPort: process.env.BACKEND_PORT,
    debug: process.env.DEBUG === 'true'
}
</code>```

This way all your environment imports have a single entrance point.
Note however, that it doesn't provide code stripping:

import myenv from './myenv';
if (myenv.debug) {
    console.log('We are debugging something');
}
```

this code never will be stripped out. To use code stripping, you have to use process.env.DEBUG === "true" notation, so it is replaced as "false" === "true" by quasar and later stripped out with code bundlers as an unreachable code block.

ContentLicense: CC BY-SA 3.0

Body:
I have the next docker-compose configuration

version: '3'

services:
 frontend:
  image: frontend-image
  depends_on:
   - backend-image
  ports:
    - 8081:8081
  environment:
   - OAUTH_CLIENT="client"
   - OAUTH_CLIENT_KEY="Client111"
   - BACKEND_HOSTNAME="localhost"
   - BACKEND_PORT="8080"

This is the frontend-image Dockerfile

FROM  quasarframework/quasar-org:1.0.0

WORKDIR /opt/app

COPY package.json /opt/app/package.json

RUN rm -r node_modules

RUN npm install

RUN npm -g install quasar-cli

COPY . /opt/app

EXPOSE 4000

EXPOSE 8081

CMD ["quasar", "dev"]

But when I execute console.log(process.env) I'm only getting one property:

{NODE_ENV:"development"}

Everything on the front end is working OK, my unique problem is with environment variables.
My objective is to set different environment variables for different environments.

Docker version

Client:
 Version:       17.12.0-ce
 API version:   1.35
 Go version:    go1.9.2
 Git commit:    c97c6d6
 Built: Wed Dec 27 20:11:19 2017
 OS/Arch:       linux/amd64

Server:
 Engine:
  Version:      17.12.0-ce
  API version:  1.35 (minimum version 1.12)
  Go version:   go1.9.2
  Git commit:   c97c6d6
  Built:        Wed Dec 27 20:09:53 2017
  OS/Arch:      linux/amd64
  Experimental: false

Docker Compose Version

docker-compose version 1.18.0, build 8dd22a9
docker-py version: 2.6.1
CPython version: 2.7.13
OpenSSL version: OpenSSL 1.0.1t  3 May 2016

Body:
Quasar lets you pass custom environment variables through build.env property of quasar.conf.js.

Quasar App CLI v2+

{
    // ...
    build: {
        env: {
            OAUTH_CLIENT: process.env.OAUTH_CLIENT,
            OAUTH_CLIENT_KEY: process.env.OAUTH_CLIENT_KEY),
            BACKEND_HOSTNAME: process.env.BACKEND_HOSTNAME,
            BACKEND_PORT: parseInt(process.env.BACKEND_PORT),
        }
    }
}

You now will be able to use your env variables inside your quasar application:

console.log(process.env.APP_OAUTH_CLIENT);
// note, that
console.log(process.env);
// won't work as you might expect

Quasar App CLI before v2

You can be as simple as:

{
    // ...
    build: {
        env: {
            OAUTH_CLIENT: JSON.stringify(process.env.OAUTH_CLIENT),
            OAUTH_CLIENT_KEY: JSON.stringify(process.env.OAUTH_CLIENT_KEY),
            BACKEND_HOSTNAME: JSON.stringify(process.env.BACKEND_HOSTNAME),
            BACKEND_PORT: process.env.BACKEND_PORT, // this will be integer at runtime!
        }
    }
}

Or pass everything in bulk:

{
    // ...
    build: {
        env: Object.fromEntries(Object.entries(process.env)
            /* Filter variables which you want to pass to quasar, for example only pass variables starting with APP_ */
            .filter(([ key, value ]) => /^APP_/.test(key))
            /* Enquote strings so that they remain strings when inlined to source code by quasar */
            .map(([ key, value ]) => [ key, JSON.stringify(value) ])
        )
    }
}

You now will be able to use your env variables inside your quasar application:

console.log(process.env);
console.log(process.env.APP_OAUTH_CLIENT);

A couple of notes, though

First, it is strongly advised to filter variables passed down to your quasar application, i.e. meaning to public scope.

vue-cli does a similar thing by default:

Note that only NODE_ENV, BASE_URL, and variables that start with VUE_APP_ will be statically embedded into the client bundle ... (from vue-cli guide).

Quasar doesn't embed anything out of the box, but let you have full control over what and how to embed using it's build.env config property.

Second, note that when you pass { BACKEND_HOSTNAME: "localhost" } variable and then use it like var h = process.env.BACKEND_HOSTNAME; quasar statically replaces it with localhost as is, not trying to somehow serialize the value, so it evaluates to var h = localhost, which is not a valid JS and you will probably receive a syntax error. Instead, if you want to be on a safe side, I'd recommend to serialize all env values to strings with JSON.stringify when passing to quasar config, so that var h = process.env.BACKEND_HOSTNAME; becomes var h = "localhost".

I also find it useful to define a dedicated module to deal with env variables:

export default {
    oauthClient: process.env.OAUTH_CLIENT,
    oauthClientKey: process.env.OAUTH_CLIENT_KEY,
    backendHostname: process.env.BACKEND_HOSTNAME,
    backendPort: process.env.BACKEND_PORT,
    debug: process.env.DEBUG === 'true'
}

This way all your environment imports have a single entrance point.
Note however, that it doesn't provide code stripping:

import myenv from './myenv';
if (myenv.debug) {
    console.log('We are debugging something');
}

this code never will be stripped out. To use code stripping, you have to use process.env.DEBUG === "true" notation, so it is replaced as "false" === "true" by quasar and later stripped out with code bundlers as an unreachable code block.


问:
Select only one checkbox from multiple checkbox columns in questionnaire style DataGridView
I've create an application which displays a DataGridView with a series of questions.
The dgv structure consists of one string column for the question text and three bool/checkbox columns for the answers (yes, no, N/A).
Each single question is displayed on its own row.

I would like my program to only allow the user to select only Yes, only No or only N/A on each row.

I think I would need to uncheck the other checkbox options when one option is checked but I'm not too sure on how to do this.

I've setup CellValueChanged and CellContentClick events but I'm unsure of the code needed to achieve the desired functionality.

DataGridView is bound to a DataTable.

Code I have so far:

```<code>private void dgvQuestions_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    int columnIndex = e.ColumnIndex;
    int rowIndex = e.RowIndex;

    DataGridViewCheckBoxCell chkYes = dgvQuestions.Rows[rowIndex].Cells[2] as DataGridViewCheckBoxCell;
    DataGridViewCheckBoxCell chkNo = dgvQuestions.Rows[rowIndex].Cells[3] as DataGridViewCheckBoxCell;
    DataGridViewCheckBoxCell chkNA = dgvQuestions.Rows[rowIndex].Cells[4] as DataGridViewCheckBoxCell;

    if (Convert.ToBoolean(chkYes.Value) == true)
    {

    }

    if (Convert.ToBoolean(chkNo.Value) == true)
    {

    }

    if (Convert.ToBoolean(chkNA.Value) == true)
    {

    }
}

private void dgvQuestions_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    dgvQuestions.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
</code>```

答:
I hope this sample is useful for making DataGridView simple and powerful; it relates to the post as originally worded which was "Any help appreciated".

Does this video show the behavior that you're looking for? What works for me is to use a BindingList as the DataSource of the DataGridView. Then, using the 'CellDirty' event that occurs when a checkbox changes you can make them act like one-hot radio buttons and answer your question: "select only one checkbox from multiple checkbox items".

Here's an example of a class representing one line item of the questionaire.

```<code>class QuestionaireItem
{
    public string Question { get; internal set; } = "Question " + _count++;
    public bool Yes { get; set; }
    public bool No { get; set; }
    public bool Maybe { get; set; } // OOPS! I should have said "NA"

    static int _count = 1;
}
</code>```

When you bind this class to a DataGridView the columns will be automatically populated with a column named 'Question' (which is read-only (because the 'set' is marked internal) and the three checkbox columns whose value can be changed (because both get and set are public).
Taking this approach works for any class T and does nearly all the heavy lifting of using DataGridView.

Here's how you handle the CellDirty event to make the three checkboxes (I named them Yes, No and Maybe) act like radio buttons:

```<code>private void DataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
    // The cell will be considered "dirty" or modified so Commit first.
    dataGridView1.EndEdit(DataGridViewDataErrorContexts.Commit);
    // Get the QuestionaireItem that is bound to the row
    QuestionaireItem item = (QuestionaireItem)
        dataGridView1
        .Rows[dataGridView1.CurrentCell.RowIndex]
        .DataBoundItem;
    // Now see which column changed:
    switch (dataGridView1.Columns[dataGridView1.CurrentCell.ColumnIndex].Name)
    {
        case "Yes":
            item.No = false;        // i.e. "unchecked"
            item.Maybe = false;
            break;
        case "No":
            item.Yes = false;
            item.Maybe = false;
            break;
        case "Maybe":
            item.Yes = false;
            item.No = false;
            break;
    }
    dataGridView1.Refresh();    // Update the binding list to the display
}
</code>```

The binding itself is simple to do once the MainForm has its window Handle. We can override OnHandleCreated for this purpose. Here, the binding process will work properly and we can also set the display widths for the columns. This shows how to initialize dataGridView1. I've put comments in to explain what's happening:

```<code>protected override void OnHandleCreated(EventArgs e)
{
    base.OnHandleCreated(e);
    if (!DesignMode)    // We only want this behavior at runtime
    {
        // Create the binding list
        BindingList<QuestionaireItem> testdata = new BindingList<QuestionaireItem>();
        // And add 5 example items to it
        for (int i = 0; i < 5; i++) testdata.Add(new QuestionaireItem());
        // Now make this list the DataSource of the DGV.
        dataGridView1.DataSource = testdata;

        // This just formats the column widths a little bit
        dataGridView1.Columns["Question"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        dataGridView1.Columns["Maybe"].Width =
        dataGridView1.Columns["Yes"].Width =
        dataGridView1.Columns["No"].Width = 40;

        // And this subscribes to the event (one of them anyway...)
        // that will fire when the checkbox is changed
        dataGridView1.CurrentCellDirtyStateChanged += DataGridView1_CurrentCellDirtyStateChanged;
    }
}
</code>```

Clone or Download this example from GitHub.

Body:
I've create an application which displays a DataGridView with a series of questions.
The dgv structure consists of one string column for the question text and three bool/checkbox columns for the answers (yes, no, N/A).
Each single question is displayed on its own row.

I would like my program to only allow the user to select only Yes, only No or only N/A on each row.

I think I would need to uncheck the other checkbox options when one option is checked but I'm not too sure on how to do this.

I've setup CellValueChanged and CellContentClick events but I'm unsure of the code needed to achieve the desired functionality.

DataGridView is bound to a DataTable.

Code I have so far:

private void dgvQuestions_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    int columnIndex = e.ColumnIndex;
    int rowIndex = e.RowIndex;

    DataGridViewCheckBoxCell chkYes = dgvQuestions.Rows[rowIndex].Cells[2] as DataGridViewCheckBoxCell;
    DataGridViewCheckBoxCell chkNo = dgvQuestions.Rows[rowIndex].Cells[3] as DataGridViewCheckBoxCell;
    DataGridViewCheckBoxCell chkNA = dgvQuestions.Rows[rowIndex].Cells[4] as DataGridViewCheckBoxCell;

    if (Convert.ToBoolean(chkYes.Value) == true)
    {

    }

    if (Convert.ToBoolean(chkNo.Value) == true)
    {

    }

    if (Convert.ToBoolean(chkNA.Value) == true)
    {

    }
}

private void dgvQuestions_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    dgvQuestions.CommitEdit(DataGridViewDataErrorContexts.Commit);
}

Body:
I hope this sample is useful for making DataGridView simple and powerful; it relates to the post as originally worded which was "Any help appreciated".

Does this video show the behavior that you're looking for? What works for me is to use a BindingList as the DataSource of the DataGridView. Then, using the 'CellDirty' event that occurs when a checkbox changes you can make them act like one-hot radio buttons and answer your question: "select only one checkbox from multiple checkbox items".

Here's an example of a class representing one line item of the questionaire.

class QuestionaireItem
{
    public string Question { get; internal set; } = "Question " + _count++;
    public bool Yes { get; set; }
    public bool No { get; set; }
    public bool Maybe { get; set; } // OOPS! I should have said "NA"

    static int _count = 1;
}

When you bind this class to a DataGridView the columns will be automatically populated with a column named 'Question' (which is read-only (because the 'set' is marked internal) and the three checkbox columns whose value can be changed (because both get and set are public).
Taking this approach works for any class T and does nearly all the heavy lifting of using DataGridView.

Here's how you handle the CellDirty event to make the three checkboxes (I named them Yes, No and Maybe) act like radio buttons:

private void DataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
    // The cell will be considered "dirty" or modified so Commit first.
    dataGridView1.EndEdit(DataGridViewDataErrorContexts.Commit);
    // Get the QuestionaireItem that is bound to the row
    QuestionaireItem item = (QuestionaireItem)
        dataGridView1
        .Rows[dataGridView1.CurrentCell.RowIndex]
        .DataBoundItem;
    // Now see which column changed:
    switch (dataGridView1.Columns[dataGridView1.CurrentCell.ColumnIndex].Name)
    {
        case "Yes":
            item.No = false;        // i.e. "unchecked"
            item.Maybe = false;
            break;
        case "No":
            item.Yes = false;
            item.Maybe = false;
            break;
        case "Maybe":
            item.Yes = false;
            item.No = false;
            break;
    }
    dataGridView1.Refresh();    // Update the binding list to the display
}

The binding itself is simple to do once the MainForm has its window Handle. We can override OnHandleCreated for this purpose. Here, the binding process will work properly and we can also set the display widths for the columns. This shows how to initialize dataGridView1. I've put comments in to explain what's happening:

protected override void OnHandleCreated(EventArgs e)
{
    base.OnHandleCreated(e);
    if (!DesignMode)    // We only want this behavior at runtime
    {
        // Create the binding list
        BindingList<QuestionaireItem> testdata = new BindingList<QuestionaireItem>();
        // And add 5 example items to it
        for (int i = 0; i < 5; i++) testdata.Add(new QuestionaireItem());
        // Now make this list the DataSource of the DGV.
        dataGridView1.DataSource = testdata;

        // This just formats the column widths a little bit
        dataGridView1.Columns["Question"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        dataGridView1.Columns["Maybe"].Width =
        dataGridView1.Columns["Yes"].Width =
        dataGridView1.Columns["No"].Width = 40;

        // And this subscribes to the event (one of them anyway...)
        // that will fire when the checkbox is changed
        dataGridView1.CurrentCellDirtyStateChanged += DataGridView1_CurrentCellDirtyStateChanged;
    }
}

Clone or Download this example from GitHub.


问:
Get response from a webview in android
I am using a payment gateway(Voguepay) where the request URL generates a response URL I want to redirect to that URL in webview

my code for the webview

```<code>    @SuppressLint("SetJavaScriptEnabled")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webveiw);
        mWebView = findViewById(R.id.activity_main_webview);
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        mWebView.setWebViewClient(new MyWebViewClient());

        // REMOTE RESOURCE
         mWebView.loadUrl("https://voguepay.com/?p=linkToken&v_merchant_id=demo&\n" +
                 " memo=Payment for laptop&total=1000&merchant_ref=ref123&\n" +
                 " notify_url=https://example.com/notification.php&\n" +
                 " success_url=https://example.com/success.php&\n" +
                 " fail_url=https://example.com/fail.php&developer_code=ddd&cur=NGN");
}
</code>```

the request URL loads successfully and display this

I want to redirect the webview to load the link in the image above

答:
If I have understood your problem correctly you could use this code :</p>

```<code>webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url){
    // do your handling codes here, which url is the requested url
    // probably you need to open that url rather than redirect:
    view.loadUrl(url);
    return false; // then it is not handled by default action
}
});
</code>```

Title: Get response from a webview in android

Body:
I am using a payment gateway(Voguepay) where the request URL generates a response URL I want to redirect to that URL in webview

my code for the webview

    @SuppressLint("SetJavaScriptEnabled")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webveiw);
        mWebView = findViewById(R.id.activity_main_webview);
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        mWebView.setWebViewClient(new MyWebViewClient());

        // REMOTE RESOURCE
         mWebView.loadUrl("https://voguepay.com/?p=linkToken&v_merchant_id=demo&\n" +
                 " memo=Payment for laptop&total=1000&merchant_ref=ref123&\n" +
                 " notify_url=https://example.com/notification.php&\n" +
                 " success_url=https://example.com/success.php&\n" +
                 " fail_url=https://example.com/fail.php&developer_code=ddd&cur=NGN");
}

the request URL loads successfully and display this

I want to redirect the webview to load the link in the image above

Body:
If I have understood your problem correctly you could use this code :

webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url){
    // do your handling codes here, which url is the requested url
    // probably you need to open that url rather than redirect:
    view.loadUrl(url);
    return false; // then it is not handled by default action
}
});


问:
Making jQuery slideUp when clicking off
I am using jQuery to make a nav slideDown. I want when people click anywhere outside of the nav it slideUp.

The problem is that with my code it slideUp even if I click on the element. I basically want it to slideUp if the user clicks anywhere other than the element which slideDown

```<code> //News Drop Down
$(document).ready(function () {
$('li.newsDrop').mouseenter(function () {
    $('div.newsadviceDrop').slideDown('medium');
});
});

$('body').click(function() {
    $('div.newsadviceDrop').slideUp('slow', function() {
    // Animation complete.
   });
});
</code>```

答:
```<code>$(':not([attr="value"])').click(function() {
$('div.newsadviceDrop').slideUp('slow', function() {
// Animation complete.
</code>```

});

in not your li element..so the other elements besides your li would be selected

Title: Making jQuery slideUp when clicking off

Body:
I am using jQuery to make a nav slideDown. I want when people click anywhere outside of the nav it slideUp.

The problem is that with my code it slideUp even if I click on the element. I basically want it to slideUp if the user clicks anywhere other than the element which slideDown

 //News Drop Down
$(document).ready(function () {
$('li.newsDrop').mouseenter(function () {
    $('div.newsadviceDrop').slideDown('medium');
});
});

$('body').click(function() {
    $('div.newsadviceDrop').slideUp('slow', function() {
    // Animation complete.
   });
});

Body:
$(':not([attr="value"])').click(function() {
$('div.newsadviceDrop').slideUp('slow', function() {
// Animation complete.

});

in not your li element..so the other elements besides your li would be selected


问:
How to remove red base glyph from my oh-my-posh/posh-git display?
I'm using windows terminal v1.0.1402.0 with powershell v7.0.1 with oh-my-posh and posh-git. I'm currently getting the following red base glyph when I open up my terminal.

I've installed and tried using MesloLGL NF and Cascadia Mono PL for the fonts which both should work with oh-my-posh.

Here is my powershell profile:

```<code>Import-Module posh-git
Import-Module oh-my-posh
Set-Theme Paradox
</code>```

Here is my windows terminal settings

```<code> "defaults":
        {
            "colorScheme":  "One Half Dark",
            //"fontFace": "MesloLGL NF"
            "fontFace": "Cascadia Mono PL"
            // Put settings here that you want to apply to all profiles.
        },
        "list":
        [
            {
                // Make changes here to the powershell.exe profile
                "guid": "{61c54bbd-c2c6-5271-96e7-009a87ff44bf}",
                "name": "Windows PowerShell",
                "commandline": "pwsh.exe",
                "useAcrylic": true,
                "acrylicOpacity": 0.8,
                "hidden": false
            },
</code>```

I get this error regardless of what directory I'm in.

If it helps, here are my theme settings too: (Side note: The error count just went to 1, when I printed this before it was still 0)

```<code>PromptSymbols        : {SegmentBackwardSymbol, RootSymbol, PromptIndicator, VirtualEnvSymbol...}
CurrentHostname      : MyHost
MyThemesLocation     : C:\MyPath\PowerShell\PoshThemes
CurrentThemeLocation : C:\MyPath\PowerShell\Modules\oh-my-posh\2.0.412\Themes\Paradox.psm1
GitSymbols           : {BeforeIndexSymbol, LocalStagedStatusSymbol, DelimSymbol, BranchUntrackedSymbol...¦}
Options              : {ConsoleTitle, OriginSymbols}
ErrorCount           : 1
CurrentUser          : user
Colors               : {GitForegroundColor, GitDefaultColor, PromptForegroundColor, VirtualEnvBackgroundColor...¦}
</code>```

答:
I was able to fix this by referencing this https://superuser.com/q/1424905/1183235 question. I listed all my powershell profiles, saw one that initialized conda and removed it. Now it works!

To list all powershell profiles:

```<code>$PROFILE | Format-List -Force
</code>```

Body:
I'm using windows terminal v1.0.1402.0 with powershell v7.0.1 with oh-my-posh and posh-git. I'm currently getting the following red base glyph when I open up my terminal.

I've installed and tried using MesloLGL NF and Cascadia Mono PL for the fonts which both should work with oh-my-posh.

Here is my powershell profile:

Import-Module posh-git
Import-Module oh-my-posh
Set-Theme Paradox

Here is my windows terminal settings

 "defaults":
        {
            "colorScheme":  "One Half Dark",
            //"fontFace": "MesloLGL NF"
            "fontFace": "Cascadia Mono PL"
            // Put settings here that you want to apply to all profiles.
        },
        "list":
        [
            {
                // Make changes here to the powershell.exe profile
                "guid": "{61c54bbd-c2c6-5271-96e7-009a87ff44bf}",
                "name": "Windows PowerShell",
                "commandline": "pwsh.exe",
                "useAcrylic": true,
                "acrylicOpacity": 0.8,
                "hidden": false
            },

I get this error regardless of what directory I'm in.

If it helps, here are my theme settings too: (Side note: The error count just went to 1, when I printed this before it was still 0)

PromptSymbols        : {SegmentBackwardSymbol, RootSymbol, PromptIndicator, VirtualEnvSymbol...}
CurrentHostname      : MyHost
MyThemesLocation     : C:\MyPath\PowerShell\PoshThemes
CurrentThemeLocation : C:\MyPath\PowerShell\Modules\oh-my-posh\2.0.412\Themes\Paradox.psm1
GitSymbols           : {BeforeIndexSymbol, LocalStagedStatusSymbol, DelimSymbol, BranchUntrackedSymbol...¦}
Options              : {ConsoleTitle, OriginSymbols}
ErrorCount           : 1
CurrentUser          : user
Colors               : {GitForegroundColor, GitDefaultColor, PromptForegroundColor, VirtualEnvBackgroundColor...¦}

Body:
I was able to fix this by referencing this https://superuser.com/q/1424905/1183235 question. I listed all my powershell profiles, saw one that initialized conda and removed it. Now it works!

To list all powershell profiles:

$PROFILE | Format-List -Force


问:
Why HashMap is not good for a big dataset of integer keys?
I've a non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.

For example, in array A such that below:

```<code>A[0] = 9 , A[1] = 3 , A[2] = 9 , A[3] = 3 , A[4] = 9 , A[5] = 7 , A[6] = 9
</code>```

I need to write a functon that returns the value of the unpaired element.

One of my first native solutions was to create a hashmap structure with unique keys - N integers of given array and iterate through the array adding values if the key is already exists in the hashmap. After all the key that has only 1 at it's value field is the unpaired element.

I know that the hashcode of Integer is it's int unique value...
So I soposed that there will not be a duplicate keys of different Integers..So I supposed that there will not be a duplicate keys for different Integers..But for a big sets of data this solution does not work...I think this has something to do with load factor.
But I can't get on it. I don't need an alterntive solution, becouse I have it already, I just want to understand what's wrong with hashmap when we use a big sets of integer keys..
Here is my code and thank you very much!:
Map a = new HashMap();

```<code>       for(int i=0;i<A.length;i++) {

           if(a.containsKey(A[i])){
               a.put(A[i], a.get(A[i])+1);
           }else  a.put(A[i], 1);

       }

       for (Integer i : a.keySet()) {
              if(a.get(i)==1)
                  return i;
            }

       return -1;
</code>```

enter image description here

答:
I think this has something to do with load factor.

No, the problem is not in the HashMap, it's in the way you are using it.

Your solution is not complete because it assumes all the pairs are unique. i.e. it assumes there can be at most one pair of 9 (which is not true in the example you posted, which contains 2 pairs of 9).

Having multiple identical pairs will not necessarily result in a wrong answer, but what
if, for example, there are 3 9's, two of them are paired, but the 3rd is not? Your solution won't find it, since a.get(9) would return 3, but you check if it's equal to 1.

Instead of checking

```<code>if(a.get(i)==1)
</code>```

you should check if it's odd

```<code>if(a.get(i)%2==1)
</code>```

Body:
I've a non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.

For example, in array A such that below:

A[0] = 9 , A[1] = 3 , A[2] = 9 , A[3] = 3 , A[4] = 9 , A[5] = 7 , A[6] = 9

I need to write a functon that returns the value of the unpaired element.

One of my first native solutions was to create a hashmap structure with unique keys - N integers of given array and iterate through the array adding values if the key is already exists in the hashmap. After all the key that has only 1 at it's value field is the unpaired element.

I know that the hashcode of Integer is it's int unique value...
So I soposed that there will not be a duplicate keys of different Integers..So I supposed that there will not be a duplicate keys for different Integers..But for a big sets of data this solution does not work...I think this has something to do with load factor.
But I can't get on it. I don't need an alterntive solution, becouse I have it already, I just want to understand what's wrong with hashmap when we use a big sets of integer keys..
Here is my code and thank you very much!:
Map a = new HashMap();

       for(int i=0;i<A.length;i++) {

           if(a.containsKey(A[i])){
               a.put(A[i], a.get(A[i])+1);
           }else  a.put(A[i], 1);

       }

       for (Integer i : a.keySet()) {
              if(a.get(i)==1)
                  return i;
            }

       return -1;

enter image description here

Body:
I think this has something to do with load factor.

No, the problem is not in the HashMap, it's in the way you are using it.

Your solution is not complete because it assumes all the pairs are unique. i.e. it assumes there can be at most one pair of 9 (which is not true in the example you posted, which contains 2 pairs of 9).

Having multiple identical pairs will not necessarily result in a wrong answer, but what
if, for example, there are 3 9's, two of them are paired, but the 3rd is not? Your solution won't find it, since a.get(9) would return 3, but you check if it's equal to 1.

Instead of checking

if(a.get(i)==1)

you should check if it's odd

if(a.get(i)%2==1)


问:
Truncate multiple one line text elements
I want to truncate multiple text elements.

The text in the red and green box have both variable lenghts. The blue box with some UI-Elements has a fixed length of 200px.

If you resize the browser window, the blue box is shifted left and at FIRST the text in the green box should be truncated. If there isn't any more to truncate in the green box, then the text in the red box should be truncated.

I have tried it with display:flex but then the green box has some space on left to the red box, but the green box should be close to the red box - as shown in my snippet. Annotation: As explained above > the text in red/green box is variable > they havn't a fixed width.

(At the moment the blue box is shifted downside - I wasn't also able to fix this.)

            Text with High Priority

            Text with Low Priority

            <button type="submit" name="action" value="1">test</button>

```

答:
You can do this with flexbox by giving the low priority element a big flex-shrink factor

.box {
  display: flex;
  border: 1px solid black;
}

.high,
.low{
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  border: 1px solid red;
  min-width:20px;
}

.low {
  flex-shrink:9999;
  border: 1px solid green;
}

.button {
  margin-left:auto;
  min-width: 200px;
  border: 1px solid blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">
  <div class="high">
    Text with High Priority
  </div>
  <div class="low">
    Text with Low Priority
  </div>
  <div class="button">
    <button type="submit" name="action" value="1">test</button>
  </div>
</div></code>```

Body:
You can do this with flexbox by giving the low priority element a big flex-shrink factor

.box {
  display: flex;
  border: 1px solid black;
}

.high,
.low{
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  border: 1px solid red;
  min-width:20px;
}

.low {
  flex-shrink:9999;
  border: 1px solid green;
}

.button {
  margin-left:auto;
  min-width: 200px;
  border: 1px solid blue;
}

<div class="box">
  <div class="high">
    Text with High Priority
  </div>
  <div class="low">
    Text with Low Priority
  </div>
  <div class="button">
    <button type="submit" name="action" value="1">test</button>
  </div>
</div>


问:
When connecting to Grafana I get an error 502
I use the SimpleJson plugin to connect.
But I get error 502 (PHOTO)

I add CORS in my startup file:

```<code>app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
</code>```

And I create endpoints for GET (/) and POSTS (/query, /annotations, /search) as written in the documentation in GitHub docs:

```<code>using System.Net.Http;
using System.Text;
using Microsoft.AspNetCore.Mvc;

namespace Grafana
{
    [ApiController]
    public class BugsMonitoringController : ControllerBase
    {

        [HttpGet]
        [Route("/")]
        public void Empty()
        {
        }

        [HttpPost]
        [Route("query")]
        public HttpResponseMessage Query()
        {
            return new HttpResponseMessage()
            {
                Content = new StringContent("[{\"columns\":[{\"text\":\"Time\",\"type\":\"time\"},{\"text\":\"Country\",\"type\":\"string\"},{\"text\":\"Number\",\"type\":\"number\"}],\"rows\":[[1234567,\"SE\",182],[1234567,\"DE\",282],[1234567,\"US\",382]],\"type\":\"table\"}]", Encoding.UTF8, "application/json")
            };
        }

        [HttpPost]
        [Route("search")]
        public HttpResponseMessage Search()
        {
            return new HttpResponseMessage()
            {
                Content = new StringContent("[ { \"text\" :\"upper_25\", \"value\": 1}, { \"text\" :\"upper_75\", \"value\": 2} ]", Encoding.UTF8, "application/json")
            };
        }

        [HttpPost]
        [Route("annotations")]
        public HttpResponseMessage Annotation()
        {
            return new HttpResponseMessage()
            {
                Content = new StringContent("[{\"text\":\"text shown in body\",\"title\":\"Annotation Title\",\"isRegion\":true,\"time\":\"timestamp\",\"timeEnd\":\"timestamp\",\"tags\":[\"tag1\"]}]", Encoding.UTF8, "application/json")
            };
        }

    }
</code>```

Indicated server address in DataSource (PHOTO)

答:
I solved this problem
When I wrote URL in JSON plugin I used localhost:5000. Need to use your local address, for example: 192.168.1.10. And change "applicationUrl" in launchSettings.json</p>

Body:
I use the SimpleJson plugin to connect.
But I get error 502 (PHOTO)

I add CORS in my startup file:

app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());

And I create endpoints for GET (/) and POSTS (/query, /annotations, /search) as written in the documentation in GitHub docs:

using System.Net.Http;
using System.Text;
using Microsoft.AspNetCore.Mvc;

namespace Grafana
{
    [ApiController]
    public class BugsMonitoringController : ControllerBase
    {

        [HttpGet]
        [Route("/")]
        public void Empty()
        {
        }

        [HttpPost]
        [Route("query")]
        public HttpResponseMessage Query()
        {
            return new HttpResponseMessage()
            {
                Content = new StringContent("[{\"columns\":[{\"text\":\"Time\",\"type\":\"time\"},{\"text\":\"Country\",\"type\":\"string\"},{\"text\":\"Number\",\"type\":\"number\"}],\"rows\":[[1234567,\"SE\",182],[1234567,\"DE\",282],[1234567,\"US\",382]],\"type\":\"table\"}]", Encoding.UTF8, "application/json")
            };
        }

        [HttpPost]
        [Route("search")]
        public HttpResponseMessage Search()
        {
            return new HttpResponseMessage()
            {
                Content = new StringContent("[ { \"text\" :\"upper_25\", \"value\": 1}, { \"text\" :\"upper_75\", \"value\": 2} ]", Encoding.UTF8, "application/json")
            };
        }

        [HttpPost]
        [Route("annotations")]
        public HttpResponseMessage Annotation()
        {
            return new HttpResponseMessage()
            {
                Content = new StringContent("[{\"text\":\"text shown in body\",\"title\":\"Annotation Title\",\"isRegion\":true,\"time\":\"timestamp\",\"timeEnd\":\"timestamp\",\"tags\":[\"tag1\"]}]", Encoding.UTF8, "application/json")
            };
        }

    }

Indicated server address in DataSource (PHOTO)


问:
What's the correct way to pass token with git clone using PyPi?
I am using PyPi to clone a github repository, however it a private repo. So I also need to authorise it with my token. I am unable to find any example of how to pass token with the clone request.

```<code>import git
git.Git('/local/file/path').clone('git@github.com:sample-repo.git', token=(mytoken))
</code>```

This gives an error

"GitCommandError: Cmd('git') failed due to: exit code(129)"
cmdline: git clone --token=mytoken git@github.com:sample-repo.git
stderr: 'error: unknown option token=mytoken'

It works fine without the token when I try to clone a public repository. So the only issue here is how to pass the token to the above request. Is that possible or is there any other way to authorise git clone in a python script? My objective here is to automate a process to clone a github repository, generate some files using some API calls, add and commit those files to the repository, all within the same python script.

答:
Thanks to the comments, I was able to clone my repository using the https url instead of the ssh url and it worked without the need for token.</p>

```<code>import git
git.Git('/local/file/path').clone('https://github.com/sample-repo')
</code>```

Body:
I am using PyPi to clone a github repository, however it a private repo. So I also need to authorise it with my token. I am unable to find any example of how to pass token with the clone request.

import git
git.Git('/local/file/path').clone('git@github.com:sample-repo.git', token=(mytoken))

This gives an error

"GitCommandError: Cmd('git') failed due to: exit code(129)"
cmdline: git clone --token=mytoken git@github.com:sample-repo.git
stderr: 'error: unknown option token=mytoken'

It works fine without the token when I try to clone a public repository. So the only issue here is how to pass the token to the above request. Is that possible or is there any other way to authorise git clone in a python script? My objective here is to automate a process to clone a github repository, generate some files using some API calls, add and commit those files to the repository, all within the same python script.

Body:
Thanks to the comments, I was able to clone my repository using the https url instead of the ssh url and it worked without the need for token.

import git
git.Git('/local/file/path').clone('https://github.com/sample-repo')


问:
How to solve an equation y=ax^2+bx+c when x is unknown and y known
I have this equation:

y = -0.00248793*x^2+20.77173764*x-371.01805798

And I would like to obtain the result of the equation when I give "y" numbers,

edited explanation 2/06/20:
I want to add a vector as my "y", and receive an output of one vector also.

This problem is a biological one, in which I performed citokine bead array (CBA) and I stablished a reference curve which is sinusoidal.

after stablishing the degree of the equation making the following:

```<code>fitil6_1=lm(Standards$`IL6 median`~poly(concentration,1,raw=TRUE))
fitil6_2=lm(Standards$`IL6 median`~poly(concentration,2,raw=TRUE))
fitil6_3=lm(Standards$`IL6 median`~poly(concentration,3,raw=TRUE))
fitil6_4=lm(Standards$`IL6 median`~poly(concentration,4,raw=TRUE))

lines(concentration,predict(fitil6_1,data.frame(x=concentration)),col="red")
lines(concentration,predict(fitil6_2,data.frame(x=concentration)),col="green")
lines(concentration,predict(fitil6_3,data.frame(x=concentration)),col="blue")
lines(concentration,predict(fitil6_4,data.frame(x=concentration)),col="purple)
legend(20,40000,legend=c("de grau 1","de grau 2","de grau 3","de grau 4"),lty=1,col=c("red","green","blue","purple"))
</code>```

I have chosen the degree 2 formula as it fits better to my dots for this cytokine (and most cytokines in this study)

So when I make

```<code>coef(fitil6_2)

 (Intercept)        poly(concentration, 2, raw = TRUE)1  poly(concentration, 2, raw = TRUE)2
-8.262381e+02                              2.371377e+01                       -2.847135e-03
</code>```

I receive that output and then I am able to build the formula (in this case):

y=-2.847135e-03 *x^2+2.371377e+01*x-8.262381e+02

but as my independent value is what I know is pretty difficult to isolate x!
(end of the editing)

I have tried many things like making function(x,y) but when you specify this you need to give a number of y, so really I am litlle bit lost!

Thank you

答:
Thank you for all who answered I have just started in this page, this worked for me:

isolating "y" and then making a function with the quadratic formula to x:

```<code>   delta<-function(y,a,b,c)
   {k=(-b+sqrt(b^2-4*a*(c-y)))/(2*a)
   print(k)
   }

delta(citoquines_valero$`IFNg median`,-1.957128e-03,1.665741e+01,-7.522327e+02)

#I will use that one as a provisional solution.
#I have also been told to use this, but is not working properly:

result <- function(y,a,b,c){
  # Constructing delta
  delta<-function(y,a,b,c){
    b^2-4*a*(c-y)
  }
  if(delta(a,b,d) > 0){ # first case D>0
    x_1 = (-b+sqrt(delta(y,a,b,c)))/(2*a)
    x_2 = (-b-sqrt(delta(y,a,b,c)))/(2*a)
    if (x_1 >= 0) {
      print(x_1)
      else if (x_2 >= 0){
        print(x_2)
      }
    }
    print(result)
    else if(delta(a,b,d) == 0){ # second case D=0
      x = -b/(2*a); return(x)
    }
    else {"There are no real roots."}; # third case D<0```
    return("There are no real roots.")
  }
}
```

Body:
I have this equation:

y = -0.00248793*x^2+20.77173764*x-371.01805798

And I would like to obtain the result of the equation when I give "y" numbers,

edited explanation 2/06/20:
I want to add a vector as my "y", and receive an output of one vector also.

This problem is a biological one, in which I performed citokine bead array (CBA) and I stablished a reference curve which is sinusoidal.

after stablishing the degree of the equation making the following:

fitil6_1=lm(Standards$`IL6 median`~poly(concentration,1,raw=TRUE))
fitil6_2=lm(Standards$`IL6 median`~poly(concentration,2,raw=TRUE))
fitil6_3=lm(Standards$`IL6 median`~poly(concentration,3,raw=TRUE))
fitil6_4=lm(Standards$`IL6 median`~poly(concentration,4,raw=TRUE))

lines(concentration,predict(fitil6_1,data.frame(x=concentration)),col="red")
lines(concentration,predict(fitil6_2,data.frame(x=concentration)),col="green")
lines(concentration,predict(fitil6_3,data.frame(x=concentration)),col="blue")
lines(concentration,predict(fitil6_4,data.frame(x=concentration)),col="purple)
legend(20,40000,legend=c("de grau 1","de grau 2","de grau 3","de grau 4"),lty=1,col=c("red","green","blue","purple"))

I have chosen the degree 2 formula as it fits better to my dots for this cytokine (and most cytokines in this study)

So when I make

coef(fitil6_2)

 (Intercept)        poly(concentration, 2, raw = TRUE)1  poly(concentration, 2, raw = TRUE)2
-8.262381e+02                              2.371377e+01                       -2.847135e-03

I receive that output and then I am able to build the formula (in this case):

y=-2.847135e-03 *x^2+2.371377e+01*x-8.262381e+02

but as my independent value is what I know is pretty difficult to isolate x!
(end of the editing)

I have tried many things like making function(x,y) but when you specify this you need to give a number of y, so really I am litlle bit lost!

Thank you

Body:
Thank you for all who answered I have just started in this page, this worked for me:

isolating "y" and then making a function with the quadratic formula to x:

   delta<-function(y,a,b,c)
   {k=(-b+sqrt(b^2-4*a*(c-y)))/(2*a)
   print(k)
   }

delta(citoquines_valero$`IFNg median`,-1.957128e-03,1.665741e+01,-7.522327e+02)

#I will use that one as a provisional solution.
#I have also been told to use this, but is not working properly:

result <- function(y,a,b,c){
  # Constructing delta
  delta<-function(y,a,b,c){
    b^2-4*a*(c-y)
  }
  if(delta(a,b,d) > 0){ # first case D>0
    x_1 = (-b+sqrt(delta(y,a,b,c)))/(2*a)
    x_2 = (-b-sqrt(delta(y,a,b,c)))/(2*a)
    if (x_1 >= 0) {
      print(x_1)
      else if (x_2 >= 0){
        print(x_2)
      }
    }
    print(result)
    else if(delta(a,b,d) == 0){ # second case D=0
      x = -b/(2*a); return(x)
    }
    else {"There are no real roots."}; # third case D<0```
    return("There are no real roots.")
  }
}


问:
Take data from List<class> and put it in to String object
I'm making an java simple app for better code learning that combine some gui on intellji.

I already have a main page and I'm just trying to make a popup Table That have all the data on my product this is my tableView CODE:

```<code>public class ProductTable extends JFrame
{
    private Model.product product;
    private List<product> list;

    public ProductTable() {
        list = product.ProductList();

        // headers for the table
        String[] columns = {"Product Name",
                "Quantity",
                "Expiration day",
                "Need fridge"};
        Object[][] data = new Object[][] {
        };

        // create table with data
        JTable table = new JTable(data, columns);

        // add the table to the frame
        this.add(new JScrollPane(table));
        this.setTitle("ProductList");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.pack();
        this.setVisible(true);
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new ProductTable();
            }
        });
    }
}
</code>```

In the Product class I have:

```<code>product.name = String
product.quantity = int
Product.Expiration_day = String
product.fridge = boolean
</code>```

I want to load into the String Object

```<code>Data={ {product.name, product.quantity, Product.Expiration_day, Product.fridge} ,{.....,....,....,...}{..............}};
</code>```

till i put in all off my data now i know how to know the size but i need load it one by one into the data object please can anyone guide through it?!

My Product code:

```<code>package Model;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class product
{
    private String product_name;
    private Integer product_quantity;
    private String experation_day;
    private boolean fridge = false;
    private boolean matched= false;
    private Connection connection;

    public product()
    {
        this.product_name = "";
        this.product_quantity = 0;
        this.experation_day = "";
    }

    public product(String product_name, Integer product_quantity, String experation_day) {
        this.product_name = product_name;
        this.product_quantity = product_quantity;
        this.experation_day = experation_day;
    }

    public Integer getProduct_quantity() {
        return product_quantity;
    }

    public String getExperation_day() {
        return experation_day;
    }

    public String getProduct_name()
    {
        return product_name;
    }

    public void setProduct_quantity(Integer product_quantity) {
        this.product_quantity = product_quantity;
    }

    public void setExperation_day(String experation_day) {
        this.experation_day = experation_day;
    }

    public void setProduct_name(String product_name)
    {
        this.product_name = product_name;
    }

    public List<product> ProductList() {

        String windownsUserName = System.getProperty("user.name");
        try
        {
            System.out.println("Connecting to a selected database...");
            Connection connection = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\"+windownsUserName+"\\IdeaProjects\\Software-engineer-final-project\\untitled\\src\\DButills\\account.db");
            System.out.println("Connected database successfully...");
            String sqlQuery = "SELECT product_name, product_amount, product_expration_date FROM products";
            PreparedStatement ps = connection.prepareStatement(sqlQuery);
            ResultSet rs = ps.executeQuery();
            {

            }
            List<product> products = new ArrayList<>();
            while (rs.next()) {
                product product = new product();
                product.setProduct_quantity(rs.getInt("product_amount"));
                product.setProduct_name(rs.getString("product_name"));
                product.setExperation_day(rs.getString("product_expration_date"));
                products.add(product);
            }
            return products;

        } catch (SQLException e) {
            System.out.println("Query failed: " + e.getMessage());
            return null;
        }
    }
}
</code>```

答:
Why do you need String? According to code you provided - what you need is an array Object[][], but filled with values, so simply loop over your product list and fill your data in correct order.

EDIT:

Look at this pseudocode, it should look somehow like this:

```<code>   String[] columns = {"Product Name",
            "Quantity",
            "Expiration day",
            "Need fridge"};
   Object[][] data = new Object[list.size()][columns.length];
   int columnCounter = 0;
   for(Product product : list) {
       data[columnCounter][0] = product.getName();
       data[columnCounter][1] = product.getQuantity();
       data[columnCounter][2] = product.getExpDay();
       data[columnCounter][3] = product.getNeedFridge();
       columnCounter++;
   }
</code>```

Body:
I'm making an java simple app for better code learning that combine some gui on intellji.

I already have a main page and I'm just trying to make a popup Table That have all the data on my product this is my tableView CODE:

public class ProductTable extends JFrame
{
    private Model.product product;
    private List<product> list;

    public ProductTable() {
        list = product.ProductList();

        // headers for the table
        String[] columns = {"Product Name",
                "Quantity",
                "Expiration day",
                "Need fridge"};
        Object[][] data = new Object[][] {
        };

        // create table with data
        JTable table = new JTable(data, columns);

        // add the table to the frame
        this.add(new JScrollPane(table));
        this.setTitle("ProductList");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.pack();
        this.setVisible(true);
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new ProductTable();
            }
        });
    }
}

In the Product class I have:

product.name = String
product.quantity = int
Product.Expiration_day = String
product.fridge = boolean

I want to load into the String Object

Data={ {product.name, product.quantity, Product.Expiration_day, Product.fridge} ,{.....,....,....,...}{..............}};

till i put in all off my data now i know how to know the size but i need load it one by one into the data object please can anyone guide through it?!

My Product code:

package Model;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class product
{
    private String product_name;
    private Integer product_quantity;
    private String experation_day;
    private boolean fridge = false;
    private boolean matched= false;
    private Connection connection;

    public product()
    {
        this.product_name = "";
        this.product_quantity = 0;
        this.experation_day = "";
    }

    public product(String product_name, Integer product_quantity, String experation_day) {
        this.product_name = product_name;
        this.product_quantity = product_quantity;
        this.experation_day = experation_day;
    }

    public Integer getProduct_quantity() {
        return product_quantity;
    }

    public String getExperation_day() {
        return experation_day;
    }

    public String getProduct_name()
    {
        return product_name;
    }

    public void setProduct_quantity(Integer product_quantity) {
        this.product_quantity = product_quantity;
    }

    public void setExperation_day(String experation_day) {
        this.experation_day = experation_day;
    }

    public void setProduct_name(String product_name)
    {
        this.product_name = product_name;
    }

    public List<product> ProductList() {

        String windownsUserName = System.getProperty("user.name");
        try
        {
            System.out.println("Connecting to a selected database...");
            Connection connection = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\"+windownsUserName+"\\IdeaProjects\\Software-engineer-final-project\\untitled\\src\\DButills\\account.db");
            System.out.println("Connected database successfully...");
            String sqlQuery = "SELECT product_name, product_amount, product_expration_date FROM products";
            PreparedStatement ps = connection.prepareStatement(sqlQuery);
            ResultSet rs = ps.executeQuery();
            {

            }
            List<product> products = new ArrayList<>();
            while (rs.next()) {
                product product = new product();
                product.setProduct_quantity(rs.getInt("product_amount"));
                product.setProduct_name(rs.getString("product_name"));
                product.setExperation_day(rs.getString("product_expration_date"));
                products.add(product);
            }
            return products;

        } catch (SQLException e) {
            System.out.println("Query failed: " + e.getMessage());
            return null;
        }
    }
}

Body:
Why do you need String? According to code you provided - what you need is an array Object[][], but filled with values, so simply loop over your product list and fill your data in correct order.

EDIT:

Look at this pseudocode, it should look somehow like this:

   String[] columns = {"Product Name",
            "Quantity",
            "Expiration day",
            "Need fridge"};
   Object[][] data = new Object[list.size()][columns.length];
   int columnCounter = 0;
   for(Product product : list) {
       data[columnCounter][0] = product.getName();
       data[columnCounter][1] = product.getQuantity();
       data[columnCounter][2] = product.getExpDay();
       data[columnCounter][3] = product.getNeedFridge();
       columnCounter++;
   }


问:
Redux dispatching actions in a specific order
previously i asked a question on how to force a dispatch to complete before doing an action , however i did not really come to a resolution to my problem. redux problem .

It would seem that wrapping dispatch in a promise does nothing as the promise would be resolved once the dispatch is made , not necessarily reduced as mentioned by in one of the comments .

Here is my code:

```<code>export const selectObjectTransition = (transition) => {
  return dispatch => {
    dispatch({
      type: IS_DONE,
      isDone: false
      })
    dispatch(loadObjectTransitionApprovals(transition.id));
    dispatch(loadObjectTransitionHooks(transition.id));
    dispatch({
      type: SELECT_TRANSITION,
      selected_transition: transition,
    });
    dispatch({
      type: IS_DONE,
      isDone: true
      })
    }
}
</code>```

basically , what i wish to achieve is that the dispatch be carried out and completed in the following order (top to bottm) . Right now , it would occasionally break and complete the dispatch in different orders , resulting in an error at my front end .

My redux dev tool :

```<code>IS_DONE -> SELECT_TRANSITION -> IS_DONE -> ......
</code>```

Whereas the 2nd IS_DONE action is supposed to be carried out the last

答:
Besides my comments above, you can also try this </p>

```<code>export const toDispatch = () =>{
  return dispatch =>{
    axios.get(url).then(()=>{
     dispatch(functionToDispatch())
    })
  }
}
</code>```

Body:
previously i asked a question on how to force a dispatch to complete before doing an action , however i did not really come to a resolution to my problem. redux problem .

It would seem that wrapping dispatch in a promise does nothing as the promise would be resolved once the dispatch is made , not necessarily reduced as mentioned by in one of the comments .

Here is my code:

export const selectObjectTransition = (transition) => {
  return dispatch => {
    dispatch({
      type: IS_DONE,
      isDone: false
      })
    dispatch(loadObjectTransitionApprovals(transition.id));
    dispatch(loadObjectTransitionHooks(transition.id));
    dispatch({
      type: SELECT_TRANSITION,
      selected_transition: transition,
    });
    dispatch({
      type: IS_DONE,
      isDone: true
      })
    }
}

basically , what i wish to achieve is that the dispatch be carried out and completed in the following order (top to bottm) . Right now , it would occasionally break and complete the dispatch in different orders , resulting in an error at my front end .

My redux dev tool :

IS_DONE -> SELECT_TRANSITION -> IS_DONE -> ......

Whereas the 2nd IS_DONE action is supposed to be carried out the last

Body:
Besides my comments above, you can also try this

export const toDispatch = () =>{
  return dispatch =>{
    axios.get(url).then(()=>{
     dispatch(functionToDispatch())
    })
  }
}


问:
Retrieve IE proxy username and password
I want to retrieve proxy username and password from IE7
Here is my code

```<code>CString UserName;
LPINTERNET_PROXY_INFO ProxyInfo;

DWORD dwSize;
InternetQueryOption(NULL,INTERNET_OPTION_PROXY,NULL,&dwSize);

if (dwSize > 0)
{
    BYTE * lpszData = new BYTE [dwSize];
    InternetQueryOption (NULL, INTERNET_OPTION_PROXY, lpszData, & dwSize);
    ProxyInfo= (LPINTERNET_PROXY_INFO) lpszData;
    InternetQueryOption (NULL, INTERNET_OPTION_PROXY_USERNAME, NULL, &dwSize);
     if (dwSize> 0)
     {
         lpszData = new BYTE [dwSize];
         InternetQueryOption (NULL, INTERNET_OPTION_PROXY_USERNAME, lpszData, &dwSize);
         UserName = lpszData;
         delete [] lpszData;
     }
}
</code>```

InternetQueryOption with INTERNET_OPTION_PROXY works fine. But when I use it with INTERNET_OPTION_PROXY_USERNAME or INTERNET_OPTION_PROXY_PASSWORD, it fails with dwSize equal to 0. GetLastError function returns error code 12018.
Any idea why these functions fail?

答:
Those functions will only work if the user has already authenticated to the proxy (by typing credentials in the popup prompt) inside the current process. Until they do so, WinINET doesn't have the proxy credentials, and the result will be empty.

The result will also be empty if the proxy is only relying upon the user's current Windows login credentials via NTLM or Kerberos.

Title: Retrieve IE proxy username and password

Body:
I want to retrieve proxy username and password from IE7
Here is my code

CString UserName;
LPINTERNET_PROXY_INFO ProxyInfo;

DWORD dwSize;
InternetQueryOption(NULL,INTERNET_OPTION_PROXY,NULL,&dwSize);

if (dwSize > 0)
{
    BYTE * lpszData = new BYTE [dwSize];
    InternetQueryOption (NULL, INTERNET_OPTION_PROXY, lpszData, & dwSize);
    ProxyInfo= (LPINTERNET_PROXY_INFO) lpszData;
    InternetQueryOption (NULL, INTERNET_OPTION_PROXY_USERNAME, NULL, &dwSize);
     if (dwSize> 0)
     {
         lpszData = new BYTE [dwSize];
         InternetQueryOption (NULL, INTERNET_OPTION_PROXY_USERNAME, lpszData, &dwSize);
         UserName = lpszData;
         delete [] lpszData;
     }
}

InternetQueryOption with INTERNET_OPTION_PROXY works fine. But when I use it with INTERNET_OPTION_PROXY_USERNAME or INTERNET_OPTION_PROXY_PASSWORD, it fails with dwSize equal to 0. GetLastError function returns error code 12018.
Any idea why these functions fail?


问:
Alpine JS not correctly update x-model
I have a problem with the selected option in simple Alpine form part. My selectbox get its values from an api. The x-model is set before the fetch. The selectbox sometimes shows the correct selected value and sometimes not. Even if I'll set the value after fetch then the selected option is not (always) selected. How I'll make sure that always the correct selected value is set?

Note: the value of selectbox 2 depends on the value who's set on the first. But if both set they must both show the correct selected value who's given at valueA and valueB.

This is my function

```<code><script>
function alpineSelectFunction() {
    return {
        valueA: '100',
        arrayA: [],
        valueB: '101',
        arrayB: [],
        isLoading: false,
        apiUrl: "apiurl",
        fetchArrayA() {
            fetchUrl = this.apiUrl + `arrayA.json`;
            this.isLoading = true;
            fetch(fetchUrl)
                .then(res => res.json())
                .then(data =>  this.arrayA = data.data);
            this.isLoading = false;
        },
        fetchArrayB() {
            fetchUrl = this.apiUrl + `arrayB.json?id=${this.valueA}`;
            this.isLoading = true;
            fetch(fetchUrl)
            .then(res => res.json())
            .then(data => this.arrayB = data.data);
            this.isLoading = false;
        },
        init() {
            this.fetchArrayA();
            this.fetchArrayB();
        }
    }
}
</script>
</code>```

This is the html

```<code><div x-data="alpineSelectFunction()" x-init="init()">
    <select name="valueA" x-model="valueA" :disabled="isLoading" x-on:input.debounce.750="fetchArrayB()">
        <option value="">Choose...</option>
        <template x-for="option in arrayA">
            <option :value="option.id" x-text="option.title"></option>
        </template>
    </select>

    <select name="valueB" x-model="valueB" :disabled="isLoading">
        <option value="">Choose...</option>
        <template x-for="option in arrayB">
            <option :value="option.id" x-text="option.title"></option>
        </template>
    </select>
</div>
</code>```

答:
In this case, you've got an issue because x-model gets run before x-for.

To circumvent this, you can bind to selected:

    <select name="valueA" x-model="valueA" :disabled="isLoading" x-on:input.debounce.750="fetchArrayB()">
        <option value="">Choose...</option>
        <template x-for="option in arrayA">
            <option :value="option.id" :selected="option.id === valueA" x-text="option.title"></option>
        </template>
    </select>

    <select name="valueB" x-model="valueB" :disabled="isLoading">
        <option value="">Choose...</option>
        <template x-for="option in arrayB">
            <option :value="option.id" :selected="option.id === valueB" x-text="option.title"></option>
        </template>
    </select>

```
<p>Key code are the following lines:</p>
<pre class="lang-html prettyprint-override"><code><option :value="option.id" :selected="option.id === valueA" x-text="option.title"></option>

<option :value="option.id" :selected="option.id === valueB" x-text="option.title"></option>
</code>```

You can find a discussion/explanation to the issue (& another potential workaround) at https://github.com/alpinejs/alpine/issues/495#issuecomment-629671762.

Title: Alpine JS not correctly update x-model

Body:
I have a problem with the selected option in simple Alpine form part. My selectbox get its values from an api. The x-model is set before the fetch. The selectbox sometimes shows the correct selected value and sometimes not. Even if I'll set the value after fetch then the selected option is not (always) selected. How I'll make sure that always the correct selected value is set?

Note: the value of selectbox 2 depends on the value who's set on the first. But if both set they must both show the correct selected value who's given at valueA and valueB.

This is my function

This is the html

    <select name="valueA" x-model="valueA" :disabled="isLoading" x-on:input.debounce.750="fetchArrayB()">
        <option value="">Choose...</option>
        <template x-for="option in arrayA">
            <option :value="option.id" x-text="option.title"></option>
        </template>
    </select>

    <select name="valueB" x-model="valueB" :disabled="isLoading">
        <option value="">Choose...</option>
        <template x-for="option in arrayB">
            <option :value="option.id" x-text="option.title"></option>
        </template>
    </select>

Body:
In this case, you've got an issue because x-model gets run before x-for.

To circumvent this, you can bind to selected:

<div x-data="alpineSelectFunction()" x-init="init()">
    <select name="valueA" x-model="valueA" :disabled="isLoading" x-on:input.debounce.750="fetchArrayB()">
        <option value="">Choose...</option>
        <template x-for="option in arrayA">
            <option :value="option.id" :selected="option.id === valueA" x-text="option.title"></option>
        </template>
    </select>

    <select name="valueB" x-model="valueB" :disabled="isLoading">
        <option value="">Choose...</option>
        <template x-for="option in arrayB">
            <option :value="option.id" :selected="option.id === valueB" x-text="option.title"></option>
        </template>
    </select>
</div>

Key code are the following lines:

<option :value="option.id" :selected="option.id === valueA" x-text="option.title"></option>

<option :value="option.id" :selected="option.id === valueB" x-text="option.title"></option>

You can find a discussion/explanation to the issue (& another potential workaround) at https://github.com/alpinejs/alpine/issues/495#issuecomment-629671762.


问:
UISearchBar with a white background is impossible?
I really thought it would be easy to set the background color of my UISearchBar's text field to white. But no matter what I try, it always stays offwhite / light gray (#efeff0).

import UIKit

class ViewController: UIViewController {
  private let searchController = UISearchController()

  override func viewDidLoad() {
    super.viewDidLoad()
    navigationItem.title = "Hello World"
    view.backgroundColor = #colorLiteral(red: 0.9588784575, green: 0.9528519511, blue: 0.9350754619, alpha: 1)
    searchController.searchBar.searchTextField.backgroundColor = .white
    navigationItem.searchController = searchController
  }
}
```

How can I make the search bar have a pure white background color? App is iOS 13+, if that helps.

Tiny test project: https://github.com/kevinrenskers/WhiteSearch.

答:
Here is My complete Custom Search Bar Which you can define the searchbar backgroundColor and TextField background Color

Tested

```<code>import Foundation

class SearchBar: UISearchBar {

    override init(frame: CGRect) {
        super.init(frame: frame)

        makeUI()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)

        makeUI()

    }

    private func makeUI( ) {

        //SearchBar BackgroundColor
        self.backgroundImage = UIImage(color: UIColor.white)

        //Border Width
        self.layer.borderWidth = 1

        //Border Color
        self.layer.borderColor = UIColor("DEDEDE")?.cgColor

        //Corner Radius
        self.layer.cornerRadius = 3
        self.layer.masksToBounds = true

        //Change Icon
        self.setImage(UIImage(named: "search")?
            .byResize(to: CGSize(width: 30, height: 30)), for: .search, state: .normal)

        if let searchTextField = self.value(forKey: "searchField") as? UISearchTextField {

            //TextField Background !!!!!
            searchTextField.backgroundColor = UIColor.white

            //TextField Font
            searchTextField.font = UIFont(name: "Poppins-Regular", size: 21)
            searchTextField.textColor = .black
        }

    }

}
</code>```

Body:
I really thought it would be easy to set the background color of my UISearchBar's text field to white. But no matter what I try, it always stays offwhite / light gray (#efeff0).

import UIKit

class ViewController: UIViewController {
  private let searchController = UISearchController()

  override func viewDidLoad() {
    super.viewDidLoad()
    navigationItem.title = "Hello World"
    view.backgroundColor = #colorLiteral(red: 0.9588784575, green: 0.9528519511, blue: 0.9350754619, alpha: 1)
    searchController.searchBar.searchTextField.backgroundColor = .white
    navigationItem.searchController = searchController
  }
}

How can I make the search bar have a pure white background color? App is iOS 13+, if that helps.

Tiny test project: https://github.com/kevinrenskers/WhiteSearch.

Body:
Here is My complete Custom Search Bar Which you can define the searchbar backgroundColor and TextField background Color

Tested

import Foundation

class SearchBar: UISearchBar {

    override init(frame: CGRect) {
        super.init(frame: frame)

        makeUI()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)

        makeUI()

    }

    private func makeUI( ) {

        //SearchBar BackgroundColor
        self.backgroundImage = UIImage(color: UIColor.white)

        //Border Width
        self.layer.borderWidth = 1

        //Border Color
        self.layer.borderColor = UIColor("DEDEDE")?.cgColor

        //Corner Radius
        self.layer.cornerRadius = 3
        self.layer.masksToBounds = true

        //Change Icon
        self.setImage(UIImage(named: "search")?
            .byResize(to: CGSize(width: 30, height: 30)), for: .search, state: .normal)

        if let searchTextField = self.value(forKey: "searchField") as? UISearchTextField {

            //TextField Background !!!!!
            searchTextField.backgroundColor = UIColor.white

            //TextField Font
            searchTextField.font = UIFont(name: "Poppins-Regular", size: 21)
            searchTextField.textColor = .black
        }

    }

}


问:
Hiding nil values, understanding why Go fails here
I fail to understand how to correctly assure that something is not nil in this case:

```<code>package main

type shower interface {
  getWater() []shower
}

type display struct {
  SubDisplay *display
}

func (d display) getWater() []shower {
  return []shower{display{}, d.SubDisplay}
}

func main() {
  // SubDisplay will be initialized with null
  s := display{}
  // water := []shower{nil}
  water := s.getWater()
  for _, x := range water {
    if x == nil {
      panic("everything ok, nil found")
    }

    // First iteration display{} is not nil and will
    // therefore work, on the second iteration
    // x is nil, and getWater panics.
    x.getWater()
  }
}
</code>```

The only way I found to check if that value is actually nil is by using reflection.

Is this really wanted behaviour? Or do I fail to see some major mistake in my code?

Play link here

答:
I'll take an alternative route to answer your concrete question, by providing the exact answer you were looking for:

Replace the check:

```<code>if x == nil {
    panic("everything is ok. nil found")
}
</code>```

with:

```<code>if _, ok := x.(display); !ok {
    panic("everything is ok. nil found")
}
</code>```

The idea here is that we are trying to convert the interface type (shower) to the concrete type display. Obviously the second slice item (d.SubDisplay) is not.

Body:
I fail to understand how to correctly assure that something is not nil in this case:

package main

type shower interface {
  getWater() []shower
}

type display struct {
  SubDisplay *display
}

func (d display) getWater() []shower {
  return []shower{display{}, d.SubDisplay}
}

func main() {
  // SubDisplay will be initialized with null
  s := display{}
  // water := []shower{nil}
  water := s.getWater()
  for _, x := range water {
    if x == nil {
      panic("everything ok, nil found")
    }

    // First iteration display{} is not nil and will
    // therefore work, on the second iteration
    // x is nil, and getWater panics.
    x.getWater()
  }
}

The only way I found to check if that value is actually nil is by using reflection.

Is this really wanted behaviour? Or do I fail to see some major mistake in my code?

Play link here

Body:
I'll take an alternative route to answer your concrete question, by providing the exact answer you were looking for:

Replace the check:

if x == nil {
    panic("everything is ok. nil found")
}

with:

if _, ok := x.(display); !ok {
    panic("everything is ok. nil found")
}

The idea here is that we are trying to convert the interface type (shower) to the concrete type display. Obviously the second slice item (d.SubDisplay) is not.


问:
UICollectionView insetForSectionAtIndex not being called
I have a class with the following declaration and constructor:

```<code>class GameView: UIView, UICollectionViewDelegate,  UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
{
    var collectionView: UICollectionView?
    var flowLayout =  UICollectionViewFlowLayout()

    init (frame : CGRect, navigationController:UINavigationController, parentViewController: ScrambleViewController)
{
    super.init(frame : frame)
    cvFrame = CGRect(x: cvLeftBorder, y: cvY, width: Int(UIScreen.main.bounds.width) -  (2 * cvLeftBorder), height: cvHeight)
    collectionView = UICollectionView(frame: cvFrame!, collectionViewLayout: flowLayout);
    collectionView!.dataSource = self
    collectionView!.delegate = self;
    .....
}
</code>```

This is a game where there is a different number of cells each round.   I want to center the cells, so I inserted:

```<code>func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {

 // calculate the insets and return a UIEdgeInsets
}
</code>```

For some reason, the function is never called.   Otherwise, the program is working fine.   Or is there a better way to center the cells in each round?

Thanks in advance.

答:
@Eyzuky's answer would work. What you need to understand is that UICollectionViewDelegateFlowLayout is the child of UICollectionViewDelegate so I don't exactly know what would happen now that you are conforming to both of them.

The reason @Eyzuky's answer would work is that Objective-C doesn't have a strict conforming protocol like Swift but instead, if you have the function implemented in your conforming class, Objective-C will look to see if the delegate object is responding to that selector and as the delegate object is a weak reference to your class and your class currently has that function implemented, it does.

It's a basic mistake that people new to Objective-C usually think that they must have the <UICollectionViewDelegate> with their interface declaration for it to all work, but it doesn't really make a difference.

However, when doing that in swift, the respondToSelector method isn't being called anymore, therefore you can tell your collectionView delegate that it's ok and you can use my function by adding an @objc sign and the exact address of the protocol method.

Also, conforming to UICollectionViewDelegateFlowLayout as well as UICollectionViewDelegate might cause issues considering now there might be two different objects in place. I wasn't able to de-reference the same situation in my own code, but that might be what's causing your issue. I would suggest that you remove the UICollectionViewDelegate from your class implementation while having your collectionView delegate object to self. so the references don't get mixed up.

So your class would look something like this:
class GameView: UIView,  UICollectionViewDataSource, UICollectionViewDelegateFlowLayout

and in your collectionView implementation you will have:

collectionView!.dataSource = self
collectionView!.delegate = self

Body:
I have a class with the following declaration and constructor:

class GameView: UIView, UICollectionViewDelegate,  UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
{
    var collectionView: UICollectionView?
    var flowLayout =  UICollectionViewFlowLayout()

    init (frame : CGRect, navigationController:UINavigationController, parentViewController: ScrambleViewController)
{
    super.init(frame : frame)
    cvFrame = CGRect(x: cvLeftBorder, y: cvY, width: Int(UIScreen.main.bounds.width) -  (2 * cvLeftBorder), height: cvHeight)
    collectionView = UICollectionView(frame: cvFrame!, collectionViewLayout: flowLayout);
    collectionView!.dataSource = self
    collectionView!.delegate = self;
    .....
}

This is a game where there is a different number of cells each round.   I want to center the cells, so I inserted:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {

 // calculate the insets and return a UIEdgeInsets
}

For some reason, the function is never called.   Otherwise, the program is working fine.   Or is there a better way to center the cells in each round?

Thanks in advance.