问:
Creating Pandas DataFrame from SmartSheet API (nested, awkward, JSON)
I'm trying to connect to my office's SmartSheet API via Python to create some performance tracking dashboards that utilize data outside of SmartSheet. All I want to do is create a simple DataFrame where fields reflect columnId and cell values reflect the displayValue key in the Smartsheet dictionary. I am doing this using a standard API requests.get rather than SmartSheet's API documentation because I've found the latter less easy to work with.

The table (sample) is set up as:

```<code>Number  Letter  Name
1       A       Joe
2       B       Jim
3       C       Jon
</code>```

The JSON syntax from the sheet GET request is:

```<code>{'id': 339338304219012,
 'name': 'Sample Smartsheet',
 'version': 1,
 'totalRowCount': 3,
 'accessLevel': 'OWNER',
 'effectiveAttachmentOptions': ['GOOGLE_DRIVE',
  'EVERNOTE',
  'DROPBOX',
  'ONEDRIVE',
  'LINK',
  'FILE',
  'BOX_COM',
  'EGNYTE'],
 'ganttEnabled': False,
 'dependenciesEnabled': False,
 'resourceManagementEnabled': False,
 'cellImageUploadEnabled': True,
 'userSettings': {'criticalPathEnabled': False, 'displaySummaryTasks': True},
 'userPermissions': {'summaryPermissions': 'ADMIN'},
 'hasSummaryFields': False,
 'permalink': 'https://app.smartsheet.com/sheets/5vxMCJQhMV7VFFPMVfJgg2hX79rj3fXgVGG8fp61',
 'createdAt': '2020-02-13T16:32:02Z',
 'modifiedAt': '2020-02-14T13:15:18Z',
 'isMultiPicklistEnabled': True,
 'columns': [{'id': 6273865019090820,
   'version': 0,
   'index': 0,
   'title': 'Number',
   'type': 'TEXT_NUMBER',
   'primary': True,
   'validation': False,
   'width': 150},
  {'id': 4022065205405572,
   'version': 0,
   'index': 1,
   'title': 'Letter',
   'type': 'TEXT_NUMBER',
   'validation': False,
   'width': 150},
  {'id': 8525664832776068,
   'version': 0,
   'index': 2,
   'title': 'Name',
   'type': 'TEXT_NUMBER',
   'validation': False,
   'width': 150}],
 'rows': [{'id': 8660990817003396,
   'rowNumber': 1,
   'expanded': True,
   'createdAt': '2020-02-14T13:15:18Z',
   'modifiedAt': '2020-02-14T13:15:18Z',
   'cells': [{'columnId': 6273865019090820, 'value': 1.0, 'displayValue': '1'},
    {'columnId': 4022065205405572, 'value': 'A', 'displayValue': 'A'},
    {'columnId': 8525664832776068, 'value': 'Joe', 'displayValue': 'Joe'}]},
  {'id': 498216492394372,
   'rowNumber': 2,
   'siblingId': 8660990817003396,
   'expanded': True,
   'createdAt': '2020-02-14T13:15:18Z',
   'modifiedAt': '2020-02-14T13:15:18Z',
   'cells': [{'columnId': 6273865019090820, 'value': 2.0, 'displayValue': '2'},
    {'columnId': 4022065205405572, 'value': 'B', 'displayValue': 'B'},
    {'columnId': 8525664832776068, 'value': 'Jim', 'displayValue': 'Jim'}]},
  {'id': 5001816119764868,
   'rowNumber': 3,
   'siblingId': 498216492394372,
   'expanded': True,
   'createdAt': '2020-02-14T13:15:18Z',
   'modifiedAt': '2020-02-14T13:15:18Z',
   'cells': [{'columnId': 6273865019090820, 'value': 3.0, 'displayValue': '3'},
    {'columnId': 4022065205405572, 'value': 'C', 'displayValue': 'C'},
    {'columnId': 8525664832776068, 'value': 'Jon', 'displayValue': 'Jon'}]}]}
</code>```

Here are the two ways I've approached the problem:

INPUT:

```<code>from pandas.io.json import json_normalize
samplej = sample.json()
s_rows = json_normalize(data=samplej['rows'], record_path='cells', meta=['id', 'rowNumber'])
s_rows
</code>```

OUTPUT:

DataFrame with columnId, value, disdlayValue, id, and rowNumber as their own fields.

If I could figure out how to transpose this data in the right way I could probably make it work, but that seems incredibly complicated.

INPUT:

```<code>samplej = sample.json()
cellist = []
def get_cells():
    srows = samplej['rows']
    for s_cells in srows:
        scells = s_cells['cells']
        cellist.append(scells)
get_cells()
celldf = pd.DataFrame(cellist)
celldf
</code>```

OUTPUT:

This returns a DataFrame with the correct number of columns and rows, but each cell is populated with a dictionary that looks like

```<code>In [14]:
celldf.loc[1,1]
Out [14]:
{'columnId': 4022065205405572, 'value': 'B', 'displayValue': 'B'}
</code>```

If there was a way to remove everything except the value corresponding to the displayValue key in every cell, this would probably solve my problem.  Again, though, it seems weirdly complicated.

I'm fairly new to Python and working with API's, so there may be a simple way to address the problem I'm overlooking. Or, if you have a suggestion for approaching the possible solutions I outlined above I'm all ears. Thanks for your help!

答:
You must make use of the columns field:

```<code>colnames = {x['id']: x['title'] for x in samplej['columns']}
columns = [x['title'] for x in samplej['columns']]
cellist = [{colnames[scells['columnId']]: scells['displayValue']
            for scells in s_cells['cells']} for s_cells in samplej['rows']]
celldf = pd.DataFrame(cellist, columns=columns)
</code>```

This gives as expected:

```<code>  Number Letter Name
0      1      A  Joe
1      2      B  Jim
2      3      C  Jon
</code>```

If some cells could contain only a columnId but no displayValue field, scells['displayValue'] should be replaced in above code with scells.get('displayValue', defaultValue), where defaultValue could be None, np.nan or any other relevant default.

Body:
I'm trying to connect to my office's SmartSheet API via Python to create some performance tracking dashboards that utilize data outside of SmartSheet. All I want to do is create a simple DataFrame where fields reflect columnId and cell values reflect the displayValue key in the Smartsheet dictionary. I am doing this using a standard API requests.get rather than SmartSheet's API documentation because I've found the latter less easy to work with.

The table (sample) is set up as:

Number  Letter  Name
1       A       Joe
2       B       Jim
3       C       Jon

The JSON syntax from the sheet GET request is:

{'id': 339338304219012,
 'name': 'Sample Smartsheet',
 'version': 1,
 'totalRowCount': 3,
 'accessLevel': 'OWNER',
 'effectiveAttachmentOptions': ['GOOGLE_DRIVE',
  'EVERNOTE',
  'DROPBOX',
  'ONEDRIVE',
  'LINK',
  'FILE',
  'BOX_COM',
  'EGNYTE'],
 'ganttEnabled': False,
 'dependenciesEnabled': False,
 'resourceManagementEnabled': False,
 'cellImageUploadEnabled': True,
 'userSettings': {'criticalPathEnabled': False, 'displaySummaryTasks': True},
 'userPermissions': {'summaryPermissions': 'ADMIN'},
 'hasSummaryFields': False,
 'permalink': 'https://app.smartsheet.com/sheets/5vxMCJQhMV7VFFPMVfJgg2hX79rj3fXgVGG8fp61',
 'createdAt': '2020-02-13T16:32:02Z',
 'modifiedAt': '2020-02-14T13:15:18Z',
 'isMultiPicklistEnabled': True,
 'columns': [{'id': 6273865019090820,
   'version': 0,
   'index': 0,
   'title': 'Number',
   'type': 'TEXT_NUMBER',
   'primary': True,
   'validation': False,
   'width': 150},
  {'id': 4022065205405572,
   'version': 0,
   'index': 1,
   'title': 'Letter',
   'type': 'TEXT_NUMBER',
   'validation': False,
   'width': 150},
  {'id': 8525664832776068,
   'version': 0,
   'index': 2,
   'title': 'Name',
   'type': 'TEXT_NUMBER',
   'validation': False,
   'width': 150}],
 'rows': [{'id': 8660990817003396,
   'rowNumber': 1,
   'expanded': True,
   'createdAt': '2020-02-14T13:15:18Z',
   'modifiedAt': '2020-02-14T13:15:18Z',
   'cells': [{'columnId': 6273865019090820, 'value': 1.0, 'displayValue': '1'},
    {'columnId': 4022065205405572, 'value': 'A', 'displayValue': 'A'},
    {'columnId': 8525664832776068, 'value': 'Joe', 'displayValue': 'Joe'}]},
  {'id': 498216492394372,
   'rowNumber': 2,
   'siblingId': 8660990817003396,
   'expanded': True,
   'createdAt': '2020-02-14T13:15:18Z',
   'modifiedAt': '2020-02-14T13:15:18Z',
   'cells': [{'columnId': 6273865019090820, 'value': 2.0, 'displayValue': '2'},
    {'columnId': 4022065205405572, 'value': 'B', 'displayValue': 'B'},
    {'columnId': 8525664832776068, 'value': 'Jim', 'displayValue': 'Jim'}]},
  {'id': 5001816119764868,
   'rowNumber': 3,
   'siblingId': 498216492394372,
   'expanded': True,
   'createdAt': '2020-02-14T13:15:18Z',
   'modifiedAt': '2020-02-14T13:15:18Z',
   'cells': [{'columnId': 6273865019090820, 'value': 3.0, 'displayValue': '3'},
    {'columnId': 4022065205405572, 'value': 'C', 'displayValue': 'C'},
    {'columnId': 8525664832776068, 'value': 'Jon', 'displayValue': 'Jon'}]}]}

Here are the two ways I've approached the problem:

INPUT:

from pandas.io.json import json_normalize
samplej = sample.json()
s_rows = json_normalize(data=samplej['rows'], record_path='cells', meta=['id', 'rowNumber'])
s_rows

OUTPUT:

DataFrame with columnId, value, disdlayValue, id, and rowNumber as their own fields.

If I could figure out how to transpose this data in the right way I could probably make it work, but that seems incredibly complicated.

INPUT:

samplej = sample.json()
cellist = []
def get_cells():
    srows = samplej['rows']
    for s_cells in srows:
        scells = s_cells['cells']
        cellist.append(scells)
get_cells()
celldf = pd.DataFrame(cellist)
celldf

OUTPUT:

This returns a DataFrame with the correct number of columns and rows, but each cell is populated with a dictionary that looks like

In [14]:
celldf.loc[1,1]
Out [14]:
{'columnId': 4022065205405572, 'value': 'B', 'displayValue': 'B'}

If there was a way to remove everything except the value corresponding to the displayValue key in every cell, this would probably solve my problem.  Again, though, it seems weirdly complicated.

I'm fairly new to Python and working with API's, so there may be a simple way to address the problem I'm overlooking. Or, if you have a suggestion for approaching the possible solutions I outlined above I'm all ears. Thanks for your help!

Body:
You must make use of the columns field:

colnames = {x['id']: x['title'] for x in samplej['columns']}
columns = [x['title'] for x in samplej['columns']]
cellist = [{colnames[scells['columnId']]: scells['displayValue']
            for scells in s_cells['cells']} for s_cells in samplej['rows']]
