问:
Sequelize: Using "where" inside a child include overrides parent's "where" criteria. Composite primary key involved
So,

I have two tables, with a 1:M relationship. They have in common two primary keys: tenant and user_id.

I have defined the model relationship and btw, I am not sure if I did it correctly because I am still not sure how to handle composite primary keys on Sequelize. This works well with my many other queries, and I think it influences the problem.

```<code>// Sequelize model set-up:
const user = serviceLayerDB.define('user',
    { // Database columns:
        tenant: {
            type: Sequelize.STRING(45),
            primaryKey: true
        },
        user_id: {
            type: Sequelize.STRING(24),
            primaryKey: true
        },
        status: {
            type: Sequelize.STRING(11)
        }
    });

const user_component = serviceLayerDB.define('user_component',
    { // Database columns:
        tenant: {
            type: Sequelize.STRING(45),
            primaryKey: true
        },
        user_id: {
            type: Sequelize.STRING(24),
            primaryKey: true
        },
        component_id: {
            type: Sequelize.STRING(24),
            primaryKey: true
        },
        active: {
            type: Sequelize.BOOLEAN
        }
    });

// Sequelize relationship set-up:
user.hasMany(user_component, { foreignKey: 'user_id' });
user.hasMany(user_component, { foreignKey: 'tenant' });
</code>```

BUT the problem comes when I have the following query:

```<code>// Retrieving user and related components.
function getSubscriptions() {
        let options = {
            where: {
                tenant: 'company_A',
                user_id: '1001'
            },
            include: [{ // Adding components, filtered by "active" value:
                model: user_component,
                where: {
                    active: 1
                },
                required: false
            }]
        };

        user.findAll(options)
            .then(function(data) {
                if (data.length === 0) { // If no data found:
                    console.log('No data found');
                    return;
                }

                // Curate Sequelize result:
                let curatedData = data.map(function(userInstance) { return userInstance.get({ plain: true}) }); // Workaround to be able to perform .get().
                console.log(JSON.stringify(curatedData, null, 2));
            })
            .catch(function(error) {
                console.log('critical', 'Failed to find data in database. Error: ' + error);
            })
}

// Execute:
getSubscriptions();
</code>```

What I want is to find the user and its components, but only the ones with the active value set to 1. It is not working: the result is every component with the value active set to 1 under the same "tenant", the child include is ignoring the "user_id" that we indicated in the parent.

Am I right to think this is related to my composite primary key? How to fix this in the most elegant manner?

答:
You have to use aliases when you associate a model to another model more then once.
For instance:

```<code>user.hasMany(user_component, { foreignKey: 'user_id', as: 'UserComponents' });
user.hasMany(user_component, { foreignKey: 'tenant', as: 'TenantComponents' });
</code>```

And afterwards you should decide for what exact association you wish to do an include operation:
the association by user_id field

```<code>let options = {
            where: {
                tenant: 'company_A',
                user_id: '1001'
            },
            include: [{ // Adding components, filtered by "active" value:
                model: user_component,
                as: 'UserComponents'
                where: {
                    active: 1
                },
                required: false
            }]
        };
</code>```

the association by tenant field

```<code>let options = {
            where: {
                tenant: 'company_A',
                user_id: '1001'
            },
            include: [{ // Adding components, filtered by "active" value:
                model: user_component,
                as: 'TenantComponents'
                where: {
                    active: 1
                },
                required: false
            }]
        };
</code>```

If you would like both child collections with the active: 1 condition you can do this:

```<code>let options = {
            where: {
                tenant: 'company_A',
                user_id: '1001'
            },
            include: [{ // Adding components, filtered by "active" value:
                model: user_component,
                as: 'UserComponents'
                where: {
                    active: 1
                },
                required: false,
                separate: true
            }, { // Adding components, filtered by "active" value:
                model: user_component,
                as: 'TenantComponents'
                where: {
                    active: 1
                },
                required: false,
                separate: true
            }]
        };
</code>```

Please pay attention to separate: true option: this option tells sequielize to do separate queries for childs.
If you wish to get not all users but those ones with active only components (which ones: through user_id or tenant field?) you should set required: true in include. But in this case don't include both associations with required: true. This leads to miltiplication of amount of records in the result SQL query and consumes much more memory.

Body:
So,

I have two tables, with a 1:M relationship. They have in common two primary keys: tenant and user_id.

I have defined the model relationship and btw, I am not sure if I did it correctly because I am still not sure how to handle composite primary keys on Sequelize. This works well with my many other queries, and I think it influences the problem.

// Sequelize model set-up:
const user = serviceLayerDB.define('user',
    { // Database columns:
        tenant: {
            type: Sequelize.STRING(45),
            primaryKey: true
        },
        user_id: {
            type: Sequelize.STRING(24),
            primaryKey: true
        },
        status: {
            type: Sequelize.STRING(11)
        }
    });

const user_component = serviceLayerDB.define('user_component',
    { // Database columns:
        tenant: {
            type: Sequelize.STRING(45),
            primaryKey: true
        },
        user_id: {
            type: Sequelize.STRING(24),
            primaryKey: true
        },
        component_id: {
            type: Sequelize.STRING(24),
            primaryKey: true
        },
        active: {
            type: Sequelize.BOOLEAN
        }
    });

// Sequelize relationship set-up:
user.hasMany(user_component, { foreignKey: 'user_id' });
user.hasMany(user_component, { foreignKey: 'tenant' });

BUT the problem comes when I have the following query:

// Retrieving user and related components.
function getSubscriptions() {
        let options = {
            where: {
                tenant: 'company_A',
                user_id: '1001'
            },
            include: [{ // Adding components, filtered by "active" value:
                model: user_component,
                where: {
                    active: 1
                },
                required: false
            }]
        };

        user.findAll(options)
            .then(function(data) {
                if (data.length === 0) { // If no data found:
                    console.log('No data found');
                    return;
                }

                // Curate Sequelize result:
                let curatedData = data.map(function(userInstance) { return userInstance.get({ plain: true}) }); // Workaround to be able to perform .get().
                console.log(JSON.stringify(curatedData, null, 2));
            })
            .catch(function(error) {
                console.log('critical', 'Failed to find data in database. Error: ' + error);
            })
}

// Execute:
getSubscriptions();

What I want is to find the user and its components, but only the ones with the active value set to 1. It is not working: the result is every component with the value active set to 1 under the same "tenant", the child include is ignoring the "user_id" that we indicated in the parent.

Am I right to think this is related to my composite primary key? How to fix this in the most elegant manner?

Body:
You have to use aliases when you associate a model to another model more then once.
For instance:

user.hasMany(user_component, { foreignKey: 'user_id', as: 'UserComponents' });
user.hasMany(user_component, { foreignKey: 'tenant', as: 'TenantComponents' });

And afterwards you should decide for what exact association you wish to do an include operation:
the association by user_id field

let options = {
            where: {
                tenant: 'company_A',
                user_id: '1001'
            },
            include: [{ // Adding components, filtered by "active" value:
                model: user_component,
                as: 'UserComponents'
                where: {
                    active: 1
                },
                required: false
            }]
        };

the association by tenant field

let options = {
            where: {
                tenant: 'company_A',
                user_id: '1001'
            },
            include: [{ // Adding components, filtered by "active" value:
                model: user_component,
                as: 'TenantComponents'
                where: {
                    active: 1
                },
                required: false
            }]
        };

If you would like both child collections with the active: 1 condition you can do this:

let options = {
            where: {
                tenant: 'company_A',
                user_id: '1001'
            },
            include: [{ // Adding components, filtered by "active" value:
                model: user_component,
                as: 'UserComponents'
                where: {
                    active: 1
                },
                required: false,
                separate: true
            }, { // Adding components, filtered by "active" value:
                model: user_component,
                as: 'TenantComponents'
                where: {
                    active: 1
                },
                required: false,
                separate: true
            }]
        };

Please pay attention to separate: true option: this option tells sequielize to do separate queries for childs.
If you wish to get not all users but those ones with active only components (which ones: through user_id or tenant field?) you should set required: true in include. But in this case don't include both associations with required: true. This leads to miltiplication of amount of records in the result SQL query and consumes much more memory.


来源: stackexchange

问:
Can't reach MySQL hosted DB from Docker .NET Core
I’ve got a DigitalOcean Droplet that run Ubuntu and I’ve installed MySQL to it. I can reach it from my computer with SSH connection from MySQL workbench, so the remote access is Ok.
The hostname is 127.0.0.1

```<code>The bind address in my mysqld.cnf: 127.0.0.1
</code>```

I’ve got a .NET Core API and I would like to use Docker to run it. I made the container push to docker hub and pulled it to the droplet. When I try to run I get this error:

An error occurred using the connection to database “ on server
  ‘127.0.0.1’.

My connection string:

```<code>"Server=127.0.0.1;Port=3306;Database=db;Uid=user;Pwd=pass”
</code>```

I tried to server: localhost

IP address for docker0: 172.17.0.1 so I tried this to connectionString as well.

I don’t understand why can I connect to DB from MySQL workbench and cannot from .NET Core Web API.

The .NET Core version is 3.1.

答:
Your .NET Core is inside container. Thus if you try to connect localhost or 127.0.0.1, it will try to connect the container itself, not the host. Since your MySQL is on your host, not inside the container, you can access it with other IP.

For example you have eth0 or enps0 or something like that, then that interface have IP 192.168.1.2, then you can use this IP as connection string.

Or, the alternate way, is using --network host when creating container. In this way, if you use 127.0.0.1, it will try to connect the host.

ContentLicense: CC BY-SA 4.0

Body:
I’ve got a DigitalOcean Droplet that run Ubuntu and I’ve installed MySQL to it. I can reach it from my computer with SSH connection from MySQL workbench, so the remote access is Ok.
The hostname is 127.0.0.1

The bind address in my mysqld.cnf: 127.0.0.1

I’ve got a .NET Core API and I would like to use Docker to run it. I made the container push to docker hub and pulled it to the droplet. When I try to run I get this error:

An error occurred using the connection to database “ on server
  ‘127.0.0.1’.

My connection string:

"Server=127.0.0.1;Port=3306;Database=db;Uid=user;Pwd=pass”

I tried to server: localhost

IP address for docker0: 172.17.0.1 so I tried this to connectionString as well.

I don’t understand why can I connect to DB from MySQL workbench and cannot from .NET Core Web API.

The .NET Core version is 3.1.


问:
Calling setstate inside the callback of setstate
Can I use setstate inside the callback function of the setstate
'''this.setstate(update,function(){this.setstate}.bind)'''
is the above given code correct and will it work</p>

答:
this.setState({
 someState: newValue,
}, callback);
```

<p>above code is using callback function in setState.</p>

<p>so you may write code like this.</p>

<pre class="lang-js prettyprint-override"><code>this.setState({
 someState: newValue,
}, () => {
 // some code you want
});
</code>```

Body:
this.setState({
 someState: newValue,
}, callback);

above code is using callback function in setState.

so you may write code like this.

this.setState({
 someState: newValue,
}, () => {
 // some code you want
});


