问:
Axios blocked by CORS policy with Django REST Framework
I'm trying to make requests to my API(Django REST Framework) using Axios but I get the following error:

```<code>Access to XMLHttpRequest at 'http://trvl.hopto.org:8000/api/airports/MSP/routes' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</code>```

Even tough when you use cUrl to check:

```<code>curl -I -X GET   -H "Origin: http://localhost:3000"   -H 'Access-Control-Request-Method: GET'   http://trvl.hopto.org:8000/api/airports/MSP/routes 2>&1 | grep 'Access-Control-Allow-Origin'
Response: Access-Control-Allow-Origin: *

Full response from cUrl Options:
OPTIONS request: curl -I -X OPTIONS   -H "Origin: http://localhost:3000"   -H 'Access-Control-Request-Method: GET'   http://trvl.hopto.org:8000/api/airports/MSP/routes
HTTP/1.1 200 OK
Date: Wed, 27 Mar 2019 10:58:01 GMT
Server: WSGIServer/0.2 CPython/3.6.8
Content-Type: text/html; charset=utf-8
Content-Length: 0
Vary: Origin
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: accept, accept-encoding, authorization, content-type, dnt, origin, user-agent, x-csrftoken, x-requested-with
Access-Control-Allow-Methods: DELETE, GET, OPTIONS, PATCH, POST, PUT
Access-Control-Max-Age: 86400
</code>```

When using Axios:

```<code>let url = 'http://A.hopto.org:8000/api/airports/MSP/routes';

axios.get(url)
      .catch((err) => {
        console.error(err);
      })
      .then((response, ) => {
        console.log(response);
      });

Response:
Access to XMLHttpRequest at 'http://API.hopto.org:8000/api/airports/MSP/routes' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</code>```

The problem is the API has the CORS enabled but I cannot make it work with Axios and React in my WebApp.

UPDATE:

```<code>Here is my Django settings.py I'm using the https://github.com/ottoyiu/django-cors-headers module.

**settings.py**

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']

# Application definition

INSTALLED_APPS = [
    'corsheaders',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'trvl',
    'rest_framework',
    'coreapi',
    'django_filters',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    #'corsheaders.middleware.CorsPostCsrfMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware'
]

CORS_ORIGIN_ALLOW_ALL = True
</code>```

答:
This is because you forgot '/' at the end of your url.</p>
```<code>let url = 'http://A.hopto.org:8000/api/airports/MSP/routes/';
</code>```

Body:
I'm trying to make requests to my API(Django REST Framework) using Axios but I get the following error:

Access to XMLHttpRequest at 'http://trvl.hopto.org:8000/api/airports/MSP/routes' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Even tough when you use cUrl to check:

curl -I -X GET   -H "Origin: http://localhost:3000"   -H 'Access-Control-Request-Method: GET'   http://trvl.hopto.org:8000/api/airports/MSP/routes 2>&1 | grep 'Access-Control-Allow-Origin'
Response: Access-Control-Allow-Origin: *

Full response from cUrl Options:
OPTIONS request: curl -I -X OPTIONS   -H "Origin: http://localhost:3000"   -H 'Access-Control-Request-Method: GET'   http://trvl.hopto.org:8000/api/airports/MSP/routes
HTTP/1.1 200 OK
Date: Wed, 27 Mar 2019 10:58:01 GMT
Server: WSGIServer/0.2 CPython/3.6.8
Content-Type: text/html; charset=utf-8
Content-Length: 0
Vary: Origin
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: accept, accept-encoding, authorization, content-type, dnt, origin, user-agent, x-csrftoken, x-requested-with
Access-Control-Allow-Methods: DELETE, GET, OPTIONS, PATCH, POST, PUT
Access-Control-Max-Age: 86400

When using Axios:

let url = 'http://A.hopto.org:8000/api/airports/MSP/routes';

axios.get(url)
      .catch((err) => {
        console.error(err);
      })
      .then((response, ) => {
        console.log(response);
      });

Response:
Access to XMLHttpRequest at 'http://API.hopto.org:8000/api/airports/MSP/routes' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

The problem is the API has the CORS enabled but I cannot make it work with Axios and React in my WebApp.

UPDATE:

Here is my Django settings.py I'm using the https://github.com/ottoyiu/django-cors-headers module.

**settings.py**

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']

# Application definition

INSTALLED_APPS = [
    'corsheaders',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'trvl',
    'rest_framework',
    'coreapi',
    'django_filters',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    #'corsheaders.middleware.CorsPostCsrfMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware'
]

CORS_ORIGIN_ALLOW_ALL = True

Body:
This is because you forgot '/' at the end of your url.

let url = 'http://A.hopto.org:8000/api/airports/MSP/routes/';


来源: stackexchange

问:
Cloud Functions in Firebase Realtime Database
i've a database structure like this:

```<code>root: {
       timer: 1,
       data: {
                id1: val,
                id2: val,
       },
       cronology: {
                id:{
                       id1: val,
                       id2: val,
                },
                id:{
                       id1: val,
                       id2: val,
                }
         }
</code>```

I'm trying to make a trigger that, when the timer value is modified, it adds to cronology a child that contains the actual values of the path: '/data'.
So i created a function with the onUpdate method on the DatabaseReference '/timer'. The problem is that i  don't know how to access to '/data' values in this function

```<code>export const cronologyBuilder = functions.database.ref("/timer")
.onUpdate((change, context) => {
    const newdata = admin.database.ref('/data');

    return admin.database.ref('/cronology').set(newdata);
});
</code>```

I tried with this code but it tells me that newdata object is not good for set method.
How can i get the values of '/data' path ?

答:
Your code is not actually querying for any data.  This line of code just builds a Reference object.  It does not contain any data:

```<code>const newdata = admin.database.ref('/data');
</code>```

If you want to query that location, you will need to call once() on it and use the returned promise to wait for the data at that location:

```<code>return admin.database.ref('/data').once('value')
.then(snapshot => {
    return admin.database.ref('/cronology').set(snapshot.val());
})
</code>```

I suggest reading the documentation for the Admin SDK database API to learn how to read and write data.  You will also need to understand how promises work in order to deal with them properly.

ContentLicense: CC BY-SA 4.0

Body:
i've a database structure like this:

root: {
       timer: 1,
       data: {
                id1: val,
                id2: val,
       },
       cronology: {
                id:{
                       id1: val,
                       id2: val,
                },
                id:{
                       id1: val,
                       id2: val,
                }
         }

I'm trying to make a trigger that, when the timer value is modified, it adds to cronology a child that contains the actual values of the path: '/data'.
So i created a function with the onUpdate method on the DatabaseReference '/timer'. The problem is that i  don't know how to access to '/data' values in this function

export const cronologyBuilder = functions.database.ref("/timer")
.onUpdate((change, context) => {
    const newdata = admin.database.ref('/data');

    return admin.database.ref('/cronology').set(newdata);
});

I tried with this code but it tells me that newdata object is not good for set method.
How can i get the values of '/data' path ?

Body:
Your code is not actually querying for any data.  This line of code just builds a Reference object.  It does not contain any data:

const newdata = admin.database.ref('/data');

If you want to query that location, you will need to call once() on it and use the returned promise to wait for the data at that location:

return admin.database.ref('/data').once('value')
.then(snapshot => {
    return admin.database.ref('/cronology').set(snapshot.val());
})

I suggest reading the documentation for the Admin SDK database API to learn how to read and write data.  You will also need to understand how promises work in order to deal with them properly.


问:
Different type of panda Series elements, numpy ints, during list comprehension
I have noticed that in numpy 1.18.4 (and not in previous numpy versions) the element type during list comprehensions is different than accessing element-wise.
For example:

```<code>foo = pd.DataFrame(data={'a': np.array([1, 2, 3]), 'b': np.array([1, 0, 1])})
var = {type(x) == type(foo['a'][i]) for i, x in enumerate(foo['a'])}
</code>```

I get var = {False}. What is the reason for this? Why was it not the case before?

Ideally I would like to avoid ZeroDivisionError when dividing by zero but instead get the usual 'inf' produced by numpy.int32, when doing:

```<code>[0 if x == 0 and z == 0 else x / y for x, y, z in zip(foo['a'], foo['b'], c)]
</code>```

for c another array of int32's. Is there any way to do this without re transforming the elements to np.int32 inside the list comprehension?

答:
IIUC what you want, you can use to_numpy on the columns from foo.

```<code>foo = pd.DataFrame(data={'a':np.array([0,2,3]), 'b': np.array([1,0,1])})
c = np.array([0,1,1])

[0 if x == 0 and z == 0 else x / y
 for x, y, z in zip(foo['a'].to_numpy(), foo['b'].to_numpy(), c)]
# [0, inf, 3.0]
</code>```

It works although it raises this RuntimeWarning: divide by zero encountered in long_scalars

Another alternative is to specify a pandas type likepd.Int32Dtype when creating foo:

```<code>foo = pd.DataFrame(data={'a':np.array([0,2,3]), 'b': np.array([1,0,1])},
                   dtype=pd.Int32Dtype())
# or if foo exsit already you use astype with
# foo = foo.astype(pd.Int32Dtype())

c = np.array([0,1,1])
[0 if x == 0 and z == 0 else x / y for x, y, z in zip(foo['a'], foo['b'], c)]
</code>```

same result

Body:
I have noticed that in numpy 1.18.4 (and not in previous numpy versions) the element type during list comprehensions is different than accessing element-wise.
For example:

foo = pd.DataFrame(data={'a': np.array([1, 2, 3]), 'b': np.array([1, 0, 1])})
var = {type(x) == type(foo['a'][i]) for i, x in enumerate(foo['a'])}

I get var = {False}. What is the reason for this? Why was it not the case before?

Ideally I would like to avoid ZeroDivisionError when dividing by zero but instead get the usual 'inf' produced by numpy.int32, when doing:

[0 if x == 0 and z == 0 else x / y for x, y, z in zip(foo['a'], foo['b'], c)]

for c another array of int32's. Is there any way to do this without re transforming the elements to np.int32 inside the list comprehension?

Body:
IIUC what you want, you can use to_numpy on the columns from foo.

foo = pd.DataFrame(data={'a':np.array([0,2,3]), 'b': np.array([1,0,1])})
c = np.array([0,1,1])

[0 if x == 0 and z == 0 else x / y
 for x, y, z in zip(foo['a'].to_numpy(), foo['b'].to_numpy(), c)]
# [0, inf, 3.0]

It works although it raises this RuntimeWarning: divide by zero encountered in long_scalars

Another alternative is to specify a pandas type likepd.Int32Dtype when creating foo:

foo = pd.DataFrame(data={'a':np.array([0,2,3]), 'b': np.array([1,0,1])},
                   dtype=pd.Int32Dtype())
# or if foo exsit already you use astype with
# foo = foo.astype(pd.Int32Dtype())

c = np.array([0,1,1])
[0 if x == 0 and z == 0 else x / y for x, y, z in zip(foo['a'], foo['b'], c)]

same result


问:
Entity class defines non-transient non-serializable instance field price
Below little bit of code showing SONAR bug like :Class com.sample.Submit defines non-transient non-serializable instance field price. How can we get rid from this issue.

Code

```<code>@JsonIgnoreProperties(ignoreUnknown = true)
public class Submit implements Serializable {

    /**
     * serialVersionUID of type long.
     */
    private static final long serialVersionUID = 0L;

    @JsonProperty("billCode")
    private String billCode;

    @JsonProperty("displayName")
    private String displayName;

    @JsonProperty("visible")
    private Boolean visible;

    @JsonProperty("price")
    private Price price;

    public Boolean getVisible() {
        return visible;
    }

    public void setVisible(Boolean visible) {
        this.visible = visible;
    }

    public String getBillCode() {
        return billCode;
    }

    public void setBillCode(String billCode) {
        this.billCode = billCode;
    }

    public String getDisplayName() {
        return displayName;
    }

    public void setDisplayName(String displayName) {
        this.displayName = displayName;
    }

    public Price getPrice() {
        return price;
    }

    public void setPrice(Price price) {
        this.price = price;
    }

}
</code>```

答:
Declare your class Price serializable as follows:

```<code>public class Price implements Serializable {
    ...
}
</code>```

Body:
Below little bit of code showing SONAR bug like :Class com.sample.Submit defines non-transient non-serializable instance field price. How can we get rid from this issue.

Code

@JsonIgnoreProperties(ignoreUnknown = true)
public class Submit implements Serializable {

    /**
     * serialVersionUID of type long.
     */
    private static final long serialVersionUID = 0L;

    @JsonProperty("billCode")
    private String billCode;

    @JsonProperty("displayName")
    private String displayName;

    @JsonProperty("visible")
    private Boolean visible;

    @JsonProperty("price")
    private Price price;

    public Boolean getVisible() {
        return visible;
    }

    public void setVisible(Boolean visible) {
        this.visible = visible;
    }

    public String getBillCode() {
        return billCode;
    }

    public void setBillCode(String billCode) {
        this.billCode = billCode;
    }

    public String getDisplayName() {
        return displayName;
    }

    public void setDisplayName(String displayName) {
        this.displayName = displayName;
    }

    public Price getPrice() {
        return price;
    }

    public void setPrice(Price price) {
        this.price = price;
    }

}

Body:
Declare your class Price serializable as follows:

public class Price implements Serializable {
    ...
}


问:
SQL Server Left Join producing duplicates
I have 3 tables, Budgets, Income, and Expenses.

Budget table:

Income table:

Expenses table:

This is my SQL statement:

```<code>SELECT
    Budgets.BudgetID, Budgets.BudgetName, Budgets.Username_FK,
    Budgets.BudgetAmount, Budgets.SavePercentage,
    Expenses.ExpensesID, Expenses.ExpensesAmount, Expenses.ExpensesCategory,
    Income.IncomeID, Income.IncomeAmount, Income.IncomeCategory
FROM
    Budgets
LEFT JOIN
    Income ON Budgets.BudgetID = Income.BudgetID_FK
LEFT JOIN
    Expenses ON Budgets.BudgetID = Expenses.BudgetID_FK
WHERE
    BudgetName = '2019
</code>```

And the results are as follows:

Based on my Income table, there is only 1 record tied to BudgetID = 3, but in the left join, it duplicates.

Ideally, I would want it to return "null" on the duplicates. How do I do this?

答:
You have several rows in expenses per budgetID, so your join produces that many rows. I tend to suspect that the same situation could happen with income too.

If you want one row per budgetID, then one option is pre-aggregation and a left join (or outer apply). Say you want the total expense and income per budget, you would do:

```<code>select b.*, e.expenseAmount, i.amountAmount
from budgets b
left join (
    select budgetID_FK, sum(expenseAmount) expenseAmount
    from expenses
    group by budgetID_FK
) e on e.budgetID_FK = b.budgetID
left join (
    select budgetID_FK, sum(incomeAmount) incomeAmount
    from income
    group by budgetID_FK
) i on i.budgetID_FK = b.budgetID
</code>```

Now you are grouping rows in the dependent tables by budgetID, so you can't see the other columns of these tables, such as incomeCategory or expenseCategory (which have multiple values per budgetID).

Body:
I have 3 tables, Budgets, Income, and Expenses.

Budget table:

Income table:

Expenses table:

This is my SQL statement:

SELECT
    Budgets.BudgetID, Budgets.BudgetName, Budgets.Username_FK,
    Budgets.BudgetAmount, Budgets.SavePercentage,
    Expenses.ExpensesID, Expenses.ExpensesAmount, Expenses.ExpensesCategory,
    Income.IncomeID, Income.IncomeAmount, Income.IncomeCategory
FROM
    Budgets
LEFT JOIN
    Income ON Budgets.BudgetID = Income.BudgetID_FK
LEFT JOIN
    Expenses ON Budgets.BudgetID = Expenses.BudgetID_FK
WHERE
    BudgetName = '2019

And the results are as follows:

Based on my Income table, there is only 1 record tied to BudgetID = 3, but in the left join, it duplicates.

Ideally, I would want it to return "null" on the duplicates. How do I do this?

Body:
You have several rows in expenses per budgetID, so your join produces that many rows. I tend to suspect that the same situation could happen with income too.

If you want one row per budgetID, then one option is pre-aggregation and a left join (or outer apply). Say you want the total expense and income per budget, you would do:

select b.*, e.expenseAmount, i.amountAmount
from budgets b
left join (
    select budgetID_FK, sum(expenseAmount) expenseAmount
    from expenses
    group by budgetID_FK
) e on e.budgetID_FK = b.budgetID
left join (
    select budgetID_FK, sum(incomeAmount) incomeAmount
    from income
    group by budgetID_FK
) i on i.budgetID_FK = b.budgetID

Now you are grouping rows in the dependent tables by budgetID, so you can't see the other columns of these tables, such as incomeCategory or expenseCategory (which have multiple values per budgetID).


问:
how to rename the object key in nested array of object in javascript dynamically
I need to rename the object key name dynamically in a nested array of object JavaScript, I had tried with this code. This also I got from Stack Overflow only but this is not working that means it checking first level only not doing deep replacing.

```<code>const node = {
  'id': 'de603a3e',
  'name': 'erewr',
  'subGroups': [
     {
        'id': '83d7c7e4',
        'name': 'dfds',
        'subGroups': [ ]
     },
     {
        'id': '050cde96',
        'name': 'tetwet',
        'subGroups': [ ]
     },
     {
        'id': 'd67cc4e8',
        'name': 'wewqe',
        'subGroups': [
           {
              'id': '553c301d',
              'name': 'ewqe',
              'subGroups': [

              ]
           }
        ]
     },
     {
        'id': '5d5ae5f2',
        'name': 'rwq',
        'subGroups': [
           {
              'id': 'ff29ad54',
              'name': 'wqe',
              'subGroups': [

              ]
           },
           {
              'id': '5d013943',
              'name': 'weqe',
              'subGroups': [

              ]
           }
        ]
     }
  ]
}

console.log(renameKey(node, { subGroups: 'subordinates' }))

renameKey(obj, keysMap) {
    return transform(obj, function(result, value, key) {
      const currentKey = keysMap[key] || key;
      result[currentKey] = isObject(value) ? this.renameKey(value, keysMap) : value;
    });
  }
</code>```

I am using this code in TypeScript.
note : transform and isObject are lodash

I am getting error ERROR TypeError: Cannot read property 'replaceKeysDeep' of undefined

答:
const node = {
  'id': 'de603a3e',
  'name': 'erewr',
  'subGroups': [
     {
        'id': '83d7c7e4',
        'name': 'dfds',
        'subGroups': [ ]
     },
     {
        'id': '050cde96',
        'name': 'tetwet',
        'subGroups': [ ]
     },
     {
        'id': 'd67cc4e8',
        'name': 'wewqe',
        'subGroups': [
           {
              'id': '553c301d',
              'name': 'ewqe',
              'subGroups': [

              ]
           }
        ]
     },
     {
        'id': '5d5ae5f2',
        'name': 'rwq',
        'subGroups': [
           {
              'id': 'ff29ad54',
              'name': 'wqe',
              'subGroups': [

              ]
           },
           {
              'id': '5d013943',
              'name': 'weqe',
              'subGroups': [

              ]
           }
        ]
     }
  ]
}

console.log(renameKey(node, { subGroups: 'subordinates' }))

function renameKey(obj, keysMap) {
    return _.transform(obj, function(result, value, key) {
      const currentKey = keysMap[key] || key;
      result[currentKey] = _.isObject(value) ? renameKey(value, keysMap) : value;
    });
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script></code>```

Body:
I need to rename the object key name dynamically in a nested array of object JavaScript, I had tried with this code. This also I got from Stack Overflow only but this is not working that means it checking first level only not doing deep replacing.

const node = {
  'id': 'de603a3e',
  'name': 'erewr',
  'subGroups': [
     {
        'id': '83d7c7e4',
        'name': 'dfds',
        'subGroups': [ ]
     },
     {
        'id': '050cde96',
        'name': 'tetwet',
        'subGroups': [ ]
     },
     {
        'id': 'd67cc4e8',
        'name': 'wewqe',
        'subGroups': [
           {
              'id': '553c301d',
              'name': 'ewqe',
              'subGroups': [

              ]
           }
        ]
     },
     {
        'id': '5d5ae5f2',
        'name': 'rwq',
        'subGroups': [
           {
              'id': 'ff29ad54',
              'name': 'wqe',
              'subGroups': [

              ]
           },
           {
              'id': '5d013943',
              'name': 'weqe',
              'subGroups': [

              ]
           }
        ]
     }
  ]
}

console.log(renameKey(node, { subGroups: 'subordinates' }))

renameKey(obj, keysMap) {
    return transform(obj, function(result, value, key) {
      const currentKey = keysMap[key] || key;
      result[currentKey] = isObject(value) ? this.renameKey(value, keysMap) : value;
    });
  }

I am using this code in TypeScript.
note : transform and isObject are lodash

I am getting error ERROR TypeError: Cannot read property 'replaceKeysDeep' of undefined

Body:
const node = {
  'id': 'de603a3e',
  'name': 'erewr',
  'subGroups': [
     {
        'id': '83d7c7e4',
        'name': 'dfds',
        'subGroups': [ ]
     },
     {
        'id': '050cde96',
        'name': 'tetwet',
        'subGroups': [ ]
     },
     {
        'id': 'd67cc4e8',
        'name': 'wewqe',
        'subGroups': [
           {
              'id': '553c301d',
              'name': 'ewqe',
              'subGroups': [

              ]
           }
        ]
     },
     {
        'id': '5d5ae5f2',
        'name': 'rwq',
        'subGroups': [
           {
              'id': 'ff29ad54',
              'name': 'wqe',
              'subGroups': [

              ]
           },
           {
              'id': '5d013943',
              'name': 'weqe',
              'subGroups': [

              ]
           }
        ]
     }
  ]
}

console.log(renameKey(node, { subGroups: 'subordinates' }))

function renameKey(obj, keysMap) {
    return _.transform(obj, function(result, value, key) {
      const currentKey = keysMap[key] || key;
      result[currentKey] = _.isObject(value) ? renameKey(value, keysMap) : value;
    });
  }

<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>


问:
Remove value from array on click React.js
Im building an image slider that maps out and lists an array of image url's.

I'm trying to save an array of image urls that the user wants to hide from view.

My plan is to store the array value in a dynamoDB table, then retrieve the array of urls that do not want to be shown, and then filter them out from the mapped images in the slider.

I have an EyeOFF icon shown over the image they click, and that toggles the icon hide true and false with the onClick prop of the image and the icon. --- see const handleBottomImageClick().

My issue is that Im unable to remove the value of the image (img url) from the array thats saved in the state variable selectedImage. --- see const handleTopImageClick().

I tried array.pop(), and array.splice(), but I don't know if those methods would work efficiently for what i'm trying to do.

Slider Component

```<code>import React, { useState, useEffect, useRef } from "react";
import { IonModal, IonContent, IonButton, IonIcon, IonGrid, IonRow, IonCol, IonItem, IonLabel } from '@ionic/react';
import { chevronBackOutline, chevronForwardOutline } from 'ionicons/icons';
import { Storage } from "aws-amplify";
import Image from '../components/SliderImages.js';
import FullImage from '../components/LargeSliderImage.js';
import Slider from "react-slick";
import "slick-carousel/slick/slick.scss";
import { chunk } from 'lodash';
import Modal from 'react-modal';
import { eyeOffOutline, createSharp, shareSharp } from 'ionicons/icons';

const SliderComponent = (props) => {

    const { job, hideImages } = props;
    const [selectedImage, setSlectedImage] = useState([]);
    const [images, setImages] = useState([]);
    const [showModal, setShowModal] = useState(false);
    const [activeSlide, setActiveSlide] = useState(false);
    const [initialSlide, setInitialSlide] = useState(0)
    const [state, setState] = useState({
        nav1: null,
        nav2: null
    });
    const slider1 = useRef();
    const slider2 = useRef();

       let imagesToHide = [];

    const SlickArrowLeft = ({ ...props }) => (

        <IonIcon  {...props} type="button" size="large" icon={chevronBackOutline} />

    );

    const SlickArrowRight = ({ ...props }) => (
        <IonIcon {...props} type="button" size="large" icon={chevronForwardOutline} />
    );

    const customStyles = {
        content: {
            top: '50%',
            left: '50%',
            right: 'auto',
            bottom: 'auto',
            marginRight: '-50%',
            transform: 'translate(-50%, -50%)'
        }
    };

    useEffect(() => {
        setState({
            nav1: slider1.current,
            nav2: slider2.current
        });
    }, []);

    const {
        nav1,
        nav2
    } = state;

    const settings = {
        infinite: false,
        lazyLoad: "ondemand",
        useCSS: true,
        useTransform: true,
        slidesToShow: 5,
        slidesToScroll: 5,
        speed: 500,
        initialSlide: 0,
        autoHeight: false,
        draggable: true,
        arrows: true,
        prevArrow: <SlickArrowLeft class="prevArrowButton" />,
        nextArrow: <SlickArrowRight class="nextArrowButton" />,

        responsive: [
            {
                breakpoint: 1024,
                settings: {
                    lazyLoad: "ondemand",
                    slidesToShow: 4,
                    slidesToScroll: 4,
                    speed: 500,
                    initialSlide: 0,
                    autoHeight: false,

                    arrows: false,
                }
            },
            {
                breakpoint: 600,
                settings: {
                    lazyLoad: "ondemand",
                    slidesToShow: 3,
                    slidesToScroll: 3,
                    speed: 500,
                    initialSlide: 0,
                    autoHeight: false,

                    arrows: false,

                }
            },
            {
                breakpoint: 480,
                settings: {
                    lazyLoad: "ondemand",
                    slidesToShow: 2,
                    slidesToScroll: 2,
                    speed: 500,
                    initialSlide: 0,
                    autoHeight: false,

                    arrows: true,
                    prevArrow: <SlickArrowLeft class="prevArrowButton" />,
                    nextArrow: <SlickArrowRight class="nextArrowButton" />,
                }
            }
        ]
    };

    const viewSettings = {
        infinite: true,
        lazyLoad: "ondemand",
        slidesToShow: 1,
        slidesToScroll: 1,
        speed: 500,
        autoHeight: false,
        focusOnSelect: false,
        initialSlide: initialSlide,
        arrows: true,
        prevArrow: <SlickArrowLeft class="prevArrowButton" />,
        nextArrow: <SlickArrowRight class="nextArrowButton" />,

    }

    useEffect(() => {
        async function onLoad() {

            try {
                const downloadedImage = await getImage(job);
                setImages(downloadedImage);
            } catch (e) {
                alert(e);
            }
        }

        onLoad();
    }, [job]);

    async function getImage(jobID) {
        const imageURL = await Storage.list(`${jobID}/completed/`);
        let imagesToDownload = imageURL
        let imagesAsArray = [];
        for (let i = 0; i < imagesToDownload.length; i++) {
            const imagesDownloaded = await getURLFromS3(imagesToDownload[i]);
            imagesAsArray.push(imagesDownloaded)
        }
        return imagesAsArray
    }

    async function getURLFromS3(fileToDownload) {
        const result = await Storage.get(fileToDownload.key)
        return result;
    }

    const handleBottomImageClick = function (index, image2) {
        if (hideImages) {
            if (selectedImage[image2]) {
                setSlectedImage({ ...selectedImage, [image2]: false })
            } else {
                setSlectedImage({ ...selectedImage, [image2]: !selectedImage[image2] })
            }

        } else {

            setShowModal(true)
            const i = index + index + 1
            setInitialSlide(i)

        }

    }

    const handleTopImageClick = function (index, image1) {
        if (hideImages) {
            if (selectedImage[image1]) {
                const arr = [selectedImage]
                arr.splice(selectedImage[image1])
                setSlectedImage(arr)
            } else {
                setSlectedImage({ ...selectedImage, [image1]: !selectedImage[image1]})
            }
        } else {
            setShowModal(true)
            const i = index + index
            setInitialSlide(i)
        }
    }

    return (
        <>
            {hideImages ? (

                <div className="ion-padding" style={{ textAlign: "center" }}>
                    <IonLabel position="stacked"> Select the images you want to hide from the customer view. Tap finished when done. </IonLabel>
                    <br /><br />
                    <div style={{ justifyContent: 'center', display: "flex" }}>
                        <IonButton onClick={() => console.log(selectedImage)} size="small">
                            Finished
                    </IonButton>
                    </div>
                    <br />
                </div>

            ) : (
                    null
                )}
            <div style={{ justifyContent: 'center', display: "flex" }}>

                <Slider className="image-slider-frame" asNavFor={nav1} ref={slider => (slider1.current = slider)} {...settings}>
                    {chunk(images, 2).map(([image1, image2], i) =>

                        <ul className="listing-image-slidee" key={i}>

                            <div>
                                <li className="listing-image-pairs">
                                    <img onClick={() => {handleTopImageClick(i, image1);} } height="206px" width="272px" className="img" src={image1} />
                                    <IonIcon onClick={() => handleTopImageClick(i, image1)} className="image-hide" key={image1} size="large" hidden={selectedImage[image1] ? false : true} icon={eyeOffOutline} />
                                </li>
                            </div>

                            <div >
                                {image2 && <li className="listing-image-pairs">
                                    <img onClick={() => handleBottomImageClick(i, image2)} height="206px" width="272px" className="img" src={image2} />
                                    <IonIcon className="image-hide" key={image2} size="large" onClick={() => handleBottomImageClick(i, image2)} hidden={selectedImage[image2] ? false : true} icon={eyeOffOutline} />
                                </li>}
                            </div>

                        </ul>

                    )}
                </Slider>

            </div>
            <div>

                <Modal ariaHideApp={false} className="Modal" isOpen={showModal}>
                    <IonGrid>
                        <IonRow clasName="ion-no-padding" style={{ justifyContent: 'center' }} >
                            <IonCol sizeXs="13" sizeSm="13" sizeMd="9" sizeLg="7" sizeXl="7" >
                                <Slider style={{ maxHeight: "768px" }} asNavFor={nav2} ref={slider => (slider2.current = slider)}  {...viewSettings}>
                                    {(images).map((image, i) =>
                                        <div>
                                            <br />
                                            <img src={image} />
                                        </div>

                                    )}
                                </Slider>
                                <br/>
                                <IonItem lines="none">
                                    <IonButton size="small" color="secondary" slot="end" onClick={() => setShowModal(false)}>close</IonButton>
                                </IonItem>
                            </IonCol>
                        </IonRow>
                    </IonGrid>
                </Modal>

            </div>
        </>
    )
}
export default SliderComponent;
</code>```

答:
You should not use splice or pop to remove item from an array, because it mutates react state directly. You may use the filter function to remove that item. The filter function returns a new array without modifying the original one.

```<code>const newArr = selectedImage.filter(item => item !== image1);
setSelectedImage(newArr);
</code>```

Body:
Im building an image slider that maps out and lists an array of image url's.

I'm trying to save an array of image urls that the user wants to hide from view.

My plan is to store the array value in a dynamoDB table, then retrieve the array of urls that do not want to be shown, and then filter them out from the mapped images in the slider.

I have an EyeOFF icon shown over the image they click, and that toggles the icon hide true and false with the onClick prop of the image and the icon. --- see const handleBottomImageClick().

My issue is that Im unable to remove the value of the image (img url) from the array thats saved in the state variable selectedImage. --- see const handleTopImageClick().

I tried array.pop(), and array.splice(), but I don't know if those methods would work efficiently for what i'm trying to do.

Slider Component

import React, { useState, useEffect, useRef } from "react";
import { IonModal, IonContent, IonButton, IonIcon, IonGrid, IonRow, IonCol, IonItem, IonLabel } from '@ionic/react';
import { chevronBackOutline, chevronForwardOutline } from 'ionicons/icons';
import { Storage } from "aws-amplify";
import Image from '../components/SliderImages.js';
import FullImage from '../components/LargeSliderImage.js';
import Slider from "react-slick";
import "slick-carousel/slick/slick.scss";
import { chunk } from 'lodash';
import Modal from 'react-modal';
import { eyeOffOutline, createSharp, shareSharp } from 'ionicons/icons';

const SliderComponent = (props) => {

    const { job, hideImages } = props;
    const [selectedImage, setSlectedImage] = useState([]);
    const [images, setImages] = useState([]);
    const [showModal, setShowModal] = useState(false);
    const [activeSlide, setActiveSlide] = useState(false);
    const [initialSlide, setInitialSlide] = useState(0)
    const [state, setState] = useState({
        nav1: null,
        nav2: null
    });
    const slider1 = useRef();
    const slider2 = useRef();

       let imagesToHide = [];

    const SlickArrowLeft = ({ ...props }) => (

        <IonIcon  {...props} type="button" size="large" icon={chevronBackOutline} />

    );

    const SlickArrowRight = ({ ...props }) => (
        <IonIcon {...props} type="button" size="large" icon={chevronForwardOutline} />
    );

    const customStyles = {
        content: {
            top: '50%',
            left: '50%',
            right: 'auto',
            bottom: 'auto',
            marginRight: '-50%',
            transform: 'translate(-50%, -50%)'
        }
    };

    useEffect(() => {
        setState({
            nav1: slider1.current,
            nav2: slider2.current
        });
    }, []);

    const {
        nav1,
        nav2
    } = state;

    const settings = {
        infinite: false,
        lazyLoad: "ondemand",
        useCSS: true,
        useTransform: true,
        slidesToShow: 5,
        slidesToScroll: 5,
        speed: 500,
        initialSlide: 0,
        autoHeight: false,
        draggable: true,
        arrows: true,
        prevArrow: <SlickArrowLeft class="prevArrowButton" />,
        nextArrow: <SlickArrowRight class="nextArrowButton" />,

        responsive: [
            {
                breakpoint: 1024,
                settings: {
                    lazyLoad: "ondemand",
                    slidesToShow: 4,
                    slidesToScroll: 4,
                    speed: 500,
                    initialSlide: 0,
                    autoHeight: false,

                    arrows: false,
                }
            },
            {
                breakpoint: 600,
                settings: {
                    lazyLoad: "ondemand",
                    slidesToShow: 3,
                    slidesToScroll: 3,
                    speed: 500,
                    initialSlide: 0,
                    autoHeight: false,

                    arrows: false,

                }
            },
            {
                breakpoint: 480,
                settings: {
                    lazyLoad: "ondemand",
                    slidesToShow: 2,
                    slidesToScroll: 2,
                    speed: 500,
                    initialSlide: 0,
                    autoHeight: false,

                    arrows: true,
                    prevArrow: <SlickArrowLeft class="prevArrowButton" />,
                    nextArrow: <SlickArrowRight class="nextArrowButton" />,
                }
            }
        ]
    };

    const viewSettings = {
        infinite: true,
        lazyLoad: "ondemand",
        slidesToShow: 1,
        slidesToScroll: 1,
        speed: 500,
        autoHeight: false,
        focusOnSelect: false,
        initialSlide: initialSlide,
        arrows: true,
        prevArrow: <SlickArrowLeft class="prevArrowButton" />,
        nextArrow: <SlickArrowRight class="nextArrowButton" />,

    }

    useEffect(() => {
        async function onLoad() {

            try {
                const downloadedImage = await getImage(job);
                setImages(downloadedImage);
            } catch (e) {
                alert(e);
            }
        }

        onLoad();
    }, [job]);

    async function getImage(jobID) {
        const imageURL = await Storage.list(`${jobID}/completed/`);
        let imagesToDownload = imageURL
        let imagesAsArray = [];
        for (let i = 0; i < imagesToDownload.length; i++) {
            const imagesDownloaded = await getURLFromS3(imagesToDownload[i]);
            imagesAsArray.push(imagesDownloaded)
        }
        return imagesAsArray
    }

    async function getURLFromS3(fileToDownload) {
        const result = await Storage.get(fileToDownload.key)
        return result;
    }

    const handleBottomImageClick = function (index, image2) {
        if (hideImages) {
            if (selectedImage[image2]) {
                setSlectedImage({ ...selectedImage, [image2]: false })
            } else {
                setSlectedImage({ ...selectedImage, [image2]: !selectedImage[image2] })
            }

        } else {

            setShowModal(true)
            const i = index + index + 1
            setInitialSlide(i)

        }

    }

    const handleTopImageClick = function (index, image1) {
        if (hideImages) {
            if (selectedImage[image1]) {
                const arr = [selectedImage]
                arr.splice(selectedImage[image1])
                setSlectedImage(arr)
            } else {
                setSlectedImage({ ...selectedImage, [image1]: !selectedImage[image1]})
            }
        } else {
            setShowModal(true)
            const i = index + index
            setInitialSlide(i)
        }
    }

    return (
        <>
            {hideImages ? (

                    <IonLabel position="stacked"> Select the images you want to hide from the customer view. Tap finished when done. </IonLabel>

                        <IonButton onClick={() => console.log(selectedImage)} size="small">
                            Finished
                    </IonButton>

            ) : (
                    null
                )}

                <Slider className="image-slider-frame" asNavFor={nav1} ref={slider => (slider1.current = slider)} {...settings}>
                    {chunk(images, 2).map(([image1, image2], i) =>

                                     {handleTopImageClick(i, image1);} } height="206px" width="272px" className="img" src={image1} />
                                    <IonIcon onClick={() => handleTopImageClick(i, image1)} className="image-hide" key={image1} size="large" hidden={selectedImage[image1] ? false : true} icon={eyeOffOutline} />

                                {image2 &&

                                     handleBottomImageClick(i, image2)} height="206px" width="272px" className="img" src={image2} />
                                    <IonIcon className="image-hide" key={image2} size="large" onClick={() => handleBottomImageClick(i, image2)} hidden={selectedImage[image2] ? false : true} icon={eyeOffOutline} />

}

                    )}
                </Slider>

                <Modal ariaHideApp={false} className="Modal" isOpen={showModal}>
                    <IonGrid>
                        <IonRow clasName="ion-no-padding" style={{ justifyContent: 'center' }} >
                            <IonCol sizeXs="13" sizeSm="13" sizeMd="9" sizeLg="7" sizeXl="7" >
                                <Slider style={{ maxHeight: "768px" }} asNavFor={nav2} ref={slider => (slider2.current = slider)}  {...viewSettings}>
                                    {(images).map((image, i) =>

                                    )}
                                </Slider>

                                <IonItem lines="none">
                                    <IonButton size="small" color="secondary" slot="end" onClick={() => setShowModal(false)}>close</IonButton>
                                </IonItem>
                            </IonCol>
                        </IonRow>
                    </IonGrid>
                </Modal>

        </>
    )
}
export default SliderComponent;

Body:
You should not use splice or pop to remove item from an array, because it mutates react state directly. You may use the filter function to remove that item. The filter function returns a new array without modifying the original one.

const newArr = selectedImage.filter(item => item !== image1);
setSelectedImage(newArr);


问:
Debugging Rust in VSCode, no debug symbols on library, but debug symbols on example
I'm trying to debug with LLDB on VSCode. I added a breakpoint into my library, it stops on the breakpoint but I get a call stack with unnamed symbols and I can't see any variables:

This is an example from the library, which I built with cargo build --example my_example_name. I researched and to build in release mode, --release should be added. So I think I built in debug mode.

I'd guess the library is being built somehow in release mode. How can I check this?

If I put the breakpoint in the example file itself, then the symbol appear when the breakpoint happens.
When I put the breakpoint in the library used by the example, then no symbols appear when the breakpoint happens.

Is it possible that cargo build --example my_example builds the example in debug mode but the library in release mode?

答:
According to https://doc.rust-lang.org/cargo/commands/cargo-build.html, "Dependencies use the dev/release profiles."

To override that, you could try RUSTFLAGS=-g cargo build ... (-g is equivalent to -C debuginfo=2).


问:
Shortest Process Next Scheduling Algorithm
I am wondering which answer is correct?For answer 1, when P5 is finish executing, then we compared about P3,P6 and P4 ,if we compare them according to the arrival time then P3 will execute first. So,my question is about do we need to follow the arrival time? Which answer is correct? Thanks.
This is the question image</p>

答:
The first answer is correct.

A case could be made that both are correct, but the first is "more correct."  The tiebreaker for this scheduling algorithm should be the arrival time.  Your goal is to minimize the process wait time, and it makes more sense to first run the process that has been waiting longer.

Algorithms like this will often use a priority queue, which would sort the elements from shortest burst time to longest burst time.  Queues use FIFO (first in, first out), which means if there are two elements with the same burst time, the one that was added first would be selected first.


答:
I'm assuming the 'date_of_purchase' column already has the datetime dtype.

```<code>>>> df
   customer_id  purchase_amount date_of_purchase
0          760             25.0       2009-06-11
1          860             50.0       2012-09-28
2         1200            100.0       2005-10-25
>>> df['days_since'] = df['date_of_purchase'].sub(pd.to_datetime('01/01/2016')).dt.days.abs()
>>> df
   customer_id  purchase_amount date_of_purchase  days_since
0          760             25.0       2009-06-11        2395
1          860             50.0       2012-09-28        1190
2         1200            100.0       2005-10-25        3720
</code>```

Title: Subtracting fix date from whole panda data frame - python

Body:
I have data

    customer_id purchase_amount date_of_purchase
0   760       25.0  06-11-2009
1   860      50.0   09-28-2012
2   1200    100.0   10-25-2005
3   1420    50.0    09-07-2009
4   1940    70.0    01-25-2013
5   1960    40.0    10-29-2013
6   2620    30.0    09-03-2006
7   3050    50.0    12-04-2007
8   3120    150.0   08-11-2006
9   3260    45.0    10-20-2010
10  3510    35.0    04-05-2013
11  3970    30.0    07-06-2007
12  4000    20.0    11-25-2005
13  4180    20.0    09-22-2010
14  4390    30.0    04-15-2011
15  4750    60.0    02-12-2013
16  4840    30.0    10-14-2005
17  4910    15.0    12-13-2006
18  4950    50.0    05-19-2010
19  4970    30.0    01-12-2006
20  5250    50.0    12-20-2005

Now I want to subtract 01-01-2016 from each row of date_of_purchase

I tried the following so I should have a new column days_since with a number of days.

NOW = pd.to_datetime('01/01/2016').strftime('%m-%d-%Y')
gb = customer_purchases_df.groupby('customer_id')
df2 = gb.agg({'date_of_purchase': lambda x: (NOW - x.max()).days})

any suggestion. how I can achieve this

Thanks in advance

Body:
I'm assuming the 'date_of_purchase' column already has the datetime dtype.

>>> df
   customer_id  purchase_amount date_of_purchase
0          760             25.0       2009-06-11
1          860             50.0       2012-09-28
2         1200            100.0       2005-10-25
>>> df['days_since'] = df['date_of_purchase'].sub(pd.to_datetime('01/01/2016')).dt.days.abs()
>>> df
   customer_id  purchase_amount date_of_purchase  days_since
0          760             25.0       2009-06-11        2395
1          860             50.0       2012-09-28        1190
2         1200            100.0       2005-10-25        3720


问:
Longest subArray with no more than two distinct values that differ by no more than 1
Given an array of integers what is the length of the longest subArray containing no more than two distinct values such that the distinct values differ by no more than 1

For Example:

arr = [0, 1, 2, 1, 2, 3] -> length = 4;  [1,2,1,2]

arr = [1, 2, 3, 4, 5] -> length = 2;  [1,2]

arr = [1, 1, 1, 3, 3, 2, 2] -> length = 4;  [3,3,2,2]

I have such code

```<code> public static int longestSubarray(List<Integer> arr) {
        int max = 0;
        Set<Integer> set = new HashSet<>();
        int i = 0;
        int j = 1;
        while (i < arr.size() - 1) {
            set.add(arr.get(i));
            while (j < arr.size() && Math.abs(arr.get(i) - arr.get(j)) < 2) {
                if (!set.contains(arr.get(j))) {
                    if (set.size() == 2) {
                        break;
                    } else {
                        set.add(arr.get(j));
                    }
                }
                ++j;
            }
            max = Math.max(max, j - i);
            j = ++i + 1;
            set.clear();
        }
        return max;
    }
</code>```

Can there be a better solution?

答:
C# code:</p>

```<code>using System.IO;
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> arr = new List<int>(){ 0, 1, 2, 1, 2, 3};
        List<int> set = new List<int>();
        int n = arr.Count;
        int max = 1;
        int i,j;
        for(i=0 ; i<n-1; i++)
        {
            set.Add(arr[i]);
            for(j=i+1; j<n; )
            {
                if(Math.Abs(arr[i]-arr[j])<2)
                {
                    if(!set.Contains(arr[j]))
                    {
                        if(set.Count == 2)
                        break;
                        else
                        set.Add(arr[j]);
                    }
                }
                else
                break;
            j++;
            }
            max = Math.Max(max,j-i);
            set.Clear();
        }
        Console.WriteLine(max);
    }
}
</code>```

Body:
Given an array of integers what is the length of the longest subArray containing no more than two distinct values such that the distinct values differ by no more than 1

For Example:

arr = [0, 1, 2, 1, 2, 3] -> length = 4;  [1,2,1,2]

arr = [1, 2, 3, 4, 5] -> length = 2;  [1,2]

arr = [1, 1, 1, 3, 3, 2, 2] -> length = 4;  [3,3,2,2]

I have such code

 public static int longestSubarray(List<Integer> arr) {
        int max = 0;
        Set<Integer> set = new HashSet<>();
        int i = 0;
        int j = 1;
        while (i < arr.size() - 1) {
            set.add(arr.get(i));
            while (j < arr.size() && Math.abs(arr.get(i) - arr.get(j)) < 2) {
                if (!set.contains(arr.get(j))) {
                    if (set.size() == 2) {
                        break;
                    } else {
                        set.add(arr.get(j));
                    }
                }
                ++j;
            }
            max = Math.max(max, j - i);
            j = ++i + 1;
            set.clear();
        }
        return max;
    }

Can there be a better solution?

Body:
C# code:

using System.IO;
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> arr = new List<int>(){ 0, 1, 2, 1, 2, 3};
        List<int> set = new List<int>();
        int n = arr.Count;
        int max = 1;
        int i,j;
        for(i=0 ; i<n-1; i++)
        {
            set.Add(arr[i]);
            for(j=i+1; j<n; )
            {
                if(Math.Abs(arr[i]-arr[j])<2)
                {
                    if(!set.Contains(arr[j]))
                    {
                        if(set.Count == 2)
                        break;
                        else
                        set.Add(arr[j]);
                    }
                }
                else
                break;
            j++;
            }
            max = Math.Max(max,j-i);
            set.Clear();
        }
        Console.WriteLine(max);
    }
}


问:
Mongoose .stream doesn't have populated fields
I have a schema "Reports" that looks like this:

```<code>    var Reports = new Schema(
  {
    identifiersub: {            // Id of reported submission, populate stuff
      type: Schema.Types.ObjectId,
      ref: "Submission"
    },
    identifiercom: {            // Id of reported comment, populate stuff
      type: Schema.Types.ObjectId,
      ref: "Comments"
    },
    identifieruse: {            // Id of reported user, populate stuff
      type: Schema.Types.ObjectId,
      ref: "AccountDetails"
    },
    solved: {                   // Whether this problem has been solved or not
      type: Boolean,
      default: false
    },
    processed: [{               // Array of moderators who were participating in processing this report
      type: Schema.Types.ObjectId,
      ref: "AccountDetails"
    }],
    type: String,               // Type of content. bug, user, submission or comment
    reports: [                  // Additional text for each type of reported content
      {
        description: String,    // Text from select component. For bugs: the feature that is affected,
        reason: String,         // Reason for this report
        by: {                   // Reporter
          type: Schema.Types.ObjectId,
          ref: "AccountDetails"
        }
      }
    ],
    notes: [{                   // Admin notes
      title: String,            // Fleshed out discussion/reasoning
      note: String,             // Decided outcome that each note represents
      outcome: String,          // ("Keep reported", "delete", etc)
      date: Date,               // Date this note was added
      moderator: {              // Moderator who added this note
        type: Schema.Types.ObjectId,
        ref: "AccountDetails"
      }
    }]
  },
  { strict: false, timestamps: true }
)
</code>```

And in my admin panel I want to implement a search function that searches all reports with the specified keyword. The most important field here is reports: it's an array of objects containing a "by" field which is an ObjectId. Now I wanted to populate the username for this id, but I'm not seeing it in my document...I use the .stream method to check the whole document including nested objects and arrays of objects. Here's my query:

```<code>  var cursor = Reports
  .find({ type: req.query.type})
  .limit(500)
  .populate("notes.moderator reports.by processed", "username")
  .populate("identifieruse", "username dob email ipaddress")
  .populate("identifiercom", "by.username comment")
  .populate("identifiersub", "meta.title by deleted")
  .sort("-createdAt")
  .lean()
  .stream();

  cursor.on('data', function(doc) {
    console.log(doc);
    if (doc.toString().includes(key)) results.push(doc)
  })
  cursor.on('error', function(err) {
    return catcherror(new Error(err), res)
  })
  cursor.on('close', function() {
    console.log(results);
    return res.send(results)
  })