celldf = pd.DataFrame(cellist, columns=columns)

This gives as expected:

  Number Letter Name
0      1      A  Joe
1      2      B  Jim
2      3      C  Jon

If some cells could contain only a columnId but no displayValue field, scells['displayValue'] should be replaced in above code with scells.get('displayValue', defaultValue), where defaultValue could be None, np.nan or any other relevant default.


来源: stackexchange

问:
How to clone public submodule in "Github Actions"
Reason for this Q&A-Style question: It took me a few hours to get this to run because I had some typos and thought the solution is more complicated. If I would have found a tutorial like this on google or Stackoverflow I would have checked for typos.

Git Repository Setup:

Private repository A - name: repoA

with submodule B (public repository) - name: repoB

Goal:

I want to run a gradle build in repository A > Github Actions

Github Action Workflow

```<code>name: Test
on:
  push:
    branches:
      - master

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v1
</code>```

Problem:

The actions/checkout@v1 step fails to access the submodule

.gitmodules

```<code>[submodule "library"]
    path = library
    url = git@github.com:organization/repoB.git

</code>```

Github Actions Step Build with Gradle error

```<code>FAILURE: Build failed with an exception.

* What went wrong:
Could not determine the dependencies of task ':repoA:compileReleaseAidl'.
> Could not resolve all task dependencies for configuration ':repoA:releaseCompileClasspath'.
   > Could not resolve project :repoBSubmodule1.
     Required by:
         project :repoA
</code>```

What I tried:

Add with: submodules: true to actions/checkout@v1

```<code>    - uses: actions/checkout@v1
      with:
        submodules: true
</code>```

Github Actions Step Run actions/checkout@v1 error

```<code>(...)
git submodule sync
git -c http.https://github.com.extraheader="AUTHORIZATION: basic ***" submodule update --init --force
Submodule 'repoB' (git@github.com:organization/repoB.git) registered for path 'repoB'
Cloning into '/home/runner/work/repoA/repoA/repoB'...
Host key verification failed.
##[error]fatal: Could not read from remote repository.
</code>```

Use 3rd party Github Actions like textbook/git-checkout-submodule-action@2.0.0

Run textbook/git-checkout-submodule-action@2.00 error:

```<code>fatal: Not a git repository (or any parent up to mount point /github/workspace)
Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).
##[error]Docker run failed with exit code 128
</code>```

Add a personal access token to the actions/checkout

The token was generated from a github user which has access to that repository

The repoA is owned by an organization

the token has full repo permissions

```<code>    - uses: actions/checkout@v1
      with:
        submodules: true
        token: ${{ secrets.GITHUB_REPO_TOKEN }}
</code>```

Run actions/checkout@v1 error:

```<code>git submodule sync
git -c http.https://github.com.extraheader="AUTHORIZATION: basic ***" submodule update --init --force
Submodule 'repoB' (git@github.com:organization/repoB.git) registered for path 'repoB'
Cloning into '/home/runner/work/repoA/repoA/repoB'...
Host key verification failed.
##[error]fatal: Could not read from remote repository.
</code>```

I.e. with the that token which has access to both, repoA and repoB I was not even able to checkout the parent repoA.

答:
Now you can use actions/checkout@v2

As https://github.com/actions/checkout#checkout-submodules said:

```<code>- uses: actions/checkout@v2 # checkout root
- name: Checkout submodules # checkout rest
  shell: bash
  run: |
    # If your submodules are configured to use SSH instead of HTTPS please uncomment the following line
    # git config --global url."https://github.com/".insteadOf "git@github.com:"
    auth_header="$(git config --local --get http.https://github.com/.extraheader)"
    git submodule sync --recursive
    git -c "http.extraheader=$auth_header" -c protocol.version=2 submodule update --init --force --recursive --depth=1

</code>```

ContentLicense: CC BY-SA 4.0

Body:
Reason for this Q&A-Style question: It took me a few hours to get this to run because I had some typos and thought the solution is more complicated. If I would have found a tutorial like this on google or Stackoverflow I would have checked for typos.

Git Repository Setup:

Private repository A - name: repoA

with submodule B (public repository) - name: repoB

Goal:

I want to run a gradle build in repository A > Github Actions

Github Action Workflow

name: Test
on:
  push:
    branches:
      - master

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v1

Problem:

The actions/checkout@v1 step fails to access the submodule

.gitmodules

[submodule "library"]
    path = library
    url = git@github.com:organization/repoB.git

Github Actions Step Build with Gradle error

FAILURE: Build failed with an exception.

* What went wrong:
Could not determine the dependencies of task ':repoA:compileReleaseAidl'.
> Could not resolve all task dependencies for configuration ':repoA:releaseCompileClasspath'.
   > Could not resolve project :repoBSubmodule1.
     Required by:
         project :repoA

What I tried:

Add with: submodules: true to actions/checkout@v1

    - uses: actions/checkout@v1
      with:
        submodules: true

Github Actions Step Run actions/checkout@v1 error

(...)
git submodule sync
git -c http.https://github.com.extraheader="AUTHORIZATION: basic ***" submodule update --init --force
Submodule 'repoB' (git@github.com:organization/repoB.git) registered for path 'repoB'
Cloning into '/home/runner/work/repoA/repoA/repoB'...
Host key verification failed.
##[error]fatal: Could not read from remote repository.

Use 3rd party Github Actions like textbook/git-checkout-submodule-action@2.0.0

Run textbook/git-checkout-submodule-action@2.00 error:

fatal: Not a git repository (or any parent up to mount point /github/workspace)
Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).
##[error]Docker run failed with exit code 128

Add a personal access token to the actions/checkout

The token was generated from a github user which has access to that repository

The repoA is owned by an organization

the token has full repo permissions

    - uses: actions/checkout@v1
      with:
        submodules: true
        token: ${{ secrets.GITHUB_REPO_TOKEN }}

Run actions/checkout@v1 error:

git submodule sync
git -c http.https://github.com.extraheader="AUTHORIZATION: basic ***" submodule update --init --force
Submodule 'repoB' (git@github.com:organization/repoB.git) registered for path 'repoB'
Cloning into '/home/runner/work/repoA/repoA/repoB'...
Host key verification failed.
##[error]fatal: Could not read from remote repository.

I.e. with the that token which has access to both, repoA and repoB I was not even able to checkout the parent repoA.

Body:
Now you can use actions/checkout@v2

As https://github.com/actions/checkout#checkout-submodules said:

- uses: actions/checkout@v2 # checkout root
- name: Checkout submodules # checkout rest
  shell: bash
  run: |
    # If your submodules are configured to use SSH instead of HTTPS please uncomment the following line
    # git config --global url."https://github.com/".insteadOf "git@github.com:"
    auth_header="$(git config --local --get http.https://github.com/.extraheader)"
    git submodule sync --recursive
    git -c "http.extraheader=$auth_header" -c protocol.version=2 submodule update --init --force --recursive --depth=1


问:
JAXWS CLIENT ALWAYS SEND HTTP NOT HTTPS
Hi I use jaxws to generate wsdl in my java project.I use java 11 and jaxws-maven-plugin to import mywsdl
Myproblem in my wsdl there is a http://myservice block.And I want to use https://myservice as url.
I generate and import wsdl.And this always try to reach http address not https.How can I force my webclient to consume http address.</p>

```<code>/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.3.2
 * Generated source version: 2.2
 *
 */
@WebServiceClient(name =

  MyResponse response=reply.getMyService().MyRequest(request);

   <groupId>org.codehaus.mojo</groupId>
                    <artifactId>jaxws-maven-plugin</artifactId>
                    <version>2.6</version>
</code>```

答:
BindingProvider  is the solution.  </p>

```<code>  QName qname2 = new QName("http://myschema", "MYserviceImpl");
                Service service = MYserviceImpl.create(new URL("https://mysiteRequest"), qname2);
                MYservice reply=   service.getPort(MYservice.class);
                BindingProvider bindingProvider = (BindingProvider)reply;
                bindingProvider.getRequestContext().put(
                        BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
                        "https://mysite");

                MyResponse response=  reply.myRequest(request2);
</code>```

Title: JAXWS CLIENT ALWAYS SEND HTTP NOT HTTPS

Body:
Hi I use jaxws to generate wsdl in my java project.I use java 11 and jaxws-maven-plugin to import mywsdl
Myproblem in my wsdl there is a http://myservice block.And I want to use https://myservice as url.
I generate and import wsdl.And this always try to reach http address not https.How can I force my webclient to consume http address.

/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.3.2
 * Generated source version: 2.2
 *
 */