问:
Crystal Report - Linq select statement finds nulls in fields
I'm trying to use a Linq query to a custom crystal report in MyReports folder. However, crystal reports engine is complaining of nulls.

I have managed to make a blank for the Serial Number where it might be null, but DateTime is more of an issue for me.

I have tried:

```<code>InspectionDate = subpat.InspectionDate == null ? "" : subpat.InspectionDate,
</code>```

But the error is:

```<code>Type of conditional expression cannot be determined because there is no implicit conversion between 'string' and 'System.DateTime?'
</code>```

I would just want a blank result if null.

My Query:

```<code>        var today = DateTime.Now.Date;
        var tomorrow = today.AddDays(30);

        var dateresult = db.ClinicalINSs.GroupBy(d => d.ClinicalAssetID)
                   .SelectMany(g => g.OrderByDescending(d => d.NextInspectionDate)
                                     .Take(1));

        var ClinicalIDVM = (from s in dateresult.Where(q => q.NextInspectionDate <= tomorrow)
                           join co in db.ClinicalAssets on s.ClinicalAssetID equals co.ClinicalAssetID into AR
                           let subred = AR.OrderByDescending(subredASS => subredASS.ClinicalAssetID).FirstOrDefault()
                           join cp in db.ClinicalPATs on s.ClinicalAssetID equals cp.ClinicalAssetID into AP
                           let subpat = AP.OrderByDescending(SubPATASS => SubPATASS.ClinicalAssetID).FirstOrDefault()
                           orderby s.NextInspectionDate descending

                           select new ClinicalIDVM
                           {
                               ClinicalAssetID = s.ClinicalAssetID,
                               ProductName = subred.ProductName,
                               SerialNo = subred.SerialNo == null ? "" : subred.SerialNo,
                               InspectionDate = subpat.InspectionDate,
                               NextInspectionDate = s.NextInspectionDate

                           }).ToList();
</code>```

答:
You can try this way

```<code>InspectionDate = subpat.InspectionDate == null ? (DateTime?)null : subpat.InspectionDate
</code>```

or change type of InspectionDate to string, then you will do

```<code>InspectionDate = subpat.InspectionDate.HasValue
? subpat.InspectionDate.Value.ToString("yyyy-MM-dd") : "";
</code>```

Updated

```<code> InspectionDate = subpat.InspectionDate == null ? (object) "" : subpat.InspectionDate
</code>```

Body:
I'm trying to use a Linq query to a custom crystal report in MyReports folder. However, crystal reports engine is complaining of nulls.

I have managed to make a blank for the Serial Number where it might be null, but DateTime is more of an issue for me.

I have tried:

InspectionDate = subpat.InspectionDate == null ? "" : subpat.InspectionDate,

But the error is:

Type of conditional expression cannot be determined because there is no implicit conversion between 'string' and 'System.DateTime?'

I would just want a blank result if null.

My Query:

        var today = DateTime.Now.Date;
        var tomorrow = today.AddDays(30);

        var dateresult = db.ClinicalINSs.GroupBy(d => d.ClinicalAssetID)
                   .SelectMany(g => g.OrderByDescending(d => d.NextInspectionDate)
                                     .Take(1));

        var ClinicalIDVM = (from s in dateresult.Where(q => q.NextInspectionDate <= tomorrow)
                           join co in db.ClinicalAssets on s.ClinicalAssetID equals co.ClinicalAssetID into AR
                           let subred = AR.OrderByDescending(subredASS => subredASS.ClinicalAssetID).FirstOrDefault()
                           join cp in db.ClinicalPATs on s.ClinicalAssetID equals cp.ClinicalAssetID into AP
                           let subpat = AP.OrderByDescending(SubPATASS => SubPATASS.ClinicalAssetID).FirstOrDefault()
                           orderby s.NextInspectionDate descending

                           select new ClinicalIDVM
                           {
                               ClinicalAssetID = s.ClinicalAssetID,
                               ProductName = subred.ProductName,
                               SerialNo = subred.SerialNo == null ? "" : subred.SerialNo,
                               InspectionDate = subpat.InspectionDate,
                               NextInspectionDate = s.NextInspectionDate

                           }).ToList();

Body:
You can try this way

InspectionDate = subpat.InspectionDate == null ? (DateTime?)null : subpat.InspectionDate

or change type of InspectionDate to string, then you will do

InspectionDate = subpat.InspectionDate.HasValue
? subpat.InspectionDate.Value.ToString("yyyy-MM-dd") : "";

Updated

 InspectionDate = subpat.InspectionDate == null ? (object) "" : subpat.InspectionDate


问:
Angular drag and drop using transferArrayItem points to wrong index number upon filtering (working example)
I am trying to filter a list of items using the Drag Material CDK... all is working well when my list is not filtered, however when I filter it, and drag and drop, I get the wrong item (wrong index) on the drop, I created a working example, as you can see, filter by let's say "av" and drag avocado to drop area and you will get Carrot as the index is referring to the old data source, any ideas are appreciated,

here is a working example of the problem: https://stackblitz.com/edit/angular-agf3kv-wjxwdm?file=app/cdk-drag-drop-disabled-sorting-example.css

Sean

答:
I had the same issue and having a getter function to get itemsFiltered bugged on my end for the data. Note that I'm working with dynamic lists, so the user can choose how many drag & drop lists are available and which.

I solved my issue by just not displaying the card based on the filter, that way the index remained correct:

 {{product.productModelName}}

 {{product.productName}}

```

And in the styles i have .item__hidden{ display:none }

Body:
I had the same issue and having a getter function to get itemsFiltered bugged on my end for the data. Note that I'm working with dynamic lists, so the user can choose how many drag & drop lists are available and which.

I solved my issue by just not displaying the card based on the filter, that way the index remained correct:

   <div     cdkDropList
            id="{{list.projectName}}"
            [cdkDropListData]="list.products"
            class="list-droparea"
            (cdkDropListDropped)="drop($event, list)">
        <div    *ngFor="let product of list.products"
                class="card-dropable"
                cdkDrag
<!--here-->     [class.item__hidden]="!product.productName.toLocaleLowerCase().includes(list.searchTerm.toLowerCase())"
                [class.item__moved]="product.originalProjectId !== list.id">
            <div class="row">
                <div class="col-12"><h6> {{product.productModelName}} </h6></div>
                <div class="col-12"><small class="m-0 secondary"> {{product.productName}}     </small></div>
                <div class="col-12" *ngIf="product.originalProjectId !== list.id">
                    <strong [innerHTML]="getProject(product.originalProjectId)"></strong>
                </div>
            </div>
        </div>
    </div>

And in the styles i have .item__hidden{ display:none }


问:
How to convert values from 0: 270 to 0:1023 in Python?
Hi i need help with my script for Arduino with Python
I have python script it put out angle between 0-270
I need to convert this value to servo-read-able in meaning 0-1023
Can some one from community help me
Thanks</p>

答:
Do you mean something like the map function?
https://www.arduino.cc/reference/en/language/functions/math/map/ or https://processing.org/reference/map_.html

```<code>def maprange( a, b, s):
    (a1, a2), (b1, b2) = a, b
    return  b1 + ((s - a1) * (b2 - b1) / (a2 - a1))

maprange((0, 270), (0, 1023), value)
</code>```

Taken from https://rosettacode.org/wiki/Map_range#Python

I hope that helps :-)

Body:
Do you mean something like the map function?
https://www.arduino.cc/reference/en/language/functions/math/map/ or https://processing.org/reference/map_.html

def maprange( a, b, s):
    (a1, a2), (b1, b2) = a, b
    return  b1 + ((s - a1) * (b2 - b1) / (a2 - a1))

maprange((0, 270), (0, 1023), value)

Taken from https://rosettacode.org/wiki/Map_range#Python

I hope that helps :-)


问:
How to return a vector of pairs
I am trying to solve this challenge from testdome. I think my approach to the solution is not optimal (or even correct). But before changing my approach I was wondering is it possible to return a vector of pairs? if yes, how?.
Below you will see the challenge, and afterwards my code.
Thank you.

#include <stdexcept>
#include <iostream>
#include <vector>
#include <utility>

std::pair<int, int> findTwoSum(const std::vector<int>& list, int sum)
{
    int tracker = list.size();
    std::pair <int, int> result;
    std::vector <std::pair <int,int>> list1(100);
    for (int i = 0; i < (int)list.size(); i++){
        for (int j = ((int)list.size()-tracker); j < (int)list.size(); j++){

            if (list[i]+list[j] == sum)
                list1.push_back(std::make_pair(list[i], list[j]) );
        }
        tracker--;
    }

    return list1; // I am stuck here

    //throw std::logic_error("Waiting to be implemented");
}

#ifndef RunTests
int main()
{
    std::vector<int> list = {3, 1, 5, 7, 5, 9};
    std::pair<int, int> indices = findTwoSum(list, 10);
    std::cout << indices.first << '\n' << indices.second;
}
#endif
```

<p><strong>EDIT</strong></p>

<p>Initially, this was my solution. But once I posted it on testdome, I am getting zero correct answers out of 4 categories. It is test number 5. That is why I thought, returning only one answer was wrong.</p>

<pre class="lang-c++ prettyprint-override"><code>
#include <stdexcept>
#include <iostream>
#include <vector>
#include <utility>

std::pair<int, int> findTwoSum(const std::vector<int>& list, int sum)
{
    int tracker = list.size();
    std::pair <int, int> result;
    std::vector <std::pair <int,int>> list1(100);
    for (int i = 0; i < (int)list.size(); i++){
        for (int j = ((int)list.size()-tracker); j < (int)list.size(); j++){
            if (list[i]+list[j] == sum)

                return result=std::make_pair(list[i], list[j]);
        }
        tracker--;
    }

    return std::make_pair(-1,-1);

    //throw std::logic_error("Waiting to be implemented");
}

#ifndef RunTests
int main()
{
    std::vector<int> list = {3, 1, 5, 7, 5, 9};
    std::pair<int, int> indices = findTwoSum(list, 10);
    std::cout << indices.first << '\n' << indices.second;
}
#endif
</code>```

答:
You can simply use std::vector<std::pair<int, int>> as the return value of your function. (and not only std::pair<int, int> as you've done in your example)

So your function becomes:

std::vector<std::pair<int, int>> findTwoSum(const std::vector<int>& list, int sum) { ... }
```

Title: How to return a vector of pairs

Body:
I am trying to solve this challenge from testdome. I think my approach to the solution is not optimal (or even correct). But before changing my approach I was wondering is it possible to return a vector of pairs? if yes, how?.
Below you will see the challenge, and afterwards my code.
Thank you.

#include <stdexcept>
#include <iostream>
#include <vector>
#include <utility>

std::pair<int, int> findTwoSum(const std::vector<int>& list, int sum)
{
    int tracker = list.size();
    std::pair <int, int> result;
    std::vector <std::pair <int,int>> list1(100);
    for (int i = 0; i < (int)list.size(); i++){
        for (int j = ((int)list.size()-tracker); j < (int)list.size(); j++){

            if (list[i]+list[j] == sum)
                list1.push_back(std::make_pair(list[i], list[j]) );
        }
        tracker--;
    }

    return list1; // I am stuck here

    //throw std::logic_error("Waiting to be implemented");
}