</code>```

Thanks for help!

答: Use .cursor() instead of .stream() and it works.

Body:
I have a schema "Reports" that looks like this:

    var Reports = new Schema(
  {
    identifiersub: {            // Id of reported submission, populate stuff
      type: Schema.Types.ObjectId,
      ref: "Submission"
    },
    identifiercom: {            // Id of reported comment, populate stuff
      type: Schema.Types.ObjectId,
      ref: "Comments"
    },
    identifieruse: {            // Id of reported user, populate stuff
      type: Schema.Types.ObjectId,
      ref: "AccountDetails"
    },
    solved: {                   // Whether this problem has been solved or not
      type: Boolean,
      default: false
    },
    processed: [{               // Array of moderators who were participating in processing this report
      type: Schema.Types.ObjectId,
      ref: "AccountDetails"
    }],
    type: String,               // Type of content. bug, user, submission or comment
    reports: [                  // Additional text for each type of reported content
      {
        description: String,    // Text from select component. For bugs: the feature that is affected,
        reason: String,         // Reason for this report
        by: {                   // Reporter
          type: Schema.Types.ObjectId,
          ref: "AccountDetails"
        }
      }
    ],
    notes: [{                   // Admin notes
      title: String,            // Fleshed out discussion/reasoning
      note: String,             // Decided outcome that each note represents
      outcome: String,          // ("Keep reported", "delete", etc)
      date: Date,               // Date this note was added
      moderator: {              // Moderator who added this note
        type: Schema.Types.ObjectId,
        ref: "AccountDetails"
      }
    }]
  },
  { strict: false, timestamps: true }
)

And in my admin panel I want to implement a search function that searches all reports with the specified keyword. The most important field here is reports: it's an array of objects containing a "by" field which is an ObjectId. Now I wanted to populate the username for this id, but I'm not seeing it in my document...I use the .stream method to check the whole document including nested objects and arrays of objects. Here's my query:

  var cursor = Reports
  .find({ type: req.query.type})
  .limit(500)
  .populate("notes.moderator reports.by processed", "username")
  .populate("identifieruse", "username dob email ipaddress")
  .populate("identifiercom", "by.username comment")
  .populate("identifiersub", "meta.title by deleted")
  .sort("-createdAt")
  .lean()
  .stream();

  cursor.on('data', function(doc) {
    console.log(doc);
    if (doc.toString().includes(key)) results.push(doc)
  })
  cursor.on('error', function(err) {
    return catcherror(new Error(err), res)
  })
  cursor.on('close', function() {
    console.log(results);
    return res.send(results)
  })

Thanks for help!


问:
How to get the value of a particular textView inside ListView in Android?
In my application I need to move from one activity to another depending on the list clicked. In each listview there will be three textview namely: Emp_id, Emp_name,Emp_address, so whenever I click on a particular list that should move to next activity of the corresponding Emp_id. So here I want to catch the Emp_id, which I am unable. I have tried a lot but got only the first Emp_id not the list that I have clicked.

CODE:

```<code>ArrayList<HashMap<String, String>> mylist2 = new ArrayList<HashMap<String, String>>();

        try{
            JSONObject jObj = new JSONObject(Mydetail);
            JSONArray data = jObj.getJSONArray("mydata");

            for(int i=0;i<data.length();i++){
                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject e = data.getJSONObject(i);

                map.put("id", String.valueOf(i));
                map.put("Eid", "" + e.getString("E_id"));
                map.put("Ename", "" + e.getString("E_name"));
                map.put("Eaddress", "" + e.getString("E_address"));
                mylist2.add(map);
            }
        }catch(JSONException e)        {
             Log.e("log_tag", "Error parsing data "+e.toString());
        }

         ListAdapter adapter = new SimpleAdapter(this, mylist2 , R.layout.datalist,
                                  new String[] { "Eid", "Ename", "Eaddress" },
                                  new int[] {  R.id.TextView1,R.id.TextView2e,R.id.TextView3 });
                                  setListAdapter(adapter);

        final ListView lv = getListView();
        lv.setTextFilterEnabled(true);
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                @SuppressWarnings("unchecked")
                HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
                //String val = o.get("id");

                Pnm = (TextView)findViewById(R.id.TextView1);
                 String str = ((TextView)Pnm).getText().toString();

                Toast.makeText(projects.this, str,Toast.LENGTH_LONG).show();

                Intent newActivitySecond = new Intent(projects.this, modules.class);
                projects.this.startActivity(newActivitySecond);

            }
        });
