问:
Unfurling two columns in a Pandas dataframe into a list of lists
I have two columns in a Pandas dataframe whose values logically follow one another.  See the following:

```<code>Name                Includes

Account             Product Account
Product Account     Card Account
Card Account        Plastic
Card Account        Token
Token               Token Vault
Account             Savings Account
</code>```

So Account > Product Account > Card Account, etc.  Ultimately I want to create a list of lists where the root ('Account') is the first element of each list.  The output should look like the following:

```<code>[['Account', 'Product Account', 'Card Account', 'Plastic'],
 ['Account', 'Product Account', 'Card Account', 'Token', 'Token Vault'],
 ['Account', 'Savings Account']]
</code>```

I basically want to find any and all possible paths between the dataframe elements that may exist.  I currently have a code that converts the two dataframe columns into a dictionary structure:

```<code>def link_hops(dictionary):

    dictionary = dict(df.groupby('Name')['Includes'].apply(set))
    dictionary = {k: list(v) for k, v in dictionary.items()}

    all_values = set(x for xs in dictionary.values() for x in xs)
    refs = all_values & set(dictionary.keys())

    for k, v in dictionary.items():
        for i in range(len(v)):
            if v[i] in refs:
                v[i] = {v[i]: v1 for k1, v1 in dictionary.items() if v[i] == k1}

    dictionary = {k: v for k, v in dictionary.items() if k not in refs}

    return dictionary
</code>```

I get the following:

```<code>{'Account': ['Savings Account',
            {'Product Account': [{'Card Account': ['Plastic',
            {'Token': ['Token Vault']}]}]}]}
</code>```

This code does the job of defining all of the paths that exist from the root ('Account') to the terminus for each path ('Savings Account', 'Plastic', 'Token Vault'), but I cannot figure out how to convert this into a list format that is scalable.  I have a recursion script which does work on small examples like this, but the actual dataframes I am working with can potentially be hundreds or thousands of levels deep when I convert them into dictionaries via link_hops, and easily blow past the recursion limit when I call that script.

I want to know if it is possible to skip the intermediate step of converting my dataframe into a dictionary and directly convert it into a list of lists, or even just use .map() or something similar to work on the dataframe directly.

答:
 #Approach1

Here's one approach, taking each row from the dataframe as a graph edge of a directed graph using NetworkX and looking for the shortest_path from Account to the different targets:

```<code>import numpy as np
a = df.values
# check correspondence with value in next row and first col
m = np.r_[False, (a[:-1, 1] != a[1:, 0])].cumsum()
# array([0, 0, 0, 1, 1, 2], dtype=int32)
# get indices of where theres is not a correspondence
m_diff = np.r_[m[:-1] != m[1:], True]
# array([False, False,  True, False,  True,  True])
# get targets of all paths
targets = a[m_diff, 1]
# array(['Plastic', 'TokenVault', 'SavingsAccount'], dtype=object)

# define a directed graph using networkx
import networkx as nx
#add edges from the graph
G = nx.from_pandas_edgelist(df, source='Name', target='Includes')
#find all shortest paths from Account to the different found targets
[nx.shortest_path(G, 'Account', target) for target in targets]

[['Account', 'ProductAccount', 'CardAccount', 'Plastic'],
 ['Account', 'ProductAccount', 'CardAccount', 'Token', 'TokenVault'],
 ['Account', 'SavingsAccount']]
</code>```

 #Approach2

Another way to find the graph end nodes could be to look at the degree, and keep those that have a degree of 1:

```<code>G = nx.from_pandas_edgelist(df, source='Name', target='Includes')
[nx.shortest_path(G, 'Account', node) for node, degree in G.degree() if degree==1]

[['Account', 'ProductAccount', 'CardAccount', 'Plastic'],
 ['Account', 'ProductAccount', 'CardAccount', 'Token', 'TokenVault'],
 ['Account', 'SavingsAccount']]
</code>```

For a visual understanding of the graph problem being solved:

```<code>pos = nx.spring_layout(G, scale=20)
nx.draw(G, pos, node_color='lightblue', node_size=500, with_labels=True)
</code>```

As we can see, by knowing the sources and targets to look for, by using nx.shortest_path we can obtain the path between Account and the obtained targets

Body:
I have two columns in a Pandas dataframe whose values logically follow one another.  See the following:

Name                Includes

Account             Product Account
Product Account     Card Account
Card Account        Plastic
Card Account        Token
Token               Token Vault
Account             Savings Account

So Account > Product Account > Card Account, etc.  Ultimately I want to create a list of lists where the root ('Account') is the first element of each list.  The output should look like the following:

[['Account', 'Product Account', 'Card Account', 'Plastic'],
 ['Account', 'Product Account', 'Card Account', 'Token', 'Token Vault'],
 ['Account', 'Savings Account']]

I basically want to find any and all possible paths between the dataframe elements that may exist.  I currently have a code that converts the two dataframe columns into a dictionary structure:

def link_hops(dictionary):

    dictionary = dict(df.groupby('Name')['Includes'].apply(set))
    dictionary = {k: list(v) for k, v in dictionary.items()}

    all_values = set(x for xs in dictionary.values() for x in xs)
    refs = all_values & set(dictionary.keys())

    for k, v in dictionary.items():
        for i in range(len(v)):
            if v[i] in refs:
                v[i] = {v[i]: v1 for k1, v1 in dictionary.items() if v[i] == k1}

    dictionary = {k: v for k, v in dictionary.items() if k not in refs}

    return dictionary

I get the following:

{'Account': ['Savings Account',
            {'Product Account': [{'Card Account': ['Plastic',
            {'Token': ['Token Vault']}]}]}]}

This code does the job of defining all of the paths that exist from the root ('Account') to the terminus for each path ('Savings Account', 'Plastic', 'Token Vault'), but I cannot figure out how to convert this into a list format that is scalable.  I have a recursion script which does work on small examples like this, but the actual dataframes I am working with can potentially be hundreds or thousands of levels deep when I convert them into dictionaries via link_hops, and easily blow past the recursion limit when I call that script.

I want to know if it is possible to skip the intermediate step of converting my dataframe into a dictionary and directly convert it into a list of lists, or even just use .map() or something similar to work on the dataframe directly.

Body:
 #Approach1

Here's one approach, taking each row from the dataframe as a graph edge of a directed graph using NetworkX and looking for the shortest_path from Account to the different targets:

import numpy as np
a = df.values
# check correspondence with value in next row and first col
m = np.r_[False, (a[:-1, 1] != a[1:, 0])].cumsum()
# array([0, 0, 0, 1, 1, 2], dtype=int32)
# get indices of where theres is not a correspondence
m_diff = np.r_[m[:-1] != m[1:], True]
# array([False, False,  True, False,  True,  True])
# get targets of all paths
targets = a[m_diff, 1]
# array(['Plastic', 'TokenVault', 'SavingsAccount'], dtype=object)

# define a directed graph using networkx
import networkx as nx
#add edges from the graph
G = nx.from_pandas_edgelist(df, source='Name', target='Includes')
#find all shortest paths from Account to the different found targets
[nx.shortest_path(G, 'Account', target) for target in targets]

[['Account', 'ProductAccount', 'CardAccount', 'Plastic'],
 ['Account', 'ProductAccount', 'CardAccount', 'Token', 'TokenVault'],
 ['Account', 'SavingsAccount']]

 #Approach2

Another way to find the graph end nodes could be to look at the degree, and keep those that have a degree of 1:

G = nx.from_pandas_edgelist(df, source='Name', target='Includes')
[nx.shortest_path(G, 'Account', node) for node, degree in G.degree() if degree==1]

[['Account', 'ProductAccount', 'CardAccount', 'Plastic'],
 ['Account', 'ProductAccount', 'CardAccount', 'Token', 'TokenVault'],
 ['Account', 'SavingsAccount']]

For a visual understanding of the graph problem being solved:

pos = nx.spring_layout(G, scale=20)
nx.draw(G, pos, node_color='lightblue', node_size=500, with_labels=True)

As we can see, by knowing the sources and targets to look for, by using nx.shortest_path we can obtain the path between Account and the obtained targets


来源: stackexchange

问:
Problem with PrimeFaces taglib in using JSF
I downloaded and added primefaces-3.0.M1.jar file to my project.

Then, I added this code to my JSP page:

```<code><%@ taglib uri="http://primefaces.prime.com.tr/ui" prefix="p" %>
</code>```

But it gives the error:

Can not find the tag library descriptor for "http://primefaces.prime.com.tr/ui"

Can anyone guide me how to overcome this problem?

答:
You could try the following workaround:</p>

```<code><% response.setContentType("application/xhtml+xml"); %>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I downloaded and added primefaces-3.0.M1.jar file to my project.

Then, I added this code to my JSP page:

<%@ taglib uri="http://primefaces.prime.com.tr/ui" prefix="p" %>

But it gives the error:

Can not find the tag library descriptor for "http://primefaces.prime.com.tr/ui"

Can anyone guide me how to overcome this problem?

Body:
You could try the following workaround:

<% response.setContentType("application/xhtml+xml"); %>


问:
Elasticsearch dsl OR query formation
I have index with multiple documents. The documents contains below fields:

name

adhar_number

pan_number

acc_number

I want to create a elasticsearch dsl query. For this query two inputs are available like adhar_number and pan_number. This query should match OR Condition on this.

Example:  If one document contains provided adhar_number only then I want that document too.

I have one dictionary with below contents (my_dict):

```<code>{
  "adhar_number": "123456789012",
  "pan_number": "BGPPG4315B"
}
</code>```

I tried like below:

```<code>from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search

es = Elasticsearch([{'host': 'localhost', 'port': 9200}])
s = Search(using=es, index="my_index")
for key, value in my_dict.items():
   s = s.query("match", **{key:value})