#ifndef RunTests
int main()
{
    std::vector<int> list = {3, 1, 5, 7, 5, 9};
    std::pair<int, int> indices = findTwoSum(list, 10);
    std::cout << indices.first << '\n' << indices.second;
}
#endif

EDIT

Initially, this was my solution. But once I posted it on testdome, I am getting zero correct answers out of 4 categories. It is test number 5. That is why I thought, returning only one answer was wrong.

#include <stdexcept>
#include <iostream>
#include <vector>
#include <utility>

std::pair<int, int> findTwoSum(const std::vector<int>& list, int sum)
{
    int tracker = list.size();
    std::pair <int, int> result;
    std::vector <std::pair <int,int>> list1(100);
    for (int i = 0; i < (int)list.size(); i++){
        for (int j = ((int)list.size()-tracker); j < (int)list.size(); j++){
            if (list[i]+list[j] == sum)

                return result=std::make_pair(list[i], list[j]);
        }
        tracker--;
    }

    return std::make_pair(-1,-1);

    //throw std::logic_error("Waiting to be implemented");
}

#ifndef RunTests
int main()
{
    std::vector<int> list = {3, 1, 5, 7, 5, 9};
    std::pair<int, int> indices = findTwoSum(list, 10);
    std::cout << indices.first << '\n' << indices.second;
}
#endif


问:
Unable to catch 403 in try-catch during fetch
I'm making a put request using ReactJS, however, when I put in the wrong email/password combination, I get this logged on Chrome, even though I'm trying to catch all errors and show them in errorDiv:

async connect(event) {
  try {
    const userObject = {
      username: this.state.userName,
      password: this.state.password
    };
    if (!userObject.username || !userObject.password) {
      throw Error('The username/password is empty.');
    }
    let response = await fetch(('someurl.com'), {
      method: "PUT",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(userObject)
    });
    let resJSON = await response.json();
    if (!response.ok) {
      throw Error(resJSON.message);
    }
    console.info(resJSON.message);
    console.info(resJSON.message.auth_token);
    window.location = "/ledger/home";
  } catch (e) {
    document.getElementById("errorDiv").style.display = 'block';
    document.getElementById("errorDiv").innerHTML = e;
  }
}```

答:
I completely agree with @Sagiv, but there is a quick workaround to do that, although it is not a suggested way.
Inside of try or promise.then(), you need to do this check.

```<code>const res = await fetch();
console.log(res);    // You can see the response status here by doing res.status
</code>```

So, by some simple checks it is possible to resolve or reject a promise. For e.g. in your case

async connect(event) {
  try {
    const userObject = {
      username: this.state.userName,
      password: this.state.password
    };
    if (!userObject.username || !userObject.password) {
      throw Error('The username/password is empty.');
    }
    let response = await fetch('someurl.com', {
      method: 'PUT',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(userObject)
    });
    if (response.status === 403) throw new Error('403 is unacceptable for me!');
    let resJSON = await response.json();
    if (!response.ok) {
      throw Error(resJSON.message);
    }
    console.info(resJSON.message);
    console.info(resJSON.message.auth_token);
    window.location = '/ledger/home';
  } catch (e) {
    document.getElementById('errorDiv').style.display = 'block';
    document.getElementById('errorDiv').innerHTML = e;
  }
}
```

I strongly recommend using axios. For the fetch issue, you can refer to this link

Body:
I completely agree with @Sagiv, but there is a quick workaround to do that, although it is not a suggested way.
Inside of try or promise.then(), you need to do this check.

const res = await fetch();
console.log(res);    // You can see the response status here by doing res.status

So, by some simple checks it is possible to resolve or reject a promise. For e.g. in your case

async connect(event) {
  try {
    const userObject = {
      username: this.state.userName,
      password: this.state.password
    };
    if (!userObject.username || !userObject.password) {
      throw Error('The username/password is empty.');
    }
    let response = await fetch('someurl.com', {
      method: 'PUT',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(userObject)
    });
    if (response.status === 403) throw new Error('403 is unacceptable for me!');
    let resJSON = await response.json();
    if (!response.ok) {
      throw Error(resJSON.message);
    }
    console.info(resJSON.message);
    console.info(resJSON.message.auth_token);
    window.location = '/ledger/home';
  } catch (e) {
    document.getElementById('errorDiv').style.display = 'block';
    document.getElementById('errorDiv').innerHTML = e;
  }
}

I strongly recommend using axios. For the fetch issue, you can refer to this link


问:
Javascript Syntax Differences
What is the difference between these two?

```<code>collapse: function(fold)
{
...
...
}
</code>```

and

```<code>function collapse(fold)
{
...
...
}
</code>```

答: The first syntax declares a method on an object.  The second declares a regular function.</p>

ContentLicense: CC BY-SA 3.0

Title: Javascript Syntax Differences

Body:
What is the difference between these two?

collapse: function(fold)
{
...
...
}

and

function collapse(fold)
{
...
...
}


答:
you just need to switch the function signature to

```<code>std::vector<std::pair<int, int>> findTwoSum(const std::vector<int>& list, int sum)
</code>```

But in the main you are assigning it to a pair, so you need also to change this:

```<code>std::pair<int, int> indices = findTwoSum(list, 10); // from
std::vector<std::pair<int, int>> indices = findTwoSum(list, 10); // to
std::vector<std::pair<int, int>> indices { findTwoSum(list, 10) }; // but this is better because you call just one constructor instead of a default constructor and a copy constructor
</code>```

Title: How to return a vector of pairs

Body:
you just need to switch the function signature to

std::vector<std::pair<int, int>> findTwoSum(const std::vector<int>& list, int sum)

But in the main you are assigning it to a pair, so you need also to change this:

std::pair<int, int> indices = findTwoSum(list, 10); // from
std::vector<std::pair<int, int>> indices = findTwoSum(list, 10); // to
std::vector<std::pair<int, int>> indices { findTwoSum(list, 10) }; // but this is better because you call just one constructor instead of a default constructor and a copy constructor


问:
Laravel attach() method not working to hasMany side
The application has the models:

Atividade.php

class Atividade extends Eloquent {
    public function intervencoes() {
        return $this->belongsToMany('Intervencao');
    }
}
```

<p><br/></p>

<h3>Intervencao.php</h3>

<pre class="lang-php prettyprint-override"><code>class Intervencao extends Eloquent {
    public function atividades() {
        return $this->hasMany('Atividade');
    }
}
</code>```

The following code works:

Atividade::find($id)->intervencoes()->attach($intervencao_id);
```

<p>But, this...</p>

<pre class="lang-php prettyprint-override"><code>Intervencao::find($id)->atividades()->attach($atividade_id);
</code>```

Returns an BadMethodCallException:

Call to undefined method Illuminate\Database\Query\Builder::attach()

SOLUTION (thanks to @gnack):

I was trying to set a many-to-many relationship, so just needed to change this...

return $this->hasMany('Atividade');
```

<p>To this:</p>

<pre class="lang-php prettyprint-override"><code>return $this->belongsToMany('Atividade');
</code>```

答:
See the documentation Laravel 5.7

A Comment belongTo an unique Post

```<code>class Comment extends Model
{
    /**
     * Get the post that owns the comment.
     */
    public function post()
    {
        return $this->belongsTo('App\Post');
    }
}
</code>```

A Post can Have multiple Comments

```<code>class Post extends Model
{
    /**
     * Get the comments for the blog post.
     */
    public function comments()
    {
        return $this->hasMany('App\Comment');
    }
</code>```

When you want to update/delete a belongsTo relationship, you may use the associate/dissociate method.

```<code>$post= App\Post::find(10);
$comment= App\Comment::find(3);
$comment->post()->associate($post); //update the model

$comment->save(); //you have to call save() method

//delete operation
$comment->post()->dissociate();

$comment->save(); //save() method
</code>```

Body:
The application has the models:

Atividade.php

class Atividade extends Eloquent {
    public function intervencoes() {
        return $this->belongsToMany('Intervencao');
    }
}

Intervencao.php

class Intervencao extends Eloquent {
    public function atividades() {
        return $this->hasMany('Atividade');
    }
}

The following code works:

Atividade::find($id)->intervencoes()->attach($intervencao_id);

But, this...

Intervencao::find($id)->atividades()->attach($atividade_id);

Returns an BadMethodCallException:

Call to undefined method Illuminate\Database\Query\Builder::attach()

SOLUTION (thanks to @gnack):

I was trying to set a many-to-many relationship, so just needed to change this...

return $this->hasMany('Atividade');

To this:

return $this->belongsToMany('Atividade');

Body:
See the documentation Laravel 5.7

A Comment belongTo an unique Post

class Comment extends Model
{
    /**
     * Get the post that owns the comment.
     */
    public function post()
    {
        return $this->belongsTo('App\Post');
    }
}

A Post can Have multiple Comments

class Post extends Model
{
    /**
     * Get the comments for the blog post.
     */
    public function comments()
    {
        return $this->hasMany('App\Comment');
    }

When you want to update/delete a belongsTo relationship, you may use the associate/dissociate method.

$post= App\Post::find(10);
$comment= App\Comment::find(3);
$comment->post()->associate($post); //update the model

$comment->save(); //you have to call save() method

//delete operation
$comment->post()->dissociate();

$comment->save(); //save() method


问:
Accept Insertion and reject deletion openxml
I need to compare two Word files and merge all insertions into a third one.
I have managed to do that with OpenXML-Power-Tools and WmlCompare, but how do I reject only deletions?

Accepting insertions is easy with OpenXmlPowerTools.RevisionAccepter but I can't get the rejection of deletions to work, that way I would get merged file without revisions.

Should I take this approach or would you suggest different approach?

Rules are:

1) Text can be added anywhere in the file.

2) Text is always added to file, never deleted.

3) Files have a .docx file extension

答:
It is relatively easy to reject, or undo, deletions. So, say you have the following sample paragraph with one w:del element that wraps a deleted w:r element.

<w:p>
  <w:r>
    <w:t xml:space="preserve">This is </w:t>
  </w:r>
  <w:del w:id="0" w:author="Thomas Barnekow" w:date="2020-02-16T14:37:00Z">
    <w:r>
      <w:delText xml:space="preserve">deleted </w:delText>
    </w:r>
  </w:del>
  <w:r>
    <w:t>text.</w:t>
  </w:r>
</w:p>
```

<p>To reject the deletion, you need to unwrap the deleted <code>w:r</code> and turn the <code>w:delText</code> into a <code>w:t</code> again. Without any further processing (see below), the result of your rejecting the deletion would look like this:</p>

<pre class="lang-xml prettyprint-override"><code><w:p>
  <w:r>
    <w:t xml:space="preserve">This is </w:t>
  </w:r>
  <w:r>
    <w:t xml:space="preserve">deleted </w:delText>
  </w:r>
  <w:r>
    <w:t>text.</w:t>
  </w:r>
</w:p>
</code>```