</code>```

Thanks

答:
try this </p>

```<code>lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            @SuppressWarnings("unchecked")
            HashMap<String, String> o = (HashMap<String, String>) mylist2.get(position);

             String Emp_id = o.get("Eid");
             //use this Emp_id

        }
    });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In my application I need to move from one activity to another depending on the list clicked. In each listview there will be three textview namely: Emp_id, Emp_name,Emp_address, so whenever I click on a particular list that should move to next activity of the corresponding Emp_id. So here I want to catch the Emp_id, which I am unable. I have tried a lot but got only the first Emp_id not the list that I have clicked.

CODE:

ArrayList<HashMap<String, String>> mylist2 = new ArrayList<HashMap<String, String>>();

        try{
            JSONObject jObj = new JSONObject(Mydetail);
            JSONArray data = jObj.getJSONArray("mydata");

            for(int i=0;i<data.length();i++){
                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject e = data.getJSONObject(i);

                map.put("id", String.valueOf(i));
                map.put("Eid", "" + e.getString("E_id"));
                map.put("Ename", "" + e.getString("E_name"));
                map.put("Eaddress", "" + e.getString("E_address"));
                mylist2.add(map);
            }
        }catch(JSONException e)        {
             Log.e("log_tag", "Error parsing data "+e.toString());
        }

         ListAdapter adapter = new SimpleAdapter(this, mylist2 , R.layout.datalist,
                                  new String[] { "Eid", "Ename", "Eaddress" },
                                  new int[] {  R.id.TextView1,R.id.TextView2e,R.id.TextView3 });
                                  setListAdapter(adapter);

        final ListView lv = getListView();
        lv.setTextFilterEnabled(true);
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                @SuppressWarnings("unchecked")
                HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
                //String val = o.get("id");

                Pnm = (TextView)findViewById(R.id.TextView1);
                 String str = ((TextView)Pnm).getText().toString();

                Toast.makeText(projects.this, str,Toast.LENGTH_LONG).show();

                Intent newActivitySecond = new Intent(projects.this, modules.class);
                projects.this.startActivity(newActivitySecond);

            }
        });