print(s.to_dict())
response = s.execute()
print(response.to_dict())
</code>```

It creates below query:

```<code>{
  'query': {
    'bool': {
      'must': [
        {
          'match': {
            'adhar_number': '123456789012'
          }
        },
        {
          'match': {
            'pan_number': 'BGPPG4315B'
          }
        }
      ]
    }
  }
}
</code>```

Above code is providing me the result with AND condition instead of OR Condition.

Please suggest me the good suggestions to include OR Condition.

答:
You can use should as also mentioned by @ifo20. Note that you most likely want ot define the minimum_should_match parameters as well:

You can use the minimum_should_match parameter to specify the number or percentage of should clauses returned documents must match.

If the bool query includes at least one should clause and no must or filter clauses, the default value is 1. Otherwise, the default value is 0.

```<code>{
  'query': {
    'bool': {
      'should': [
        {
          'match': {
            'adhar_number': '123456789012'
          }
        },
        {
          'match': {
            'pan_number': 'BGPPG4315B'
          }
        }
      ],
      "minimum_should_match" : 1
    }
  }
}
</code>```

Note also that the should clause contributes to the final score. I don't know how to avoid this but you may not want this to be part of an OR logic.

ContentLicense: CC BY-SA 4.0

Title: Elasticsearch dsl OR query formation

Body:
I have index with multiple documents. The documents contains below fields:

name

adhar_number

pan_number

acc_number

I want to create a elasticsearch dsl query. For this query two inputs are available like adhar_number and pan_number. This query should match OR Condition on this.

Example:  If one document contains provided adhar_number only then I want that document too.

I have one dictionary with below contents (my_dict):

{
  "adhar_number": "123456789012",
  "pan_number": "BGPPG4315B"
}

I tried like below:

from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search

es = Elasticsearch([{'host': 'localhost', 'port': 9200}])
s = Search(using=es, index="my_index")
for key, value in my_dict.items():
   s = s.query("match", **{key:value})

print(s.to_dict())
response = s.execute()
print(response.to_dict())

It creates below query:

{
  'query': {
    'bool': {
      'must': [
        {
          'match': {
            'adhar_number': '123456789012'
          }
        },
        {
          'match': {
            'pan_number': 'BGPPG4315B'
          }
        }
      ]
    }
  }
}

Above code is providing me the result with AND condition instead of OR Condition.

Please suggest me the good suggestions to include OR Condition.

Body:
You can use should as also mentioned by @ifo20. Note that you most likely want ot define the minimum_should_match parameters as well:

You can use the minimum_should_match parameter to specify the number or percentage of should clauses returned documents must match.

If the bool query includes at least one should clause and no must or filter clauses, the default value is 1. Otherwise, the default value is 0.

{
  'query': {
    'bool': {
      'should': [
        {
          'match': {
            'adhar_number': '123456789012'
          }
        },
        {
          'match': {
            'pan_number': 'BGPPG4315B'
          }
        }
      ],
      "minimum_should_match" : 1
    }
  }
}

Note also that the should clause contributes to the final score. I don't know how to avoid this but you may not want this to be part of an OR logic.


问:
Error: Schema validation failed with the following errors: Data path "" should NOT have additional properties(project)
After migrating application from angular 5 to 6, on running ng serve the following errors pop up.

Schema validation failed with the following errors:
    Data path "" should NOT have additional properties(project).
  Error: Schema validation failed with the following errors:
    Data path "" should NOT have additional properties(project).
      at MergeMapSubscriber._registry.compile.pipe.operators_1.concatMap.validatorResult [as project] (.../TemplateApp/me-cmf-web-template-angular/node_modules/@angular-devkit/core/src/workspace/workspace.js:210:42)
      at MergeMapSubscriber._tryNext (/.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/mergeMap.js:65:27)
      at MergeMapSubscriber._next (.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/mergeMap.js:55:18)
      at MergeMapSubscriber.Subscriber.next (/home/training/Attinad_Projects/TemplateApp/me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Subscriber.js:64:18)
      at MergeMapSubscriber.notifyNext (.../TemplateApp/me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/mergeMap.js:84:26)
      at InnerSubscriber._next (.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/InnerSubscriber.js:25:21)
      at InnerSubscriber.Subscriber.next (/.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Subscriber.js:64:18)
      at MapSubscriber._next (.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/map.js:52:26)
      at MapSubscriber.Subscriber.next (/.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Subscriber.js:64:18)
      at SwitchMapSubscriber.notifyNext (.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/switchMap.js:77:26)

I assume that the error is with .angular.json file which I re-named from .angular-cli.json .

My .angular.json file is as follows :

```<code>{
    "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
    "project": {
        "name": "mediaweb"
    },
    "apps": [{
            "root": "src",
            "outDir": "dist/browser",
            "assets": [
                "assets",
                "favicon.ico"
            ],
            "index": "index.html",
            "main": "main.ts",
            "polyfills": "polyfills.ts",
            "test": "test.ts",
            "tsconfig": "tsconfig.app.json",
            "testTsconfig": "tsconfig.spec.json",
            "prefix": "app",
            "styles": [
                "styles.scss",
                "../node_modules/owl.carousel/dist/assets/owl.carousel.css",
                "../node_modules/owl.carousel/dist/assets/owl.theme.default.css",
                "../node_modules/video.js/dist/video-js.css"
            ],
            "scripts": [
                "../node_modules/jquery/dist/jquery.js",
                "../node_modules/owl.carousel/dist/owl.carousel.js",
                "../node_modules/video.js/dist/ie8/videojs-ie8.js",
                "../node_modules/video.js/dist/video.js"
            ],
            "environmentSource": "environments/environment.ts",
            "environments": {
                "dev": "environments/environment.dev.ts",
                "prod": "environments/environment.prod.ts"
            }
        },
        {
            "platform": "server",
            "root": "src",
            "outDir": "dist/server",
            "assets": [
                "assets",
                "favicon.ico"
            ],
            "index": "index.html",
            "main": "main.server.ts",
            "test": "test.ts",
            "tsconfig": "tsconfig.server.json",
            "testTsconfig": "tsconfig.spec.json",
            "prefix": "app",
            "styles": [
                "styles.scss"
            ],
            "scripts": [],
            "environmentSource": "environments/environment.ts",
            "environments": {
                "dev": "environments/environment.dev.ts",
                "prod": "environments/environment.prod.ts"
            }
        }
    ],
    "e2e": {
        "protractor": {
            "config": "./protractor.conf.js"
        }
    },
    "lint": [{
            "project": "src/tsconfig.app.json",
            "exclude": ["**/node_modules/**", "**/UI/**"]
        },
        {
            "project": "src/tsconfig.spec.json",
            "exclude": "**/node_modules/**"
        },
        {
            "project": "e2e/tsconfig.e2e.json",
            "exclude": "**/node_modules/**"
        }
    ],
    "test": {
        "karma": {
            "config": "./karma.conf.js"
        }
    },
    "defaults": {
        "styleExt": "scss",
        "component": {}
    }
}
</code>```

Should I re-structure the json file, if so how?.

Any help would be great.

答:
When i was getting version error issues,Following command worked for me:

First run:

```<code>npm update
</code>```

Second run:

```<code>ng update
</code>```

Third run:
(It will update all the mismatching packages)

```<code>npm update --all --force
</code>```

Body:
After migrating application from angular 5 to 6, on running ng serve the following errors pop up.

Schema validation failed with the following errors:
    Data path "" should NOT have additional properties(project).
  Error: Schema validation failed with the following errors:
    Data path "" should NOT have additional properties(project).
      at MergeMapSubscriber._registry.compile.pipe.operators_1.concatMap.validatorResult [as project] (.../TemplateApp/me-cmf-web-template-angular/node_modules/@angular-devkit/core/src/workspace/workspace.js:210:42)
      at MergeMapSubscriber._tryNext (/.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/mergeMap.js:65:27)
      at MergeMapSubscriber._next (.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/mergeMap.js:55:18)
      at MergeMapSubscriber.Subscriber.next (/home/training/Attinad_Projects/TemplateApp/me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Subscriber.js:64:18)
      at MergeMapSubscriber.notifyNext (.../TemplateApp/me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/mergeMap.js:84:26)
      at InnerSubscriber._next (.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/InnerSubscriber.js:25:21)
      at InnerSubscriber.Subscriber.next (/.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Subscriber.js:64:18)
      at MapSubscriber._next (.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/map.js:52:26)
      at MapSubscriber.Subscriber.next (/.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/Subscriber.js:64:18)
      at SwitchMapSubscriber.notifyNext (.../me-cmf-web-template-angular/node_modules/@angular-devkit/core/node_modules/rxjs/internal/operators/switchMap.js:77:26)

I assume that the error is with .angular.json file which I re-named from .angular-cli.json .

My .angular.json file is as follows :

{
    "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
    "project": {
        "name": "mediaweb"
    },
    "apps": [{
            "root": "src",
            "outDir": "dist/browser",
            "assets": [
                "assets",
                "favicon.ico"
            ],
            "index": "index.html",
            "main": "main.ts",
            "polyfills": "polyfills.ts",
            "test": "test.ts",
            "tsconfig": "tsconfig.app.json",
            "testTsconfig": "tsconfig.spec.json",
            "prefix": "app",
            "styles": [
                "styles.scss",
                "../node_modules/owl.carousel/dist/assets/owl.carousel.css",
                "../node_modules/owl.carousel/dist/assets/owl.theme.default.css",
                "../node_modules/video.js/dist/video-js.css"
            ],
            "scripts": [
                "../node_modules/jquery/dist/jquery.js",
                "../node_modules/owl.carousel/dist/owl.carousel.js",
                "../node_modules/video.js/dist/ie8/videojs-ie8.js",
                "../node_modules/video.js/dist/video.js"
            ],
            "environmentSource": "environments/environment.ts",
            "environments": {
                "dev": "environments/environment.dev.ts",
                "prod": "environments/environment.prod.ts"
            }
        },
        {
            "platform": "server",
            "root": "src",
            "outDir": "dist/server",
            "assets": [
                "assets",
                "favicon.ico"
            ],
            "index": "index.html",
            "main": "main.server.ts",
            "test": "test.ts",
            "tsconfig": "tsconfig.server.json",
            "testTsconfig": "tsconfig.spec.json",
            "prefix": "app",
            "styles": [
                "styles.scss"
            ],
            "scripts": [],
            "environmentSource": "environments/environment.ts",
            "environments": {
                "dev": "environments/environment.dev.ts",
                "prod": "environments/environment.prod.ts"
            }
        }
    ],
    "e2e": {
        "protractor": {
            "config": "./protractor.conf.js"
        }
    },
    "lint": [{
            "project": "src/tsconfig.app.json",
            "exclude": ["**/node_modules/**", "**/UI/**"]
        },
        {
            "project": "src/tsconfig.spec.json",
            "exclude": "**/node_modules/**"
        },
        {
            "project": "e2e/tsconfig.e2e.json",
            "exclude": "**/node_modules/**"
        }
    ],
    "test": {
        "karma": {
            "config": "./karma.conf.js"
        }
    },
    "defaults": {
        "styleExt": "scss",
        "component": {}
    }
}

Should I re-structure the json file, if so how?.

Any help would be great.

Body:
When i was getting version error issues,Following command worked for me:

First run:

npm update

Second run:

ng update

Third run:
(It will update all the mismatching packages)

npm update --all --force


问:
How to automate the creation of a list based on an integer input in Excel
This is undoubtedly a very simple problem, but I don't have much experience with coding in Excel.

In this example, I would like the user to input the # of students into cell B3.

After inputting the # into the cell (for example, if the person input 5), I would like to create that number of rows from A4-A9 based on the notation Student_# (Student_1, Student_2, Student_3, Student_4, Student_5).

If the person put in 10, I would like there to be 10 rows of Student_1 through Student_10 (updated automatically).

The "Student_" will be static as this is an unidentified list, I'd just like to create the number of rows based on this initial input value.

Thanks in advance for any help.

答:
In A5 put:

```<code>=IF(ROW(A1)<=$B$3,"Student_" & ROW(A1),"")
</code>```

And copy down enough to cover the largest number allowed in B3

If one has the Dynamic Array formula simply put:

```<code>="Student_"&SEQUENCE(B3)
</code>```

In A5 and Excel will spill the results down.

Body:
In A5 put:

=IF(ROW(A1)<=$B$3,"Student_" & ROW(A1),"")

And copy down enough to cover the largest number allowed in B3

If one has the Dynamic Array formula simply put:

="Student_"&SEQUENCE(B3)

In A5 and Excel will spill the results down.


问:
How to recursively append to file name in powershell?
I have multiple .txt files in folders/their sub-folders.

I want to append _old to their file names.

I tried:

```<code>Get-ChildItem -Recurse | Rename-Item -NewName {$_.name -replace '.txt','_old.txt' }
</code>```

This results in:

Some files get updated correctly

Some files get updated incorrectly - they get _old twice - example: .._old_old.txt

There are few errors: Rename-Item : Source and destination path must be different.

答:
The below command will return ALL files from the current folder and sub-folders within the current directory the command is executed from.

```<code>Get-ChildItem -Recurse
</code>```

Because of this you are also re-turning all the files you have already updated to have the _old suffix.

What you need to do is use the -Include -Exclude paramters of the Get-Childitem Cmdlet in order to ignore files that already have the _old suffix, and meet your include criteria, for example.

```<code>Get-ChildItem -Recure -Include "*.txt" -Exclude "*_old"
</code>```

Then pipe the results into your re-name item command

Get-ChildItem cmdlet explanation can be found here.

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-childitem?view=powershell-7

Body:
I have multiple .txt files in folders/their sub-folders.

I want to append _old to their file names.

I tried:

Get-ChildItem -Recurse | Rename-Item -NewName {$_.name -replace '.txt','_old.txt' }

This results in:

Some files get updated correctly

Some files get updated incorrectly - they get _old twice - example: .._old_old.txt

There are few errors: Rename-Item : Source and destination path must be different.

Body:
The below command will return ALL files from the current folder and sub-folders within the current directory the command is executed from.

Get-ChildItem -Recurse

Because of this you are also re-turning all the files you have already updated to have the _old suffix.

What you need to do is use the -Include -Exclude paramters of the Get-Childitem Cmdlet in order to ignore files that already have the _old suffix, and meet your include criteria, for example.

Get-ChildItem -Recure -Include "*.txt" -Exclude "*_old"

Then pipe the results into your re-name item command

Get-ChildItem cmdlet explanation can be found here.

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-childitem?view=powershell-7


问:
updating sql server database using c# in asp.net
There isn't any compile error but the database doesn't get updated at all. what is wrong with the code?</p>

```<code>protected void Page_Load(object sender, EventArgs e) {
    rno.Text = Request.QueryString["rno"];//rno is a textbox

    string connectionString = @"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = db1; Integrated Security = True";
    SqlConnection cnn = new SqlConnection(connectionString);
    cnn.Open();

    String sql = "select fname from table1 where rno = @rno";

    SqlCommand command = new SqlCommand(sql, cnn);
    command.Parameters.AddWithValue("@rno", rno.Text.Trim());
    SqlDataReader reader = command.ExecuteReader();
    if (reader.Read()) {
        fname.Text = reader["xcountry"].ToString().Trim(); //fname is a textbox
    }
    reader.Close();
    command.Dispose();
    cnn.Close();

    fName.ReadOnly = true;
}