As an optional step, using the MarkupSimplifier of the Open XML PowerTools, you could also coalesce adjacent runs having identical formatting, which would result in the following markup:

<w:p>
  <w:r>
    <w:t>This is deleted text.</w:t>
  </w:r>
</w:p>
```

Body:
It is relatively easy to reject, or undo, deletions. So, say you have the following sample paragraph with one w:del element that wraps a deleted w:r element.

<w:p>
  <w:r>
    <w:t xml:space="preserve">This is </w:t>
  </w:r>
  <w:del w:id="0" w:author="Thomas Barnekow" w:date="2020-02-16T14:37:00Z">
    <w:r>
      <w:delText xml:space="preserve">deleted </w:delText>
    </w:r>
  </w:del>
  <w:r>
    <w:t>text.</w:t>
  </w:r>
</w:p>

To reject the deletion, you need to unwrap the deleted w:r and turn the w:delText into a w:t again. Without any further processing (see below), the result of your rejecting the deletion would look like this:

<w:p>
  <w:r>
    <w:t xml:space="preserve">This is </w:t>
  </w:r>
  <w:r>
    <w:t xml:space="preserve">deleted </w:delText>
  </w:r>
  <w:r>
    <w:t>text.</w:t>
  </w:r>
</w:p>

As an optional step, using the MarkupSimplifier of the Open XML PowerTools, you could also coalesce adjacent runs having identical formatting, which would result in the following markup:

<w:p>
  <w:r>
    <w:t>This is deleted text.</w:t>
  </w:r>
</w:p>


问:
My webpage only displays the PHP part and ignores all HTML
Good afternoon!

When I upload my website to my hosting partner, only the bits between my php tags are displayed on my website. I tried echoing all the html code inside the php tags, but that doesn't seem to work either. I put an echo 'test' in the code to display my problem. My file is called index.php.

The website : www.mjacartrading.nl

The top part of the code:

```<code>echo 'testtest';
if ($_SERVER['HTTPS'] != "on") {
    $url = "https://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
    header("Location: $url");
    exit;
}
include 'partials/header.php';
aCars();
?>

<!doctype html>
<html lang="en">

<head>

    <title>M.J.A. | Home</title>

</head>

   <body>
<div class="jumbotron jumbotron-fluid vh100 d-flex justify-content-center indexbgimg mb-0">
    <div class="d-flex align-self-center mobile">
        <img src="img/LOGOWHITE.png" class="indexlogo">
        <ul class="list-group antresiet mt-5 border-left border-white responsivemenu">
            <li class="list-group-item indexmenu menuactive"><a class="indexmenua" href="index.php"><b>HOME</b></a></li>
            <li class="list-group-item indexmenu"><a class="indexmenua" href="aanbod.php">AANBOD</a></li>
            <li class="list-group-item indexmenu"><a class="indexmenua" href="impressie.php">IMPRESSIE</a></li>
            <li class="list-group-item indexmenu"><a class="indexmenua" href="contact.php">CONTACT</a></li>
        </ul>
    </div>
</div>
</code>```

In my localhost this construction works just fine. How do I display this page as intended?

答:
We'd need a more complete version of the code to know for sure. Some ideas though:

In the code you've posted you are missing the opening <?php. That should be on the line before your opening echo 'testtest';

Check you are using <?php, not <?, as the open php tag

Check you have any included files on the server
your code is looking for partials/header.php, make sure that's been uploaded too.

Finally it's possible that your server does not have php installed / setup correctly.

Hope that helps.

Body:
Good afternoon!

When I upload my website to my hosting partner, only the bits between my php tags are displayed on my website. I tried echoing all the html code inside the php tags, but that doesn't seem to work either. I put an echo 'test' in the code to display my problem. My file is called index.php.

The website : www.mjacartrading.nl

The top part of the code:

echo 'testtest';
if ($_SERVER['HTTPS'] != "on") {
    $url = "https://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
    header("Location: $url");
    exit;
}
include 'partials/header.php';
aCars();
?>

<!doctype html>

    <title>M.J.A. | Home</title>

HOME

AANBOD

IMPRESSIE

CONTACT

In my localhost this construction works just fine. How do I display this page as intended?


问:
Some main commands not found in MSYS2 after update-core

Issue

Some main commands not found in MSYS2 after update-core.

Environment

Windows 8.1 64bit

msys2-x86_64-20150916

Detail

I introduced MSYS2 to my computer and performed update-core. However, after the update, when I type pacman or update-core, the terminal says bash: pacman: command not found. I rebooted MSYS2 and tried the same process but the result was the same. I re-installed MSYS2 and tried the same process but the result was the same. I'd like to get things right but don't know how.

Any suggestion would be appreciated. Thanks.

答: For me running: pacman -S openssh solved it (found it here)


问:
Generating PDF and Microsoft Word files in Ruby on Rails
I want to build a web app that will allow, based on answering questions from a series of prompts from users, to generate a report in Microsoft Word and/or PDF format. I would like the output of the report to be configured in the actual code, where the end result will not have to be altered by an user. Is that possible using Ruby and the Rails framework?</p>

答:
Yes, it's quite possible to do with Ruby on Rails.

But that said, this could be done with most any other language, with or without a Web application framework. I would suggest beginning with the language you are already familiar with--if you've done some PHP before, as most beginners have, just use PHP!

Also, find some prebuilt libraries that you can use to do the Word and PDF generation. For example, in Rails, you could use Prawn to generate PDFs. Here's more information on how to generate Word docs in Rails.


问:
SVG gradient not working
I've a svg and I need to fill it with a gradient, the css is added by a script, if U work with a single RGB color it all work fines but with a gradient the SVG results in a white background.

The result code after the script:

```<code><svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"
id="Livello_1" x="0px" y="0px" viewBox="0 0 70 70"
style="enable-background:new 0 0 70 70;width: 50px; height: 50px;"
xml:space="preserve">
<defs>
  <lineargradient id="grC29M" x1="0%" y1="0%" x2="100%" y2="0%">
    <stop offset="0%" style="stop-color:rgb(88,88,88);stop-opacity:1"></stop>
    <stop offset="100%" style="stop-color:rgb(255,255,255);stop-opacity:1"></stop>
    </lineargradient>
</defs>

<path class="st0" d="......" style="fill: url("#grC29M")">
</svg>
</code>```

Thanks!

Title: SVG gradient not working

Body:
I've a svg and I need to fill it with a gradient, the css is added by a script, if U work with a single RGB color it all work fines but with a gradient the SVG results in a white background.

The result code after the script:

<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"
id="Livello_1" x="0px" y="0px" viewBox="0 0 70 70"
style="enable-background:new 0 0 70 70;width: 50px; height: 50px;"
xml:space="preserve">
<defs>
  <lineargradient id="grC29M" x1="0%" y1="0%" x2="100%" y2="0%">
    <stop offset="0%" style="stop-color:rgb(88,88,88);stop-opacity:1"></stop>
    <stop offset="100%" style="stop-color:rgb(255,255,255);stop-opacity:1"></stop>
    </lineargradient>
</defs>

<path class="st0" d="......" style="fill: url("#grC29M")">
</svg>

Thanks!

Body:
I had a very strange bug in chrome when this gradient didn't work

<svg width="442" height="249" viewBox="0 0 442 249" fill="none" xmlns="http://www.w3.org/2000/svg">
    <mask id="mask0" mask-type="alpha" maskUnits="userSpaceOnUse" x="0" y="0" width="442" height="249">
        <path
            d="M225.158 123.903H441.656C401.021 94.5929 319.085 35.7055 316.42 34.6397C313.089 33.3074 151.215 0 148.551 0C146.419 0 71.2778 15.5434 33.9735 23.3152L0 145.886C8.88197 178.75 28.1114 245.275 33.9735 248.473C41.3011 252.47 97.2575 232.485 115.243 230.487C129.632 228.888 194.515 158.765 225.158 123.903Z"
            fill="#C4C4C4" />
    </mask>
    <g mask="url(#mask0)">
        <path
            d="M49.8681 219.88C42.8755 215.861 40.5446 206.754 44.6687 199.578C48.7928 192.403 57.8357 189.833 64.8283 193.852C71.8209 197.871 74.1518 206.978 70.0277 214.154C65.9037 221.329 56.8607 223.899 49.8681 219.88ZM60.0531 202.16C57.5288 200.709 54.2499 201.646 52.7639 204.231C51.2779 206.817 52.1191 210.121 54.6434 211.572C57.1677 213.023 60.4466 212.086 61.9326 209.501C63.4186 206.915 62.5774 203.611 60.0531 202.16Z"
            fill="url(#gradient1)" />
        <path
            d="M127.776 283.054C125.861 281.954 124.95 279.575 125.754 277.371C126.65 274.871 129.337 273.555 131.775 274.416C187.265 293.788 249.429 269.847 279.55 217.441C313.928 157.627 294.543 81.7525 236.31 48.2827C178.077 14.8128 102.787 36.272 68.4251 96.0567C53.5818 121.882 48.2006 152.064 53.2367 181.045C53.6857 183.622 51.9799 186.119 49.4165 186.617C46.8531 187.115 44.4166 185.444 43.9677 182.867C38.5354 151.687 44.3513 119.205 60.33 91.404C97.3008 27.0127 178.413 3.95305 241.085 39.9744C303.758 75.9957 324.662 157.69 287.662 222.065C255.237 278.48 188.329 304.293 128.534 283.413C128.286 283.309 128.037 283.204 127.776 283.054Z"
            fill="url(#gradient2)" />
    </g>
    <defs>
        <linearGradient id="gradient1" x1="157" y1="24.5" x2="157" y2="248.5" gradientUnits="userSpaceOnUse">
            <stop stop-color="#FF8B00" />
            <stop offset="1" stop-color="#FF8B00" stop-opacity="0" />
        </linearGradient>
        <linearGradient id="gradient2" x1="175" y1="22.5" x2="175" y2="238.5" gradientUnits="userSpaceOnUse">
            <stop stop-color="#FF8B00" />
            <stop offset="1" stop-color="#FF8B00" stop-opacity="0" />
        </linearGradient>
    </defs>
</svg>

until I've changed the ids from paint0_linear and paint1_linear to gradient1 and gradient2.

Quite a strange issue, but maybe this will help someone


答:
If you want to return a vector of pairs, your function signature should look like

```<code>std::vector<std::pair<...>> f();
</code>```

Your current function is just returning a single std::pair.

Title: How to return a vector of pairs

Body:
If you want to return a vector of pairs, your function signature should look like

std::vector<std::pair<...>> f();

Your current function is just returning a single std::pair.


问:
Is there a way to make dynamic ivars show up in XCode 4's GUI debugger?
I like the convenience of skipping explicit declaration of ivars, and just using @property/@synthesize.

But ivars done this way don't show up in the Debug Area variables list in XCode 4 (at least with gdb/iOS; don't know about lldb).

Is there any way of forcing them to do so?

Notes:

I know I can get the ivar values using gdb commands in the console, or breakpoint actions

There are a couple of similar questions here (eg. xcode 3.2.2 and objective-c 2.0 and debug: where are my object's property/instance variable values in debug?) but I am specifically looking for an XCode 4 workaround.

答: We are all in the same boat, unfortunately.  Maybe LLDB will fix this to some degree, although we are waiting for Apple to add it back in as an option.  This is probably my biggest gripe with Xcode.</p>


问:
Keeping securly API tokens in the database
I have multiple companies utilising my GET endpoint, each company needs to have their own API key which they will provide as a url parameter.

I need to keep generating these token whenever new company will join in (there is a table reflecting this).

Is it safe to just:
- create company_token pivot table
- generate token as str_random(32) (because GET request might have maximum url length)

? Or is there a safer, better method?

答:
Database

The simpler and most secure way of keeping a company-level API token would be what you are already doing - using a secure PRNG to get a HTTP-safe token, which is what str_random() does, and having a UNIQUE constraint on the API token table to be sure you don't get duplicates.

UX

You could also supply a way of changing the API token by the company, after a suitable login, in order to allow them to get rid of obsolete or leaked tokens. Since you would update the API row and not keep old values, keeping track of obsolete tokens would not be a concern.

Security (as much as possible)

To avoid sending the token visibly in the URL, you could also receive them from a custom HTTP Header, as @AbdurRahman suggested.

Finally, you could use the token only once per session and per client: the API token can be consumed only by a /nonce API, which will reply with a longer token in the form of "IP:DATE:HASH" (e.g. "192.168.168.192:2020.02.16.15.35:ee2998d477ee4a1b50e886590d228239"), which would be around 64 bytes. The hash would be produced by MD5("IP:DATE:SECRET"), which guarantees that the information has not been tampered with. All subsequent APIs just verify that this token is untampered with, the IP matches and the date is not too far in the past (or the future).

The advantage is that the token being sent is now different for each client and changes every time, so even if it gets intercepted, little damage would be done. The "real" token that would be harmful if intercepted is sent only once per session; there are more secure schemes than this, but this would already be an improvement.


问:
Post request with axios one after another Vuejs
I have 2 post request, if the first one is trigger the second one must await for the response and the do a post request. I read something about await and async, but no good.</p>

```<code>let changed =false;