@WebServiceClient(name =

  MyResponse response=reply.getMyService().MyRequest(request);

   <groupId>org.codehaus.mojo</groupId>
                    <artifactId>jaxws-maven-plugin</artifactId>
                    <version>2.6</version>

Body:
BindingProvider  is the solution.

  QName qname2 = new QName("http://myschema", "MYserviceImpl");
                Service service = MYserviceImpl.create(new URL("https://mysiteRequest"), qname2);
                MYservice reply=   service.getPort(MYservice.class);
                BindingProvider bindingProvider = (BindingProvider)reply;
                bindingProvider.getRequestContext().put(
                        BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
                        "https://mysite");

                MyResponse response=  reply.myRequest(request2);


问:
Useful data structure for the following case
Which can be the beste data structures for the following case.

1.Should have operations like search, insert and delete. Mostly searching activities will be there.Around 90% of the operations will be search and rest are delete and insert.

2 Insertion,deletion and searching will  be based on the  key of the objects. Each key will point to a object. The keys will be sorted.

Any suggestion for optimal data structure will be highly appreciated.

答:
You want a tree-backed Map; basically you just want a tree where the nodes are dynamically sorted ("self-balanced") by key, with your objects hanging off of each node with corresponding key.

If you would like an "optimal" data structure, that completely depends on the distribution of patterns of inputs you expect. The nice thing about a self-balancing tree is you don't really need to care too much about the pattern of inputs. If you really want the best-guess as-close-to-optimal as possible we know of, and you don't know much about the specific sequences of queries, you can use a http://en.wikipedia.org/wiki/Tango_tree which is O(log(log(N))-competitive. This grows so slowly that, for all practical purposes, you have something which performs no worse than effectively a constant factor from the best possible data structure you could have chosen.

However it's somewhat grungy to implement, you may just be better using a library for a self-balancing tree.

Python:
https://github.com/pgrafov/python-avl-tree/

Java:
If you're just Java, just use a TreeMap (red-black tree based) and ignore the implementation details. Most languages have similar data structures in their standard libraries.

ContentLicense: CC BY-SA 3.0


问:
object of data specific to current logged in user

The goal is the user can save up to 7 field vals in obj userA, logout, log back in and the saved vals are there, retrievable. Specific to each user.

I am trying to create an object i.e. userA and update it, as the
user saves each field value (i.e. BaseMap: basemapSaved), save
the updated state in local storage, then retrieve saved state using
local storage. So, when the user logs out, then logs back in, their
saved data is still there specific to their username.

Below is my most recent attempt (full js): Any pointers? Am I going about this all wrong?

UPDATED ATTEMPT BELOW WITH BOUNTY.

I am simply trying to save an object of data and a field within it (i.e. userA.BaseMap.basemapSaved;) with local storage, on click.

I later want to parse that saved object in local storage, get that field, and update my API object i.e. object.data.field (userA.BaseMap.basemapSaved;) with the value saved and gathered. I can do this pro grammatically pretty easy, but the idea is to save the state per user, so they can log out, then log back in and have their selection saved.

```<code>  // Here I am trying to initialize the variables
    var currentUser;
    var basemapSaved;
    var userA[key] = {};

    // This function I am getting the logged in username, I want to set this as the object key in userA i.e. userA[key]

    function checkUser()  {
      var node = document.querySelectorAll("span.username")[0];
      currentUser = node.textContent;
      var key = currentUser;
      console.log("current user is:" + key);
    }

    // This is just a handler to wait to my basemap gallery loads before trying to save

    var basemapMod = document.getElementsByClassName("basemap")[0];
    basemapMod.addEventListener('click', ()=>{
      setTimeout(
        function() {
          BaseMapSaver();
        }, 2000);
    });

    function BaseMapSaver() {
      savebtnBM.addEventListener('click', ()=>{
        checkUser();
        // This is where I get the data from my API to save, gathers fine
        basemapSaved = app.widget.Manager.Gallery.activeBasemap.Item.id;
        // Below I am trying to set it, at first without the object key but would like to use the key
        var saveMap = localStorage.setItem('userA', JSON.stringify(userA));

        console.log(userA);
      });
    }
    // Home button
    var defaultViewHbtn = document.getElementById("home");

    defaultViewHbtn.addEventListener('click', ()=>{

        checkUser();

        // Here I try to parse the value from local storage object
        const userAParseValue = JSON.parse(localStorage.getItem('userA'));

        // Errors with Uncaught TypeError: Cannot read property 'BaseMap' of undefined
        userBaseMap = userAParseValue.userA.BaseMap.basemapSaved;
        console.log(userBaseMap);

        app.widget.Manager.Gallery.activeBasemap.Item.id = {
          portalItem: {
              id: userA.BaseMap.basemapSaved // this is where I want to load saved value from local storage object
            }
          };
    });
</code>```

答:
Based on the two requirements that you have defined in your original question, this should do what you ask.

The goal is the user can save up to 7 field vals in obj userA, logout, log back in and the saved vals are there, retrievable. Specific to each user.

I am trying to create an object i.e. userA and update it, as the user saves each field value (i.e. BaseMap: basemapSaved), save the updated state in local storage, then retrieve saved state using local storage. So, when the user logs out, then logs back in, their saved data is still there specific to their username.

```<code>// retrieve user from localstorage. defaults to {}
// This looks to retrieve the user from local storage by username.
// Returns a `userObj` an object with two properties.
// `username` - the name of the user
// `user` - the stored object that was retrieved from local storage.
//          defaults to {} if nothing in user storage

// Not a good strategy btw, a lot of us share the same names :)

function getUser(username) {
    let user = localStorage.getItem(username) || {};
    try {
        user = JSON.parse(user);
    } catch (e) {
        user = {};
    }
    return { username, user }
}

// Store user object in localstorage
// Store a user in local storage, keyed by their username
function setUser(username, user) {
    localStorage.setItem(username, JSON.stringify(user));
}

// set a key/ value on user object in localstorage
// Don't allow anymore than 7 properties to be stored on the user object
function setUserProperty(userObj, key, value) {
    let { username, user } = userObj;

    if (Object.keys(user).length > 7) {
        throw new Error('user properties exceeds 7')
    }

    user[key] = value;
    setUser(username, user);
}

// modified to return a user from local storage or {}
function checkUser()  {
    var node = document.querySelectorAll("span.username")[0];
    const currentUser = node.textContent;
    return getUser(currentUser);
}

// This is just a handler to wait to my basemap gallery loads before trying to save
var basemapMod = document.getElementsByClassName("basemap")[0];
basemapMod.addEventListener('click', () => {
    setTimeout(
        function() {
            BaseMapSaver();
    }, 2000);
});

// Fyi Capitals indicate constructors - not functions!
function BaseMapSaver() {
    savebtnBM.addEventListener('click', () => {
        const userObj = checkUser(); // get the user from localstorage
        const basemapSaved = app.widget.Manager.Gallery.activeBasemap.Item.id;
        setUserProperty(userObj, 'basemap', basemapSaved) // store the basemap on the user object in local storage with the key 'basemap'
        console.log(JSON.stringify(userObj));
    });
}

var defaultViewHbtn = document.getElementById("home");

defaultViewHbtn.addEventListener('click', () => {
    // get user from localstorage
    const { user } = checkUser();
    const userBaseMap = user.basemap

    // if we have a store basemap
    if (userBaseMap) {
        app.widget.Manager.Gallery.activeBasemap.Item.id = {
            portalItem: {
              id: userBaseMap // load it
            }
        };
    }
});

</code>```

Body:
The goal is the user can save up to 7 field vals in obj userA, logout, log back in and the saved vals are there, retrievable. Specific to each user.

I am trying to create an object i.e. userA and update it, as the
user saves each field value (i.e. BaseMap: basemapSaved), save
the updated state in local storage, then retrieve saved state using
local storage. So, when the user logs out, then logs back in, their
saved data is still there specific to their username.

Below is my most recent attempt (full js): Any pointers? Am I going about this all wrong?

UPDATED ATTEMPT BELOW WITH BOUNTY.

I am simply trying to save an object of data and a field within it (i.e. userA.BaseMap.basemapSaved;) with local storage, on click.

I later want to parse that saved object in local storage, get that field, and update my API object i.e. object.data.field (userA.BaseMap.basemapSaved;) with the value saved and gathered. I can do this pro grammatically pretty easy, but the idea is to save the state per user, so they can log out, then log back in and have their selection saved.

  // Here I am trying to initialize the variables
    var currentUser;
    var basemapSaved;
    var userA[key] = {};

    // This function I am getting the logged in username, I want to set this as the object key in userA i.e. userA[key]

    function checkUser()  {
      var node = document.querySelectorAll("span.username")[0];
      currentUser = node.textContent;
      var key = currentUser;
      console.log("current user is:" + key);
    }

    // This is just a handler to wait to my basemap gallery loads before trying to save

    var basemapMod = document.getElementsByClassName("basemap")[0];
    basemapMod.addEventListener('click', ()=>{
      setTimeout(
        function() {
          BaseMapSaver();
        }, 2000);
    });

    function BaseMapSaver() {
      savebtnBM.addEventListener('click', ()=>{
        checkUser();
        // This is where I get the data from my API to save, gathers fine
        basemapSaved = app.widget.Manager.Gallery.activeBasemap.Item.id;
        // Below I am trying to set it, at first without the object key but would like to use the key
        var saveMap = localStorage.setItem('userA', JSON.stringify(userA));

        console.log(userA);
      });
    }
    // Home button
    var defaultViewHbtn = document.getElementById("home");

    defaultViewHbtn.addEventListener('click', ()=>{

        checkUser();

        // Here I try to parse the value from local storage object
        const userAParseValue = JSON.parse(localStorage.getItem('userA'));

        // Errors with Uncaught TypeError: Cannot read property 'BaseMap' of undefined
        userBaseMap = userAParseValue.userA.BaseMap.basemapSaved;
        console.log(userBaseMap);

        app.widget.Manager.Gallery.activeBasemap.Item.id = {
          portalItem: {
              id: userA.BaseMap.basemapSaved // this is where I want to load saved value from local storage object
            }
          };
    });

Body:
Based on the two requirements that you have defined in your original question, this should do what you ask.

The goal is the user can save up to 7 field vals in obj userA, logout, log back in and the saved vals are there, retrievable. Specific to each user.

I am trying to create an object i.e. userA and update it, as the user saves each field value (i.e. BaseMap: basemapSaved), save the updated state in local storage, then retrieve saved state using local storage. So, when the user logs out, then logs back in, their saved data is still there specific to their username.

// retrieve user from localstorage. defaults to {}
// This looks to retrieve the user from local storage by username.
// Returns a `userObj` an object with two properties.
// `username` - the name of the user
// `user` - the stored object that was retrieved from local storage.
//          defaults to {} if nothing in user storage

// Not a good strategy btw, a lot of us share the same names :)

function getUser(username) {
    let user = localStorage.getItem(username) || {};
    try {
        user = JSON.parse(user);
    } catch (e) {
        user = {};
    }
    return { username, user }
}

// Store user object in localstorage
// Store a user in local storage, keyed by their username
function setUser(username, user) {
    localStorage.setItem(username, JSON.stringify(user));
}

// set a key/ value on user object in localstorage
// Don't allow anymore than 7 properties to be stored on the user object
function setUserProperty(userObj, key, value) {
    let { username, user } = userObj;

    if (Object.keys(user).length > 7) {
        throw new Error('user properties exceeds 7')
    }

    user[key] = value;
    setUser(username, user);
}

// modified to return a user from local storage or {}
function checkUser()  {
    var node = document.querySelectorAll("span.username")[0];
    const currentUser = node.textContent;
    return getUser(currentUser);
}

// This is just a handler to wait to my basemap gallery loads before trying to save
var basemapMod = document.getElementsByClassName("basemap")[0];
basemapMod.addEventListener('click', () => {
    setTimeout(
        function() {
            BaseMapSaver();
    }, 2000);
});

// Fyi Capitals indicate constructors - not functions!
function BaseMapSaver() {
    savebtnBM.addEventListener('click', () => {
        const userObj = checkUser(); // get the user from localstorage
        const basemapSaved = app.widget.Manager.Gallery.activeBasemap.Item.id;
        setUserProperty(userObj, 'basemap', basemapSaved) // store the basemap on the user object in local storage with the key 'basemap'
        console.log(JSON.stringify(userObj));
    });
}

var defaultViewHbtn = document.getElementById("home");

defaultViewHbtn.addEventListener('click', () => {
    // get user from localstorage
    const { user } = checkUser();
    const userBaseMap = user.basemap

    // if we have a store basemap
    if (userBaseMap) {
        app.widget.Manager.Gallery.activeBasemap.Item.id = {
            portalItem: {
              id: userBaseMap // load it
            }
        };
    }
});


问:
Using Async/Await with Array.map
So I know that async/await will not work with map. I am just returning my request and using Promise.all() to execute them. My question is that I have other promises inside and was wondering if the Promise.all() will also execute those inside the map in the correct order.

Here is the code:

const productImageIds = Object.keys(data.webImages)

        for(let i = productImageIds.length; i--;){
            const productId = productImageIds[i]
            const images = data.webImages[productId]
            const requests = images.map(async (image, i) => {
                const name = `${productId}_${i}.${image.split(`.`).pop()}`
                const imageStream = await downloadImage(image, name) // IS THIS WORKING CORRECTLY WITH USING PROMISE.ALL() ??
                const res =  sanityRequest({
                    ...sanityConfig,
                    type: `images`,
                    endpoint: `assets`,
                    contentType: `image/jpeg`,
                    body: imageStream,
                params: `?filename=${name}`,
                })

                    await unlinkSync(name) // IS THIS WORKING CORRECTLY WITH USING PROMISE.ALL() ??
                    return res

            })

            const uploadedImages = await Promise.all(requests)
        }
```

答:
My question is that I have other promises inside and was wondering if the Promise.all() will also execute those inside the map in the correct order.

No.

Promise.all() will create a promise which resolves when all the promises passed to it resolve. It has no influence over what order those promises resolve in (and couldn't because they will have started running before Promise.all is invoked).

If you want to deal with each value of images in sequence (rather than in parallel) then use a regular for loop.

Title: Using Async/Await with Array.map


问:
Parcel build command not working
I am following the basic tutorial for Parcel to bundle js, css and image files.

My file structure

```<code>  dist
  node_modules
  src
    - index.html
    - style.css
    - index.js
    - somemodule.js
</code>```

When I run parcel ./src/index.html a server is started and the website is displayed correctly. According to the tutorial you can finalize the build using parcel build index.js. I expected to get this output:

```<code>  dist
    - style.css
    - index.js
    - index.html
</code>```

But instead, after running parcel build index.js I get this output:

```<code>  dist
    - 4wyd98y98790.css
    - 948y59hslas8.js
</code>```

What could possibly be going wrong?

答: try to remove old build stuff like dist folder and build again

Title: Parcel build command not working

Body:
I am following the basic tutorial for Parcel to bundle js, css and image files.

My file structure

  dist
  node_modules
  src
    - index.html
    - style.css
    - index.js
    - somemodule.js

When I run parcel ./src/index.html a server is started and the website is displayed correctly. According to the tutorial you can finalize the build using parcel build index.js. I expected to get this output:

  dist
    - style.css
    - index.js
    - index.html

But instead, after running parcel build index.js I get this output:

  dist
    - 4wyd98y98790.css
    - 948y59hslas8.js

What could possibly be going wrong?


问:
Retrieving Reduced Cost of Dvar composed of "tuples" in CPLEX OPL
I want to retrieve the reduced cost of a decision variable in CPLEX OPL.
However, the dvar indices are tuples, and cplex cannot iterate over a tuple to print the reduced costs. Is it impossible with tuples, or is there a way for it?
For example there is a decision variable as below:

```<code>dvar float+ Production[ProductionLocations][TimePeriods];

tuple timeperiod {
  string TimePeriodID;
  string TimePeriodName;
  float CurrencyRate;
  float Rank;
  string ActivePeriod;
}
{timeperiod} TimePeriods = ...;
tuple productionlocation {
  string ProductID;
  string ProductName;
  string LocationID;
  string LocationName;
}
{productionlocation} ProductionLocations = ...;
</code>```

Thanks in advance.

答:
you may iterate on tuple set.

In oil.mod in OPL CPLEX examples you may see

```<code>execute DISPLAY_REDUCED_COSTS{
  for( var g in Gasolines ) {
    writeln("a[",g,"].reducedCost = ",a[g].reducedCost);
  }
}
</code>```

Gasolines is a string set but could be a tuple set, this would work too

Body:
I want to retrieve the reduced cost of a decision variable in CPLEX OPL.
However, the dvar indices are tuples, and cplex cannot iterate over a tuple to print the reduced costs. Is it impossible with tuples, or is there a way for it?
For example there is a decision variable as below:

dvar float+ Production[ProductionLocations][TimePeriods];

tuple timeperiod {
  string TimePeriodID;
  string TimePeriodName;
  float CurrencyRate;
  float Rank;
  string ActivePeriod;
}
{timeperiod} TimePeriods = ...;
tuple productionlocation {
  string ProductID;
  string ProductName;
  string LocationID;
  string LocationName;
}
{productionlocation} ProductionLocations = ...;

Thanks in advance.

Body:
you may iterate on tuple set.

In oil.mod in OPL CPLEX examples you may see

execute DISPLAY_REDUCED_COSTS{
  for( var g in Gasolines ) {
    writeln("a[",g,"].reducedCost = ",a[g].reducedCost);
  }
}

Gasolines is a string set but could be a tuple set, this would work too


问:
C++ usual arithmetic conversions not converting
First, I'd like to point out that I did read some of the other answers with generally similar titles. However, those either refer to what I assume is an older version of the standard, or deal with promotions, not conversions.

I've been crawling through "C++ Crash Course", where the author states the following in the chapter exploring built-in operators:

If none of the floating-point promotion rules apply, you then check
whether either argument is signed. If so, both operands become signed.
Finally, as with the promotion rules for floating-point types, the size of the
largest operand is used to promote the other operand: ...

If I read the standard correctly, this is not true, because, as per cppreference.com,

If both operands are signed or both are unsigned, the operand with lesser conversion rank is converted to the operand with the greater integer conversion rank

Otherwise, if the unsigned operand's conversion rank is greater or equal to the conversion rank of the signed operand, the signed operand is converted to the unsigned operand's type.

Otherwise, if the signed operand's type can represent all values of the unsigned operand, the unsigned operand is converted to the signed operand's type

Otherwise, both operands are converted to the unsigned counterpart of the signed operand's type.

What confuses me even more is the fact that the following code:

```<code>printf("Size of int is %d bytes\n", sizeof(int));
printf("Size of short is %d bytes\n", sizeof(short));
printf("Size of long is %d bytes\n", sizeof(long));
printf("Size of long long is %d bytes\n", sizeof(long long));
unsigned int x = 4000000000;
signed int y = -1;
signed long z = x + y;
printf("x + y = %ld\n", z);
</code>```

produces the following output:

```<code>Size of int is 4 bytes
Size of short is 2 bytes
Size of long is 8 bytes
Size of long long is 8 bytes
x + y = 3999999999
</code>```

As I understand the standard, y should have been converted to unsigned int, leading to an incorrect result. The result is correct, which leads me to assume that no conversion happens in this case. Why? I would be grateful for any clafirication on this matter. Thank you.

(I would also appreciate someone telling me that I won't ever need this kind of arcane knowledge in real life, even if it's not true - just for the peace of mind.)

答:
I would also appreciate someone telling me that I won't ever need this
  kind of arcane knowledge in real life

There is one implicit promotion not addressed above that is a common cause of bugs:

```<code>unsigned short x = 0xffff;
unsigned short y = 0x0001;
if ((x + y) == 0)
</code>```

The result of this is false because arithmetic operations are implicitly promoted to at least int.

Body:
First, I'd like to point out that I did read some of the other answers with generally similar titles. However, those either refer to what I assume is an older version of the standard, or deal with promotions, not conversions.

I've been crawling through "C++ Crash Course", where the author states the following in the chapter exploring built-in operators:

If none of the floating-point promotion rules apply, you then check
whether either argument is signed. If so, both operands become signed.
Finally, as with the promotion rules for floating-point types, the size of the
largest operand is used to promote the other operand: ...

If I read the standard correctly, this is not true, because, as per cppreference.com,

If both operands are signed or both are unsigned, the operand with lesser conversion rank is converted to the operand with the greater integer conversion rank

Otherwise, if the unsigned operand's conversion rank is greater or equal to the conversion rank of the signed operand, the signed operand is converted to the unsigned operand's type.

Otherwise, if the signed operand's type can represent all values of the unsigned operand, the unsigned operand is converted to the signed operand's type

Otherwise, both operands are converted to the unsigned counterpart of the signed operand's type.

What confuses me even more is the fact that the following code:

printf("Size of int is %d bytes\n", sizeof(int));
printf("Size of short is %d bytes\n", sizeof(short));
printf("Size of long is %d bytes\n", sizeof(long));
printf("Size of long long is %d bytes\n", sizeof(long long));
unsigned int x = 4000000000;
signed int y = -1;
signed long z = x + y;
printf("x + y = %ld\n", z);

produces the following output:

Size of int is 4 bytes
Size of short is 2 bytes
Size of long is 8 bytes
Size of long long is 8 bytes
x + y = 3999999999

As I understand the standard, y should have been converted to unsigned int, leading to an incorrect result. The result is correct, which leads me to assume that no conversion happens in this case. Why? I would be grateful for any clafirication on this matter. Thank you.

(I would also appreciate someone telling me that I won't ever need this kind of arcane knowledge in real life, even if it's not true - just for the peace of mind.)

Body:
I would also appreciate someone telling me that I won't ever need this
  kind of arcane knowledge in real life

There is one implicit promotion not addressed above that is a common cause of bugs:

unsigned short x = 0xffff;
unsigned short y = 0x0001;
if ((x + y) == 0)

The result of this is false because arithmetic operations are implicitly promoted to at least int.


问:
Why doesn't it print Armstrong numbers up to 1000?
It was working without the nested loop just to check if the input number was Armstrong number.</p>

```<code>c=0
for y in range(1000):
    for x in str(y):
        c += int(x) ** len(str(y))
        if c == y:
            print(c)
</code>```

答:
Your problem is that the variable c must be cleaned in each iteration:

```<code>for y in range(1000):
    c=0
    for x in str(y):
        c += int(x) ** len(str(y))
        if c == y:
            print(c)
</code>```

Or you can use a variant like the one in @CDJB:

```<code>for y in range(1000):
    if sum(int(x)**len(str(y)) for x in str(y)) == y:
        print(y)
</code>```

Body:
It was working without the nested loop just to check if the input number was Armstrong number.

c=0
for y in range(1000):
    for x in str(y):
        c += int(x) ** len(str(y))
        if c == y:
            print(c)

Body:
Your problem is that the variable c must be cleaned in each iteration:

for y in range(1000):
    c=0
    for x in str(y):
        c += int(x) ** len(str(y))
        if c == y:
            print(c)

Or you can use a variant like the one in @CDJB:

for y in range(1000):
    if sum(int(x)**len(str(y)) for x in str(y)) == y:
        print(y)


问:
firing a jQuery change function at document ready
My change function allows users to switch from country to country and get different text and features. It works when changing country selections. But at initial page load, it does not fire jQuery change to set the hide and show text divs for the default / initial country.

Both divs display at initial page load. When I change away and then back to the default/initial country, change fires, hide and show fire, and shows the proper information and features.

I have tried document.ready with a change function both inside the switch selections and outside the change function. Neither work - they don't fire the hide, show and other jQuery in the switch cases at doc ready.  Its not clear to me whether 'ready' is a valid trigger event.

I have also tried:

```<code>$('input[name=country]').value('US').trigger('click');
</code>```

but it broke the change function. Here's the code.  The country selection below is just 2 countries to keep it simple, but actually, there are many.

```<code>$(document).ready(function()
{
//1st tier - select country via radio buttons:
//Initialize country
$('input[name=country]:first').attr('checked', true);   //Set first radio button (United States)
//$('input[name=country]:first').attr('checked', true).trigger('ready');  //sets 1st button, but does not fire change
//$('input[name=country]:first').trigger('click'); //sets 1st button, but does not fire change

$('input[name=country]').change(function ()
{
// change user instructions to be country specific
    switch ($('input[name=country]:checked').val())
    {
        case 'US':
        $('#stateMessage1').text('2. Select a state or territory of the United States.');
        $('#stateMessage2').text('Start typing a state of the United States, then click on it in the dropdown box.');
        $('#threeSelects').show();
        $('#twoSelects').hide();
        //select via 3 steps
        break;
        case 'CA':
        $('#stateMessage1').text('2. Select a province or territory of Canada.');
        $('#stateMessage2').text('Start typing a province of Canada, then click on it in the dropdown box.');
        $('#twoSelects').show();
        $('#threeSelects').hide();
        //select town via 2 steps - country, town
        break;
    }
});
});
</code>```

答:
Why not just trigger change after selecting the appropriate radio buttons?

```<code>$('input[name=country]').change();
</code>```

This is equivalent to

```<code>$('input[name=country]').trigger('change');
</code>```

Body:
My change function allows users to switch from country to country and get different text and features. It works when changing country selections. But at initial page load, it does not fire jQuery change to set the hide and show text divs for the default / initial country.

Both divs display at initial page load. When I change away and then back to the default/initial country, change fires, hide and show fire, and shows the proper information and features.

I have tried document.ready with a change function both inside the switch selections and outside the change function. Neither work - they don't fire the hide, show and other jQuery in the switch cases at doc ready.  Its not clear to me whether 'ready' is a valid trigger event.

I have also tried:

$('input[name=country]').value('US').trigger('click');

but it broke the change function. Here's the code.  The country selection below is just 2 countries to keep it simple, but actually, there are many.

$(document).ready(function()
{
//1st tier - select country via radio buttons:
//Initialize country
$('input[name=country]:first').attr('checked', true);   //Set first radio button (United States)
//$('input[name=country]:first').attr('checked', true).trigger('ready');  //sets 1st button, but does not fire change
//$('input[name=country]:first').trigger('click'); //sets 1st button, but does not fire change

$('input[name=country]').change(function ()
{
// change user instructions to be country specific
    switch ($('input[name=country]:checked').val())
    {
        case 'US':
        $('#stateMessage1').text('2. Select a state or territory of the United States.');
        $('#stateMessage2').text('Start typing a state of the United States, then click on it in the dropdown box.');
        $('#threeSelects').show();
        $('#twoSelects').hide();
        //select via 3 steps
        break;
        case 'CA':
        $('#stateMessage1').text('2. Select a province or territory of Canada.');
        $('#stateMessage2').text('Start typing a province of Canada, then click on it in the dropdown box.');
        $('#twoSelects').show();
        $('#threeSelects').hide();
        //select town via 2 steps - country, town
        break;
    }
});
});

Body:
Why not just trigger change after selecting the appropriate radio buttons?

$('input[name=country]').change();

This is equivalent to

$('input[name=country]').trigger('change');


问:
How could I configure the MSSQLLocal default datetime format
I am writing a program to interact with MSSQLLocal DB using C# through winforms but I find a problem witht the default datetime, it is not the date time format we use in my countr, I wonder how could I through Sql client -sql default C# classes I could change the default date format for a database or All the existing databases?

this could let me to format the datetime https://learn.microsoft.com/en-us/sql/t-sql/statements/set-dateformat-transact-sql?view=sql-server-ver15

but this doesnt change the default dateformat, how can i change programatically the DB datetime default format?

some code example

```<code>var connectionstr = $@"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog={DBname};Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
                var con = new SqlConnection(connectionstr);
                con.Open();

                string changeDate = $@"SET DATEFORMAT dmy;";
                SqlCommand command = new SqlCommand(changeDate , con);
                var res = command.ExecuteNonQuery();
                SqlCommand cmd = new SqlCommand(InsertCmd, con);

                SqlDataAdapter adapter = new SqlDataAdapter() { InsertCommand = cmd };

                adapter.InsertCommand.ExecuteNonQuery();

                adapter.Dispose();
                con.Close();
                con.Dispose();
                cmd.Dispose();
                command.Dispose();
</code>```

答: Turns out before adding a new value to the row you would need to include in the string CAST(01/01/2020) as dateformat</p>

Body:
I am writing a program to interact with MSSQLLocal DB using C# through winforms but I find a problem witht the default datetime, it is not the date time format we use in my countr, I wonder how could I through Sql client -sql default C# classes I could change the default date format for a database or All the existing databases?

this could let me to format the datetime https://learn.microsoft.com/en-us/sql/t-sql/statements/set-dateformat-transact-sql?view=sql-server-ver15

but this doesnt change the default dateformat, how can i change programatically the DB datetime default format?

some code example

var connectionstr = $@"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog={DBname};Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
                var con = new SqlConnection(connectionstr);
                con.Open();

                string changeDate = $@"SET DATEFORMAT dmy;";
                SqlCommand command = new SqlCommand(changeDate , con);
                var res = command.ExecuteNonQuery();
                SqlCommand cmd = new SqlCommand(InsertCmd, con);

                SqlDataAdapter adapter = new SqlDataAdapter() { InsertCommand = cmd };

                adapter.InsertCommand.ExecuteNonQuery();

                adapter.Dispose();
                con.Close();
                con.Dispose();
                cmd.Dispose();
                command.Dispose();


问:
Compilation of x264 project
I had downloaded the source of x264 library.

The version of x264 is 148.

For compilation of shared dlls I am using the following command under
MSYS Environment:

```<code>./configure --disable-cli --enable-shared --prefix=.
</code>```

The result is following:

```<code>platform:      X86_64
byte order:    little-endian
system:        WINDOWS
cli:           no
libx264:       internal
shared:        yes
static:        no
asm:           yes
interlaced:    yes
avs:           no
lavf:          no
ffms:          no
mp4:           no
gpl:           yes
thread:        win32
opencl:        yes
filters:       crop select_every
debug:         no
gprof:         no
strip:         no
PIC:           yes
bit depth:     8
chroma format: all
</code>```

After execution of make I have the following error:

```<code>common/win32thread.o:win32thread.c:(.text+0x60): undefined reference to `_beginthreadex'
common/win32thread.o:win32thread.c:(.text+0x60): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `_beginthreadex'
collect2: error: ld returned 1 exit status
Makefile:192: recipe for target 'libx264-148.dll' failed
make: *** [libx264-148.dll] Error 1
</code>```

My working Environment:

Windows 10 Pro

MSYS64 with mingw64

Microsoft Visual Studio 2015

The configure command was executed without errors, but the make gives me the error described above.

答:
GCC is built by MSYS2/MinGW with different configurations, and bundled with different versions of MinGW-w64 headers/libs.

MSYS2 only provides the posix thread model (pthreads); dwarf for i686, seh for x86_64.

MinGW provides posix and win32 thread models; sjlj and dwarf for i686, seh and sjlj for x86_64.

Ergo, MSYS applications need to be built using the pthreads library. You can force an MSYS build of x264 to use the posix thread model, instead of the win32 model like this:

$ ./configure --disable-cli --enable-shared --disable-win32thread
```

<blockquote>
  <p>platform:      X86_64<br>
  byte order:    little-endian<br>
  system:        WINDOWS<br>
  cli:           yes<br>
  libx264:       internal<br>
  shared:        yes<br>
  static:        no<br>
  asm:           yes<br>
  interlaced:    yes<br>
  avs:           avisynth<br>
  lavf:          no<br>
  ffms:          no<br>
  mp4:           no<br>
  gpl:           yes<br>
  thread:        posix<br>
  opencl:        no<br>
  filters:       crop select_every<br>
  lto:           no<br>
  debug:         no<br>
  gprof:         no<br>
  strip:         no<br>
  PIC:           yes<br>
  bit depth:     all<br>
  chroma format: all </p>

  <p>You can run 'make' or 'make fprofiled' now.</p>
</blockquote>

<p>The problem is, there is no <code>msys/winpthreads</code> package, so you would first need to cross-compile <code>pthreads-win32</code> for MSYS2.</p>

<hr>

<p>Having said all that, you say</p>

<blockquote>
  <p>For compilation of shared dlls</p>
</blockquote>

<p>and not</p>

<blockquote>
  <p>For compilation of .so shared libraries</p>
</blockquote>

<p>So this seems like an x-Y problem to me. I think you should be using MSYS to cross-compile x264 like this:</p>

<pre class="lang-none prettyprint-override"><code>$ ./configure --host=x86_64-w64-mingw32 --disable-cli --enable-shared --cross-prefix=x86_64-w64-mingw32-
</code>```

(I would also use --prefix=/usr/local, as well as --disable-opencl for compatability with FFmpeg.

Title: Compilation of x264 project

Body:
I had downloaded the source of x264 library.

The version of x264 is 148.

For compilation of shared dlls I am using the following command under
MSYS Environment:

./configure --disable-cli --enable-shared --prefix=.

The result is following:

platform:      X86_64
byte order:    little-endian
system:        WINDOWS
cli:           no
libx264:       internal
shared:        yes
static:        no
asm:           yes
interlaced:    yes
avs:           no
lavf:          no
ffms:          no
mp4:           no
gpl:           yes
thread:        win32
opencl:        yes
filters:       crop select_every
debug:         no
gprof:         no
strip:         no
PIC:           yes
bit depth:     8
chroma format: all

After execution of make I have the following error:

common/win32thread.o:win32thread.c:(.text+0x60): undefined reference to `_beginthreadex'
common/win32thread.o:win32thread.c:(.text+0x60): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `_beginthreadex'
collect2: error: ld returned 1 exit status
Makefile:192: recipe for target 'libx264-148.dll' failed
make: *** [libx264-148.dll] Error 1

My working Environment:

Windows 10 Pro

MSYS64 with mingw64

Microsoft Visual Studio 2015

The configure command was executed without errors, but the make gives me the error described above.

Body:
GCC is built by MSYS2/MinGW with different configurations, and bundled with different versions of MinGW-w64 headers/libs.

MSYS2 only provides the posix thread model (pthreads); dwarf for i686, seh for x86_64.

MinGW provides posix and win32 thread models; sjlj and dwarf for i686, seh and sjlj for x86_64.

Ergo, MSYS applications need to be built using the pthreads library. You can force an MSYS build of x264 to use the posix thread model, instead of the win32 model like this:

$ ./configure --disable-cli --enable-shared --disable-win32thread

platform:      X86_64

  byte order:    little-endian

  system:        WINDOWS

  cli:           yes

  libx264:       internal

  shared:        yes

  static:        no

  asm:           yes

  interlaced:    yes

  avs:           avisynth

  lavf:          no

  ffms:          no

  mp4:           no

  gpl:           yes

  thread:        posix

  opencl:        no

  filters:       crop select_every

  lto:           no

  debug:         no

  gprof:         no

  strip:         no

  PIC:           yes

  bit depth:     all

  chroma format: all

You can run 'make' or 'make fprofiled' now.

The problem is, there is no msys/winpthreads package, so you would first need to cross-compile pthreads-win32 for MSYS2.

Having said all that, you say

For compilation of shared dlls

and not

For compilation of .so shared libraries

So this seems like an x-Y problem to me. I think you should be using MSYS to cross-compile x264 like this:

$ ./configure --host=x86_64-w64-mingw32 --disable-cli --enable-shared --cross-prefix=x86_64-w64-mingw32-

(I would also use --prefix=/usr/local, as well as --disable-opencl for compatability with FFmpeg.


问:
Commutative operator + overloading causes infinite recursion
```<code>#include <iostream>
using namespace std;

class StringNum {
public:
    string s;
    StringNum() {s = "";}
public:
    StringNum(int n) {
        s = "";
        for (int i=1; i<=n; i++) s += "x";
    }

    operator int () {
        return s.length();
    }

    StringNum operator + (StringNum v) {
        cout << "operator + is called\n";
        int len = s.length() + v.s.length();
        StringNum res;
        for (int i=1;i<=len;i++) res.s += "x";
        return res;
    }

    template <class T>
    StringNum operator + (T value) {
        return (*this) + StringNum(value);
    }
};

template<class T>
StringNum operator + (T value, const StringNum& num) {
    cout << "operator + opposite is called\n";
    //return value + num; // infinite recursion, of course
    // return num + value;  // infinite recursion, despite StringNum + <class T> is defined
    return num + StringNum(value); // STILL infinite recursion
    //return StringNum(num) + value; // correct, output 6
}

int main()
{
    StringNum x(4);
    cout << (x + 2.5) << "\n"; // StringNum + <class T>, output 6
    int res = (2 + x);
    cout << res;
    return 0;
}
</code>```

Class StringNum represents an integer number > 0, where length of the string is the number.

StringNum + StringNum are member functions and work correctly.

StringNum + <class T> is also a member function and works correctly.

However, for <class T> + StringNum, it requires a external function. However,  the behavior of operator + is confusing and doesn't make any sense:

```<code>template<class T>
StringNum operator + (T value, const StringNum& num) {
    cout << "operator + opposite is called\n";
    //return value + num; // infinite recursion, of course
    // return num + value;  // StringNum + <class T>, infinite recursion. Why??
    return num + StringNum(value); // STILL infinite recursion
    //return StringNum(num) + value; // StringNum + <class T> -> this time it's correct, output 6
}
</code>```

How is it that num + StringNum(value) causes infinite recursion, while it should call StringNum + StringNum ? Also, why does num + value cause infinite recursion, while it should call StringNum + <class T> ? Finally, how does StringNum(num) + value solve the problem when num is a StringNum in the first place?

How can I correctly implement commutative operator + in this case ? Thank you.

答:
Use correct constness:

```<code>StringNum operator + (const StringNum& v) const {
    cout << "operator + is called\n";
    int len = s.length() + v.s.length();
    StringNum res;
    for (int i=1;i<=len;i++) res.s += "x";
    return res;
}

template <class T>
StringNum operator + (T value) const {
    return (*this) + StringNum(value);
}
</code>```

Demo

As In your template,

You call operator+ with const StringNum& and StringNum

And candidates are:

StringNum StringNum::operator + (StringNum v) Doesn't match, apply only to non const lhs

template <class T> StringNum StringNum::operator + (T value) Doesn't match, same reason as above

template<class T> StringNum operator + (T value, const StringNum& num) Matches, so leading to infinite recursion.

Body:
#include <iostream>
using namespace std;

class StringNum {
public:
    string s;
    StringNum() {s = "";}
public:
    StringNum(int n) {
        s = "";
        for (int i=1; i<=n; i++) s += "x";
    }

    operator int () {
        return s.length();
    }

    StringNum operator + (StringNum v) {
        cout << "operator + is called\n";
        int len = s.length() + v.s.length();
        StringNum res;
        for (int i=1;i<=len;i++) res.s += "x";
        return res;
    }

    template <class T>
    StringNum operator + (T value) {
        return (*this) + StringNum(value);
    }
};

template<class T>
StringNum operator + (T value, const StringNum& num) {
    cout << "operator + opposite is called\n";
    //return value + num; // infinite recursion, of course
    // return num + value;  // infinite recursion, despite StringNum + <class T> is defined
    return num + StringNum(value); // STILL infinite recursion
    //return StringNum(num) + value; // correct, output 6
}

int main()
{
    StringNum x(4);
    cout << (x + 2.5) << "\n"; // StringNum + <class T>, output 6
    int res = (2 + x);
    cout << res;
    return 0;
}

Class StringNum represents an integer number > 0, where length of the string is the number.

StringNum + StringNum are member functions and work correctly.

StringNum + <class T> is also a member function and works correctly.

However, for <class T> + StringNum, it requires a external function. However,  the behavior of operator + is confusing and doesn't make any sense:

template<class T>
StringNum operator + (T value, const StringNum& num) {
    cout << "operator + opposite is called\n";
    //return value + num; // infinite recursion, of course
    // return num + value;  // StringNum + <class T>, infinite recursion. Why??
    return num + StringNum(value); // STILL infinite recursion
    //return StringNum(num) + value; // StringNum + <class T> -> this time it's correct, output 6
}

How is it that num + StringNum(value) causes infinite recursion, while it should call StringNum + StringNum ? Also, why does num + value cause infinite recursion, while it should call StringNum + <class T> ? Finally, how does StringNum(num) + value solve the problem when num is a StringNum in the first place?

How can I correctly implement commutative operator + in this case ? Thank you.

Body:
Use correct constness:

StringNum operator + (const StringNum& v) const {
    cout << "operator + is called\n";
    int len = s.length() + v.s.length();
    StringNum res;
    for (int i=1;i<=len;i++) res.s += "x";
    return res;
}

template <class T>
StringNum operator + (T value) const {
    return (*this) + StringNum(value);
}

Demo

As In your template,

You call operator+ with const StringNum& and StringNum

And candidates are:

StringNum StringNum::operator + (StringNum v) Doesn't match, apply only to non const lhs

template <class T> StringNum StringNum::operator + (T value) Doesn't match, same reason as above

template<class T> StringNum operator + (T value, const StringNum& num) Matches, so leading to infinite recursion.


问:
Is this a timestamp error in the Bitstamp api?
I am trying to find out the transactions in bitcoins using the Bitstamp API and the time stamp seems to be wrong as it shows transactions in milliseconds (Unix timestamp) from 1970(Jan 19 1970 precisely). Am i missing something or is it a mistake from their side?

API Link : https://www.bitstamp.net/api/v2/transactions/btcusd/
API Documentation : https://www.bitstamp.net/api/

答:
I have tested their API and it seems to be right.

They use UNIX Timestamp in the 'date' field. You can use a convertor (https://www.unixtimestamp.com/index.php) to check the date in the format we're used to, like:


问:
Meson copy/install header files to output directory and keep folder structure
Basically i would like to be able to have a mix between the functions install_subdir and install_headers.

I want to copy all header files from my project source directory over to some other directory and still maintain the subdirectory structure.

Source

```<code>MyProject
|-- folder1
|   |-- file11.h
|   |-- file11.cpp
|   |-- file12.h
|   `-- file12.cpp
`-- folder2
    `-- file21.h
</code>```

Destination

```<code>
MyProject
|-- folder1
|   |-- file11.h
|   |-- file12.h
`-- folder2
    `-- file21.h
</code>```

What I tried was copying the source directory and exclude all cpp files and to just use the intended install_headers() function but both didn't work out.

I added comments to things I did and why. Maybe somebody knows what's up:

```<code>project('MyProject', 'cpp')

test_src = [  'src/MyProject/folder1/file11.cpp'
              'src/MyProject/folder1/file12.cpp']

# Passing files seems to be preferred but exclude_files only takes list of strings
# test_src = files([  'src/MyProject/folder1/file11.cpp'
#                     'src/MyProject/folder1/file12.cpp'])

test_hdr = files([  'src/MyProject/folder1/file11.h',
                    'src/MyProject/folder1/file12.h',
                    'src/MyProject/folder2/file21.h'])

base_dir = meson.current_source_dir()

static_library('MyProject', name_prefix: '', name_suffix : 'lib',
                sources: test_src,
                install: true,
                install_dir: base_dir + '/build/lib')

# Produces flat hierarchy
install_headers(test_hdr, install_dir: base_dir + '/build/include')

# Also copies all cpp files into destination folder
install_subdir('src/MyProject', install_dir: base_dir + '/build/include', exclude_files: '*.cpp')

# Same result as wildcard exclusion
install_subdir('src/MyProject', install_dir: base_dir + '/build/include', exclude_files: test_src)
</code>```

Does anyone have a solution to this?

I have a full list of my sources and headers if that is necessary for any method.

I am currently copying the files via shell commands, but including this into the install/build process would be preferred.

// EDIT:

I am using meson-build on windows.

答:
I found a work-around that does what i want.

If someone finds a better solution to this that requires a list of all header files feel free to still answer and i will accept it.

For now here is what i did:

```<code>project('MyProject', 'cpp')

test_src = files([  'src/MyProject/folder1/file11.cpp',
                    'src/MyProject/folder1/file12.cpp' ])

# Note that i'm omitting the base folder here since exclude_files searches relative to the subdir path
# Also, forward slash doesnt work. You have to use double backslash
test_src_exclude = [  'folder1\\file11.cpp',
                      'folder1\\file12.cpp' ]

dir_base = meson.current_source_dir()
dir_install = join_paths(dir_base, 'build/meson-out/MyProject')
dir_install_hdr = join_paths(dir_install, 'include')

static_library('MyProject', name_prefix: '', name_suffix : 'lib',
                sources: test_src,
                install: true,
                install_dir: dir_install)

install_subdir( 'src/MyProject',
                install_dir: dir_install_hdr,
                strip_directory: true,
                exclude_files: text_src_exclude)
</code>```

Body:
Basically i would like to be able to have a mix between the functions install_subdir and install_headers.

I want to copy all header files from my project source directory over to some other directory and still maintain the subdirectory structure.

Source

MyProject
|-- folder1
|   |-- file11.h
|   |-- file11.cpp
|   |-- file12.h
|   `-- file12.cpp
`-- folder2
    `-- file21.h

Destination

MyProject
|-- folder1
|   |-- file11.h
|   |-- file12.h
`-- folder2
    `-- file21.h

What I tried was copying the source directory and exclude all cpp files and to just use the intended install_headers() function but both didn't work out.

I added comments to things I did and why. Maybe somebody knows what's up:

project('MyProject', 'cpp')

test_src = [  'src/MyProject/folder1/file11.cpp'
              'src/MyProject/folder1/file12.cpp']

# Passing files seems to be preferred but exclude_files only takes list of strings
# test_src = files([  'src/MyProject/folder1/file11.cpp'
#                     'src/MyProject/folder1/file12.cpp'])

test_hdr = files([  'src/MyProject/folder1/file11.h',
                    'src/MyProject/folder1/file12.h',
                    'src/MyProject/folder2/file21.h'])

base_dir = meson.current_source_dir()

static_library('MyProject', name_prefix: '', name_suffix : 'lib',
                sources: test_src,
                install: true,
                install_dir: base_dir + '/build/lib')

# Produces flat hierarchy
install_headers(test_hdr, install_dir: base_dir + '/build/include')

# Also copies all cpp files into destination folder
install_subdir('src/MyProject', install_dir: base_dir + '/build/include', exclude_files: '*.cpp')

# Same result as wildcard exclusion
install_subdir('src/MyProject', install_dir: base_dir + '/build/include', exclude_files: test_src)

Does anyone have a solution to this?

I have a full list of my sources and headers if that is necessary for any method.

I am currently copying the files via shell commands, but including this into the install/build process would be preferred.

// EDIT:

I am using meson-build on windows.

Body:
I found a work-around that does what i want.

If someone finds a better solution to this that requires a list of all header files feel free to still answer and i will accept it.

For now here is what i did:

project('MyProject', 'cpp')

test_src = files([  'src/MyProject/folder1/file11.cpp',
                    'src/MyProject/folder1/file12.cpp' ])

# Note that i'm omitting the base folder here since exclude_files searches relative to the subdir path
# Also, forward slash doesnt work. You have to use double backslash
test_src_exclude = [  'folder1\\file11.cpp',
                      'folder1\\file12.cpp' ]

dir_base = meson.current_source_dir()
dir_install = join_paths(dir_base, 'build/meson-out/MyProject')
dir_install_hdr = join_paths(dir_install, 'include')

static_library('MyProject', name_prefix: '', name_suffix : 'lib',
                sources: test_src,
                install: true,
                install_dir: dir_install)

install_subdir( 'src/MyProject',
                install_dir: dir_install_hdr,
                strip_directory: true,
                exclude_files: text_src_exclude)


问:
How to count the number of clicks for button
How to count the number of clicks for CAT or DOG button in my program and save to log.txt  </p>

```<code>from Tkinter import *

import Tkinter as tk

import sys

stdoutOrigin=sys.stdout
sys.stdout = open("log.txt", "w")

master = Tk()
Label(master, text='Who is your favourate animal ?? ').grid(row=0)

Button(master, text='CAT' ,).grid(row=1, sticky=W, pady=4)
Button(master, text='DOG' ,).grid(row=1,column=1,sticky=W, pady=4)
mainloop()

sys.stdout.close()
sys.stdout=stdoutOrigin
</code>```

答: You can also just make a command that adds one to a variable every click.</p>

Body:
How to count the number of clicks for CAT or DOG button in my program and save to log.txt

from Tkinter import *

import Tkinter as tk

import sys

stdoutOrigin=sys.stdout
sys.stdout = open("log.txt", "w")

master = Tk()
Label(master, text='Who is your favourate animal ?? ').grid(row=0)

Button(master, text='CAT' ,).grid(row=1, sticky=W, pady=4)
Button(master, text='DOG' ,).grid(row=1,column=1,sticky=W, pady=4)
mainloop()

sys.stdout.close()
sys.stdout=stdoutOrigin


问:
ngSubmit not executing in Angular Reactive Form
I'm new to angular, and was messing around reactive forms watching a tutorial. My ngSubmit() function is not executing and nothing happens when I click the submit button, spend an hour trying to find the root cause. Can someone help out?

Employee.ts

```<code>export class Employee {

  private name: string;
  private email: string;
  private salary: number;
  private notes?: string;

}
</code>```

App.component.html

```<code>  <div class="container-fluid">
  <app-header></app-header>
</div>

<div class="row justify-content-lg-center">
  <div class="col-md-4">
    <app-employee-list></app-employee-list>
  </div>

  <div class="col-md-4">
    <app-employee-form></app-employee-form>
  </div>
</div>
</code>```

Employee-component.html

```<code><form [formGroup]="reactiveForm" (submit)="employeeSubmit(this.reactiveForm.value)">
  <div class="input-group mb-3">
    <div class="input-group-prepend">
      <span class="input-group-text" id="basic-addon1">@</span>
    </div>
    <input formControlName="name" type="text" class="form-control" placeholder="Username" aria-label="Username"
           aria-describedby="basic-addon1">
  </div>

  <div class="input-group mb-3">
    <input formControlName="email" type="text" class="form-control" placeholder="Recipient's username" aria-label="Recipient's username"
           aria-describedby="basic-addon2">
    <div class="input-group-append">
      <span class="input-group-text" id="basic-addon2">@example.com</span>
    </div>
  </div>

  <div class="input-group mb-3">
    <div class="input-group-prepend">
      <span class="input-group-text">$</span>
    </div>
    <input formControlName="salary" type="text" class="form-control" aria-label="Amount (to the nearest dollar)">
    <div class="input-group-append">
      <span class="input-group-text">.00</span>
    </div>
  </div>

  <div class="input-group">
    <div class="input-group-prepend">
      <span class="input-group-text">With textarea</span>
    </div>
    <textarea formControlName="notes" class="form-control" aria-label="With textarea"></textarea>
  </div>

  <div class="input-group">
  <button type="button" class="btn btn-primary">Submit</button>
  </div>

</form>
</code>```

Employee-form-component.ts

```<code>import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup} from '@angular/forms';