Thanks

Body:
try this

lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            @SuppressWarnings("unchecked")
            HashMap<String, String> o = (HashMap<String, String>) mylist2.get(position);

             String Emp_id = o.get("Eid");
             //use this Emp_id

        }
    });


问:
Subclass UIButton with system font, bold, and kerning
You have to use attributed text to do kerning. But. On the other hand, you can't get at system fonts in the IB attributed text menu.

How do I make (in code) a UIButton which has

system font, weight bold

size 11

kern attribute set to -2

Ideally it would collect the text of the button from plain text Title in IB. But if the text has to be set in code that is fine.

```<code>class NiftyButton: UIButton {
    ????
}
</code>```

Normally I initialize UIButton like this .. but I don't even know if that's the best place to do this?  (You can't do it in layoutSubviews, since it will loop of course.)

```<code>class InitializeyButton: UIButton {

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

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        common()
    }

    func common() {
        ...
    }
}
</code>```

How to achieve in code ...

system font, weight bold

size 11

kern attribute set to -2

答:
Copy-paste UIButton for systemFont + kerning:

I've tidied up Jawad's excellent information:

Firstly, at bringup time, you have to create the attributed title:

```<code>import UIKit

class SmallChatButton: UIIButton { // (note the extra "I" !!)

    override func common() {
        super.common()
        backgroundColor = .your corporate color
        contentEdgeInsets = UIEdgeInsets(top: 7, left: 11, bottom: 7, right: 11)
        titles()
    }

    private func titles() {
        let states: [UIControl.State] = [.normal, .highlighted, .selected, .disabled]
        for state in states {
            let currentText = super.title(for: state)
            setTitle(currentText, for: state)
        }
    }

</code>```

so to achieve that ..

```<code>    override func setTitle(_ title: String?, for state: UIControl.State) {

        let _f = UIFont.systemFont(ofSize: 10, weight: .heavy)

        let attributedTitle = NSAttributedString(
            string: title ?? "Click",
            attributes: [
                NSAttributedString.Key.kern: -0.5,
                NSAttributedString.Key.foregroundColor: UIColor.white,
                NSAttributedString.Key.font: _f
        ])
        setAttributedTitle(attributedTitle, for: state)
    }

    override func layoutSubviews() { // example of rounded corners
        super.layoutSubviews()
        layer.cornerRadius = bounds.height / 2.0
        clipsToBounds = true
    }
}
</code>```

Note that a kern of "-0.5" is about what most typographers want for typical "slightly tight type".

It looks good with say all caps, or a slightly bold font, or small type. The Apple measurement system is unlike anything used by typographers, so, you'll just have to vary it until the typographer on your app is satisfied.

What is UIIButton (note the extra "I" !!)

Inevitably in any project you will need a UIButton which has an "I" initializer, so you'll proabbly have:

```<code>import UIKit

class UIIButton: UIButton {

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

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        common()
    }

    func common() {

    }

}
</code>```

(It's quite amazing that in iOS one has to do all of the above to "kern the system font" !)

Body:
You have to use attributed text to do kerning. But. On the other hand, you can't get at system fonts in the IB attributed text menu.

How do I make (in code) a UIButton which has

system font, weight bold

size 11

kern attribute set to -2

Ideally it would collect the text of the button from plain text Title in IB. But if the text has to be set in code that is fine.

class NiftyButton: UIButton {
    ????
}

Normally I initialize UIButton like this .. but I don't even know if that's the best place to do this?  (You can't do it in layoutSubviews, since it will loop of course.)

class InitializeyButton: UIButton {

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

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        common()
    }

    func common() {
        ...
    }
}

How to achieve in code ...

system font, weight bold

size 11

kern attribute set to -2

Body:
Copy-paste UIButton for systemFont + kerning:

I've tidied up Jawad's excellent information:

Firstly, at bringup time, you have to create the attributed title:

import UIKit

class SmallChatButton: UIIButton { // (note the extra "I" !!)

    override func common() {
        super.common()
        backgroundColor = .your corporate color
        contentEdgeInsets = UIEdgeInsets(top: 7, left: 11, bottom: 7, right: 11)
        titles()
    }

    private func titles() {
        let states: [UIControl.State] = [.normal, .highlighted, .selected, .disabled]
        for state in states {
            let currentText = super.title(for: state)
            setTitle(currentText, for: state)
        }
    }

so to achieve that ..

    override func setTitle(_ title: String?, for state: UIControl.State) {

        let _f = UIFont.systemFont(ofSize: 10, weight: .heavy)

        let attributedTitle = NSAttributedString(
            string: title ?? "Click",
            attributes: [
                NSAttributedString.Key.kern: -0.5,
                NSAttributedString.Key.foregroundColor: UIColor.white,
                NSAttributedString.Key.font: _f
        ])
        setAttributedTitle(attributedTitle, for: state)
    }

    override func layoutSubviews() { // example of rounded corners
        super.layoutSubviews()
        layer.cornerRadius = bounds.height / 2.0
        clipsToBounds = true
    }
}

Note that a kern of "-0.5" is about what most typographers want for typical "slightly tight type".

It looks good with say all caps, or a slightly bold font, or small type. The Apple measurement system is unlike anything used by typographers, so, you'll just have to vary it until the typographer on your app is satisfied.

What is UIIButton (note the extra "I" !!)

Inevitably in any project you will need a UIButton which has an "I" initializer, so you'll proabbly have:

import UIKit

class UIIButton: UIButton {

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

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        common()
    }

    func common() {

    }

}

(It's quite amazing that in iOS one has to do all of the above to "kern the system font" !)


问:
Port Scanner written in python does not display output normally
So I tried to write a port scanner in python3
Here is my code:

```<code>import sys #allows us to enter command line arguments, among other things
import socket
from datetime import datetime

if len(sys.argv) == 2:
    target = socket.gethostbyname(sys.argv[1]) #Translate a hostname to IPv4
else:
    print("Invalid amount of arguments.")
    print("Syntax: python3 scanner.py <ip>")
    sys.exit()

#Add a banner
print("-" * 50)
print("Scanning target "+target)
print("Time started: "+str(datetime.now()))
print("-" * 50)
try:
    for port in range(50,85):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        socket.setdefaulttimeout(1)
        result = s.connect_ex((target,port)) #returns error indicator
        print("Checking port {}".format(port))
        if result == 0:
            print("Port {} is open".format(port))
        s.close()

except KeyboardInterrupt:
    print("\nExiting program.")
    sys.exit()

except socket.gaierror:
    print("Hostname could not be resolved.")
    sys.exit()

except socket.error:
    print("Couldn't connect to server.")
    sys.exit()
</code>```

using Kali Linux 2020.2, with the newest version of python,

I executes python3 scanner.py google.com

It is expected that the scanner will display "Checking port 50", "Checking port 51" one by one during the scanning process.

And if it find any one of the ports is open, it shows "Port xx is open" after the "Checking port xx"

However, my scanner was stuck as the initial banner.

And eventually when it has completed the scanning, it displays all the output in one go.

Can anyone please tell me how can I solve this problem?

答:
Just switch the following lines in your code:

result = s.connect_ex((target,port)) #returns error indicator
print("Checking port {}".format(port))
```

<p>becomes:</p>

<pre class="lang-py prettyprint-override"><code>print("Checking port {}".format(port))
result = s.connect_ex((target,port)) #returns error indicator
</code>```

Body:
So I tried to write a port scanner in python3
Here is my code:

import sys #allows us to enter command line arguments, among other things
import socket
from datetime import datetime

if len(sys.argv) == 2:
    target = socket.gethostbyname(sys.argv[1]) #Translate a hostname to IPv4
else:
    print("Invalid amount of arguments.")
    print("Syntax: python3 scanner.py <ip>")
    sys.exit()

#Add a banner
print("-" * 50)
print("Scanning target "+target)
print("Time started: "+str(datetime.now()))
print("-" * 50)
try:
    for port in range(50,85):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        socket.setdefaulttimeout(1)
        result = s.connect_ex((target,port)) #returns error indicator
        print("Checking port {}".format(port))
        if result == 0:
            print("Port {} is open".format(port))
        s.close()

except KeyboardInterrupt:
    print("\nExiting program.")
    sys.exit()

except socket.gaierror:
    print("Hostname could not be resolved.")
    sys.exit()

except socket.error:
    print("Couldn't connect to server.")
    sys.exit()

using Kali Linux 2020.2, with the newest version of python,

I executes python3 scanner.py google.com

It is expected that the scanner will display "Checking port 50", "Checking port 51" one by one during the scanning process.

And if it find any one of the ports is open, it shows "Port xx is open" after the "Checking port xx"

However, my scanner was stuck as the initial banner.

And eventually when it has completed the scanning, it displays all the output in one go.

Can anyone please tell me how can I solve this problem?

Body:
Just switch the following lines in your code:

result = s.connect_ex((target,port)) #returns error indicator
print("Checking port {}".format(port))

becomes:

print("Checking port {}".format(port))
result = s.connect_ex((target,port)) #returns error indicator


问:
How to concatenate multiple column values into a single column in Pandas dataframe
This question is same to this posted earlier. I want to concatenate three columns instead of concatenating two columns:

Here is the combining two columns:

```<code>df = DataFrame({'foo':['a','b','c'], 'bar':[1, 2, 3], 'new':['apple', 'banana', 'pear']})

df['combined']=df.apply(lambda x:'%s_%s' % (x['foo'],x['bar']),axis=1)

df
    bar foo new combined
0   1   a   apple   a_1
1   2   b   banana  b_2
2   3   c   pear    c_3
</code>```

I want to combine three columns with this command but it is not working, any idea?

```<code>df['combined']=df.apply(lambda x:'%s_%s' % (x['bar'],x['foo'],x['new']),axis=1)
</code>```

答:
Possibly the fastest solution is to operate in plain Python:

```<code>Series(
    map(
        '_'.join,
        df.values.tolist()
        # when non-string columns are present:
        # df.values.astype(str).tolist()
    ),
    index=df.index
)
</code>```

Comparison against @MaxU answer (using the big data frame which has both numeric and string columns):

```<code>%timeit big['bar'].astype(str) + '_' + big['foo'] + '_' + big['new']
# 29.4 ms ± 1.08 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit Series(map('_'.join, big.values.astype(str).tolist()), index=big.index)
# 27.4 ms ± 2.36 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
</code>```

Comparison against @derchambers answer (using their df data frame where all columns are strings):

```<code>from functools import reduce

def reduce_join(df, columns):
    slist = [df[x] for x in columns]
    return reduce(lambda x, y: x + '_' + y, slist[1:], slist[0])

def list_map(df, columns):
    return Series(
        map(
            '_'.join,
            df[columns].values.tolist()
        ),
        index=df.index
    )

%timeit df1 = reduce_join(df, list('1234'))
# 602 ms ± 39 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit df2 = list_map(df, list('1234'))
# 351 ms ± 12.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
</code>```

Body:
This question is same to this posted earlier. I want to concatenate three columns instead of concatenating two columns:

Here is the combining two columns:

df = DataFrame({'foo':['a','b','c'], 'bar':[1, 2, 3], 'new':['apple', 'banana', 'pear']})

df['combined']=df.apply(lambda x:'%s_%s' % (x['foo'],x['bar']),axis=1)

df
    bar foo new combined
0   1   a   apple   a_1
1   2   b   banana  b_2
2   3   c   pear    c_3

I want to combine three columns with this command but it is not working, any idea?

df['combined']=df.apply(lambda x:'%s_%s' % (x['bar'],x['foo'],x['new']),axis=1)

Body:
Possibly the fastest solution is to operate in plain Python:

Series(
    map(
        '_'.join,
        df.values.tolist()
        # when non-string columns are present:
        # df.values.astype(str).tolist()
    ),
    index=df.index
)

Comparison against @MaxU answer (using the big data frame which has both numeric and string columns):

%timeit big['bar'].astype(str) + '_' + big['foo'] + '_' + big['new']
# 29.4 ms ± 1.08 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit Series(map('_'.join, big.values.astype(str).tolist()), index=big.index)
# 27.4 ms ± 2.36 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Comparison against @derchambers answer (using their df data frame where all columns are strings):

from functools import reduce

def reduce_join(df, columns):
    slist = [df[x] for x in columns]
    return reduce(lambda x, y: x + '_' + y, slist[1:], slist[0])

def list_map(df, columns):
    return Series(
        map(
            '_'.join,
            df[columns].values.tolist()
        ),
        index=df.index
    )

%timeit df1 = reduce_join(df, list('1234'))
# 602 ms ± 39 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit df2 = list_map(df, list('1234'))
# 351 ms ± 12.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)


问:
invalid type argument of unary ‘*’ (have ‘int’) - for implementing a multiplication and exponential operation
I have wrote a program to replace the zeros in a number with 5 with a time complexity of Order of logn N base 10. But cpp implementation make some mistake as show under the code snippet.

Code:

```<code>int convertFive(int n) {
int i = 0, temp = 0;
do{
    if ((n%10) == 0)
        temp = temp+(5*(10**i));
    else
        temp = temp+(n%10*(10**i))
    i++;
    n = n/10;
}while(n/10 != 0);
return temp;
</code>```

Error:

```<code>prog.cpp:24:33: error: invalid type argument of unary ‘*’ (have ‘int’)
         temp = temp+(5*(10**i));
                             ^
prog.cpp:26:36: error: invalid type argument of unary ‘*’ (have ‘int’)
             temp = temp+(n%10*(10**i))
</code>```

答:
There is no ** operator in C++, but exponentiation is unnecessary anyway.

Instead of repeated exponentiation, multiply by 10 on each iteration.

You also have bug where you ignore the first digit because you're exiting the loop too soon.

```<code>int convertFive(int n) {
    int result = 0;
    int position = 1;
    do {
        int digit = n % 10;
        if (digit == 0)
            result += 5 * position;
        else
            result += digit * position;
        position *= 10;
        n /= 10;
    } while (n != 0);
    return result;
}
</code>```

Body:
I have wrote a program to replace the zeros in a number with 5 with a time complexity of Order of logn N base 10. But cpp implementation make some mistake as show under the code snippet.

Code:

int convertFive(int n) {
int i = 0, temp = 0;
do{
    if ((n%10) == 0)
        temp = temp+(5*(10**i));
    else
        temp = temp+(n%10*(10**i))
    i++;
    n = n/10;
}while(n/10 != 0);
return temp;

Error:

prog.cpp:24:33: error: invalid type argument of unary ‘*’ (have ‘int’)
         temp = temp+(5*(10**i));
                             ^
prog.cpp:26:36: error: invalid type argument of unary ‘*’ (have ‘int’)
             temp = temp+(n%10*(10**i))

Body:
There is no ** operator in C++, but exponentiation is unnecessary anyway.

Instead of repeated exponentiation, multiply by 10 on each iteration.

You also have bug where you ignore the first digit because you're exiting the loop too soon.

int convertFive(int n) {
    int result = 0;
    int position = 1;
    do {
        int digit = n % 10;
        if (digit == 0)
            result += 5 * position;
        else
            result += digit * position;
        position *= 10;
        n /= 10;
    } while (n != 0);
    return result;
}


问:
DropdownButtonFormField gives Error when try to display String
I want to make DropdownButtonFormField that shows cities like this:

```<code>final List<String> cities = ['London', 'New York', 'Paris', 'Shanghahai', 'Tokyo'];

String _currentCity;

DropdownButtonFormField(
            value: _currentCity ?? ' ',
            decoration: textInputDecoration,
            items: cities.map((city) {
              return DropdownMenuItem(
                value: city,
                child: Text('$city City '),
              );
            }).toList(),
            onChanged: (val) => setState(() => _currentCity = val ),
          ),
</code>```

But when I try to show these Strings I get red screen error :

and If I changed the Strings inside the List to numbers it works well:

```<code> final List<String> cities = ['0', '1', '2', '3', '4'];
</code>```

Can someone tell me what is wrong with it although I use List of strings

答:
You can try set _currentCity for default value?</p>

```<code>String _currentCity = 'London';
</code>```

Body:
I want to make DropdownButtonFormField that shows cities like this:

final List<String> cities = ['London', 'New York', 'Paris', 'Shanghahai', 'Tokyo'];

String _currentCity;

DropdownButtonFormField(
            value: _currentCity ?? ' ',
            decoration: textInputDecoration,
            items: cities.map((city) {
              return DropdownMenuItem(
                value: city,
                child: Text('$city City '),
              );
            }).toList(),
            onChanged: (val) => setState(() => _currentCity = val ),
          ),

But when I try to show these Strings I get red screen error :

and If I changed the Strings inside the List to numbers it works well:

 final List<String> cities = ['0', '1', '2', '3', '4'];

Can someone tell me what is wrong with it although I use List of strings

Body:
You can try set _currentCity for default value?

String _currentCity = 'London';


问:
How much time should it take to find the sum of all prime numbers less than 2 million?
I was trying to solve this Project Euler Question. I implemented the sieve of euler as a helper class in java. It works pretty well for the small numbers. But when I input 2 million as the limit it doesn't return the answer. I use Netbeans IDE. I waited for a lot many hours once, but it still didn't print the answer. When I stopped running the code, it gave the following result

Java Result: 2147483647

  BUILD
  SUCCESSFUL (total time: 2,097 minutes
  43 seconds)

This answer is incorrect. Even after waiting for so much time, this isn't correct. While the same code returns correct answers for smaller limits.

Sieve of euler has a very simple algo given at the botton of this page.

My implementation is this:

```<code>package support;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author admin
 */
public class SieveOfEuler {
    int upperLimit;
    List<Integer> primeNumbers;

    public SieveOfEuler(int upperLimit){
        this.upperLimit = upperLimit;
        primeNumbers = new ArrayList<Integer>();
        for(int i = 2 ; i <= upperLimit ; i++)
            primeNumbers.add(i);
        generatePrimes();
    }

    private void generatePrimes(){
        int currentPrimeIndex = 0;
        int currentPrime = 2;
        while(currentPrime <= Math.sqrt(upperLimit)){
            ArrayList<Integer> toBeRemoved = new ArrayList<Integer>();
            for(int i = currentPrimeIndex ; i < primeNumbers.size() ; i++){
                int multiplier = primeNumbers.get(i);
                toBeRemoved.add(currentPrime * multiplier);
            }

            for(Integer i : toBeRemoved){
                primeNumbers.remove(i);
            }

            currentPrimeIndex++;
            currentPrime = primeNumbers.get(currentPrimeIndex);
        }
    }

    public List getPrimes(){
        return primeNumbers;
    }

    public void displayPrimes(){
        for(double i : primeNumbers)
            System.out.println(i);
    }
}
</code>```

I am perplexed! My questions is

1) Why is it taking so much time? Is there something wrong in what I am doing?

Please suggest ways for improving my coding style, if you find something wrong.

Question Updated:

Here is the code, where I calculate the sum of the the calculated prime numbers:

```<code>package projecteuler;

import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import support.SieveOfEuler;

/**
 *
 * @author admin
 */
public class Problem10 {
    private int upperLimit;
    private BigInteger sumOfPrimes;
    public void getInput() {
        try {
            System.out.println("Enter the upper limit");
            upperLimit = Integer.parseInt(br.readLine());
        } catch (IOException ex) {
            Logger.getLogger(Problem10.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void execute() {
        BigInteger sum = new BigInteger("0");
        SieveOfEuler soe = new SieveOfEuler(upperLimit);
        ArrayList<Integer> primeNumbers = (ArrayList<Integer>)soe.getPrimes();
        for(int i : primeNumbers){
            sum = sum.add(new BigInteger(Integer.toString(i))) ;
        }
        System.out.println(sum);
    }

    public void printOutput() {
       //System.out.println(sumOfPrimes);
    }
}
</code>```

答:
```<code>import java.util.*;

public class PrimeSum
{
    public static int isPrime(int num)
    {
        int sum = 0;
        int factor = 1;
        while(factor <= num)
        {
            if(num % factor != 0)
            {
                sum += factor;
                factor ++;
            }
            else
            {
                factor ++;
            }
        }
        return sum;
    }

    public static void main(String[] args)
    {
        System.out.println("The program gets the sum of all prime numbers.");

        Scanner scan = new Scanner(System.in);

        System.out.print("Enter a number: ");
        int num = scan.nextInt();

        int sum = isPrime(num);

        System.out.println(sum);
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I was trying to solve this Project Euler Question. I implemented the sieve of euler as a helper class in java. It works pretty well for the small numbers. But when I input 2 million as the limit it doesn't return the answer. I use Netbeans IDE. I waited for a lot many hours once, but it still didn't print the answer. When I stopped running the code, it gave the following result

Java Result: 2147483647

  BUILD
  SUCCESSFUL (total time: 2,097 minutes
  43 seconds)

This answer is incorrect. Even after waiting for so much time, this isn't correct. While the same code returns correct answers for smaller limits.

Sieve of euler has a very simple algo given at the botton of this page.

My implementation is this:

package support;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author admin
 */
public class SieveOfEuler {
    int upperLimit;
    List<Integer> primeNumbers;

    public SieveOfEuler(int upperLimit){
        this.upperLimit = upperLimit;
        primeNumbers = new ArrayList<Integer>();
        for(int i = 2 ; i <= upperLimit ; i++)
            primeNumbers.add(i);
        generatePrimes();
    }

    private void generatePrimes(){
        int currentPrimeIndex = 0;
        int currentPrime = 2;
        while(currentPrime <= Math.sqrt(upperLimit)){
            ArrayList<Integer> toBeRemoved = new ArrayList<Integer>();
            for(int i = currentPrimeIndex ; i < primeNumbers.size() ; i++){
                int multiplier = primeNumbers.get(i);
                toBeRemoved.add(currentPrime * multiplier);
            }

            for(Integer i : toBeRemoved){
                primeNumbers.remove(i);
            }

            currentPrimeIndex++;
            currentPrime = primeNumbers.get(currentPrimeIndex);
        }
    }

    public List getPrimes(){
        return primeNumbers;
    }

    public void displayPrimes(){
        for(double i : primeNumbers)
            System.out.println(i);
    }
}

I am perplexed! My questions is

1) Why is it taking so much time? Is there something wrong in what I am doing?

Please suggest ways for improving my coding style, if you find something wrong.

Question Updated:

Here is the code, where I calculate the sum of the the calculated prime numbers:

package projecteuler;

import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import support.SieveOfEuler;

/**
 *
 * @author admin
 */
public class Problem10 {
    private int upperLimit;
    private BigInteger sumOfPrimes;
    public void getInput() {
        try {
            System.out.println("Enter the upper limit");
            upperLimit = Integer.parseInt(br.readLine());
        } catch (IOException ex) {
            Logger.getLogger(Problem10.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void execute() {
        BigInteger sum = new BigInteger("0");
        SieveOfEuler soe = new SieveOfEuler(upperLimit);
        ArrayList<Integer> primeNumbers = (ArrayList<Integer>)soe.getPrimes();
        for(int i : primeNumbers){
            sum = sum.add(new BigInteger(Integer.toString(i))) ;
        }
        System.out.println(sum);
    }

    public void printOutput() {
       //System.out.println(sumOfPrimes);
    }
}


问:
How to use the crypto processor on the dev board?
On the data sheet, the SoM comes with an ATECC608A crypographic coprocessor, but there are no documentations on how to use it. Are there some usecase for this HW and any instructions on how to use it?</p>

答:
The internal ECC608 seems to be connected to the internal i2c (I2C1). The external i2c busses are I2C2 and I2C3.
If adapted to bus I2C1 (bus 0), the example code finds an ECC608 at address 0x60 on my device and I can read out the serial number of the chip.
Although - the ECC608 has many configuration and key-storage options. If haven't found any documentation on the internal use of the chip yet. </p>


问:
How to use global to share app-root-path across modules in nodejs
I am using import-export in node js every time when I import a modules I will be using lots of like these ../../ then later I found a lib 'npm app-root-path' but I wanna use this lib globally by assigning it to a global variable in app.js and wanna use that across all pages.How to accomplish this </p>

答:
You can use ~/ instead of ../../.

Reference: https://stackoverflow.com/a/31937237/2025156


问:
How to slice a list from an element n to the end in python?
I'm having some trouble figuring out how to slice python lists, it is illustrated as follows:

```<code>>>> test = range(10)
>>> test
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> test[3:-1]
[3, 4, 5, 6, 7, 8]
>>> test[3:0]
[]
>>> test[3:1]
[]
>>> test
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</code>```

To my understanding, python slice means lst[start:end], and including start, excluding end. So how would i go about finding the "rest" of a list starting from an element n?

Thanks a lot for all your help!

答:
Simply omit the end.</p>

```<code>test[n:]
</code>```

OwnerDisplayName: FurtiveFelon

Body:
I'm having some trouble figuring out how to slice python lists, it is illustrated as follows:

>>> test = range(10)
>>> test
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> test[3:-1]
[3, 4, 5, 6, 7, 8]
>>> test[3:0]
[]
>>> test[3:1]
[]
>>> test
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

To my understanding, python slice means lst[start:end], and including start, excluding end. So how would i go about finding the "rest" of a list starting from an element n?

Thanks a lot for all your help!

Body:
Simply omit the end.

test[n:]

OwnerDisplayName: Matthew


问:
Folder not avalible
I am working from home with an Access project. I have a VPN connection to a customer that times out after 15 minutes if I don't use it. If the VPN is up my code below works fine. If the VPN is down the code gets stuck for 60 seconds, checking for a folder that is not available. Is there a way to change this to say 5 seconds and "do something else".</p>

```<code>Sub check()
Dim fso As New FileSystemObject
    If fso.FolderExists("z:\abc") Then
        'do something
    else
        'do something else
    End If
End Sub
</code>```

答:
You could actually implement this without pinging the server by using a second process to test if the folder exists. This is relevant when the path may or may not refer to a network share, for example.

The code starts a PowerShell process to check if the file exists, then waits for a set amount of time for that PowerShell process to complete, and moves on otherwise.

An added advantage of this approach is that you can call DoEvents while waiting, which will prevent Access from locking up even when waiting for your set timeout.

The disadvantage is that this will cause a considerable overhead if the expected time it'll take to run is short.

```<code>Dim strPath As String
strPath = "Z:\abc"
Dim cmd As String
cmd = "powershell.exe -c Test-Path '" & Replace(strPath, "'", "''") & "'"
Dim shellobj As Object
Set shellobj = CreateObject("WScript.Shell")
Dim cmdObject As Object
Set cmdObject = shellobj.Exec(cmd)
Dim startTime As Single
startTime = Timer()
Dim fileExists As Boolean
Dim timeoutReached As Boolean
Do While cmdObject.Status = 0
    If Timer() - startTime > 30 Then
        timeoutReached = True
        Exit Do
    End If
    DoEvents
Loop
If Not timeoutReached Then
    fileExists = Trim(cmdObject.StdOut.ReadAll) = "True" & vbCrLf
End If
</code>```

Title: Folder not avalible

Body:
I am working from home with an Access project. I have a VPN connection to a customer that times out after 15 minutes if I don't use it. If the VPN is up my code below works fine. If the VPN is down the code gets stuck for 60 seconds, checking for a folder that is not available. Is there a way to change this to say 5 seconds and "do something else".

Sub check()
Dim fso As New FileSystemObject
    If fso.FolderExists("z:\abc") Then
        'do something
    else
        'do something else
    End If
End Sub

Body:
You could actually implement this without pinging the server by using a second process to test if the folder exists. This is relevant when the path may or may not refer to a network share, for example.

The code starts a PowerShell process to check if the file exists, then waits for a set amount of time for that PowerShell process to complete, and moves on otherwise.

An added advantage of this approach is that you can call DoEvents while waiting, which will prevent Access from locking up even when waiting for your set timeout.

The disadvantage is that this will cause a considerable overhead if the expected time it'll take to run is short.

Dim strPath As String
strPath = "Z:\abc"
Dim cmd As String
cmd = "powershell.exe -c Test-Path '" & Replace(strPath, "'", "''") & "'"
Dim shellobj As Object
Set shellobj = CreateObject("WScript.Shell")
Dim cmdObject As Object
Set cmdObject = shellobj.Exec(cmd)
Dim startTime As Single
startTime = Timer()
Dim fileExists As Boolean
Dim timeoutReached As Boolean
Do While cmdObject.Status = 0
    If Timer() - startTime > 30 Then
        timeoutReached = True
        Exit Do
    End If
    DoEvents
Loop
If Not timeoutReached Then
    fileExists = Trim(cmdObject.StdOut.ReadAll) = "True" & vbCrLf
End If


问:
How can I do a regex pattern for Hibernate validation?
I want to use a regex @Pattern with Hibernate validation. How can I do this regex expression?

[a][b][c][d][e] is a number with 13 digits like this: 1831222132132

```<code>a - one digit, 1 or 2, nothing else;
b - from 01 to 99, it is the last 2 digits from the year, for ex 1983 => b = 83;
c - from 01 to 12;
d - from 01 to 31;
e - 6 digits;
</code>```

Any help will be appreciated. Thank you!

答:
To validate that in Hibernate you can use @Pattern annotation like this

```<code>@Column(name = "myInpt")
@Pattern(regexp = "^[12](0[1-9]|[1-9][0-9])(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])([0-9]{6})$", message = "Incorrect format")
private String myInput;
</code>```

Body:
I want to use a regex @Pattern with Hibernate validation. How can I do this regex expression?

[a][b][c][d][e] is a number with 13 digits like this: 1831222132132

a - one digit, 1 or 2, nothing else;
b - from 01 to 99, it is the last 2 digits from the year, for ex 1983 => b = 83;
c - from 01 to 12;
d - from 01 to 31;
e - 6 digits;

Any help will be appreciated. Thank you!

Body:
To validate that in Hibernate you can use @Pattern annotation like this

@Column(name = "myInpt")
@Pattern(regexp = "^[12](0[1-9]|[1-9][0-9])(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])([0-9]{6})$", message = "Incorrect format")
private String myInput;