if(//something then){
    changed = true;
    axios.post('/uploadfile/' + id,  // This must be first
        formData,
    {
    headers: {
        'Content-Type': 'multipart/form-data',
    }
    })
    .then(function(response){
        // get response and do something
    })
    .catch(function(){
        //
    });
}

// if changed = true, then await for response from first post
axios.post('/uploadfile' + this.id_contract,  // If
    data,
    {
    headers: {
        Authorization: getToken()
    }
})
.then(function(){
    // do something else
})
.catch(function(){
    //
});
</code>```

答:
You can simply use async/await like this:</p>

```<code>async myMethod() {
  let response1 = await axios.post('/1', ...)
  let response2 = await axios.post('/2', ...)
}
</code>```

Body:
I have 2 post request, if the first one is trigger the second one must await for the response and the do a post request. I read something about await and async, but no good.

let changed =false;

if(//something then){
    changed = true;
    axios.post('/uploadfile/' + id,  // This must be first
        formData,
    {
    headers: {
        'Content-Type': 'multipart/form-data',
    }
    })
    .then(function(response){
        // get response and do something
    })
    .catch(function(){
        //
    });
}

// if changed = true, then await for response from first post
axios.post('/uploadfile' + this.id_contract,  // If
    data,
    {
    headers: {
        Authorization: getToken()
    }
})
.then(function(){
    // do something else
})
.catch(function(){
    //
});

Body:
You can simply use async/await like this:

async myMethod() {
  let response1 = await axios.post('/1', ...)
  let response2 = await axios.post('/2', ...)
}


问:
How to convert an ArrayList containing Integers to primitive int array?
I'm trying to convert an ArrayList containing Integer objects to primitive int[] with the following piece of code, but it is throwing compile time error. Is it possible to convert in Java?</p>

```<code>List<Integer> x =  new ArrayList<Integer>();
int[] n = (int[])x.toArray(int[x.size()]);
</code>```

答:
Arrays.setAll()

```<code>    List<Integer> x = new ArrayList<>(Arrays.asList(7, 9, 13));
    int[] n = new int[x.size()];
    Arrays.setAll(n, x::get);

    System.out.println("Array of primitive ints: " + Arrays.toString(n));