protected void modify_Click(object sender, EventArgs e) {

    fName.ReadOnly = false;
}

protected void savechanges_Click(object sender, EventArgs e) {
    string connectionString = @"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = db1; Integrated Security = True";
    SqlConnection cnn = new SqlConnection(connectionString);
    cnn.Open();

    String sql = "update table1 set fname=@fname where rno = @rno";

    SqlCommand command = new SqlCommand(sql, cnn);
    command.Parameters.AddWithValue("@fname", sfname);
    command.Parameters.AddWithValue("@rno", rno.Text.Trim());

    command.ExecuteNonQuery();
    command.Dispose();
    cnn.Close();
    fName.ReadOnly = true;
}
</code>```

答:
I have tried your code which executed fine and updated database table as well.

I have tried like below :

```<code>        string connectionString = @"data source=MS-KIRON-01;initial catalog=TestDatabase;integrated security=True;MultipleActiveResultSets=True";
        SqlConnection cnn = new SqlConnection(connectionString);
        cnn.Open();

        String sql = "update TestTable set fname=@fname where rno =rno";

        SqlCommand command = new SqlCommand(sql, cnn);
        command.Parameters.AddWithValue("@fname", "Test");
        command.Parameters.AddWithValue("@rno", "rno");

        command.ExecuteNonQuery();
        command.Dispose();
        cnn.Close();
</code>```

Another way I have tried.

```<code>            using (SqlConnection connection = new SqlConnection(connectionString ))
                    {
                        connection.Open();
                        var queryText = "UPDATE TestTable SET fname = '" + requestPram.fname + "' WHERE rno ='" + requestPram.rno + "'";

                        using (SqlCommand cmd = new SqlCommand(queryText, connection))
                        {
                            responseResults = await cmd.ExecuteNonQueryAsync();
                        }
                        connection.Close();

                    }
</code>```

Hope it would help

Body:
There isn't any compile error but the database doesn't get updated at all. what is wrong with the code?

protected void Page_Load(object sender, EventArgs e) {
    rno.Text = Request.QueryString["rno"];//rno is a textbox

    string connectionString = @"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = db1; Integrated Security = True";
    SqlConnection cnn = new SqlConnection(connectionString);
    cnn.Open();

    String sql = "select fname from table1 where rno = @rno";

    SqlCommand command = new SqlCommand(sql, cnn);
    command.Parameters.AddWithValue("@rno", rno.Text.Trim());
    SqlDataReader reader = command.ExecuteReader();
    if (reader.Read()) {
        fname.Text = reader["xcountry"].ToString().Trim(); //fname is a textbox
    }
    reader.Close();
    command.Dispose();
    cnn.Close();

    fName.ReadOnly = true;
}

protected void modify_Click(object sender, EventArgs e) {

    fName.ReadOnly = false;
}

protected void savechanges_Click(object sender, EventArgs e) {
    string connectionString = @"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = db1; Integrated Security = True";
    SqlConnection cnn = new SqlConnection(connectionString);
    cnn.Open();

    String sql = "update table1 set fname=@fname where rno = @rno";

    SqlCommand command = new SqlCommand(sql, cnn);
    command.Parameters.AddWithValue("@fname", sfname);
    command.Parameters.AddWithValue("@rno", rno.Text.Trim());

    command.ExecuteNonQuery();
    command.Dispose();
    cnn.Close();
    fName.ReadOnly = true;
}

Body:
I have tried your code which executed fine and updated database table as well.

I have tried like below :

        string connectionString = @"data source=MS-KIRON-01;initial catalog=TestDatabase;integrated security=True;MultipleActiveResultSets=True";
        SqlConnection cnn = new SqlConnection(connectionString);
        cnn.Open();

        String sql = "update TestTable set fname=@fname where rno =rno";

        SqlCommand command = new SqlCommand(sql, cnn);
        command.Parameters.AddWithValue("@fname", "Test");
        command.Parameters.AddWithValue("@rno", "rno");

        command.ExecuteNonQuery();
        command.Dispose();
        cnn.Close();

Another way I have tried.

            using (SqlConnection connection = new SqlConnection(connectionString ))
                    {
                        connection.Open();
                        var queryText = "UPDATE TestTable SET fname = '" + requestPram.fname + "' WHERE rno ='" + requestPram.rno + "'";

                        using (SqlCommand cmd = new SqlCommand(queryText, connection))
                        {
                            responseResults = await cmd.ExecuteNonQueryAsync();
                        }
                        connection.Close();

                    }

Hope it would help


问:
Laravel 5.4 Upgrade - ReflectionException: Class session does not exist
I updated my local environment to use Laravel 5.4, and in doing so, I can no longer run any tests using phpunit.

The error I am getting is:

```<code>ApplicationTest::testEnvironment
ReflectionException: Class session does not exist

/home/vagrant/Code/Sites/sa4/vendor/laravel/framework/src/Illuminate/Container/Container.php:681
/home/vagrant/Code/Sites/sa4/vendor/laravel/framework/src/Illuminate/Container/Container.php:565
/home/vagrant/Code/Sites/sa4/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php:105
/home/vagrant/Code/Sites/sa4/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php:780
/home/vagrant/Code/Sites/sa4/tests/TestCase.php:30
</code>```

Anyone know of a solution for this? I've hit a brick wall :(

答: Make sure that cache directory exists inside bootstrap.</p>

Body:
I updated my local environment to use Laravel 5.4, and in doing so, I can no longer run any tests using phpunit.

The error I am getting is:

ApplicationTest::testEnvironment
ReflectionException: Class session does not exist

/home/vagrant/Code/Sites/sa4/vendor/laravel/framework/src/Illuminate/Container/Container.php:681
/home/vagrant/Code/Sites/sa4/vendor/laravel/framework/src/Illuminate/Container/Container.php:565
/home/vagrant/Code/Sites/sa4/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php:105
/home/vagrant/Code/Sites/sa4/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php:780
/home/vagrant/Code/Sites/sa4/tests/TestCase.php:30

Anyone know of a solution for this? I've hit a brick wall :(


问:
Ruby add nil value to an array
How can I initialize an array and be able to add nil value to it? as I know Array.wrap doesn't do the job.

```<code>list = Array.wrap(nil) => []
</code>```

What I want:

```<code>list = Array.add(nil) => [nil]
</code>```

Thank you

答:
Try:

```<code>list = Array.new(1)
</code>```

The number fed in as an argument dictates how many nils are added:

```<code>list = Array.new(3)
=> [nil, nil, nil]
</code>```

Title: Ruby add nil value to an array

Body:
How can I initialize an array and be able to add nil value to it? as I know Array.wrap doesn't do the job.

list = Array.wrap(nil) => []

What I want:

list = Array.add(nil) => [nil]

Thank you

Body:
Try:

list = Array.new(1)

The number fed in as an argument dictates how many nils are added:

list = Array.new(3)
=> [nil, nil, nil]


问:
How do I implement maven source dependency among sibling projects?
I have a java project that is composed of 3 sub projects that generate a .jar artifact each (and have sub-dependencies among them).
In addition there is a web projects that depends on the first 3 projects and generate a war file. The war file is my final artifact, i.e. what I ship my customers.

Additionally I have a parent module that encompasses all the other projects:

```<code><modules>
    <module>../core</module>
    <module>../commons</module>
    <module>../api</module>
    <module>../web</module>