@Component({
  selector: 'app-employee-form',
  templateUrl: './employee-form.component.html',
  styleUrls: ['./employee-form.component.css']
})
export class EmployeeFormComponent implements OnInit {

  reactiveForm: FormGroup;

  constructor(private formBuilder: FormBuilder) {
    this.reactiveForm = this.formBuilder.group({
      'name': [''],
      'email': [''],
      'salary': [''],
      'notes': ['']
    });
  }

  ngOnInit() {
  }

  employeeSubmit(value) {
    // tslint:disable-next-line:no-debugger
    debugger;
    console.log(this.reactiveForm.value);
  }

}
</code>```

答:
Your button should be type submit, not type button

```<code><button type="submit">Submit</button>
</code>```

Setting the type to button is a specific instruction that the button shouldn't submit the form. This is useful for when you have other buttons in the form that aren't the main submit button.

Body:
I'm new to angular, and was messing around reactive forms watching a tutorial. My ngSubmit() function is not executing and nothing happens when I click the submit button, spend an hour trying to find the root cause. Can someone help out?

Employee.ts

export class Employee {

  private name: string;
  private email: string;
  private salary: number;
  private notes?: string;

}

App.component.html

  <app-header></app-header>

    <app-employee-list></app-employee-list>

    <app-employee-form></app-employee-form>

Employee-component.html

<form [formGroup]="reactiveForm" (submit)="employeeSubmit(this.reactiveForm.value)">

      @

    <input formControlName="name" type="text" class="form-control" placeholder="Username" aria-label="Username"
           aria-describedby="basic-addon1">

    <input formControlName="email" type="text" class="form-control" placeholder="Recipient's username" aria-label="Recipient's username"
           aria-describedby="basic-addon2">

      @example.com

      $

    <input formControlName="salary" type="text" class="form-control" aria-label="Amount (to the nearest dollar)">

      .00

      With textarea

    <textarea formControlName="notes" class="form-control" aria-label="With textarea"></textarea>

  <button type="button" class="btn btn-primary">Submit</button>

</form>

Employee-form-component.ts

import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup} from '@angular/forms';

@Component({
  selector: 'app-employee-form',
  templateUrl: './employee-form.component.html',
  styleUrls: ['./employee-form.component.css']
})
export class EmployeeFormComponent implements OnInit {

  reactiveForm: FormGroup;

  constructor(private formBuilder: FormBuilder) {
    this.reactiveForm = this.formBuilder.group({
      'name': [''],
      'email': [''],
      'salary': [''],
      'notes': ['']
    });
  }

  ngOnInit() {
  }

  employeeSubmit(value) {
    // tslint:disable-next-line:no-debugger
    debugger;
    console.log(this.reactiveForm.value);
  }

}

Body:
Your button should be type submit, not type button

<button type="submit">Submit</button>

Setting the type to button is a specific instruction that the button shouldn't submit the form. This is useful for when you have other buttons in the form that aren't the main submit button.


问:
How to check for records that are older than today in PHP?
I've set up a timestamp field with extra set to ON UPDATE CURRENT_TIMESTAMP.
It works but I have a question:

I'd like to check for all records which are older than today - how would I do that?

答:
You could also use date_sub to make it easier </p>

```<code>SELECT * FROM table WHERE timestamp_info < DATE_SUB(NOW(), INTERVAL 1 DAY);
</code>```

Body:
You could also use date_sub to make it easier

SELECT * FROM table WHERE timestamp_info < DATE_SUB(NOW(), INTERVAL 1 DAY);


问:
React with AppSync websocket failed
I have a React app with AWSAppSync.

This has been running with AppSync for 1 year. Yesterday, in the local environment (locahost:3000) I run a function that calls some endpoints that are Lambda functions. I don't know what happened, but this is the first time that, for some reason, the app gets stuck. I had to close Chrome, and when I opened again the app, the console in chrome shows me these errors:

```<code>WebSocket connection to 'wss://XXX(hidden, just for the question)-ats.iot.us-east-1.amazonaws.com/mqtt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=XXX%XXX%2Fus-east-1%2Fiotdevicegateway%2Faws4_request&X-Amz-Date=20200214T120942Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=XXX&X-Amz-Security-Token=IQoJb3JpZ2luX2VjEL3%2F%2F%2F%2F%2F%2F%2F%2F%2F%XXX%2...Iqt%2FYbC1VcHYZvvirJEBsuewBbuWnsCopy%2BPVIKwD9dkKW983Lk7AVO3H8sJ4SXQ%2FAfdFXygrzPWx7HnAy0rWB%2FUu89w4XJg07obTA8xkVs5HakFFVrXbd1EFgEWy8tcz2dS4Wn2hfvdkNs149uAkhoO0lbahPCK3dVYKaS6vWS5bLEjN1swhpya8gU61gEN3PDr1OyDDCc%2F7pxYE%XXX%2BoP%2B7%2FqV0OTK%2B0%XXX%2BcZhgr7LkAjgG3sBho1s65ietLymn1355%2F3z2PglnETpHh9FTnHUBxPl6kajt1MBvaZTkcQp5ks7FJ21KshW2hj89cYv94cRr5xXlsw8DKc44rh%2BJpOZgNmMYWHGKnbFR%2B%XXX%2Flm3TSLzTERGwHAoJ' failed: Error during WebSocket handshake: Unexpected response code: 404
</code>```

The console looks like this:

I tried to close the server (stop yarn start), even restart windows, nothing happened, now every time that I join the app I get those messages in the console. It's always the same number, it happened those 10 times and stops. So, the weird thing (or maybe not so weird) is if I open the production environment, not localhost, I get the messages too. If someone runs their local environment of opens the production environment it doesn't happen to him, only in my pc. Everyone shares the same public IP, so I don't get it.

Should I see in AWS console if some Lambda function is running or something like that? I just use endpoints for lambda functions, I never join the AWS console tho.

What else should I look to stop those messages? the app gets really slow with those messages, plus, in the network tab I get this:

Seriously, don't know what could be.

答: Well, the problem was outside the app. The VPN where I work was blocking some ports and protocols... that was all.</p>

Title: React with AppSync websocket failed

Body:
I have a React app with AWSAppSync.

This has been running with AppSync for 1 year. Yesterday, in the local environment (locahost:3000) I run a function that calls some endpoints that are Lambda functions. I don't know what happened, but this is the first time that, for some reason, the app gets stuck. I had to close Chrome, and when I opened again the app, the console in chrome shows me these errors:

WebSocket connection to 'wss://XXX(hidden, just for the question)-ats.iot.us-east-1.amazonaws.com/mqtt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=XXX%XXX%2Fus-east-1%2Fiotdevicegateway%2Faws4_request&X-Amz-Date=20200214T120942Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=XXX&X-Amz-Security-Token=IQoJb3JpZ2luX2VjEL3%2F%2F%2F%2F%2F%2F%2F%2F%2F%XXX%2...Iqt%2FYbC1VcHYZvvirJEBsuewBbuWnsCopy%2BPVIKwD9dkKW983Lk7AVO3H8sJ4SXQ%2FAfdFXygrzPWx7HnAy0rWB%2FUu89w4XJg07obTA8xkVs5HakFFVrXbd1EFgEWy8tcz2dS4Wn2hfvdkNs149uAkhoO0lbahPCK3dVYKaS6vWS5bLEjN1swhpya8gU61gEN3PDr1OyDDCc%2F7pxYE%XXX%2BoP%2B7%2FqV0OTK%2B0%XXX%2BcZhgr7LkAjgG3sBho1s65ietLymn1355%2F3z2PglnETpHh9FTnHUBxPl6kajt1MBvaZTkcQp5ks7FJ21KshW2hj89cYv94cRr5xXlsw8DKc44rh%2BJpOZgNmMYWHGKnbFR%2B%XXX%2Flm3TSLzTERGwHAoJ' failed: Error during WebSocket handshake: Unexpected response code: 404

The console looks like this:

I tried to close the server (stop yarn start), even restart windows, nothing happened, now every time that I join the app I get those messages in the console. It's always the same number, it happened those 10 times and stops. So, the weird thing (or maybe not so weird) is if I open the production environment, not localhost, I get the messages too. If someone runs their local environment of opens the production environment it doesn't happen to him, only in my pc. Everyone shares the same public IP, so I don't get it.

Should I see in AWS console if some Lambda function is running or something like that? I just use endpoints for lambda functions, I never join the AWS console tho.

What else should I look to stop those messages? the app gets really slow with those messages, plus, in the network tab I get this:

Seriously, don't know what could be.


问:
Angular 8 Universal Build Failed on SCSS Imports
I am using AngularCLI and an Angular v8.
In regards to Angular Universal, I have encountered an issue where after I run these commands which are the preparatory steps to setup:

```<code>ng generate universal --clientProject <project_name>