</code>```

Output:

Array of primitive ints: [7, 9, 13]

The same works for an array of long or double, but not for arrays of boolean, char, byte, short or float. If you’ve got a really huge list, there’s even a parallelSetAll method that you may use instead.

To me this is good and elgant enough that I wouldn’t want to get an external library nor use streams for it.

Documentation link: Arrays.setAll(int[], IntUnaryOperator)

OwnerDisplayName: Snehal

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to convert an ArrayList containing Integer objects to primitive int[] with the following piece of code, but it is throwing compile time error. Is it possible to convert in Java?

List<Integer> x =  new ArrayList<Integer>();
int[] n = (int[])x.toArray(int[x.size()]);

LastEditorDisplayName: John Topley

Body:
Arrays.setAll()

    List<Integer> x = new ArrayList<>(Arrays.asList(7, 9, 13));
    int[] n = new int[x.size()];
    Arrays.setAll(n, x::get);

    System.out.println("Array of primitive ints: " + Arrays.toString(n));

Output:

Array of primitive ints: [7, 9, 13]

The same works for an array of long or double, but not for arrays of boolean, char, byte, short or float. If you’ve got a really huge list, there’s even a parallelSetAll method that you may use instead.

To me this is good and elgant enough that I wouldn’t want to get an external library nor use streams for it.

Documentation link: Arrays.setAll(int[], IntUnaryOperator)


问:
In PlantUML, how do I specify role names at either end of an association between two classes?
How do I specify role names 'employer' and 'employee' at either end of the association 'employs' between the classes 'Person' and 'Company'? That is, of course, different from the name of the association:

答:
```<code>@startuml
hide circle
class Person {
}
class Company {
}
Person "+employee 0..*" <-- "+employer 0..1" Company : employs
note on link: [[https://en.wiktionary.org/wiki/employ employs]] is the name of the association
@enduml
</code>```

see also wiki.bitplan.com

try it out at

http://diagrams.bitplan.com

see rendered png image

see rendered svg image

Body:
@startuml
hide circle
class Person {
}
class Company {
}
Person "+employee 0..*" <-- "+employer 0..1" Company : employs
note on link: [[https://en.wiktionary.org/wiki/employ employs]] is the name of the association
@enduml

see also wiki.bitplan.com

try it out at

http://diagrams.bitplan.com

see rendered png image

see rendered svg image


问:
Vtk charts break in QT, "no override found for 'vtkContextDevice2D"
I can't use any type of vtk 2D chart in QT without getting the error:

"Generic Warning: In vtkContextDevice2D.cxx, line 31 Error: no override found for 'vtkContextDevice2D".

There is limited discussion on this with almost all suggestions being to upgrade qt/vtk, but theses are year old and I am on the newest versions.

This doesn't help either:

```<code>include "vtkAutoInit.h"
VTK_MODULE_INIT(vtkRenderingOpenGL2); // VTK was built with vtkRenderingOpenGL2
VTK_MODULE_INIT(vtkInteractionStyle);
</code>```

Info: Win64 on 64bit machine, vtk8.2.0, Qt5.13.0, compiled/built in MCVS2017(Release x64) with cmake3.15.0

(Everything else works fine, even 3D renderings with vtk)

Code:

```<code>view->SetInteractor(this->qvtkWidgetRight->GetInteractor());
this->qvtkWidgetRight->SetRenderWindow(view->GetRenderWindow());
</code>```

What the error produces

答:
I had a similar problem when I run this example:QtBarChart, and I fixed this issue with linking with these vtk libraries:

```<code>find_package(VTK COMPONENTS
  vtkChartsCore
  vtkCommonCore
  vtkCommonDataModel
  vtkInteractionStyle
  vtkRenderingContext2D
  vtkRenderingContextOpenGL2
  vtkRenderingCore
  vtkRenderingFreeType
  vtkRenderingGL2PSOpenGL2
  vtkRenderingOpenGL2
  vtkViewsContext2D
  QUIET

</code>```

It seems I missed some libraries.

Body:
I can't use any type of vtk 2D chart in QT without getting the error:

"Generic Warning: In vtkContextDevice2D.cxx, line 31 Error: no override found for 'vtkContextDevice2D".

There is limited discussion on this with almost all suggestions being to upgrade qt/vtk, but theses are year old and I am on the newest versions.

This doesn't help either:

include "vtkAutoInit.h"
VTK_MODULE_INIT(vtkRenderingOpenGL2); // VTK was built with vtkRenderingOpenGL2
VTK_MODULE_INIT(vtkInteractionStyle);

Info: Win64 on 64bit machine, vtk8.2.0, Qt5.13.0, compiled/built in MCVS2017(Release x64) with cmake3.15.0

(Everything else works fine, even 3D renderings with vtk)

Code:

view->SetInteractor(this->qvtkWidgetRight->GetInteractor());
this->qvtkWidgetRight->SetRenderWindow(view->GetRenderWindow());

What the error produces

Body:
I had a similar problem when I run this example:QtBarChart, and I fixed this issue with linking with these vtk libraries:

find_package(VTK COMPONENTS
  vtkChartsCore
  vtkCommonCore
  vtkCommonDataModel
  vtkInteractionStyle
  vtkRenderingContext2D
  vtkRenderingContextOpenGL2
  vtkRenderingCore
  vtkRenderingFreeType
  vtkRenderingGL2PSOpenGL2
  vtkRenderingOpenGL2
  vtkViewsContext2D
  QUIET

It seems I missed some libraries.


问:
Wix React Native Navigation V2, how to lock orientation portrait on Android
I'm using RNN2 and I need to lock orientation on Android to portrait. Usually in a traditional android app it's done with  android:screenOrientation = "portrait" in manifest.xml, but when I have setup the screens with RNN2 it's not working.

Any help will be appreciated.

答:
I have a single screen with a side drawer and I got it working across the app by adding layout to the options of the center screen and not the root:</p>

```<code>Navigation.setRoot({
root: {
  sideMenu: {
    id: 'sideMenu',
    left: {
      component: {
        id: 'SideDrawer',
        name: 'yourApp.SideDrawer',
      },
      visible:true,
    },
    center: {
      stack: {
        id: 'App',
        children: [{
          component: {
            id: 'HomeScreen',
            name: 'yourApp.HomeScreen',
            options:{
              topBar: {
                leftButtons: [
                  {
                    text:'Menu',
                    id: 'sideDrawerToggle',
                    active: true,
                    visible: true,
                    display: true,
                  }
                ],
                background: {
                  color: '#000',
                  },
                title: {
                  text: 'Your App',
                  fontSize: 18,
                  color: '#fff',
                  fontFamily: 'Helvetica',
                  fontWeight: 'bold', // Available on iOS only, will ignore fontFamily style and use the iOS system fonts instead. Supported weights are: 'regular', 'bold', 'thin', 'ultraLight', 'light', 'medium', 'semibold', 'heavy' and 'black'.
                },
              },
            }
          },
        }],
        options:{
          topBar: {
            background: {
              color: '#000',
              },
            title: {
              fontSize: 18,
              color: '#fff',
              fontFamily: 'Helvetica',
              fontWeight: 'bold', // Available on iOS only, will ignore fontFamily style and use the iOS system fonts instead. Supported weights are: 'regular', 'bold', 'thin', 'ultraLight', 'light', 'medium', 'semibold', 'heavy' and 'black'.
            },
            backButton: {
              visible: true,
              color:'#fff'
            },
          },
          //add layout here
          layout: {
            orientation: ['portrait'],
          },
        }
      }
    }
  }
}});
</code>```

Body:
I have a single screen with a side drawer and I got it working across the app by adding layout to the options of the center screen and not the root:

Navigation.setRoot({
root: {
  sideMenu: {
    id: 'sideMenu',
    left: {
      component: {
        id: 'SideDrawer',
        name: 'yourApp.SideDrawer',
      },
      visible:true,
    },
    center: {
      stack: {
        id: 'App',
        children: [{
          component: {
            id: 'HomeScreen',
            name: 'yourApp.HomeScreen',
            options:{
              topBar: {
                leftButtons: [
                  {
                    text:'Menu',
                    id: 'sideDrawerToggle',
                    active: true,
                    visible: true,
                    display: true,
                  }
                ],
                background: {
                  color: '#000',
                  },
                title: {
                  text: 'Your App',
                  fontSize: 18,
                  color: '#fff',
                  fontFamily: 'Helvetica',
                  fontWeight: 'bold', // Available on iOS only, will ignore fontFamily style and use the iOS system fonts instead. Supported weights are: 'regular', 'bold', 'thin', 'ultraLight', 'light', 'medium', 'semibold', 'heavy' and 'black'.
                },
              },
            }
          },
        }],
        options:{
          topBar: {
            background: {
              color: '#000',
              },
            title: {
              fontSize: 18,
              color: '#fff',
              fontFamily: 'Helvetica',
              fontWeight: 'bold', // Available on iOS only, will ignore fontFamily style and use the iOS system fonts instead. Supported weights are: 'regular', 'bold', 'thin', 'ultraLight', 'light', 'medium', 'semibold', 'heavy' and 'black'.
            },
            backButton: {
              visible: true,
              color:'#fff'
            },
          },
          //add layout here
          layout: {
            orientation: ['portrait'],
          },
        }
      }
    }
  }
}});


问:
Rx.Net ignore certain exceptions but handle rest of the exceptions
It is easy to handle a particular set of exceptions using the Catch operator. How could we ignore certain exceptions but handle the rest in the Catch block?

Say for example I would like to let ArgumentNullException, ArgumentOutOfRangeException and TimeoutException exceptions bubble and report an error but for anything else I would like to retry.

The catch version below would catch all the exceptions, and there is no way to selectively ignore some types, as the signature requires it to return a IObservable<T>

```<code>source.Catch<T, Exception>(e=> Observable.Return(default(T)))
</code>```

If I have to retry on certain Exception then I could write something like (I think)

```<code>source.Catch<T, WebException>(e=> source.Retry())
</code>```

答:
A very meaningful operator in these situations is RetryWhen.

RetryWhen(selector) gives you an observable of Exception, and expects an observable which, triggers a retry every time it produces a value.

RetryWhen(e => e) is equivalent to Retry() (all exceptions trigger a retry).

RetryWhen(e => e.Take(3)) is equivalent to Retry(3) (first three exceptions trigger a retry).

Now you can simply transform the inner sequence into one that emits on your desired types of exceptions. For example, to only retry on TimeoutException:

```<code>source.RetryWhen(e => e.Where(exn => exn is TimeoutException))
</code>```

Body:
It is easy to handle a particular set of exceptions using the Catch operator. How could we ignore certain exceptions but handle the rest in the Catch block?

Say for example I would like to let ArgumentNullException, ArgumentOutOfRangeException and TimeoutException exceptions bubble and report an error but for anything else I would like to retry.

The catch version below would catch all the exceptions, and there is no way to selectively ignore some types, as the signature requires it to return a IObservable<T>

source.Catch<T, Exception>(e=> Observable.Return(default(T)))

If I have to retry on certain Exception then I could write something like (I think)

source.Catch<T, WebException>(e=> source.Retry())

Body:
A very meaningful operator in these situations is RetryWhen.

RetryWhen(selector) gives you an observable of Exception, and expects an observable which, triggers a retry every time it produces a value.

RetryWhen(e => e) is equivalent to Retry() (all exceptions trigger a retry).

RetryWhen(e => e.Take(3)) is equivalent to Retry(3) (first three exceptions trigger a retry).

Now you can simply transform the inner sequence into one that emits on your desired types of exceptions. For example, to only retry on TimeoutException:

source.RetryWhen(e => e.Where(exn => exn is TimeoutException))


问:
Android kodein difference between **bind() with** and **bind() from**
While studying about kodein i often see  bind() with and bind() from.

Can anyone please tell me what is the difference and why are we using it.

Ex:

```<code>    bind<Dice>() with provider { RandomDice(0, 5) }
    bind<DataSource>() with singleton { SqliteDS.open("path/to/file") }
</code>```

```<code>    bind() from singleton { RandomDice(6) }
    bind("DnD20") from provider { RandomDice(20) }
    bind() from instance(SqliteDataSource.open("path/to/file"))
</code>```

答:
bind<Type>() with defines Type explicitly. This is important when you are, for example, binding an interface type to an implementation of it:

```<code>bind<Type>() with singleton { TypeImpl() }
</code>```

Now consider that you are binding a a very simple type, such as a configuration data object:

```<code>bind<Config>() with singleton { Config("my", "config", "values") }
</code>```

You've written Config twice: once in the bind definition, and once in the bind itself.

Enter bind() from: it does not define a type but leaves the choice of the bound type to the binding itself. The bound type is defined implicitly. For example, you could write the Config binding as such:

```<code>bind() from singleton { Config("my", "config", "values") }
</code>```

Note that binding a type to itself (which is what bind() from is for) is often a bad idea (it goes against the IoC pattern) and should only be used for very simple types such as data classes.

Body:
While studying about kodein i often see  bind() with and bind() from.

Can anyone please tell me what is the difference and why are we using it.

Ex:

    bind<Dice>() with provider { RandomDice(0, 5) }
    bind<DataSource>() with singleton { SqliteDS.open("path/to/file") }

    bind() from singleton { RandomDice(6) }
    bind("DnD20") from provider { RandomDice(20) }
    bind() from instance(SqliteDataSource.open("path/to/file"))

Body:
bind<Type>() with defines Type explicitly. This is important when you are, for example, binding an interface type to an implementation of it:

bind<Type>() with singleton { TypeImpl() }

Now consider that you are binding a a very simple type, such as a configuration data object:

bind<Config>() with singleton { Config("my", "config", "values") }

You've written Config twice: once in the bind definition, and once in the bind itself.

Enter bind() from: it does not define a type but leaves the choice of the bound type to the binding itself. The bound type is defined implicitly. For example, you could write the Config binding as such:

bind() from singleton { Config("my", "config", "values") }

Note that binding a type to itself (which is what bind() from is for) is often a bad idea (it goes against the IoC pattern) and should only be used for very simple types such as data classes.


问:
Convert a list of data frames into a single data frame with list name
I am hoping to determine an efficient way to convert a list of data frames into a single data frame. Below is my reproducible MWE:

```<code>set.seed(1)
ABAge = runif(100)
ABPoints = rnorm(100)
ACAge = runif(100)
ACPoints = rnorm(100)
BCAge = runif(100)
BCPoints = rnorm(100)

A_B <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = ABAge, Points = ABPoints)
A_C <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = ACAge, Points = ACPoints)
B_C <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = BCAge, Points = BCPoints)
A_B$ID <- as.character(A_B$ID)
A_C$ID <- as.character(A_C$ID)
B_C$ID <- as.character(B_C$ID)

listFormat <- list("A_B" = A_B, "A_C" = A_C, "B_C" = B_C)

dfFormat <- data.frame(ID = as.character(paste0("ID", 1:100)), A_B.Age = ABAge, A_B.Points = ABPoints, A_C.Age = ACAge, A_C.Points = ACPoints, B_C.Age = BCAge, B_C.Points = BCPoints)
dfFormat$ID = as.character(dfFormat$ID)
</code>```

This results in a data frame format (dfFormat) that looks like this:

```<code>'data.frame':   100 obs. of  7 variables:
 $ ID        : chr  "ID1" "ID2" "ID3" "ID4" ...
 $ A_B.Age   : num  0.266 0.372 0.573 0.908 0.202 ...
 $ A_B.Points: num  0.398 -0.612 0.341 -1.129 1.433 ...
 $ A_C.Age   : num  0.6737 0.0949 0.4926 0.4616 0.3752 ...
 $ A_C.Points: num  0.409 1.689 1.587 -0.331 -2.285 ...
 $ B_C.Age   : num  0.814 0.929 0.147 0.75 0.976 ...
 $ B_C.Points: num  1.474 0.677 0.38 -0.193 1.578 ...
</code>```

and a list of data frames listFormat that looks like this:

```<code>List of 3
 $ A_B:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.266 0.372 0.573 0.908 0.202 ...
  ..$ Points: num [1:100] 0.398 -0.612 0.341 -1.129 1.433 ...
 $ A_C:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.6737 0.0949 0.4926 0.4616 0.3752 ...
  ..$ Points: num [1:100] 0.409 1.689 1.587 -0.331 -2.285 ...
 $ B_C:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.814 0.929 0.147 0.75 0.976 ...
  ..$ Points: num [1:100] 1.474 0.677 0.38 -0.193 1.578 ...
</code>```

I am hoping to come up with an automated way to convert the dfFormat to listFormat. As can be seen in the above objects there are two main conditions:

1) If there is a common column (name and contents) in each sublist of listFormat (in these examples ID), then they are not repeated in the outputted dfFormat (in this example, it has one final ID column),

2) The rest of the column names in sublists of listFormat become columns in dfFormat and have names such that they retain their sublist name (i.e "A_B") followed by a dot and then their original column name (i.e. Age), so that it becomes (i.e. "A_B.Age") in the dfFormat.

I have tried various unlist() and sapply codes but have been unsuccessful thus far. What is an efficient way to accomplish this?

答:
Copy listFormat to L in case we need to preserve the input, listFormat.  Remove the ID column from each component of L except the first, cbind what we have left together and then fix up the name of the first column.  No packages are used.

```<code>L <- listFormat
L[-1] <- lapply(L[-1], transform, ID = NULL)
DF <- do.call(cbind, L)
names(DF)[1] <- "ID"
</code>```

giving:

```<code>> str(DF)
'data.frame':   100 obs. of  7 variables:
 $ ID        : chr  "ID1" "ID2" "ID3" "ID4" ...
 $ A_B.Age   : num  0.9932 0.1451 0.6166 0.0372 0.9039 ...
 $ A_B.Points: num  0.4752 0.0288 1.0548 0.6113 0.0651 ...
 $ A_C.Age   : num  0.912 0.761 0.618 0.895 0.507 ...
 $ A_C.Points: num  -0.515 -0.945 0.398 0.502 -1.021 ...
 $ B_C.Age   : num  0.7935 0.2747 0.0487 0.6307 0.3499 ...
 $ B_C.Points: num  -0.963 -1.772 1.716 -0.819 0.577 ...