</modules>
</code>```

I generate eclipse files (mvn eclipse:eclipse) and work with eclipse. The problem is if I modify one of the non-web projects I must manually install it before deploying the web project to my web container. How can I make that the web project depends directly on the source code of the others and not on the version installed in the repository.

答: In your web application properties (right clic on the project in the Package explorer, then "properties"), add the three modules (core, commons and api) in the "J2EE Module Dependencies" (the others modules must be opened in the Eclipse workspace).</p>

OwnerDisplayName: andy

ContentLicense: CC BY-SA 2.5

Body:
I have a java project that is composed of 3 sub projects that generate a .jar artifact each (and have sub-dependencies among them).
In addition there is a web projects that depends on the first 3 projects and generate a war file. The war file is my final artifact, i.e. what I ship my customers.

Additionally I have a parent module that encompasses all the other projects:

<modules>
    <module>../core</module>
    <module>../commons</module>
    <module>../api</module>
    <module>../web</module>
</modules>

I generate eclipse files (mvn eclipse:eclipse) and work with eclipse. The problem is if I modify one of the non-web projects I must manually install it before deploying the web project to my web container. How can I make that the web project depends directly on the source code of the others and not on the version installed in the repository.

OwnerDisplayName: romaintaz


问:
AS3 Render Shape to Bitmap with Antialias
I have a drawn a Circle Shape in AS3. I want to render the Circle into a Bitmap with nice/antialiased Edges. Because I want it to work on Mobile Devices (Air Apps are limited to stagequality = low) I need a workaround. Any custom shape to bitmap renderer available?</p>

答:
In ActionScript 3 bitmap is created from BitmapData, so you need to create if first with

```<code>_bitmapData = new BitmapData(..
</code>```

BitmapData has method draw, passing DisplayObject instance (Sprite, MovieClip or other) to it as parameter, will draw it's content into BitmapData.
Example:

```<code>var c:Sprite = new Sprite();
c.graphics.clear();
c.graphics.beginFill(0x00FF00, 0.5);
c.graphics.lineStyle(2.0);
c.graphics.drawRectangle(0, 0, 100, 100);
c.graphics.endFill();
var bd:BitmapData = new BitmapData(100, 100);
bd.draw(c);
var bitmap:Bitmap = new Bitmap(bd);
</code>```

Body:
In ActionScript 3 bitmap is created from BitmapData, so you need to create if first with

_bitmapData = new BitmapData(..

BitmapData has method draw, passing DisplayObject instance (Sprite, MovieClip or other) to it as parameter, will draw it's content into BitmapData.
Example:

var c:Sprite = new Sprite();
c.graphics.clear();
c.graphics.beginFill(0x00FF00, 0.5);
c.graphics.lineStyle(2.0);
c.graphics.drawRectangle(0, 0, 100, 100);
c.graphics.endFill();
var bd:BitmapData = new BitmapData(100, 100);
bd.draw(c);
var bitmap:Bitmap = new Bitmap(bd);


问:
Rails persistent "No template for interactive request" although the template exists
I had this issue with rails. I have followed the basic guide:

rails new blog-2

rails g controller Homepage index

So now I have the standard folder with all the files, plus the controller Homepage and index.html.erb in view/homepage folder

Next I changed the routes to

Rails.application.routes.draw do

  root 'homepage#index'
end
```

<p>This is how my directory looks like</p>

<p>I did not edit the <code>homepage_controller.rb</code> nor the <code>index.html.erb</code></p>

<p>But I keep getting this error at localhost:3000</p>

<p>I have tried many ways, uninstall everything, reinstall. Desperate me, I even reset my laptop. Install everything again, but to no avail. Master railers, please help, thank you!!</p>

<p>Edit:
Here's my index action as per requested</p>

<pre class="lang-rb prettyprint-override"><code>class HomepageController < ApplicationController
  def index
  end
end
</code>```

Edit:
below is the error when I run rails s

Processing by HomepageController#index as HTML
Completed 406 Not Acceptable in 16ms (ActiveRecord: 0.0ms | Allocations: 1996)

ActionController::MissingExactTemplate (HomepageController#index is missing a template for request formats: text/html):

actionpack (6.0.2.1) lib/action_controller/metal/implicit_render.rb:45:in `default_render'
actionpack (6.0.2.1) lib/action_controller/metal/basic_implicit_render.rb:6:in `block in
send_action'
actionpack (6.0.2.1) lib/action_controller/metal/basic_implicit_render.rb:6:in `tap'
actionpack (6.0.2.1) lib/action_controller/metal/basic_implicit_render.rb:6:in `send_action'
actionpack (6.0.2.1) lib/abstract_controller/base.rb:196:in `process_action'
actionpack (6.0.2.1) lib/action_controller/metal/rendering.rb:30:in `process_action'
actionpack (6.0.2.1) lib/abstract_controller/callbacks.rb:42:in `block in process_action'activesupport (6.0.2.1) lib/active_support/callbacks.rb:135:in `run_callbacks'
actionpack (6.0.2.1) lib/abstract_controller/callbacks.rb:41:in `process_action'
actionpack (6.0.2.1) lib/action_controller/metal/rescue.rb:22:in `process_action'
actionpack (6.0.2.1) lib/action_controller/metal/instrumentation.rb:33:in `block in process_action'
activesupport (6.0.2.1) lib/active_support/notifications.rb:180:in `block in instrument'
activesupport (6.0.2.1) lib/active_support/notifications/instrumenter.rb:24:in `instrument'
activesupport (6.0.2.1) lib/active_support/notifications.rb:180:in `instrument'
actionpack (6.0.2.1) lib/action_controller/metal/instrumentation.rb:32:in `process_action'
actionpack (6.0.2.1) lib/action_controller/metal/params_wrapper.rb:245:in `process_action'
activerecord (6.0.2.1) lib/active_record/railties/controller_runtime.rb:27:in `process_action'
actionpack (6.0.2.1) lib/abstract_controller/base.rb:136:in `process'
actionview (6.0.2.1) lib/action_view/rendering.rb:39:in `process'
actionpack (6.0.2.1) lib/action_controller/metal.rb:191:in `dispatch'
actionpack (6.0.2.1) lib/action_controller/metal.rb:252:in `dispatch'
actionpack (6.0.2.1) lib/action_dispatch/routing/route_set.rb:51:in `dispatch'
actionpack (6.0.2.1) lib/action_dispatch/routing/route_set.rb:33:in `serve'
actionpack (6.0.2.1) lib/action_dispatch/journey/router.rb:49:in `block in serve'
actionpack (6.0.2.1) lib/action_dispatch/journey/router.rb:32:in `each'
actionpack (6.0.2.1) lib/action_dispatch/journey/router.rb:32:in `serve'
actionpack (6.0.2.1) lib/action_dispatch/routing/route_set.rb:837:in `call'
rack (2.1.1) lib/rack/tempfile_reaper.rb:17:in `call'
rack (2.1.1) lib/rack/etag.rb:27:in `call'
rack (2.1.1) lib/rack/conditional_get.rb:27:in `call'
rack (2.1.1) lib/rack/head.rb:14:in `call'
actionpack (6.0.2.1) lib/action_dispatch/http/content_security_policy.rb:18:in `call'
rack (2.1.1) lib/rack/session/abstract/id.rb:277:in `context'
rack (2.1.1) lib/rack/session/abstract/id.rb:271:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/cookies.rb:648:in `call'
activerecord (6.0.2.1) lib/active_record/migration.rb:567:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/callbacks.rb:27:in `block in call'
activesupport (6.0.2.1) lib/active_support/callbacks.rb:101:in `run_callbacks'
actionpack (6.0.2.1) lib/action_dispatch/middleware/callbacks.rb:26:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/executor.rb:14:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/actionable_exceptions.rb:17:in `call'actionpack (6.0.2.1) lib/action_dispatch/middleware/debug_exceptions.rb:32:in `call'
web-console (4.0.1) lib/web_console/middleware.rb:132:in `call_app'
web-console (4.0.1) lib/web_console/middleware.rb:28:in `block in call'
web-console (4.0.1) lib/web_console/middleware.rb:17:in `catch'
web-console (4.0.1) lib/web_console/middleware.rb:17:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/show_exceptions.rb:33:in `call'
railties (6.0.2.1) lib/rails/rack/logger.rb:38:in `call_app'
railties (6.0.2.1) lib/rails/rack/logger.rb:26:in `block in call'
activesupport (6.0.2.1) lib/active_support/tagged_logging.rb:80:in `block in tagged'
activesupport (6.0.2.1) lib/active_support/tagged_logging.rb:28:in `tagged'
activesupport (6.0.2.1) lib/active_support/tagged_logging.rb:80:in `tagged'
railties (6.0.2.1) lib/rails/rack/logger.rb:26:in `call'
sprockets-rails (3.2.1) lib/sprockets/rails/quiet_assets.rb:13:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/remote_ip.rb:81:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/request_id.rb:27:in `call'
rack (2.1.1) lib/rack/method_override.rb:24:in `call'
rack (2.1.1) lib/rack/runtime.rb:24:in `call'
activesupport (6.0.2.1) lib/active_support/cache/strategy/local_cache_middleware.rb:29:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/executor.rb:14:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/static.rb:126:in `call'
rack (2.1.1) lib/rack/sendfile.rb:113:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/host_authorization.rb:83:in `call'
webpacker (4.2.2) lib/webpacker/dev_server_proxy.rb:23:in `perform_request'
rack-proxy (0.6.5) lib/rack/proxy.rb:57:in `call'
railties (6.0.2.1) lib/rails/engine.rb:526:in `call'
puma (4.3.1) lib/puma/configuration.rb:228:in `call'
puma (4.3.1) lib/puma/server.rb:681:in `handle_request'
puma (4.3.1) lib/puma/server.rb:472:in `process_client'
puma (4.3.1) lib/puma/server.rb:328:in `block in run'
puma (4.3.1) lib/puma/thread_pool.rb:134:in `block in spawn_thread'
```

答:
I had the same issue (Windows 10 & same versions of Ruby and Rails), and it appears that I had created my project in a linked directory (it was c:\Local\myproject, but "Local" was a link):

When I create the project from the root, for example c:\Projects\myproject, everything works fine... Or another solution is to launch rails server from the full path c:\users\PUBLIC\Documents\myproject.

Body:
I had this issue with rails. I have followed the basic guide:

rails new blog-2

rails g controller Homepage index

So now I have the standard folder with all the files, plus the controller Homepage and index.html.erb in view/homepage folder

Next I changed the routes to

Rails.application.routes.draw do

  root 'homepage#index'
end

This is how my directory looks like

I did not edit the homepage_controller.rb nor the index.html.erb

But I keep getting this error at localhost:3000

I have tried many ways, uninstall everything, reinstall. Desperate me, I even reset my laptop. Install everything again, but to no avail. Master railers, please help, thank you!!

Edit:
Here's my index action as per requested

class HomepageController < ApplicationController
  def index
  end
end

Edit:
below is the error when I run rails s

Processing by HomepageController#index as HTML
Completed 406 Not Acceptable in 16ms (ActiveRecord: 0.0ms | Allocations: 1996)

ActionController::MissingExactTemplate (HomepageController#index is missing a template for request formats: text/html):

actionpack (6.0.2.1) lib/action_controller/metal/implicit_render.rb:45:in `default_render'
actionpack (6.0.2.1) lib/action_controller/metal/basic_implicit_render.rb:6:in `block in
send_action'
actionpack (6.0.2.1) lib/action_controller/metal/basic_implicit_render.rb:6:in `tap'
actionpack (6.0.2.1) lib/action_controller/metal/basic_implicit_render.rb:6:in `send_action'
actionpack (6.0.2.1) lib/abstract_controller/base.rb:196:in `process_action'
actionpack (6.0.2.1) lib/action_controller/metal/rendering.rb:30:in `process_action'
actionpack (6.0.2.1) lib/abstract_controller/callbacks.rb:42:in `block in process_action'activesupport (6.0.2.1) lib/active_support/callbacks.rb:135:in `run_callbacks'
actionpack (6.0.2.1) lib/abstract_controller/callbacks.rb:41:in `process_action'
actionpack (6.0.2.1) lib/action_controller/metal/rescue.rb:22:in `process_action'
actionpack (6.0.2.1) lib/action_controller/metal/instrumentation.rb:33:in `block in process_action'
activesupport (6.0.2.1) lib/active_support/notifications.rb:180:in `block in instrument'
activesupport (6.0.2.1) lib/active_support/notifications/instrumenter.rb:24:in `instrument'
activesupport (6.0.2.1) lib/active_support/notifications.rb:180:in `instrument'
actionpack (6.0.2.1) lib/action_controller/metal/instrumentation.rb:32:in `process_action'
actionpack (6.0.2.1) lib/action_controller/metal/params_wrapper.rb:245:in `process_action'
activerecord (6.0.2.1) lib/active_record/railties/controller_runtime.rb:27:in `process_action'
actionpack (6.0.2.1) lib/abstract_controller/base.rb:136:in `process'
actionview (6.0.2.1) lib/action_view/rendering.rb:39:in `process'
actionpack (6.0.2.1) lib/action_controller/metal.rb:191:in `dispatch'
actionpack (6.0.2.1) lib/action_controller/metal.rb:252:in `dispatch'
actionpack (6.0.2.1) lib/action_dispatch/routing/route_set.rb:51:in `dispatch'
actionpack (6.0.2.1) lib/action_dispatch/routing/route_set.rb:33:in `serve'
actionpack (6.0.2.1) lib/action_dispatch/journey/router.rb:49:in `block in serve'
actionpack (6.0.2.1) lib/action_dispatch/journey/router.rb:32:in `each'
actionpack (6.0.2.1) lib/action_dispatch/journey/router.rb:32:in `serve'
actionpack (6.0.2.1) lib/action_dispatch/routing/route_set.rb:837:in `call'
rack (2.1.1) lib/rack/tempfile_reaper.rb:17:in `call'
rack (2.1.1) lib/rack/etag.rb:27:in `call'
rack (2.1.1) lib/rack/conditional_get.rb:27:in `call'
rack (2.1.1) lib/rack/head.rb:14:in `call'
actionpack (6.0.2.1) lib/action_dispatch/http/content_security_policy.rb:18:in `call'
rack (2.1.1) lib/rack/session/abstract/id.rb:277:in `context'
rack (2.1.1) lib/rack/session/abstract/id.rb:271:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/cookies.rb:648:in `call'
activerecord (6.0.2.1) lib/active_record/migration.rb:567:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/callbacks.rb:27:in `block in call'
activesupport (6.0.2.1) lib/active_support/callbacks.rb:101:in `run_callbacks'
actionpack (6.0.2.1) lib/action_dispatch/middleware/callbacks.rb:26:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/executor.rb:14:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/actionable_exceptions.rb:17:in `call'actionpack (6.0.2.1) lib/action_dispatch/middleware/debug_exceptions.rb:32:in `call'
web-console (4.0.1) lib/web_console/middleware.rb:132:in `call_app'
web-console (4.0.1) lib/web_console/middleware.rb:28:in `block in call'
web-console (4.0.1) lib/web_console/middleware.rb:17:in `catch'
web-console (4.0.1) lib/web_console/middleware.rb:17:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/show_exceptions.rb:33:in `call'
railties (6.0.2.1) lib/rails/rack/logger.rb:38:in `call_app'
railties (6.0.2.1) lib/rails/rack/logger.rb:26:in `block in call'
activesupport (6.0.2.1) lib/active_support/tagged_logging.rb:80:in `block in tagged'
activesupport (6.0.2.1) lib/active_support/tagged_logging.rb:28:in `tagged'
activesupport (6.0.2.1) lib/active_support/tagged_logging.rb:80:in `tagged'
railties (6.0.2.1) lib/rails/rack/logger.rb:26:in `call'
sprockets-rails (3.2.1) lib/sprockets/rails/quiet_assets.rb:13:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/remote_ip.rb:81:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/request_id.rb:27:in `call'
rack (2.1.1) lib/rack/method_override.rb:24:in `call'
rack (2.1.1) lib/rack/runtime.rb:24:in `call'
activesupport (6.0.2.1) lib/active_support/cache/strategy/local_cache_middleware.rb:29:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/executor.rb:14:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/static.rb:126:in `call'
rack (2.1.1) lib/rack/sendfile.rb:113:in `call'
actionpack (6.0.2.1) lib/action_dispatch/middleware/host_authorization.rb:83:in `call'
webpacker (4.2.2) lib/webpacker/dev_server_proxy.rb:23:in `perform_request'
rack-proxy (0.6.5) lib/rack/proxy.rb:57:in `call'
railties (6.0.2.1) lib/rails/engine.rb:526:in `call'
puma (4.3.1) lib/puma/configuration.rb:228:in `call'
puma (4.3.1) lib/puma/server.rb:681:in `handle_request'
puma (4.3.1) lib/puma/server.rb:472:in `process_client'
puma (4.3.1) lib/puma/server.rb:328:in `block in run'
puma (4.3.1) lib/puma/thread_pool.rb:134:in `block in spawn_thread'


问:
Using insert and update on the 'when matched then' // merge
Is it possible to use an INSERT AND an UPDATE on the When matched then ?  ? I saw on the web that it's note possible so my question is : how can i do something like below ?

```<code>create table target_table(a, b, c, d, e) as (
   select 1, 2, 'NO',  100,'MDE' from dual union all
   select 1, 3, 'NO',  100,'AGC' from dual union all
   select 1, 4, 'NO',  100,'MDE' from dual union all
   select 1, 6, 'YES',  100,'MDE' from dual union all
   select 1, 5, 'NO',  100,'MDE' from dual );

create table source_table(a, b, c, d, e) as (
   select 1, 0, 'NO',  200,'AGC'  from dual union all
   select 1, 1, 'NO',  200,'MDE'  from dual union all
   select 1, 3, 'YES', 200,'AGC'  from dual union all
   select 1, 4, 'NO',  200,'MDE'  from dual union all
   select 1, 5, 'YES', 200,'MDE'  from dual );

merge into target_table t
using source_table s
on (t.a = s.a and t.b = s.b)
when matched then
case
      when t.c = 'NO' and s.c = 'YES' and t.e = 'MDE' and s.e = 'MDE' then update set t.d = s.d, t.c = s.c
      when t.e <> 'MDE' and s.e <> 'MDE' then insert values (s.a, s.b, s.c, s.d, s.e)
end
when not matched then insert values (s.a, s.b, s.c, s.d, s.e);
</code>```

答:
Let's sort things out.
First https://docs.oracle.com/en/database/oracle/oracle-database/12.2/sqlrf/MERGE.html#GUID-5692CCB7-24D9-4C0E-81A7-A22436DC968F

matched     -> update/delete

not matched -> insert

No mixing allowed.

So you want to insert when t.e and s.e are != 'MDE' or (t.a = s.a and t.b = s.b)
And the update only when  t.c = 'NO' and s.c = 'YES' and t.e = 'MDE' and s.e = 'MDE'

So did you try:

```<code>merge into target_table t
using source_table s
on (t.a = s.a and t.b = s.b and not ( t.e <> 'MDE' and s.e <> 'MDE'))
when matched then
    update set t.d = s.d, t.c = s.c
    where t.c = 'NO' and s.c = 'YES' and t.e = 'MDE' and s.e = 'MDE'
when not matched then insert values (s.a, s.b, s.c, s.d, s.e)
</code>```

Body:
Is it possible to use an INSERT AND an UPDATE on the When matched then ?  ? I saw on the web that it's note possible so my question is : how can i do something like below ?

create table target_table(a, b, c, d, e) as (
   select 1, 2, 'NO',  100,'MDE' from dual union all
   select 1, 3, 'NO',  100,'AGC' from dual union all
   select 1, 4, 'NO',  100,'MDE' from dual union all
   select 1, 6, 'YES',  100,'MDE' from dual union all
   select 1, 5, 'NO',  100,'MDE' from dual );

create table source_table(a, b, c, d, e) as (
   select 1, 0, 'NO',  200,'AGC'  from dual union all
   select 1, 1, 'NO',  200,'MDE'  from dual union all
   select 1, 3, 'YES', 200,'AGC'  from dual union all
   select 1, 4, 'NO',  200,'MDE'  from dual union all
   select 1, 5, 'YES', 200,'MDE'  from dual );

merge into target_table t
using source_table s
on (t.a = s.a and t.b = s.b)
when matched then
case
      when t.c = 'NO' and s.c = 'YES' and t.e = 'MDE' and s.e = 'MDE' then update set t.d = s.d, t.c = s.c
      when t.e <> 'MDE' and s.e <> 'MDE' then insert values (s.a, s.b, s.c, s.d, s.e)
end
when not matched then insert values (s.a, s.b, s.c, s.d, s.e);

Body:
Let's sort things out.
First https://docs.oracle.com/en/database/oracle/oracle-database/12.2/sqlrf/MERGE.html#GUID-5692CCB7-24D9-4C0E-81A7-A22436DC968F

matched     -> update/delete

not matched -> insert

No mixing allowed.

So you want to insert when t.e and s.e are != 'MDE' or (t.a = s.a and t.b = s.b)
And the update only when  t.c = 'NO' and s.c = 'YES' and t.e = 'MDE' and s.e = 'MDE'

So did you try:

merge into target_table t
using source_table s
on (t.a = s.a and t.b = s.b and not ( t.e <> 'MDE' and s.e <> 'MDE'))
when matched then
    update set t.d = s.d, t.c = s.c
    where t.c = 'NO' and s.c = 'YES' and t.e = 'MDE' and s.e = 'MDE'
when not matched then insert values (s.a, s.b, s.c, s.d, s.e)


问:
HSQL problem when using TIMESTAMP value as IN parameter in stored procedure
Overview HSQL IN parameter of type TIMESTAMP doesn't work as expected for HSQL stored procedure.

Given the following DDL :

```<code>CREATE TABLE TS_STORE (
    ID_COL VARCHAR(20) NOT NULL PRIMARY KEY,
    TS TIMESTAMP
);
</code>```

A DML statement such as :

```<code>INSERT INTO TS_STORE (ID_COL, TS) VALUES ('key1', '2020-02-19 12:17:53');
</code>```

will successfully insert a row.

Then when I attempt to create a stored procedure to do the same as:

```<code>CREATE PROCEDURE TEST_PROC(IN IN_KEY VARCHAR(20), IN IN_TS TIMESTAMP)
    MODIFIES SQL DATA
BEGIN ATOMIC
    INSERT INTO TS_STORE(ID_COL, TS)
    VALUES (IN_KEY, IN_TS);
END;
</code>```

and attempt to call it as:

```<code>CALL TEST_PROC('key2', '2020-02-19 12:17:53');
</code>```

Then I get an error: "incompatible data type in conversion".

This is a problem for me, since I am not allowed to change the signature of the the stored procedure to bypass the problem, since in my case HSQL is used as a mock for a production database (DB2) where the equivalent procedure works as expected.

答:
It works if you call the procedure with a TIMESTAMP value, as opposed to the character string.</p>

```<code>CALL TEST_PROC('key2', TIMESTAMP'2020-02-19 12:17:53');
</code>```

Body:
Overview HSQL IN parameter of type TIMESTAMP doesn't work as expected for HSQL stored procedure.

Given the following DDL :

CREATE TABLE TS_STORE (
    ID_COL VARCHAR(20) NOT NULL PRIMARY KEY,
    TS TIMESTAMP
);

A DML statement such as :

INSERT INTO TS_STORE (ID_COL, TS) VALUES ('key1', '2020-02-19 12:17:53');

will successfully insert a row.

Then when I attempt to create a stored procedure to do the same as:

CREATE PROCEDURE TEST_PROC(IN IN_KEY VARCHAR(20), IN IN_TS TIMESTAMP)
    MODIFIES SQL DATA
BEGIN ATOMIC
    INSERT INTO TS_STORE(ID_COL, TS)
    VALUES (IN_KEY, IN_TS);
END;

and attempt to call it as:

CALL TEST_PROC('key2', '2020-02-19 12:17:53');

Then I get an error: "incompatible data type in conversion".

This is a problem for me, since I am not allowed to change the signature of the the stored procedure to bypass the problem, since in my case HSQL is used as a mock for a production database (DB2) where the equivalent procedure works as expected.

Body:
It works if you call the procedure with a TIMESTAMP value, as opposed to the character string.

CALL TEST_PROC('key2', TIMESTAMP'2020-02-19 12:17:53');


问:
Angular - How to prevent nested piping with dependent observables?
In order to keep my code clean I try to prevent nested piping when it comes to observables. However I encountered a constellation (see code below) where I could not find a way to do without. I wonder if there is a way to solve this problem with only one pipe?

Example code:

```<code>class CannotSimplify {

  observableA(): Observable<number> {
    return of(1);
  }

  bDependentA(a: number): Observable<number> {
    return of(2 + a, 3 + a);
  }

  cDependentOnAAndB(a: number, b: number): Observable<number> {
    return of(a + b);
  }

  printResult(): void {
    this.observableA()
      .pipe(
        switchMap(a => this.bDependentA(a)),
        switchMap(b => this.cDependentOnAAndB(a, b)) // <-- error: a is undefined
      )
      .subscribe(c => console.log(c));
  }

}
</code>```

The only solution I could think of is to pipe this.bDependentOnA() again.
Is there a better approach?

Thanks in advance!

答:
I think you can use the zip operator for this.

this.observableA()
   .pipe(
     switchMap(a => zip(of(a), this.bDependentA(a))),
     switchMap(([a, b]) => this.cDependentOnAAndB(a, b))
   )
```

<p>As of RxJs version 7, the <strong>zip operator</strong> will be replaced with <code>zipWith</code>. More on that here.</p>

<pre class="lang-js prettyprint-override"><code>this.observableA()
   .pipe(
     switchMap(a => this.bDependentA(a).pipe(zipWith(of(a)))),
     switchMap(([b, a]) => this.cDependentOnAAndB(a, b))
   )
</code>```

Body:
In order to keep my code clean I try to prevent nested piping when it comes to observables. However I encountered a constellation (see code below) where I could not find a way to do without. I wonder if there is a way to solve this problem with only one pipe?

Example code:

class CannotSimplify {

  observableA(): Observable<number> {
    return of(1);
  }

  bDependentA(a: number): Observable<number> {
    return of(2 + a, 3 + a);
  }

  cDependentOnAAndB(a: number, b: number): Observable<number> {
    return of(a + b);
  }

  printResult(): void {
    this.observableA()
      .pipe(
        switchMap(a => this.bDependentA(a)),
        switchMap(b => this.cDependentOnAAndB(a, b)) // <-- error: a is undefined
      )
      .subscribe(c => console.log(c));
  }

}

The only solution I could think of is to pipe this.bDependentOnA() again.
Is there a better approach?

Thanks in advance!

Body:
I think you can use the zip operator for this.

this.observableA()
   .pipe(
     switchMap(a => zip(of(a), this.bDependentA(a))),
     switchMap(([a, b]) => this.cDependentOnAAndB(a, b))
   )

As of RxJs version 7, the zip operator will be replaced with zipWith. More on that here.

this.observableA()
   .pipe(
     switchMap(a => this.bDependentA(a).pipe(zipWith(of(a)))),
     switchMap(([b, a]) => this.cDependentOnAAndB(a, b))
   )


问:
PLS-00382: expression is of wrong type executing package function from anonymous block
Here is my function func in my package A:

```<code>create or replace PACKAGE A AS

    type MY_TYPE IS TABLE OF MYTABLE%ROWTYPE;

    FUNCTION func RETURN MY_TYPE;

END A;

create or replace PACKAGE BODY A AS

    FUNCTION func RETURN MY_TYPE IS
        CURSOR myCursor IS
           SELECT * FROM MYTABLE;
           var_cursor MYTABLE%ROWTYPE;
           myParam MY_TYPE;
           i NUMBER := 1;

        BEGIN
           FOR var_cursor IN myCursor
           LOOP
             myParam.EXTEND;
             myParam(i) := var_cursor;
             i := i + 1;
           END LOOP;

           RETURN myParam;
        END func;
END A;
</code>```

I want to call this function.

```<code>DECLARE
 type my_type IS TABLE OF MYTABLE%ROWTYPE;
 variable my_type;

BEGIN
   variable := A.func();
END;
</code>```

This gives error

PLS-00382: expression is of wrong type

The types are the same, so what am I doing wrong and how can I fix it?

答:
You need to use the same type, not an identical but separately defined type:

```<code>DECLARE
 variable a.my_type;

BEGIN
   variable := A.func();
END;
</code>```

Body:
Here is my function func in my package A:

create or replace PACKAGE A AS

    type MY_TYPE IS TABLE OF MYTABLE%ROWTYPE;

    FUNCTION func RETURN MY_TYPE;

END A;

create or replace PACKAGE BODY A AS

    FUNCTION func RETURN MY_TYPE IS
        CURSOR myCursor IS
           SELECT * FROM MYTABLE;
           var_cursor MYTABLE%ROWTYPE;
           myParam MY_TYPE;
           i NUMBER := 1;

        BEGIN
           FOR var_cursor IN myCursor
           LOOP
             myParam.EXTEND;
             myParam(i) := var_cursor;
             i := i + 1;
           END LOOP;

           RETURN myParam;
        END func;
END A;

I want to call this function.

DECLARE
 type my_type IS TABLE OF MYTABLE%ROWTYPE;
 variable my_type;

BEGIN
   variable := A.func();
END;

This gives error

PLS-00382: expression is of wrong type

The types are the same, so what am I doing wrong and how can I fix it?

Body:
You need to use the same type, not an identical but separately defined type:

DECLARE
 variable a.my_type;

BEGIN
   variable := A.func();
END;


问:
AJAX send to php controller not working in javascript
The snippet shows my html and js.  In my php controller I just print_r($_POST) but I only see the form data for myName I can't figure out how to access zzz

UPDATE: I added some code to make sure the send request is complete.  However, if I don't submit the form the controller doesn't execute from just issuing the xhttp request.  I still can't get any js data into php.  I could create hidden inputs and fill those in from js and the submit but that seems ugly.  can someone help?

function swagSend() {
  event.preventDefault();

  var xhttp = new XMLHttpRequest();

  xhttp.open("POST", "https://www.sustainablewestonma.org/wp-content/themes/twentytwelve-child/php/send_email.php", true);
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      console.log(xhttp.responseText);
    }
  }

  var henry = "henry"
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.send("zzz=" + henry);

  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {

      document.getElementById("myForm").submit();

    }
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="https://www.sustainablewestonma.org/wp-content/themes/twentytwelve-child/php/send_email.php" method="POST" id='myForm'>

  <input type='text' name='myname'>
  <button type='submit' value='submit' onClick=swagSend();>Submit</button>

</form></code>```

答:
If you are making an Ajax call, there is no reason to submit the form. remove it.

If you want the form data to be submitted in the Ajax call, you need to read the form input values and build up the list yourself.

function swagSend(event) {
  event.preventDefault();

  var xhttp = new XMLHttpRequest();
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.open("POST", "https://www.sustainablewestonma.org/wp-content/themes/twentytwelve-child/php/send_email.php", true);
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      console.log(xhttp.responseText);
    }
  }

  var henry = "henry"
  var name = encodeURIComponent(document.getElementById("myname").value)
  xhttp.send("zzz=" + henry + '&myname=' + name);
}
```

<pre class="lang-html prettyprint-override"><code><form action="https://www.sustainablewestonma.org/wp-content/themes/twentytwelve-child/php/send_email.php" method="POST" id='myForm'>

  <input type='text' name='myname' id='myname'>
  <button type='submit' value='submit' onClick="swagSend(event)">Submit</button>

</form>
</code>```

Body:
The snippet shows my html and js.  In my php controller I just print_r($_POST) but I only see the form data for myName I can't figure out how to access zzz

UPDATE: I added some code to make sure the send request is complete.  However, if I don't submit the form the controller doesn't execute from just issuing the xhttp request.  I still can't get any js data into php.  I could create hidden inputs and fill those in from js and the submit but that seems ugly.  can someone help?

function swagSend() {
  event.preventDefault();

  var xhttp = new XMLHttpRequest();

  xhttp.open("POST", "https://www.sustainablewestonma.org/wp-content/themes/twentytwelve-child/php/send_email.php", true);
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      console.log(xhttp.responseText);
    }
  }

  var henry = "henry"
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.send("zzz=" + henry);

  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {

      document.getElementById("myForm").submit();

    }
  }
}

<form action="https://www.sustainablewestonma.org/wp-content/themes/twentytwelve-child/php/send_email.php" method="POST" id='myForm'>

  <input type='text' name='myname'>
  <button type='submit' value='submit' onClick=swagSend();>Submit</button>

</form>

Body:
If you are making an Ajax call, there is no reason to submit the form. remove it.

If you want the form data to be submitted in the Ajax call, you need to read the form input values and build up the list yourself.

function swagSend(event) {
  event.preventDefault();

  var xhttp = new XMLHttpRequest();
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.open("POST", "https://www.sustainablewestonma.org/wp-content/themes/twentytwelve-child/php/send_email.php", true);
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      console.log(xhttp.responseText);
    }
  }

  var henry = "henry"
  var name = encodeURIComponent(document.getElementById("myname").value)
  xhttp.send("zzz=" + henry + '&myname=' + name);
}

<form action="https://www.sustainablewestonma.org/wp-content/themes/twentytwelve-child/php/send_email.php" method="POST" id='myForm'>

  <input type='text' name='myname' id='myname'>
  <button type='submit' value='submit' onClick="swagSend(event)">Submit</button>

</form>


问:
I need to sort an array of strings by popularity of the values inside the array
I have an array of strings, with some values multiple times like this.

```<code>const arr = ['banana', 'orange', 'banana', 'apple', 'apple', 'apple', 'orange', 'apple', 'banana']
</code>```

And i'd like to end up with an array of objects with the most popular value first paired with how many of those values are in the array and so on:

```<code>const newArr = [
   { fruit: 'apple', count: 4 },
   { fruit: 'banana', count: 3 },
   { fruit: 'orange', count: 2 }
]
</code>```

答:
Simply using reduce function to reduce the fruit list into object with counts should suffice

const arr = ['banana', 'orange', 'banana', 'apple', 'apple', 'apple', 'orange', 'apple', 'banana']

const partialResult = arr.reduce((result, fruit) => {
  if (!result[fruit]) result[fruit] = 1;
  else result[fruit]+=1;

  return result;
}, {});

const result = Object.entries(partialResult).map(([fruit, count]) => ({fruit, count})).sort(({count: countA},{count: countB})=> countB-countA);

console.log(result);```

Body:
I have an array of strings, with some values multiple times like this.

const arr = ['banana', 'orange', 'banana', 'apple', 'apple', 'apple', 'orange', 'apple', 'banana']

And i'd like to end up with an array of objects with the most popular value first paired with how many of those values are in the array and so on:

const newArr = [
   { fruit: 'apple', count: 4 },
   { fruit: 'banana', count: 3 },
   { fruit: 'orange', count: 2 }
]


问:
UIPicker and Text Field
I have the same kind of question as this person
How to Sync selected row of UIPicker with previously entered data

I want the picker to load with info from a text field in another tab. I'll explain.

I have a doctor tab where the user fills in all the info about their doctor or add from contacts. In another tab where they need to reference a doctor, instead of asking them to type in the same info I figure just use a picker.

But I would like to know if creating a NSMutableArray in the init, using -viewDidLoad: and then of course dealloc is just as sufficient as iterating. And should I have a separate class for the picker and just reference it?

Hope my question makes sense. Thanks in advance!

I apologize, I forgot to add I'm using Core Data if that makes a difference at all. But thanks to iamsult and the69geeks for the answers, I'll considering both.

答:
First of all create object for class A say doctorTab in class B (reference tab). Now access the array of class A through object doctorTab from class B.

```<code>NSMutableArray *referencedDoc = [[NSMutableArray alloc]init];
referencedDoc = doctorTab.doctorArray;
</code>```

doctorArray is the array defined in class A.

Hope this would work for you.

Title: UIPicker and Text Field

Body:
First of all create object for class A say doctorTab in class B (reference tab). Now access the array of class A through object doctorTab from class B.

NSMutableArray *referencedDoc = [[NSMutableArray alloc]init];
referencedDoc = doctorTab.doctorArray;

doctorArray is the array defined in class A.

Hope this would work for you.


问:
Loop over files in directory with if statement (batch file)
I'm trying to create a bat file to compile all of the .java files in a directory and to run the class called Main (and output to tulemused.txt) I was able to do this for a single .java file with a set name but I don't know how to use batch scripting well enough to loop over all of the files.

```<code>@ECHO on

FOR /d %%f DO IF NOT %%f=="compile.bat" javac -encoding utf-8 %%f

java -Dfile.encoding=UTF8 Main > tulemused.txt

@ECHO off
</code>```

This is how far I got

答:
Try this:</p>

```<code>@ECHO on
 FOR /r %%f In (*) DO IF NOT "%%~nf"=="compile.bat" javac -encoding utf-8 "%%~f"
java -Dfile.encoding=UTF8 Main >tulemused.txt
</code>```

Body:
I'm trying to create a bat file to compile all of the .java files in a directory and to run the class called Main (and output to tulemused.txt) I was able to do this for a single .java file with a set name but I don't know how to use batch scripting well enough to loop over all of the files.

@ECHO on

FOR /d %%f DO IF NOT %%f=="compile.bat" javac -encoding utf-8 %%f

java -Dfile.encoding=UTF8 Main > tulemused.txt

@ECHO off

This is how far I got

Body:
Try this:

@ECHO on
 FOR /r %%f In (*) DO IF NOT "%%~nf"=="compile.bat" javac -encoding utf-8 "%%~f"
java -Dfile.encoding=UTF8 Main >tulemused.txt


问:
How to use Promises with async and await in Javascript
I have a method that returns a JSON of all objects

```<code>const getAllItems=async function(req,res){
    localDB.find({
        selector:{type:'item'},
        fields: ['_id', 'itemNumber','itemName',"compatablities","companyID"],
        sort: ['_id']
    }).then(async function (result) {
        if (result) {
            var refinedResult=[]
            //console.log(result.docs[0]);
            for (i = 0; i < result.docs.length; i++) {
                    var parentItem={
                        itemName:result.docs[i].itemName,
                        itemNumber:result.docs[i].itemNumber,
                        companyID:result.docs[i].companyID,
                        parentItemNo:"Parent"
                        }
                        console.log("before");

                        const resolvedN=await resolveName(parentItem.companyID);
                        console.log(resolvedN)
                        console.log("Passed");
                        refinedResult.push(parentItem);
                    for (j = 0; j < result.docs[i].compatablities.length || 0; j++) {
                        var oneCompatItemConstruct={
                            itemName:result.docs[i].itemName,
                            itemNumber:result.docs[i].compatablities[j].itemNumber,
                            companyID:result.docs[i].compatablities[j].companyID,
                            parentItemNo:result.docs[i].itemNumber,
                        }
                        //console.log(oneCompatItemConstruct);
                        refinedResult.push(oneCompatItemConstruct);
                }
              }
            return res.status(200).json({
                refinedResult
            })
        }
      }).catch(function (err) {
        console.log(err);
      })
}
</code>```

and the objects have an ID to be resolved to a name so
i wrote a function to resolve its name and takes cid as a param and returns a string

```<code>function resolveName(c_id){
    localDB.find({
        selector:{type:'company',_id:c_id},
        fields: ['companyName'],
        })
        .then(company=>{
        if (company.docs.length >=1) {
            console.log(c_id);
            const result = company.docs[0].companyName
            return result
        }
        else{
            return null
        }}).catch(err => {
                    console.log(err);
                    res.status(500).json({
                        error: err
                    });
                });
}
</code>```

i want the function to be called on each loop and update the code while its executing, how
would i do that?

答:
It should probably look something like this.

Your code is sending off multiple asynchronous requests per inbound request. From a performance standpoint, these should happen in parallel: you should not simply wait for each request to return before making the next request. This is why I am using Promise.all in my solution.

Note that I can see at least one logical problem with your code that I am not in a position to correct.

const getAllItemsQuery = {
    selector: { type: 'item' },
    fields: ['_id', 'itemNumber', 'itemName', "compatablities", "companyID"],
    sort: ['_id']
}

const getAllItems = async function(req, res) {
    const { docs } = await localDB.find(getAllItemsQuery)
    if (!docs) return
    const promises = docs.map((doc) => createRefinedResultForDoc(doc))
    return res.status(200).json({ refinedResult: (await Promise.all(promises)).flat() })
}

async function createRefinedResultForDoc({ itemName, itemNumber, companyID, compatibilities }) {
     const result =  [ { itemName, itemNumber, companyID, parentItemNo: "Parent" } ]
     const resolvedN = await resolveName(companyID)
     // use resolvedN...
     compatibilities.forEach((compatibility) => {
         result.push({
             itemName,
             itemNumber: compatibility.itemNumber,
             companyID: compatibility.companyID,
             parentItemNo: itemNumber,
         }))
     return result
}

const createResolveNameQuery = (_id) => ({
    selector: { type: 'company', _id },
    fields: ['companyName'],
})

const resolveName = async(c_id) => {
    const { docs: [ doc ] } = await localDB.find(createResolveNameQuery(c_id))
    if (!doc) throw 'name not resolved'
    console.log(c_id)
    return doc.companyName
}
```

Body:
I have a method that returns a JSON of all objects

const getAllItems=async function(req,res){
    localDB.find({
        selector:{type:'item'},
        fields: ['_id', 'itemNumber','itemName',"compatablities","companyID"],
        sort: ['_id']
    }).then(async function (result) {
        if (result) {
            var refinedResult=[]
            //console.log(result.docs[0]);
            for (i = 0; i < result.docs.length; i++) {
                    var parentItem={
                        itemName:result.docs[i].itemName,
                        itemNumber:result.docs[i].itemNumber,
                        companyID:result.docs[i].companyID,
                        parentItemNo:"Parent"
                        }
                        console.log("before");

                        const resolvedN=await resolveName(parentItem.companyID);
                        console.log(resolvedN)
                        console.log("Passed");
                        refinedResult.push(parentItem);
                    for (j = 0; j < result.docs[i].compatablities.length || 0; j++) {
                        var oneCompatItemConstruct={
                            itemName:result.docs[i].itemName,
                            itemNumber:result.docs[i].compatablities[j].itemNumber,
                            companyID:result.docs[i].compatablities[j].companyID,
                            parentItemNo:result.docs[i].itemNumber,
                        }
                        //console.log(oneCompatItemConstruct);
                        refinedResult.push(oneCompatItemConstruct);
                }
              }
            return res.status(200).json({
                refinedResult
            })
        }
      }).catch(function (err) {
        console.log(err);
      })
}

and the objects have an ID to be resolved to a name so
i wrote a function to resolve its name and takes cid as a param and returns a string

function resolveName(c_id){
    localDB.find({
        selector:{type:'company',_id:c_id},
        fields: ['companyName'],
        })
        .then(company=>{
        if (company.docs.length >=1) {
            console.log(c_id);
            const result = company.docs[0].companyName
            return result
        }
        else{
            return null
        }}).catch(err => {
                    console.log(err);
                    res.status(500).json({
                        error: err
                    });
                });
}

i want the function to be called on each loop and update the code while its executing, how
would i do that?


问:
How do trigger the key combination 'CTRL+SHIFT+ENTER' using Testcafe .keypress()?
I am trying to run an e2e test with TestCafe and the scenario is that when user press the keys 'CTRL+SHIFT+ENTER' it should trigger an event. it works when i use the keyboard but not within the E2E. Thank you for your help.

the command i use is :

t.keypres('ctrl+shift+enter');
```

答:
The code you are using seems incorrect. Try

```<code>await t.pressKey('ctrl+shift enter');
</code>```

Refer https://devexpress.github.io/testcafe/documentation/test-api/actions/press-key.html

Body:
The code you are using seems incorrect. Try

await t.pressKey('ctrl+shift enter');

Refer https://devexpress.github.io/testcafe/documentation/test-api/actions/press-key.html


问:
Get child along with parent
Consider the following two classess School and Student. School got collection of Students. also Student got associated with School which is not mapped

```<code>public class School
{
    public int Id { get; set; }
    public virtual ICollection<Student> students { get; set; }
}

public class Student
{
    public int Id { get; set; }
    public int SchoolId { get; set; }
    public string Name { get; set; }
    public bool Deleted { get; set; }
    public virtual School School { get; set; }
}
</code>```

My modelbuilder looks like this

```<code>modelBuilder.Entity<School>()
        .HasMany(obj => obj.students)
        .WithOne()
        .HasForeignKey(obj => obj.SchoolId)
        .OnDelete(DeleteBehavior.Cascade)
        .IsRequired();

modelBuilder.Entity<Student>(entity =>
{
    entity.HasOne(e => e.School);
});
</code>```

What worked -

```<code>var result = mydbcontext.Schools
                        .Include(d => d.students)
                        .Where(d => d.Id == 1)
                        .Select(x => new School
                        {
                            Id = x.Id,
                            students = x.students.Where(s => !s.Deleted).ToList()
                        })
                        .AsNoTracking()
                        .ToList();
</code>```

What is NOT working -

```<code>var school = mydbcontext.Students
                        .Include(x => x.School) //returning null
                        .Where(s => !s.Deleted)
                        .ToList();
</code>```

When i tried the above code, I get all students which are not deleted, but I get Empty results for School

Am I missing anything here?

答: This looks likely to be caused by your [NotMapped] attribute on the Student class School property. Using that attribute instructs EF not to create a corresponding column in the database for keying the Student record back to the School record, therefore EF will not be able to infer the Student->Schoolrelationship, only the School->Students relationship.

Title: Get child along with parent

Body:
Consider the following two classess School and Student. School got collection of Students. also Student got associated with School which is not mapped

public class School
{
    public int Id { get; set; }
    public virtual ICollection<Student> students { get; set; }
}

public class Student
{
    public int Id { get; set; }
    public int SchoolId { get; set; }
    public string Name { get; set; }
    public bool Deleted { get; set; }
    public virtual School School { get; set; }
}

My modelbuilder looks like this

modelBuilder.Entity<School>()
        .HasMany(obj => obj.students)
        .WithOne()
        .HasForeignKey(obj => obj.SchoolId)
        .OnDelete(DeleteBehavior.Cascade)
        .IsRequired();

modelBuilder.Entity<Student>(entity =>
{
    entity.HasOne(e => e.School);
});

What worked -

var result = mydbcontext.Schools
                        .Include(d => d.students)
                        .Where(d => d.Id == 1)
                        .Select(x => new School
                        {
                            Id = x.Id,
                            students = x.students.Where(s => !s.Deleted).ToList()
                        })
                        .AsNoTracking()
                        .ToList();

What is NOT working -

var school = mydbcontext.Students
                        .Include(x => x.School) //returning null
                        .Where(s => !s.Deleted)
                        .ToList();

When i tried the above code, I get all students which are not deleted, but I get Empty results for School

Am I missing anything here?


问:
SCDF Spring Cloud Data Fflow problems with task-launcher-dataflow Incompatible version of Data Flow server detected
I Build a stream with sftp-dataflow as source (sftp-dataflow-source-kafka:2.1.1.RELEASE) connected with task-launcher-dataflow (task-launcher-dataflow-sink-kafka:1.0.2.RELEASE) as sink. The goal is to launch a task which is a spring-batch job.

My SCDF platform contains : Skipper-server version 2.3.0, dataflow-server 2.4.0 and kafka deployed as dockers.

The sftp source send a message to the task-launcher and the launcher have an exception :

Failed to instantiate
  [org.springframework.cloud.dataflow.rest.client.DataFlowOperations]:
  Factory method 'dataFlowOperations' threw exception; nested exception
  is java.lang.IllegalStateException: Incompatible version of Data Flow
  server detected.

All my components are in the last versions.

To create may stream:

```<code>stream create testStreamSftpDataflowlaunch1 --definition "sftp-dataflow --local-dir=/tmp/local-files1 --remote-dir=/data/docker/containers/SCDF/dockerSCDF/tmp/remote-files1 --password=docker* --allow-unknown-keys=true --username=docker --host=slnxdalicrprp03.mano.es.sopra --task-name=batchEODTask --logging.level.org.springframework.integration=DEBUG --task.launch.request.taskName=batchEODTask | task-launcher-dataflow --server-uri=http://slnxdalicrprp03******:57102" (skipper-server;port)
</code>```

Other thing, I don't understand, how the launcher can execute a task because the task-name is not transmit to the launcher through the message. For example, we have the file name and others properties

message: GenericMessage [payload=/tmp/local-files1/FMO.txt,
  headers={file_originalFile=/tmp/local-files1/FMO.txt,
  id=7447a3ab-cd0e-17c2-181d-7b0f5cb85d78, file_name=FMO.txt,
  file_relativePath=FMO.txt, timestamp=1582106812595}] 2020-02-19
  10:06:52.961 DEBUG 233 --- [ask-scheduler-1]
  o.s.i.e.SourcePollingChannelAdapter      : Poll resulted in Message:
  GenericMessage [payload=/tmp/local-files1/FMO2.txt,
  headers={file_originalFile=/tmp/local-files1/FMO2.txt,
  id=b0fc3c02-a3e2-2481-aa5b-68f9db6b6973, file_name=FMO2.txt,
  file_relativePath=FMO2.txt, timestamp=1582106812961}] 2020-02-19
  10:06:52.962 DEBUG 233 --- [ask-scheduler-1]
  o.s.integration.channel.DirectChannel    : preSend on channel
  'taskLaunchRequestChannel',

When I launch the SCDF sample in documentation with the ingestFile, we have the same problem.

Do you have an idea?

答:
There's a lot in this post. I will attempt to unpack a few things here.

The sftp source send a message to the task-launcher and the launcher have an exception : Failed to instantiate [org.springframework.cloud.dataflow.rest.client.DataFlowOperations]: Factory method 'dataFlowOperations' threw exception; nested exception is java.lang.IllegalStateException: Incompatible version of Data Flow server detected.

It appears the TL-Dataflow sink is bundled with rather an older SCDF client library — see tasklauncher-dataflow-app-dependencies/pom.xml#L20. You can update the version to 2.4.0.RELEASE (same as SCDF that you have got running already), and build the app and as well a local docker image for your testing/use.

Other thing, I don't understand, how the launcher can execute a task because the task-name is not transmit to the launcher through the message.

If you pay attention to TL-Dataflow docs, you will notice the input (aka payload) is accepted as a JSON with certain key/value pairs. The name is the critical bit. It is the name of the Task definition that already exists in SCDF. We have an end-to-end recipe that walk through the use-case entirely, which you can use as the reference and follow along.

Recently, we also added the enhancement to auto-create the task definition (if there's none). The name must match with an existing task-app name in the app registry — see spring-cloud-stream-app-starters/tasklauncher-dataflow#24.

I believe this covers the pressing questions on this post.

Body:
I Build a stream with sftp-dataflow as source (sftp-dataflow-source-kafka:2.1.1.RELEASE) connected with task-launcher-dataflow (task-launcher-dataflow-sink-kafka:1.0.2.RELEASE) as sink. The goal is to launch a task which is a spring-batch job.

My SCDF platform contains : Skipper-server version 2.3.0, dataflow-server 2.4.0 and kafka deployed as dockers.

The sftp source send a message to the task-launcher and the launcher have an exception :

Failed to instantiate
  [org.springframework.cloud.dataflow.rest.client.DataFlowOperations]:
  Factory method 'dataFlowOperations' threw exception; nested exception
  is java.lang.IllegalStateException: Incompatible version of Data Flow
  server detected.

All my components are in the last versions.

To create may stream:

stream create testStreamSftpDataflowlaunch1 --definition "sftp-dataflow --local-dir=/tmp/local-files1 --remote-dir=/data/docker/containers/SCDF/dockerSCDF/tmp/remote-files1 --password=docker* --allow-unknown-keys=true --username=docker --host=slnxdalicrprp03.mano.es.sopra --task-name=batchEODTask --logging.level.org.springframework.integration=DEBUG --task.launch.request.taskName=batchEODTask | task-launcher-dataflow --server-uri=http://slnxdalicrprp03******:57102" (skipper-server;port)

Other thing, I don't understand, how the launcher can execute a task because the task-name is not transmit to the launcher through the message. For example, we have the file name and others properties

message: GenericMessage [payload=/tmp/local-files1/FMO.txt,
  headers={file_originalFile=/tmp/local-files1/FMO.txt,
  id=7447a3ab-cd0e-17c2-181d-7b0f5cb85d78, file_name=FMO.txt,
  file_relativePath=FMO.txt, timestamp=1582106812595}] 2020-02-19
  10:06:52.961 DEBUG 233 --- [ask-scheduler-1]
  o.s.i.e.SourcePollingChannelAdapter      : Poll resulted in Message:
  GenericMessage [payload=/tmp/local-files1/FMO2.txt,
  headers={file_originalFile=/tmp/local-files1/FMO2.txt,
  id=b0fc3c02-a3e2-2481-aa5b-68f9db6b6973, file_name=FMO2.txt,
  file_relativePath=FMO2.txt, timestamp=1582106812961}] 2020-02-19
  10:06:52.962 DEBUG 233 --- [ask-scheduler-1]
  o.s.integration.channel.DirectChannel    : preSend on channel
  'taskLaunchRequestChannel',

When I launch the SCDF sample in documentation with the ingestFile, we have the same problem.

Do you have an idea?


问:
Javascript not working on mobile (Android) but fine on desktop
I've searched the archives but not found anything specific to my query.

In JavaScript I have a function with a callback function that fires a request at a postcode API to get coordinates for a postcode.

```<code>const getPostCodeLatLng = (strPostCode, callback) => {
    alert("used API"); // !!! DOESN'T ALERT ON MOBILE !!!
    const request = new XMLHttpRequest();
    request.addEventListener('readystatechange', () => {
        if(request.readyState == 4){
            const jsnPostCode=JSON.parse(request.responseText);
            callback(jsnPostCode);}});
    request.open('GET', 'http://api.getthedata.com/postcode/' + strPostCode);
    request.send();
};
</code>```

and

```<code>getPostCodeLatLng(strInputFieldValue, (jsnPostCode) => { // use the function to get data about the postcode and callback to this function
            if(jsnPostCode.status=="match"){
                alert("used API"); // !!! DOESN'T ALERT ON MOBILE !!!
                let strPostCodeLatLng = "LatLng(" + jsnPostCode.data.latitude + ", "
                + jsnPostCode.data.longitude + ")";
                setFieldswithLatLng(strPostCodeLatLng);
                objDisplayFindCons.value=`Postcode: ${strInputFieldValue}`;}
            else objDisplayFindCons.value=`No match found for Postcode: ${strInputFieldValue}`;})
</code>```

The functions work fine on a desktop but didn't work on either a Samsung phone nor tablet. I'm using Chrome on all devices.

The second section of code is part of a larger section that responds to an event where data is entered into a text box, validated as a possible postcode (using regex) and then requested as per the first function. The JSON text response is then parsed and checked to see if a match was found (the server returns valid JSON for unfound postcodes).

I am clear that it all works fine until it encounters the function call getPostCodeLatLng() where it never runs either of the  alert("used API") statements on mobile.

I am new to JavaScript and finding coding callback functions and events challenging but I can't see any obvious bugs/reasons for this to fail on mobiles.

Are there known problems or limitations to what I'm doing?

Is there a way to workaround this or debug it effectively on mobile?

Please help!

Thanks,

Phil

答:
So I tried various things and found the issue to be with using a http request.

Apparently from now on all requests from a Chrome browser on Android need to be https.

So changing request.open('GET', 'http://api.getthedata.com/postcode/' + strPostCode);
to request.open('GET', 'https://api.getthedata.com/postcode/' + strPostCode); fixed the problem straightaway.

Here is an article mentioning the change:-

https://www.thesslstore.com/blog/https-will-now-be-the-default-for-all-android-p-apps/

You live and learn...

Body:
I've searched the archives but not found anything specific to my query.

In JavaScript I have a function with a callback function that fires a request at a postcode API to get coordinates for a postcode.

const getPostCodeLatLng = (strPostCode, callback) => {
    alert("used API"); // !!! DOESN'T ALERT ON MOBILE !!!
    const request = new XMLHttpRequest();
    request.addEventListener('readystatechange', () => {
        if(request.readyState == 4){
            const jsnPostCode=JSON.parse(request.responseText);
            callback(jsnPostCode);}});
    request.open('GET', 'http://api.getthedata.com/postcode/' + strPostCode);
    request.send();
};

and

getPostCodeLatLng(strInputFieldValue, (jsnPostCode) => { // use the function to get data about the postcode and callback to this function
            if(jsnPostCode.status=="match"){
                alert("used API"); // !!! DOESN'T ALERT ON MOBILE !!!
                let strPostCodeLatLng = "LatLng(" + jsnPostCode.data.latitude + ", "
                + jsnPostCode.data.longitude + ")";
                setFieldswithLatLng(strPostCodeLatLng);
                objDisplayFindCons.value=`Postcode: ${strInputFieldValue}`;}
            else objDisplayFindCons.value=`No match found for Postcode: ${strInputFieldValue}`;})

The functions work fine on a desktop but didn't work on either a Samsung phone nor tablet. I'm using Chrome on all devices.

The second section of code is part of a larger section that responds to an event where data is entered into a text box, validated as a possible postcode (using regex) and then requested as per the first function. The JSON text response is then parsed and checked to see if a match was found (the server returns valid JSON for unfound postcodes).

I am clear that it all works fine until it encounters the function call getPostCodeLatLng() where it never runs either of the  alert("used API") statements on mobile.

I am new to JavaScript and finding coding callback functions and events challenging but I can't see any obvious bugs/reasons for this to fail on mobiles.

Are there known problems or limitations to what I'm doing?

Is there a way to workaround this or debug it effectively on mobile?

Please help!

Thanks,

Phil


问:
how to split a string value that contains characters and numbers
I have a std::string s=n8Name4Surname. How can I obtain in 2 strings the Name and the Surname? THX

答:
Mandatory Boost Spirit sample:</p>

```<code>#include <string>
#include <boost/spirit/include/qi.hpp>
#include <iostream>

int main()
{
    std::string s= "n8Name4Surname";

    std::string::const_iterator b(s.begin()), e(s.end());
    std::string ignore, name, surname;

    using namespace boost::spirit::qi;
    rule<std::string::const_iterator, space_type, char()>
        digit = char_("0123456789"),
        other = (char_ - digit);

    if (phrase_parse(b, e, *other >> +digit >> +other >> +digit >> +other, space, ignore, ignore, name, ignore, surname))
    {
        std::cout << "name = " << name << std::endl;
        std::cout << "surname = " << surname << std::endl;
    }

    return 0;
}
</code>```

Body:
Mandatory Boost Spirit sample:

#include <string>
#include <boost/spirit/include/qi.hpp>
#include <iostream>

int main()
{
    std::string s= "n8Name4Surname";

    std::string::const_iterator b(s.begin()), e(s.end());
    std::string ignore, name, surname;

    using namespace boost::spirit::qi;
    rule<std::string::const_iterator, space_type, char()>
        digit = char_("0123456789"),
        other = (char_ - digit);

    if (phrase_parse(b, e, *other >> +digit >> +other >> +digit >> +other, space, ignore, ignore, name, ignore, surname))
    {
        std::cout << "name = " << name << std::endl;
        std::cout << "surname = " << surname << std::endl;
    }

    return 0;
}