npm install @nguniversal/module-map-ngfactory-loader
npm install @nguniversal/express-engine

Add ModuleMapLoaderModule on AppServerModule
</code>```

or

```<code>ng add @nguniversal/express-engine --clientProject <project_name>
npm run build:ssr && npm run serve:ssr
</code>```

When I run ng build --configuration staging or even ng build --prod, the Build is successful with no errors.

But when I run ng run app:server:staging or ng run app:server:production, I will encounter an error like below:

```<code>ERROR in Module build failed (from ./node_modules/sass-loader/lib/loader.js):

@import 'base/colors';

Can't find stylesheet to import.

....
</code>```

My angular.json has these following SCSS config:

```<code>"schematics": {
    "@schematics/angular:component": {
      "styleext": "scss"
    }
  },

 ...

 "stylePreprocessorOptions": {
     "includePaths": [
     "src/",
     "src/assets/styles",
     "node_modules"
    ]
 },
</code>```

Would like to ask If I have missed something or if there's something needed to change?

Have tried reinstalling or running these commands but stil no luck:

```<code>rm -rf node_modules
rm package-lock.json
npm install
npm install node-sass
</code>```

When installing the node-sass, from "Can't find stylesheet to import." error message, it is now "File to import not found or unreadable: base/colors."

答: If non of solutions provided by @elias-sh not working -> just delete your scss file and recreate it.</p>

Body:
I am using AngularCLI and an Angular v8.
In regards to Angular Universal, I have encountered an issue where after I run these commands which are the preparatory steps to setup:

ng generate universal --clientProject <project_name>

npm install @nguniversal/module-map-ngfactory-loader
npm install @nguniversal/express-engine

Add ModuleMapLoaderModule on AppServerModule

or

ng add @nguniversal/express-engine --clientProject <project_name>
npm run build:ssr && npm run serve:ssr

When I run ng build --configuration staging or even ng build --prod, the Build is successful with no errors.

But when I run ng run app:server:staging or ng run app:server:production, I will encounter an error like below:

ERROR in Module build failed (from ./node_modules/sass-loader/lib/loader.js):

@import 'base/colors';

Can't find stylesheet to import.

....

My angular.json has these following SCSS config:

"schematics": {
    "@schematics/angular:component": {
      "styleext": "scss"
    }
  },

 ...

 "stylePreprocessorOptions": {
     "includePaths": [
     "src/",
     "src/assets/styles",
     "node_modules"
    ]
 },

Would like to ask If I have missed something or if there's something needed to change?

Have tried reinstalling or running these commands but stil no luck:

rm -rf node_modules
rm package-lock.json
npm install
npm install node-sass

When installing the node-sass, from "Can't find stylesheet to import." error message, it is now "File to import not found or unreadable: base/colors."


问:
Why Prism's Master Detail Page structure is different from Xamarin.Forms?
I developed one app about months ago with Prism. It's great tool that make perfect structure for my app.
However, today I tried to pick up that app and fix some things that pending for a long time. I used Master Detail page in my app, and today I suddenly found that actually the structure for how I developed this Master Detail page using Prism is kind of out of my knowledge.

So, here it is.

Basically my MasterDetailPage is like this:

```<code><?xml version="1.0" encoding="utf-8" ?>
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:b="clr-namespace:Prism.Behaviors;assembly=Prism.Forms"
             mc:Ignorable="d"
             x:Class="JapaneseLearnPrism.Views.MenuPage">
    <MasterDetailPage.Master>
        <NavigationPage Title="Menu" Icon="ic_hamburger.png">
            <x:Arguments>
                <ContentPage Title="{Binding Title}">
                    <ListView ItemsSource="{Binding MenuItems}"
                              SelectedItem="{Binding SelectedMenuItem, Mode=TwoWay}"
                              SeparatorColor="LightGray"
                              RowHeight="60"
                              SeparatorVisibility="Default"
                              BackgroundColor="#e8e8e8">
                        <ListView.ItemTemplate>
                            <DataTemplate>
                                <ViewCell>
                                    <StackLayout VerticalOptions="FillAndExpand"
                                                 Orientation="Horizontal"
                                                 Padding="20,10,0,10"
                                                 Spacing="20">
                                        <Label Text="{Binding PageIconText}" FontFamily="{StaticResource FontAwesomeSolid}" FontSize="Medium" VerticalOptions="Center" />
                                        <Label Text="{Binding Title}" FontSize="Medium" VerticalOptions="Center" TextColor="Black" />
                                    </StackLayout>
                                </ViewCell>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                        <ListView.Behaviors>
                            <b:EventToCommandBehavior EventName="ItemTapped" Command="{Binding NavigateCommand}" />
                        </ListView.Behaviors>
                    </ListView>
                </ContentPage>
            </x:Arguments>
        </NavigationPage>
    </MasterDetailPage.Master>