</code>```

Body:
I am hoping to determine an efficient way to convert a list of data frames into a single data frame. Below is my reproducible MWE:

set.seed(1)
ABAge = runif(100)
ABPoints = rnorm(100)
ACAge = runif(100)
ACPoints = rnorm(100)
BCAge = runif(100)
BCPoints = rnorm(100)

A_B <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = ABAge, Points = ABPoints)
A_C <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = ACAge, Points = ACPoints)
B_C <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = BCAge, Points = BCPoints)
A_B$ID <- as.character(A_B$ID)
A_C$ID <- as.character(A_C$ID)
B_C$ID <- as.character(B_C$ID)

listFormat <- list("A_B" = A_B, "A_C" = A_C, "B_C" = B_C)

dfFormat <- data.frame(ID = as.character(paste0("ID", 1:100)), A_B.Age = ABAge, A_B.Points = ABPoints, A_C.Age = ACAge, A_C.Points = ACPoints, B_C.Age = BCAge, B_C.Points = BCPoints)
dfFormat$ID = as.character(dfFormat$ID)

This results in a data frame format (dfFormat) that looks like this:

'data.frame':   100 obs. of  7 variables:
 $ ID        : chr  "ID1" "ID2" "ID3" "ID4" ...
 $ A_B.Age   : num  0.266 0.372 0.573 0.908 0.202 ...
 $ A_B.Points: num  0.398 -0.612 0.341 -1.129 1.433 ...
 $ A_C.Age   : num  0.6737 0.0949 0.4926 0.4616 0.3752 ...
 $ A_C.Points: num  0.409 1.689 1.587 -0.331 -2.285 ...
 $ B_C.Age   : num  0.814 0.929 0.147 0.75 0.976 ...
 $ B_C.Points: num  1.474 0.677 0.38 -0.193 1.578 ...

and a list of data frames listFormat that looks like this:

List of 3
 $ A_B:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.266 0.372 0.573 0.908 0.202 ...
  ..$ Points: num [1:100] 0.398 -0.612 0.341 -1.129 1.433 ...
 $ A_C:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.6737 0.0949 0.4926 0.4616 0.3752 ...
  ..$ Points: num [1:100] 0.409 1.689 1.587 -0.331 -2.285 ...
 $ B_C:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.814 0.929 0.147 0.75 0.976 ...
  ..$ Points: num [1:100] 1.474 0.677 0.38 -0.193 1.578 ...

I am hoping to come up with an automated way to convert the dfFormat to listFormat. As can be seen in the above objects there are two main conditions:

1) If there is a common column (name and contents) in each sublist of listFormat (in these examples ID), then they are not repeated in the outputted dfFormat (in this example, it has one final ID column),

2) The rest of the column names in sublists of listFormat become columns in dfFormat and have names such that they retain their sublist name (i.e "A_B") followed by a dot and then their original column name (i.e. Age), so that it becomes (i.e. "A_B.Age") in the dfFormat.

I have tried various unlist() and sapply codes but have been unsuccessful thus far. What is an efficient way to accomplish this?

Body:
Copy listFormat to L in case we need to preserve the input, listFormat.  Remove the ID column from each component of L except the first, cbind what we have left together and then fix up the name of the first column.  No packages are used.

L <- listFormat
L[-1] <- lapply(L[-1], transform, ID = NULL)
DF <- do.call(cbind, L)
names(DF)[1] <- "ID"

giving:

> str(DF)
'data.frame':   100 obs. of  7 variables:
 $ ID        : chr  "ID1" "ID2" "ID3" "ID4" ...
 $ A_B.Age   : num  0.9932 0.1451 0.6166 0.0372 0.9039 ...
 $ A_B.Points: num  0.4752 0.0288 1.0548 0.6113 0.0651 ...
 $ A_C.Age   : num  0.912 0.761 0.618 0.895 0.507 ...
 $ A_C.Points: num  -0.515 -0.945 0.398 0.502 -1.021 ...
 $ B_C.Age   : num  0.7935 0.2747 0.0487 0.6307 0.3499 ...
 $ B_C.Points: num  -0.963 -1.772 1.716 -0.819 0.577 ...


问:
Pandas: create a Dataframe from lists with similar-size lists inside
I am trying to construct a Dataframe from lists, which have similar-size lists inside.

In the example below I have 3 lists (with similar-size lists inside), which I want to use to construct an specific Dataframe.

Here are the lists:

```<code>list_type = [['A1', 'A2'], ['A2'], ['A1', 'A3', 'A4']]

list_xx = [['1', '5'], ['3'], ['2', '7', '3']]

list_date = [['Jan', 'Jan'], ['Feb'], ['Mar', 'Mar', 'Mar']]
</code>```

And the Dataframe I want to construct is:

   date type    xx
0   Jan   A1     1
1   Jan   A2     5
2   Feb   A2     3
3   Mar   A1     2
4   Mar   A3     7
5   Mar   A4     3
```

As you can see, the structure of the Dateframe is based on the inner-lists.

I would really value an efficient way of doing this in Python.

答:
You can make do with concat and list comprehension:

```<code>pd.concat(pd.DataFrame({'date':d,'type':t,'xx':xx })
          for d,t,xx in zip(list_date, list_type, list_xx))
</code>```

Or np.concatenate with transpose:

```<code>pd.DataFrame([np.concatenate(l) for l in (list_date,list_type,list_xx)],
             index=['date','type','xx']).T
</code>```

Output:

```<code>  date type xx
0  Jan   A1  1
1  Jan   A2  5
0  Feb   A2  3
0  Mar   A1  2
1  Mar   A3  7
2  Mar   A4  3
</code>```

Body:
I am trying to construct a Dataframe from lists, which have similar-size lists inside.

In the example below I have 3 lists (with similar-size lists inside), which I want to use to construct an specific Dataframe.

Here are the lists:

list_type = [['A1', 'A2'], ['A2'], ['A1', 'A3', 'A4']]

list_xx = [['1', '5'], ['3'], ['2', '7', '3']]

list_date = [['Jan', 'Jan'], ['Feb'], ['Mar', 'Mar', 'Mar']]

And the Dataframe I want to construct is:

   date type    xx
0   Jan   A1     1
1   Jan   A2     5
2   Feb   A2     3
3   Mar   A1     2
4   Mar   A3     7
5   Mar   A4     3

As you can see, the structure of the Dateframe is based on the inner-lists.

I would really value an efficient way of doing this in Python.

Body:
You can make do with concat and list comprehension:

pd.concat(pd.DataFrame({'date':d,'type':t,'xx':xx })
          for d,t,xx in zip(list_date, list_type, list_xx))

Or np.concatenate with transpose:

pd.DataFrame([np.concatenate(l) for l in (list_date,list_type,list_xx)],
             index=['date','type','xx']).T

Output:

  date type xx
0  Jan   A1  1
1  Jan   A2  5
0  Feb   A2  3
0  Mar   A1  2
1  Mar   A3  7
2  Mar   A4  3


问:
kivyMD Calling a variable into kivy language
Im having a problem, the thing i want to do is to call a variable I have in kivymd language but it always give an error.

here is my code:

KV:

```<code><Main>
    product: product

Screen:
    BoxLayout:
        size_hint: .8, .8
        pos_hint: {"center_x": .5, "y": .7}
        spacing: dp(100)
        orientation: "vertical"
        MDTextFieldRound:
            id: product
            hint_text: 'Enter a product'
            icon_left: 'magnify'
            on_text_validate: app.System()

    FloatLayout:
        MDCard:
            orientation: "vertical"
            size_hint: .43, .3
            height: self.minimum_height
            pos_hint: {"x": .05, "y": .35}

            BoxLayout:
                id: box
                size_hint_y: None
                height: dp(150)

                MDLabel:
                    text: 'self.data_ebay'                # I want to call it here

        MDCard:
            orientation: "vertical"
            size_hint: .43, .3
            height: self.minimum_height
            pos_hint: {"x": .52, "y": .35}

            BoxLayout:
                id: box
                size_hint_y: None
                height: dp(150)

        MDCard:
            orientation: "vertical"
            size_hint: .43, .3
            height: self.minimum_height
            pos_hint: {"x": .52, "y": .03}

            BoxLayout:
                id: box
                size_hint_y: None
                height: dp(150)

        MDCard:
            orientation: "vertical"
            size_hint: .43, .3
            height: self.minimum_height
            pos_hint: {"x": .05, "y": .03}

            BoxLayout:
                id: box
                size_hint_y: None
                height: dp(150)
</code>```

PY:

```<code>import kivy
from kivy.properties import ObjectProperty
from selenium import webdriver
import requests
from selectorlib import Extractor
from selenium.webdriver.common.keys import Keys
from kivymd.app import MDApp
from kivy.app import App
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.uix.floatlayout import FloatLayout

class Main(MDApp):
    Window.size = (310, 520)
    title = "Best Price"
    def build(self):
        return Builder.load_string(KV)

    product = ObjectProperty(None)
    def System(self):
        self.options = webdriver.ChromeOptions()
        self.options.add_argument('headless')
        self.options.add_argument('window-size=1920x1080')
        self.options.add_argument("disable-gpu")

        self.browser =
        webdriver.Chrome('C://Users//Yesnia//Documents//chromedriver_win32//chromedriver.exe',
        options=self.options)

        self.browser.get('https://www.ebay.com/')

        self.Esearch = self.browser.find_element_by_name('_nkw')
        self.Esearch.send_keys(self.root.ids.product.text)
        self.Esearch.send_keys(Keys.ENTER)
        self.url = self.browser.current_url

        self.Ebay = Extractor.from_yaml_file('ebay.txt')
        self.r_ebay = requests.get(self.url)
        self.data_ebay = self.Ebay.extract(self.r_ebay.text)

        print('Ebay: ', self.data_ebay)                  # This is the variable

if __name__ == "__main__":
    Main().run()
</code>```

答:
i found a solution, the problem is that the variable is inside the class function, and when you call to app.data_ebay app refers to the class, you can add in the class this:

```<code>class Main(MDApp):
    Window.size = (310, 520)
    title = "Best Price"
    def build(self):
        return Builder.load_string(KV)

    product = ObjectProperty(None)

    data_ebay = StringProperty()    #You can add this
</code>```

but data ebay has to be an 'str'

Body:
Im having a problem, the thing i want to do is to call a variable I have in kivymd language but it always give an error.

here is my code:

KV:

    product: product

Screen:
    BoxLayout:
        size_hint: .8, .8
        pos_hint: {"center_x": .5, "y": .7}
        spacing: dp(100)
        orientation: "vertical"
        MDTextFieldRound:
            id: product
            hint_text: 'Enter a product'
            icon_left: 'magnify'
            on_text_validate: app.System()

    FloatLayout:
        MDCard:
            orientation: "vertical"
            size_hint: .43, .3
            height: self.minimum_height
            pos_hint: {"x": .05, "y": .35}

            BoxLayout:
                id: box
                size_hint_y: None
                height: dp(150)

                MDLabel:
                    text: 'self.data_ebay'                # I want to call it here

        MDCard:
            orientation: "vertical"
            size_hint: .43, .3
            height: self.minimum_height
            pos_hint: {"x": .52, "y": .35}

            BoxLayout:
                id: box
                size_hint_y: None
                height: dp(150)

        MDCard:
            orientation: "vertical"
            size_hint: .43, .3
            height: self.minimum_height
            pos_hint: {"x": .52, "y": .03}

            BoxLayout:
                id: box
                size_hint_y: None
                height: dp(150)

        MDCard:
            orientation: "vertical"
            size_hint: .43, .3
            height: self.minimum_height
            pos_hint: {"x": .05, "y": .03}

            BoxLayout:
                id: box
                size_hint_y: None
                height: dp(150)

PY:

import kivy
from kivy.properties import ObjectProperty
from selenium import webdriver
import requests
from selectorlib import Extractor
from selenium.webdriver.common.keys import Keys
from kivymd.app import MDApp
from kivy.app import App
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.uix.floatlayout import FloatLayout

class Main(MDApp):
    Window.size = (310, 520)
    title = "Best Price"
    def build(self):
        return Builder.load_string(KV)

    product = ObjectProperty(None)
    def System(self):
        self.options = webdriver.ChromeOptions()
        self.options.add_argument('headless')
        self.options.add_argument('window-size=1920x1080')
        self.options.add_argument("disable-gpu")

        self.browser =
        webdriver.Chrome('C://Users//Yesnia//Documents//chromedriver_win32//chromedriver.exe',
        options=self.options)

        self.browser.get('https://www.ebay.com/')

        self.Esearch = self.browser.find_element_by_name('_nkw')
        self.Esearch.send_keys(self.root.ids.product.text)
        self.Esearch.send_keys(Keys.ENTER)
        self.url = self.browser.current_url

        self.Ebay = Extractor.from_yaml_file('ebay.txt')
        self.r_ebay = requests.get(self.url)
        self.data_ebay = self.Ebay.extract(self.r_ebay.text)

        print('Ebay: ', self.data_ebay)                  # This is the variable

if __name__ == "__main__":
    Main().run()

Body:
i found a solution, the problem is that the variable is inside the class function, and when you call to app.data_ebay app refers to the class, you can add in the class this:

class Main(MDApp):
    Window.size = (310, 520)
    title = "Best Price"
    def build(self):
        return Builder.load_string(KV)

    product = ObjectProperty(None)

    data_ebay = StringProperty()    #You can add this

but data ebay has to be an 'str'


问:
Visual Studio.NET 2008 doesn't give me english exception-messages
In previous versions of VS.NET or the .NET framework, you got english exception messages by default.
If you installed a 'language pack', you received exception messages in the language of that language pack.

Now, I'm working with an English VS.NET 2008 (no language packs have been installed) on a dutch Windows Vista.

When I'm developing, and I write some code that triggers an exception, the exception message that I receive, is in dutch (the language of my OS).
I don't want it to be in dutch; I want it to be in English.  (Reasons are obvious: easier to Google, and those translated error-messages are crap).

In VS.NET, my international settings are set to 'English', in Windows Vista, my regional settings are set to 'Dutch/Belgium'.
How can I get English exception messages, without having to change anything to my regional settings in Windows?

答:
After some searching on Stackoverflow and other sites on the net, it seems that Windows Vista decides which language-packs should be installed, and there seem to be no way to uninstall those language-packages (in XP this was possible).

I do not have Vista Ultimate (which would allow you to install multiple language packs side by side).

So, what I've done now, is this:

I've created a custom conditional compile symbol (DEVELOPER), and in my application, I've this code:

```<code>#if DEVELOPER

Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-us");

#endif
</code>```

I just need to make sure that, when I build my application for deployment, I do not include this conditional define ...
(But, I can easily do this, since my application is under CI).

OwnerDisplayName: Frederik Gheysels

LastEditorDisplayName: moocha

Body:
After some searching on Stackoverflow and other sites on the net, it seems that Windows Vista decides which language-packs should be installed, and there seem to be no way to uninstall those language-packages (in XP this was possible).

I do not have Vista Ultimate (which would allow you to install multiple language packs side by side).

So, what I've done now, is this:

I've created a custom conditional compile symbol (DEVELOPER), and in my application, I've this code:

#if DEVELOPER

Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-us");

#endif

I just need to make sure that, when I build my application for deployment, I do not include this conditional define ...
(But, I can easily do this, since my application is under CI).


答:
The cut method as outlined by @Greg is probably what you want here. One thing to note is that cut returns a factor by default, which you can suppress by supplying labels = FALSE to return the integer values:

```<code>cut(data$wt, c(178, 200, 300, Inf), labels = FALSE)
</code>```

Alternatively, if your cutting does not lend itself to natural breaks, you can use ifelse(). You can "nest" the ifelse statements similar to Excel. I use "with" to cut down on the typing needed:

```<code>data$group2 <- with(data, ifelse(wt >= 179 & wt < 200, 1,
  ifelse(wt >= 200 & wt < 300, 2, 3))
)
</code>```

Title: coding variable values into classes using R

Body:
I have a set of data in which I need to code values of certain variables (numeric) into 3 classes.

My data set is similar to this but has 60 more variables:

anim <- c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)
wt <- c(181,179,180.5,201,201.5,245,246.4,189.3,301,354,369,205,199,394,231.3)
data <- data.frame(anim,wt)

> data
   anim    wt
1     1 181.0
2     2 179.0
3     3 180.5
4     4 201.0
5     5 201.5
6     6 245.0
7     7 246.4
8     8 189.3
9     9 301.0
10   10 354.0
11   11 369.0
12   12 205.0
13   13 199.0
14   14 394.0
15   15 231.3

I need to code values of the variable "wt" up into 3 classes: (wt >= 179 & wt < 200) = 1; (wt >= 200 & wt < 300) = 2; (wt > 300) = 3

which should give me this

> data2
   anim    wt SWT
1     1 181.0   1
2     2 179.0   1
3     3 180.5   1
4     4 201.0   2
5     5 201.5   2
6     6 245.0   2
7     7 246.4   2
8     8 189.3   1
9     9 301.0   3
10   10 354.0   3
11   11 369.0   3
12   12 205.0   2
13   13 199.0   1
14   14 394.0   3
15   15 231.3   2

Body:
The cut method as outlined by @Greg is probably what you want here. One thing to note is that cut returns a factor by default, which you can suppress by supplying labels = FALSE to return the integer values:

cut(data$wt, c(178, 200, 300, Inf), labels = FALSE)

Alternatively, if your cutting does not lend itself to natural breaks, you can use ifelse(). You can "nest" the ifelse statements similar to Excel. I use "with" to cut down on the typing needed:

data$group2 <- with(data, ifelse(wt >= 179 & wt < 200, 1,
  ifelse(wt >= 200 & wt < 300, 2, 3))
)


问:
A bug that occurs during the synchronization test of a thread. Task cannot block the thread from running the following code
Questions are as follows:
According to MSDN, when a thread acquires the lock, Monitor.Enter blocks other threads until the thread releases the lock. However, during the test, Monitor.Enter (object) can block other threads from running the following code block in the case of Thread, and it still runs the following code block without blocking in the case of Task.

```<code>class program
{
    static void Main(string[] ars)
    {
        for(int i = 0; i <5; i++)
        {
            new Thread(Func){ IsBackground = true}.Start();
        }
        Console.ReadKey();

        //for(int i = 0;i< 5;i++)
        //{
        //  Task.Factory.StartNew(Func);
        //}
        Console.ReadKey();
    }

    static void Func()
    {
        Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}");
    bool b = false;
    Monitor.Enter(locker, ref b);
    Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId} 执行 b = {b}");
    }
}
</code>```

The result：
Task：

Thread：

Result: As shown in the figure above, Task performs Monitor.Enter (locker) and executes the following code twice, while Thread executes it only once.

Reason: Personally suspect that the same thread can continue to run without releasing the lock?
Hope answer

答:
Monitor locks can be entered by the same thread repeatedly several times and will unlock it once the same number of releases are done. This is called reentrancy.</p>

```<code>   private void MonitorSameThreadTest() {
    var obj = new object();

    lock (obj) {
        // Lock obtained. Must exit once to release.
        // No *other* thread can obtain a lock on obj
        // until this (outermost) "lock" completes.
        lock (obj) {
            // Same thread can actually enter again
            var lockTaken = false;
            try {
                Monitor.Enter(obj, ref lockTaken);
                // Same thread can actually enter again
                // We've *re-entered* lock again.
            }
            finally {
                if (lockTaken) Monitor.Exit(obj);

                // Must exit twice to release.
            }
        }
        // Must exit once to release.
    }
    // the lock allowing other threads to obtain it.
}
</code>```

Body:
Questions are as follows:
According to MSDN, when a thread acquires the lock, Monitor.Enter blocks other threads until the thread releases the lock. However, during the test, Monitor.Enter (object) can block other threads from running the following code block in the case of Thread, and it still runs the following code block without blocking in the case of Task.

class program
{
    static void Main(string[] ars)
    {
        for(int i = 0; i <5; i++)
        {
            new Thread(Func){ IsBackground = true}.Start();
        }
        Console.ReadKey();

        //for(int i = 0;i< 5;i++)
        //{
        //  Task.Factory.StartNew(Func);
        //}
        Console.ReadKey();
    }

    static void Func()
    {
        Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}");
    bool b = false;
    Monitor.Enter(locker, ref b);
    Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId} 执行 b = {b}");
    }
}

The result：
Task：

Thread：

Result: As shown in the figure above, Task performs Monitor.Enter (locker) and executes the following code twice, while Thread executes it only once.

Reason: Personally suspect that the same thread can continue to run without releasing the lock?
Hope answer

Body:
Monitor locks can be entered by the same thread repeatedly several times and will unlock it once the same number of releases are done. This is called reentrancy.

   private void MonitorSameThreadTest() {
    var obj = new object();

    lock (obj) {
        // Lock obtained. Must exit once to release.
        // No *other* thread can obtain a lock on obj
        // until this (outermost) "lock" completes.
        lock (obj) {
            // Same thread can actually enter again
            var lockTaken = false;
            try {
                Monitor.Enter(obj, ref lockTaken);
                // Same thread can actually enter again
                // We've *re-entered* lock again.
            }
            finally {
                if (lockTaken) Monitor.Exit(obj);

                // Must exit twice to release.
            }
        }
        // Must exit once to release.
    }
    // the lock allowing other threads to obtain it.
}