</MasterDetailPage>
</code>```

And the navigation path is this in App.xaml.cs file.

```<code>await NavigationService.NavigateAsync(nameof(MenuPage) + "/" + nameof(NavigationPage) + "/" + nameof(Views.MainPage));
</code>```

But if I look at lots of the Xamarin.Forms samples, the MasterDetailPage is actually different.
They are going to do like below:

```<code><MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
                  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                  xmlns:local="clr-namespace:MasterDetailPageNavigation;assembly=MasterDetailPageNavigation"
                  x:Class="MasterDetailPageNavigation.MainPage">
    <MasterDetailPage.Master>
        <local:MasterPage x:Name="masterPage" />
    </MasterDetailPage.Master>
    <MasterDetailPage.Detail>
        <NavigationPage>
            <x:Arguments>
                <local:ContactsPage />
            </x:Arguments>
        </NavigationPage>
    </MasterDetailPage.Detail>
</MasterDetailPage>
</code>```

And that's from Microsoft's official website. The Master Page in above is actually just one ContentPage, however, the Detail page should be NavigationPage, that one I can understand because it makes sense.

However, in my Prism app, the MasterPage also has to be a NavigaionPage, why is that? Any one can help on this?

Thanks.

答:
You can take a look at this wonderfull blog about How to make Master-Detail Page Navigation menu in Xamarin Forms with Prism.
If you scroll down to the bottom of the post, you will see some description on why it works this way, Quoting:

Note: Navigation in Prism is all based on this url format where we can define to which pages we want to go, and it can be something like this: ViewA/ViewB/ViewC/ViewD

... and if you remember we are inside of MasterDetail page so navigating from MasterDetail will get result that those pages will go to Detail part of it... and that is great for us, we have menu in side of master page and choosing menu items will open pages as Detail pages.

The way that Prism Navigation is designed, it makes sense that a DetaiPage goes inside the MasterDetail, so basically it keeps the Prism Logic of doing the Navigation.

Quoting the Basics of Prism Navigation

Navigating in a Prism application is conceptually different than standard navigation in Xamarin.Forms. While Xamarin.Forms navigation relies on a Page class instance to navigate, Prism removes all dependencies on Page types to achieve loosely coupled navigation from within a ViewModel. In Prism, the concept of navigating to a View or navigating to a ViewModel does not exist. Instead, you simply navigate to an experience, or a unique identifier, which represents the target view you wish to navigate to in your application.

Body:
I developed one app about months ago with Prism. It's great tool that make perfect structure for my app.
However, today I tried to pick up that app and fix some things that pending for a long time. I used Master Detail page in my app, and today I suddenly found that actually the structure for how I developed this Master Detail page using Prism is kind of out of my knowledge.

So, here it is.

Basically my MasterDetailPage is like this:

<?xml version="1.0" encoding="utf-8" ?>
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:b="clr-namespace:Prism.Behaviors;assembly=Prism.Forms"
             mc:Ignorable="d"
             x:Class="JapaneseLearnPrism.Views.MenuPage">
    <MasterDetailPage.Master>
        <NavigationPage Title="Menu" Icon="ic_hamburger.png">
            <x:Arguments>
                <ContentPage Title="{Binding Title}">
                    <ListView ItemsSource="{Binding MenuItems}"
                              SelectedItem="{Binding SelectedMenuItem, Mode=TwoWay}"
                              SeparatorColor="LightGray"
                              RowHeight="60"
                              SeparatorVisibility="Default"
                              BackgroundColor="#e8e8e8">
                        <ListView.ItemTemplate>
                            <DataTemplate>
                                <ViewCell>
                                    <StackLayout VerticalOptions="FillAndExpand"
                                                 Orientation="Horizontal"
                                                 Padding="20,10,0,10"
                                                 Spacing="20">

                                    </StackLayout>
                                </ViewCell>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                        <ListView.Behaviors>

                        </ListView.Behaviors>
                    </ListView>
                </ContentPage>
            </x:Arguments>
        </NavigationPage>
    </MasterDetailPage.Master>
</MasterDetailPage>

And the navigation path is this in App.xaml.cs file.

await NavigationService.NavigateAsync(nameof(MenuPage) + "/" + nameof(NavigationPage) + "/" + nameof(Views.MainPage));

But if I look at lots of the Xamarin.Forms samples, the MasterDetailPage is actually different.
They are going to do like below:

<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
                  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                  xmlns:local="clr-namespace:MasterDetailPageNavigation;assembly=MasterDetailPageNavigation"
                  x:Class="MasterDetailPageNavigation.MainPage">
    <MasterDetailPage.Master>
        <local:MasterPage x:Name="masterPage" />
    </MasterDetailPage.Master>
    <MasterDetailPage.Detail>
        <NavigationPage>
            <x:Arguments>
                <local:ContactsPage />
            </x:Arguments>
        </NavigationPage>
    </MasterDetailPage.Detail>
</MasterDetailPage>

And that's from Microsoft's official website. The Master Page in above is actually just one ContentPage, however, the Detail page should be NavigationPage, that one I can understand because it makes sense.

However, in my Prism app, the MasterPage also has to be a NavigaionPage, why is that? Any one can help on this?

Thanks.


问:
Simple way of getting instagram user name from image url (php)
someone knows a simple way of getting the username (or user-id) of an Instagram user via an image URL without the official API?

example:
I have this URL https://www.instagram.com/p/B8jEbu2A6CI/

now I want to get the username (panelpromo222)

答:
I found a solution over the Instagram api

https://api.instagram.com/oembed/?url=https://www.instagram.com/p/B8jEbu2A6CI/