问:
Hyperledger fabric 2.2v - Adding HSM to an existing network/application
This is a pre-implementation question.

We have a working fabric(2.2) application with an org containing 2 peers, an intermediate CA with TLS enabled and are now planning to implement HSM to store org related private keys. I read from official doc and other articles that to use HSM we need to have PKCS11 enabled docker centOS images and the setup requires a complete rebuild of the binaries and network.

Can we setup HSM w/o disturbing the existing network?

Does peer's couchDB container requires to be reconfigured as well if the answer for Q1 is "yes"?

How do we transfer the available private keys from local MSP keystore to HSM slots?

What are the points to take care while implementing HSM along with TLS/TLS enable existing keys?

Do we have a ready script for this operation in any samples (I did not find it so far)?

(removed point 6 and rearranged)

I have seen very few people talking about implementing HSM with HLF, is there any major issue of usage.

Also please do provide a "take care" points before starting this operation.

答:
Yes, if you have enough peers or orderers running. You will need to restart the peer or order to use HSM one-by-one after setting the environment variable or the yaml file (Or even rebuild the binary with PKCS11). Since you do it one-by-one, other nodes that are running will keep the network alive.

Nope.

Depends on the HSM provider. They will provide you a binary to do that either by GUI or command line, which usually import pkcs12 (cert, public and private key). After import into the HSM, you may remove the private keys from MSP keystore as the Orderer and Peer binary will use the HSM for private key operation. (Of course you should backup them somewhere else)

Key for TLS server or client has to be stored locally. HSM is not supported for TLS yet.

No.

I assume this is same question as number 3

Ya, there exist some issues like the Java Chaincode does not have HSM support and you will need to write the PKCS11 implementation yourself and override the cryptoPrimitive.java.


来源: stackexchange

问:
Need help with Entity Framework Relationshipships
I'm new to Entity Framework and just experimenting...

Consider 3 db tables where Person is a base table. I want the Employe table to enherit from Person, storing employee specific info. It seems that EF requires that PersonId also be the PK of the Employee table, so I made EmployeeID a unique index.

Next I added a table, Application, which stores one record for every software application that the Employee supports, creating a foreign key from Application.EmployeeId to Employee.EmployeeId.

However, EF doesn't seem to recognize relationships that involve unique indexes, but only Primary Keys.

What I can do is create a relationship from Application.PersonId to Person.PersonId, however, only Employees can be responsible for an Application, so it seems more natural to me to have Application as a "child" of the Employee table rather than the Person table.

Is this possible in EF?

答: You can build your relation between Employee (PersonId) and Application (EmployeeId). In such case the integrity should work as you expect because only PersonIds in Employee table will be only for existing employees. EF has currently no support for unique keys.

ContentLicense: CC BY-SA 3.0


问:
VSCode prettier adds `value` to imports in TypeScript React
After configuring prettier with the plugin in VSCode the format on save function adds weird value keywords to every non-default import in my React+TS code.

Like this:

```<code>import { value ApolloProvider } from '@apollo/client';
import { value BrowserRouter as Router, value Switch } from 'react-router-dom';
import Routes from './routes';
import { value client } from './data/apollo-config';
</code>```

With this TS complains about Duplicate identifier 'value'.ts(2300)

Could anyone help me with this? Not sure why this is happening and how to solve it. Running npx prettier --write someFile doesn't add the value keywords.

My package.json:

```<code>    "dependencies": {
        "@apollo/client": "^3.3.6",
        "axios": "^0.21.1",
        "graphql": "^15.4.0",
        "react": "^17.0.1",
        "react-dom": "^17.0.1",
        "react-router-dom": "^5.1.2",
        "react-scripts": "^4.0.0"
    },
    "devDependencies": {
        "prettier": "^2.1.2",
        "eslint-config-prettier": "^8.3.0",
        "eslint-plugin-cypress": "^2.11.2",
        "eslint-plugin-prettier": "^3.1.4",
        "@types/jest": "^26.0.15",
        "@types/lodash.merge": "^4.6.6",
        "@types/node": "^14.14.6",
        "@types/react": "^16.9.55",
        "@types/react-dom": "^16.9.5",
        "@types/react-router-dom": "^5.1.3",
        "cypress": "^6.4.0",
        "http-proxy-middleware": "^1.0.3",
        "lodash.merge": "^4.6.2",
        "start-server-and-test": "^1.11.7",
        "typescript": "^4.5.4"
    },
</code>```

tsconfig.json

```<code>{
  "compilerOptions": {
    "baseUrl": ".",
    "target": "es5",
    "lib": [
      "es6",
      "dom"
    ],
    "allowJs": true,
    "rootDir": "src",
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "sourceMap": true,
    "declaration": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitAny": false
  },
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "node_modules",
    "build"
  ],
  "typeRoots": [
    "./node_modules/@types"
  ],
  "types": [
    "react",
    "react-dom",
    "react-dom-router",
    "jest",
    "node"
  ]
}
</code>```

eslintrc.js

```<code>{
    "parser": "@typescript-eslint/parser", // Specifies the ESLint parser
    "extends": [
        "react-app",
        "plugin:react/recommended", // Uses the recommended rules from @eslint-plugin-react
        "plugin:@typescript-eslint/recommended", // Uses the recommended rules from @typescript-eslint/eslint-plugin+   'prettier/@typescript-eslint',  // Uses eslint-config-prettier to disable ESLint rules from @typescript-eslint/eslint-plugin that would conflict with prettier
        "plugin:prettier/recommended" // Enables eslint-plugin-prettier and displays prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array.
    ],
    "plugins": ["react", "@typescript-eslint", "jest", "cypress"],
    "env": {
        "browser": true,
        "es6": true,
        "jest": true
    },
    "parserOptions": {
        "ecmaVersion": 2018, // Allows for the parsing of modern ECMAScript features
        "sourceType": "module", // Allows for the use of imports
        "ecmaFeatures": {
            "jsx": true // Allows for the parsing of JSX
        }
    },
    "rules": {
        "no-unused-vars": "off",
        "@typescript-eslint/no-unused-vars": "off",
        "@typescript-eslint/explicit-module-boundary-types": "off",
        "@typescript-eslint/no-redeclare": "off",
        "@typescript-eslint/explicit-function-return-type": "off",
        "@typescript-eslint/triple-slash-reference": "off"
    },
    "settings": {
        "react": {
            "version": "detect" // Tells eslint-plugin-react to automatically detect the version of React to use
        }
    }
}
</code>```

答:
I noticed TS 4.5.x in the dependencies. Things like this have been happening with versions of other libraries (e.g. prettier) that don't properly account for this TS change:

```<code>// < 4.5.0
import type { ThingType } from 'mylib';
import { Thing2 } from 'mylib';

// >= 4.5.0
import { type ThingType, Thing2 } from 'mylib';
</code>```

The reason a restart is working for many people is that VSCode may keep a process alive from prior to an update. The process is killed when it closes, then, provided that compatible versions of prettier and ts are installed, it will work on restart. If it's still not working, you'll either have to upgrade prettier or downgrade TS until you can get a working set of dependencies cobbled together.

ContentLicense: CC BY-SA 4.0

Body:
After configuring prettier with the plugin in VSCode the format on save function adds weird value keywords to every non-default import in my React+TS code.

Like this:

import { value ApolloProvider } from '@apollo/client';
import { value BrowserRouter as Router, value Switch } from 'react-router-dom';
import Routes from './routes';
import { value client } from './data/apollo-config';

With this TS complains about Duplicate identifier 'value'.ts(2300)

Could anyone help me with this? Not sure why this is happening and how to solve it. Running npx prettier --write someFile doesn't add the value keywords.

My package.json:

    "dependencies": {
        "@apollo/client": "^3.3.6",
        "axios": "^0.21.1",
        "graphql": "^15.4.0",
        "react": "^17.0.1",
        "react-dom": "^17.0.1",
        "react-router-dom": "^5.1.2",
        "react-scripts": "^4.0.0"
    },
    "devDependencies": {
        "prettier": "^2.1.2",
        "eslint-config-prettier": "^8.3.0",
        "eslint-plugin-cypress": "^2.11.2",
        "eslint-plugin-prettier": "^3.1.4",
        "@types/jest": "^26.0.15",
        "@types/lodash.merge": "^4.6.6",
        "@types/node": "^14.14.6",
        "@types/react": "^16.9.55",
        "@types/react-dom": "^16.9.5",
        "@types/react-router-dom": "^5.1.3",
        "cypress": "^6.4.0",
        "http-proxy-middleware": "^1.0.3",
        "lodash.merge": "^4.6.2",
        "start-server-and-test": "^1.11.7",
        "typescript": "^4.5.4"
    },

tsconfig.json

{
  "compilerOptions": {
    "baseUrl": ".",
    "target": "es5",
    "lib": [
      "es6",
      "dom"
    ],
    "allowJs": true,
    "rootDir": "src",
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "sourceMap": true,
    "declaration": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitAny": false
  },
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "node_modules",
    "build"
  ],
  "typeRoots": [
    "./node_modules/@types"
  ],
  "types": [
    "react",
    "react-dom",
    "react-dom-router",
    "jest",
    "node"
  ]
}

eslintrc.js

{
    "parser": "@typescript-eslint/parser", // Specifies the ESLint parser
    "extends": [
        "react-app",
        "plugin:react/recommended", // Uses the recommended rules from @eslint-plugin-react
        "plugin:@typescript-eslint/recommended", // Uses the recommended rules from @typescript-eslint/eslint-plugin+   'prettier/@typescript-eslint',  // Uses eslint-config-prettier to disable ESLint rules from @typescript-eslint/eslint-plugin that would conflict with prettier
        "plugin:prettier/recommended" // Enables eslint-plugin-prettier and displays prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array.
    ],
    "plugins": ["react", "@typescript-eslint", "jest", "cypress"],
    "env": {
        "browser": true,
        "es6": true,
        "jest": true
    },
    "parserOptions": {
        "ecmaVersion": 2018, // Allows for the parsing of modern ECMAScript features
        "sourceType": "module", // Allows for the use of imports
        "ecmaFeatures": {
            "jsx": true // Allows for the parsing of JSX
        }
    },
    "rules": {
        "no-unused-vars": "off",
        "@typescript-eslint/no-unused-vars": "off",
        "@typescript-eslint/explicit-module-boundary-types": "off",
        "@typescript-eslint/no-redeclare": "off",
        "@typescript-eslint/explicit-function-return-type": "off",
        "@typescript-eslint/triple-slash-reference": "off"
    },
    "settings": {
        "react": {
            "version": "detect" // Tells eslint-plugin-react to automatically detect the version of React to use
        }
    }
}

Body:
I noticed TS 4.5.x in the dependencies. Things like this have been happening with versions of other libraries (e.g. prettier) that don't properly account for this TS change:

// < 4.5.0
import type { ThingType } from 'mylib';
import { Thing2 } from 'mylib';

// >= 4.5.0
import { type ThingType, Thing2 } from 'mylib';

The reason a restart is working for many people is that VSCode may keep a process alive from prior to an update. The process is killed when it closes, then, provided that compatible versions of prettier and ts are installed, it will work on restart. If it's still not working, you'll either have to upgrade prettier or downgrade TS until you can get a working set of dependencies cobbled together.


问:
DotNetNuke schedules running on a webfarm causing blocking
I have a website running on DotNetNuke v09.02.02 on a webfarm of 3 servers and I have a problem with the PurgeScheduleHistory.

The PurgeScheduleHistory runs once a day, but it's running at the same time from each of the servers and I frequently see dead locks because each server is trying to do the same operation.

I know the procedure can be optimized but I believe I could still see the same problem of each server picking up the Schedule History and deleting it as another server is trying to do the same.

Does DotNetNuke have a setting or ability to only run the schedules from a specified server and not others?

Has anyone else experience of running DotNetNuke on a webfarm?

答:
Yes, if you navigate to the scheduler configuration there is a "Run on Server(s)" setting, by default it is blank, you can and should, update that to list the name of a single server in your environment.

You should do this for any of the services that do not need to run on all servers, I don't have an exhaustive list at the moment but items to consider

Purge Schedule History

Search Index/Crawler

Message Dispatch

Basically anything that is DB driven should be done on a single server in this manner.


问:
How to use fizzler external lib under Monodevelop
I got a compile error using Fizzler lib (http://code.google.com/p/fizzler/) in Monodevelop IDE under Ubuntu 10.
I added .Net Assembly References and autocompletion works file, but error during the compilation occurred.

Code here:

```

    using System;
    using Fizzler.Systems.HtmlAgilityPack;
    using HtmlAgilityPack;
    using System.Collections.Generic;

    namespace test
    {
        class MainClass
        {
            public static void Main (string[] args)
            {
                HtmlAgilityPack.HtmlDocument html = new HtmlAgilityPack.HtmlDocument();
                html.LoadHtml(@"some html");
                HtmlAgilityPack.HtmlNode document = html.DocumentNode;

                document.QuerySelector("a");

            }
        }
    }

```

Error CS1061: Type HtmlAgilityPack.HtmlNode' does not contain a definition forQuerySelector' and no extension method QuerySelector' of typeHtmlAgilityPack.HtmlNode' could be found (are you missing a using directive or an assembly reference?) (CS1061) (test)

答: Are your HtmlAgilityPack.HtmlNode has that definition provided? Check again the API documentation. Please the error is clear by itself.</p>

Body:
I got a compile error using Fizzler lib (http://code.google.com/p/fizzler/) in Monodevelop IDE under Ubuntu 10.
I added .Net Assembly References and autocompletion works file, but error during the compilation occurred.

Code here:

    using System;
    using Fizzler.Systems.HtmlAgilityPack;
    using HtmlAgilityPack;
    using System.Collections.Generic;

    namespace test
    {
        class MainClass
        {
            public static void Main (string[] args)
            {
                HtmlAgilityPack.HtmlDocument html = new HtmlAgilityPack.HtmlDocument();
                html.LoadHtml(@"some html");
                HtmlAgilityPack.HtmlNode document = html.DocumentNode;

                document.QuerySelector("a");

            }
        }
    }

Error CS1061: Type HtmlAgilityPack.HtmlNode' does not contain a definition forQuerySelector' and no extension method QuerySelector' of typeHtmlAgilityPack.HtmlNode' could be found (are you missing a using directive or an assembly reference?) (CS1061) (test)


问:
How to notify Composition if a public property of Stable type changes?
As stated in the Jetpack compose documentation, a stable type must comply with the following contract.

The result of equals for two instances will forever be the same for
the same two instances.

If a public property of the type changes, Composition will be notified.

All public property types are also
stable.

The first and third contracts are straightforward. How can I comply with the second point?

For example, I have a stable type called User

```<code>data class User(val username: String, var email: String)
</code>```

and I change the email during the flow of the app, how can I notify the Composition?

答:
Compose has a special State type that allows you to notify when a recomposition is needed. This is the most common way to initiate a recomposition.

The data class is a good tool that will give you copy for all fields out of the box, but you should avoid using var and use only val for your fields to avoid mistakes.

So, a basic example of updating a field would look like this:

```<code>var state by remember { mutableStateOf(User(username = "", email = "")) }
TextField(
    value = state.username,
    onValueChange = {
        state = state.copy(username = it)
    }
)
</code>```

You can use Flow/LiveData in the same way, since they can be collected in State with collectAsState/observeAsState.

More info can be found in Compose documentation, including this youtube video which explains the basic principles.

Body:
As stated in the Jetpack compose documentation, a stable type must comply with the following contract.

The result of equals for two instances will forever be the same for
the same two instances.

If a public property of the type changes, Composition will be notified.

All public property types are also
stable.

The first and third contracts are straightforward. How can I comply with the second point?

For example, I have a stable type called User

data class User(val username: String, var email: String)

and I change the email during the flow of the app, how can I notify the Composition?

Body:
Compose has a special State type that allows you to notify when a recomposition is needed. This is the most common way to initiate a recomposition.

The data class is a good tool that will give you copy for all fields out of the box, but you should avoid using var and use only val for your fields to avoid mistakes.

So, a basic example of updating a field would look like this:

var state by remember { mutableStateOf(User(username = "", email = "")) }
TextField(
    value = state.username,
    onValueChange = {
        state = state.copy(username = it)
    }
)

You can use Flow/LiveData in the same way, since they can be collected in State with collectAsState/observeAsState.

More info can be found in Compose documentation, including this youtube video which explains the basic principles.


问:
When I define a float input function, and call it, why is the input NoneType?
Here is an example of my code:

```<code>def total():
 float(input("Type a number: "))

var1 = total()
var2 = total()
#etc.

decimal = 4.5783

list = [var1,var2,#etc]
for n in list:
 n += bob
</code>```

After I write this code, I assign the variables to a list. I then add each thing in the list by decimal. However, when I run it, it is saying that I can't add floats to nonetypes. How would I fix this? Do I need to change something in the list?

答: Without a return, the function will never provide a value that you can then assign to another variable. A function is a machine that does something to input, and returns an output</p>

Body:
Here is an example of my code:

def total():
 float(input("Type a number: "))

var1 = total()
var2 = total()
#etc.

decimal = 4.5783

list = [var1,var2,#etc]
for n in list:
 n += bob

After I write this code, I assign the variables to a list. I then add each thing in the list by decimal. However, when I run it, it is saying that I can't add floats to nonetypes. How would I fix this? Do I need to change something in the list?


问:
How to convert binary to hexadecimal using python3
which is the easiest way that i can convert binary number into a hexadecimal number using latest python3?

i tried to convert a binary to number into a hexadecimal using hex() function. but it runs into few errors.

The code that i tried -:

```<code>choice = input("Enter Your Binary Number: ")

def binaryToHex(num):
    answer = hex(num)
    return(num)

print(binaryToHex(choice))
</code>```

error that i faced :

```<code>Traceback (most recent call last):
  File "e:\#Programming\Python\Number System Converter 0.1V\test.py", line 83, in <module>
    print(binaryToHex(choice))
  File "e:\#Programming\Python\Number System Converter 0.1V\test.py", line 80, in binaryToHex
    answer = hex(num)
TypeError: 'str' object cannot be interpreted as an integer
</code>```

EXAMPLE-:

111 --> 7

1010101011 --> 2AB

答:
You may use the Hex inbuilt function of Python 3. you can use this code too.

binary_string = input("enter binary number: ")

decimal_representation = int(binary_string, 2)
hexadecimal_string = hex(decimal_representation)

print("your hexadecimal string is: ",hexadecimal_string)

Body:
which is the easiest way that i can convert binary number into a hexadecimal number using latest python3?

i tried to convert a binary to number into a hexadecimal using hex() function. but it runs into few errors.

The code that i tried -:

choice = input("Enter Your Binary Number: ")

def binaryToHex(num):
    answer = hex(num)
    return(num)

print(binaryToHex(choice))

error that i faced :

Traceback (most recent call last):
  File "e:\#Programming\Python\Number System Converter 0.1V\test.py", line 83, in <module>
    print(binaryToHex(choice))
  File "e:\#Programming\Python\Number System Converter 0.1V\test.py", line 80, in binaryToHex
    answer = hex(num)
TypeError: 'str' object cannot be interpreted as an integer

EXAMPLE-:

111 --> 7

1010101011 --> 2AB


问:
list.append faster than np.append?
Execute these lines :

```<code>import numpy as np
import time

start = time.time()

t = []
for i in range(int(1e5)):
   t.append(i)

t = np.array(t)

end = time.time()
print(end-start)
</code>```

And compare with these :

```<code>import numpy as np
import time

start = time.time()

t = np.array([])
for i in range(int(1e5)):
    t = np.append(t,[i])

end = time.time()
print(end-start)
</code>```

The first is faster than the second by approximatively a factor 100 !

What is the reason ?

答:
According to this article.

Speed test

He appends 99 999 numbers using both Python list append() and NumPy append(). Results:

```<code>The computation time of the NumPy array: 2.779465675354004
The computation time of the list: 0.010703325271606445
</code>```

Explanation for longer runtime of NumPy:

With NumPy.

Appending process does not occur in the same array. Rather a new array is created and filled.

With Python.

Things are very different. The list filling process stays within the list itself, and no new lists are generated.

Title: list.append faster than np.append?

Body:
Execute these lines :

import numpy as np
import time

start = time.time()

t = []
for i in range(int(1e5)):
   t.append(i)

t = np.array(t)

end = time.time()
print(end-start)

And compare with these :

import numpy as np
import time

start = time.time()

t = np.array([])
for i in range(int(1e5)):
    t = np.append(t,[i])

end = time.time()
print(end-start)

The first is faster than the second by approximatively a factor 100 !

What is the reason ?

Body:
According to this article.

Speed test

He appends 99 999 numbers using both Python list append() and NumPy append(). Results:

The computation time of the NumPy array: 2.779465675354004
The computation time of the list: 0.010703325271606445

Explanation for longer runtime of NumPy:

With NumPy.

Appending process does not occur in the same array. Rather a new array is created and filled.

With Python.

Things are very different. The list filling process stays within the list itself, and no new lists are generated.


问:
Git - some commit go production first, how to manage dev/stg/master branch
Good day,

I have 3 environment: dev/stg/master, I usually develop on dev branch, customer usually request some feature, and I create feature branch from dev to develop. After developed, I merge to dev and stg.

Someday, after I did 5 same things, there are 5 feature on dev/stg, lets named feature A, B, C, D, E. Customer asked me to release feature C & D to master, I used to cherry-pick to master. The reason was there are some bug had be discovered on stg, so I did some fix commit on stg (also cherry-pick back to dev).

But A, B, E still on stg and dev some month, I think they already forgot these feature or no longer nesssary, but I still develop new features that customer requested.

These three branch code is more and more different since project beginning.

Is any suggestion or existing flow can help this situation?

答:
The best way is to develop each feature in isolation in a separate "feature" branch. Then you can choose which features have to be merged into the "release" branch. The key here is to keep "feature" branches up-to-date with branch the were started from.

This is a pretty standard workflow named "Feature Branch Flow"
More detailed explanation at https://www.atlassian.com/git/tutorials/comparing-workflows/feature-branch-workflow

There are several other workflows you can find useful there. "Git Flow" is one of the most popular ones.


问:
first search algorithm
I need to use the first search algorithm

Can anyone assist me in regards how I use first search algorithm?

Thanks in advance

答:
To get the answer given by @J013R, you can use the following program:

```<code>dfs_traversal(Root) :-
   format('Open    Closed        Visited\n'),
   dfs_traversal([Root], [], -).

dfs_traversal(Open, Closed, Visited) :-
   format('~|~w~t~7+ ~|~w~t~13+ ~w\n', [Open, Closed, Visited]),
   (   Open = [Node|Rest]
   ->  findall(Successor, successor(Node, Open, Closed, Successor), Successors),
       append(Successors, Rest, NewOpen),
       dfs_traversal(NewOpen, [Node|Closed], Node)
   ;   true ).

successor(Node, Open, Closed, Successor) :-
   arc(Node, Successor),
   not(member(Successor, Open)),
   not(member(Successor, Closed)).

arc(a, f).
arc(a, g).
arc(c, a).
arc(c, d).
arc(d, c).
arc(d, f).
arc(e, c).
arc(e, d).
arc(e, g).
arc(f, e).
</code>```

Example:

```<code>?- dfs_traversal(a)
Open    Closed        Visited
[a]     []            -
[f,g]   [a]           a
[e,g]   [f,a]         f
[c,d,g] [e,f,a]       e
[d,g]   [c,e,f,a]     c
[g]     [d,c,e,f,a]   d
[]      [g,d,c,e,f,a] g
true.
</code>```

Title: first search algorithm

Body:
To get the answer given by @J013R, you can use the following program:

dfs_traversal(Root) :-
   format('Open    Closed        Visited\n'),
   dfs_traversal([Root], [], -).

dfs_traversal(Open, Closed, Visited) :-
   format('~|~w~t~7+ ~|~w~t~13+ ~w\n', [Open, Closed, Visited]),
   (   Open = [Node|Rest]
   ->  findall(Successor, successor(Node, Open, Closed, Successor), Successors),
       append(Successors, Rest, NewOpen),
       dfs_traversal(NewOpen, [Node|Closed], Node)
   ;   true ).

successor(Node, Open, Closed, Successor) :-
   arc(Node, Successor),
   not(member(Successor, Open)),
   not(member(Successor, Closed)).

arc(a, f).
arc(a, g).
arc(c, a).
arc(c, d).
arc(d, c).
arc(d, f).
arc(e, c).
arc(e, d).
arc(e, g).
arc(f, e).

Example:

?- dfs_traversal(a)
Open    Closed        Visited
[a]     []            -
[f,g]   [a]           a
[e,g]   [f,a]         f
[c,d,g] [e,f,a]       e
[d,g]   [c,e,f,a]     c
[g]     [d,c,e,f,a]   d
[]      [g,d,c,e,f,a] g
true.


问:
Django test django.db.utils.ProgrammingError: (1146, "Table 'DB.Table' doesn't exist")
I'm running a simple test case in Django, I have a model Subscribers but when I run python manage.py test
It gives me the following error

```<code>Creating test database for alias 'default'...
System check identified no issues (0 silenced).
E
======================================================================
ERROR: test_subscriber_fullname
(gatpulsecore.tests.test_models.SubscribersTest)
Test method get_fullname
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\dania\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\dania\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\mysql\base.py", line 71, in execute
    return self.cursor.execute(query, args)
  File "C:\Users\dania\AppData\Local\Programs\Python\Python36\lib\site-packages\pymysql\cursors.py", line 170, in execute
    result = self._query(query)
  File "C:\Users\dania\AppData\Local\Programs\Python\Python36\lib\site-packages\pymysql\cursors.py", line 328, in _query
    conn.query(q)
  File "C:\Users\dania\AppData\Local\Programs\Python\Python36\lib\site-packages\pymysql\connections.py", line 516, in query
    self._affected_rows = self._read_query_result(unbuffered=unbuffered)
  File "C:\Users\dania\AppData\Local\Programs\Python\Python36\lib\site-packages\pymysql\connections.py", line 727, in _read_query_result
    result.read()
  File "C:\Users\dania\AppData\Local\Programs\Python\Python36\lib\site-packages\pymysql\connections.py", line 1066, in read
    first_packet = self.connection._read_packet()
  File "C:\Users\dania\AppData\Local\Programs\Python\Python36\lib\site-packages\pymysql\connections.py", line 683, in _read_packet
    packet.check_error()
  File "C:\Users\dania\AppData\Local\Programs\Python\Python36\lib\site-packages\pymysql\protocol.py", line 220, in check_error
    err.raise_mysql_exception(self._data)
  File "C:\Users\dania\AppData\Local\Programs\Python\Python36\lib\site-packages\pymysql\err.py", line 109, in raise_mysql_exception
    raise errorclass(errno, errval)
pymysql.err.ProgrammingError: (1146, "Table 'test_gatpulsedevinstance.subscribers' doesn't exist")
</code>```

My model looks like this

```<code>from django.db import models

class Subscribers(models.Model):
    """ Subscriber Model """
    idsubscribers = models.AutoField(primary_key=True)
    legalid = models.CharField(max_length=45, blank=True, null=True)
    name = models.CharField(max_length=45, blank=True, null=True)
    lastname = models.CharField(max_length=45, blank=True, null=True)
    initialdate = models.DateField(blank=True, null=True)
    bday = models.DateField(blank=True, null=True)
    email = models.CharField(max_length=100, blank=True, null=True)
    phone = models.CharField(max_length=45, blank=True, null=True)
    emergencyphone = models.CharField(max_length=45, blank=True, null=True)
    photolink = models.CharField(max_length=200, blank=True, null=True)
    medicalconditions = models.CharField(max_length=200, blank=True, null=True)
    objectives = models.CharField(max_length=200, blank=True, null=True)
    paymentfrequency = models.CharField(max_length=45, blank=True, null=True)

    def get_fullname(self):
        return self.name + " " + self.lastname
    class Meta:
        managed = False
        db_table = 'subscribers'
</code>```

And my test file

```<code>from django.test import TransactionTestCase
from gatpulsecore.models import Subscribers

class SubscribersTest(TransactionTestCase):
    """ Test module for Subscribers model """

    def setUp(self):
        Subscribers.objects.create(
            legalid='34214555', name='Casper', lastname='Smith')
        Subscribers.objects.create(
            legalid='24612555', name='John', lastname='Rogers')

    def test_subscriber_fullname(self):
        """ Test method get_fullname """
        sub_casper = Subscribers.objects.get(name='Casper')
        sub_john = Subscribers.objects.get(name='John')
        self.assertEqual(
            sub_casper.get_fullname(), "Casper Smith")
        self.assertEqual(
            sub_john.get_fullname(), "John Rogers")
</code>```

I already tried migrating but it didn't help, also someone recommended to TransactionTestCase instead of TestCase but it didn't work either.
Does anybody has encountered with the same error? I've been searching for a workaround but I don't seem to find anything helpful.

答:
Once try explicitly specifying the test database name in settings.py, e.g.,

```<code>DATABASES = {
    'default': {
        ...
        'TEST': {
            # Avoid naming it the same as your original database name.
            # Otherwise, it will be used while testing (and even may get deleted).
            'NAME': 'name_of_your_choice',
        },
    },
    ...
}
</code>```

If you are using multiple databases, you may need to do it for all of them.

Body:
I'm running a simple test case in Django, I have a model Subscribers but when I run python manage.py test
It gives me the following error

Creating test database for alias 'default'...
System check identified no issues (0 silenced).
E
======================================================================
ERROR: test_subscriber_fullname
(gatpulsecore.tests.test_models.SubscribersTest)
Test method get_fullname
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\dania\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\dania\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\mysql\base.py", line 71, in execute
    return self.cursor.execute(query, args)
  File "C:\Users\dania\AppData\Local\Programs\Python\Python36\lib\site-packages\pymysql\cursors.py", line 170, in execute
    result = self._query(query)
  File "C:\Users\dania\AppData\Local\Programs\Python\Python36\lib\site-packages\pymysql\cursors.py", line 328, in _query
    conn.query(q)
  File "C:\Users\dania\AppData\Local\Programs\Python\Python36\lib\site-packages\pymysql\connections.py", line 516, in query
    self._affected_rows = self._read_query_result(unbuffered=unbuffered)
  File "C:\Users\dania\AppData\Local\Programs\Python\Python36\lib\site-packages\pymysql\connections.py", line 727, in _read_query_result
    result.read()
  File "C:\Users\dania\AppData\Local\Programs\Python\Python36\lib\site-packages\pymysql\connections.py", line 1066, in read
    first_packet = self.connection._read_packet()
  File "C:\Users\dania\AppData\Local\Programs\Python\Python36\lib\site-packages\pymysql\connections.py", line 683, in _read_packet
    packet.check_error()
  File "C:\Users\dania\AppData\Local\Programs\Python\Python36\lib\site-packages\pymysql\protocol.py", line 220, in check_error
    err.raise_mysql_exception(self._data)
  File "C:\Users\dania\AppData\Local\Programs\Python\Python36\lib\site-packages\pymysql\err.py", line 109, in raise_mysql_exception
    raise errorclass(errno, errval)
pymysql.err.ProgrammingError: (1146, "Table 'test_gatpulsedevinstance.subscribers' doesn't exist")

My model looks like this

from django.db import models

class Subscribers(models.Model):
    """ Subscriber Model """
    idsubscribers = models.AutoField(primary_key=True)
    legalid = models.CharField(max_length=45, blank=True, null=True)
    name = models.CharField(max_length=45, blank=True, null=True)
    lastname = models.CharField(max_length=45, blank=True, null=True)
    initialdate = models.DateField(blank=True, null=True)
    bday = models.DateField(blank=True, null=True)
    email = models.CharField(max_length=100, blank=True, null=True)
    phone = models.CharField(max_length=45, blank=True, null=True)
    emergencyphone = models.CharField(max_length=45, blank=True, null=True)
    photolink = models.CharField(max_length=200, blank=True, null=True)
    medicalconditions = models.CharField(max_length=200, blank=True, null=True)
    objectives = models.CharField(max_length=200, blank=True, null=True)
    paymentfrequency = models.CharField(max_length=45, blank=True, null=True)

    def get_fullname(self):
        return self.name + " " + self.lastname
    class Meta:
        managed = False
        db_table = 'subscribers'

And my test file

from django.test import TransactionTestCase
from gatpulsecore.models import Subscribers

class SubscribersTest(TransactionTestCase):
    """ Test module for Subscribers model """

    def setUp(self):
        Subscribers.objects.create(
            legalid='34214555', name='Casper', lastname='Smith')
        Subscribers.objects.create(
            legalid='24612555', name='John', lastname='Rogers')

    def test_subscriber_fullname(self):
        """ Test method get_fullname """
        sub_casper = Subscribers.objects.get(name='Casper')
        sub_john = Subscribers.objects.get(name='John')
        self.assertEqual(
            sub_casper.get_fullname(), "Casper Smith")
        self.assertEqual(
            sub_john.get_fullname(), "John Rogers")

I already tried migrating but it didn't help, also someone recommended to TransactionTestCase instead of TestCase but it didn't work either.
Does anybody has encountered with the same error? I've been searching for a workaround but I don't seem to find anything helpful.

Body:
Once try explicitly specifying the test database name in settings.py, e.g.,

DATABASES = {
    'default': {
        ...
        'TEST': {
            # Avoid naming it the same as your original database name.
            # Otherwise, it will be used while testing (and even may get deleted).
            'NAME': 'name_of_your_choice',
        },
    },
    ...
}

If you are using multiple databases, you may need to do it for all of them.


问:
How to use Azure Key Vault in SQL Server stored procedures
I would like to retrieve the password I saved in AKV and use it on my stored procedure. Is this possible?</p>

答:
You can use system-assigned managed identity for your Azure SQL server to access secrets in your Azure Key Vault

Enable System-Assigned managed identity for your Azure SQL server

Add access policy in your Azure Key vault for the Azure SQL server managed identity with GET permissions on secrets

Now, you can use System-Assigned identity on your Azure SQL server to retrieve Azure Key Vault secrets

To use managed identities to connect to your Azure SQL Database, you need to enable Azure Active Directory (AD) authentication and create the managed users in the database

Reference: How to Use Managed Identities with Azure SQL Database | Pluralsight


问:
creating new column based on condition (Python)
I have a dataframe where one of the columns, "deals" is a TRUE/FALSE boolean. I want to create a new column that populates 1 when the "deals" column is True, and 0 when the "deals" columns is False.

I tried the following code but it's giving me all zeros.

```<code>df['madedeal'] = np.where(df['deal']=='True', 1, 0)
</code>```

答:
You can simply use astype(int) which converts True to 1 and False to 0 (no need for np.where here):

```<code>df['madedeal'] = df['deal'].astype(int)
</code>```

Body:
I have a dataframe where one of the columns, "deals" is a TRUE/FALSE boolean. I want to create a new column that populates 1 when the "deals" column is True, and 0 when the "deals" columns is False.

I tried the following code but it's giving me all zeros.

df['madedeal'] = np.where(df['deal']=='True', 1, 0)

Body:
You can simply use astype(int) which converts True to 1 and False to 0 (no need for np.where here):

df['madedeal'] = df['deal'].astype(int)


问:
Count the number of object
I am using below code to print the obj.key, however I want to count the number of objects generated. Could you please help?

Code used:

```<code>for obj in buck.objects.filter(Prefix=recent_ocr_path):
 if obj.size > 0:  # Verifying presence of files
  print(obj.key)
</code>```

Output received using above command:

```<code>Profile_2022/02/08/16/cdd-kinesis-to-s3-prod-3-2022-02-08-16-00-00-4594cf63
Profile_2022/02/08/16/cdd-kinesis-to-s3-prod-3-2022-02-08-16-00-04-82b265de
Profile_2022/02/08/16/cdd-kinesis-to-s3-prod-3-2022-02-08-16-00-07-66179192
Profile_2022/02/08/16/cdd-kinesis-to-s3-prod-3-2022-02-08-16-00-11-713879f1
</code>```

I am looking for command to display output as "4".

答:
```<code>counter = 0
for obj in buck.objects.filter(Prefix=recent_ocr_path):
 if obj.size > 0:  # Verifying presence of files
  counter += 1
print(counter)
</code>```

Title: Count the number of object

Body:
I am using below code to print the obj.key, however I want to count the number of objects generated. Could you please help?

Code used:

for obj in buck.objects.filter(Prefix=recent_ocr_path):
 if obj.size > 0:  # Verifying presence of files
  print(obj.key)

Output received using above command:

Profile_2022/02/08/16/cdd-kinesis-to-s3-prod-3-2022-02-08-16-00-00-4594cf63
Profile_2022/02/08/16/cdd-kinesis-to-s3-prod-3-2022-02-08-16-00-04-82b265de
Profile_2022/02/08/16/cdd-kinesis-to-s3-prod-3-2022-02-08-16-00-07-66179192
Profile_2022/02/08/16/cdd-kinesis-to-s3-prod-3-2022-02-08-16-00-11-713879f1

I am looking for command to display output as "4".


问:
how to retain the localstorage session when refreshing page using typescript
```<code>  isLogin = false;
  isLogged = new Subject<boolean>();

  constructor(private _httlpClient: HttpClient) {}

  login(credential: any): any {
    this.isLogin = false;
    if (credential != '') {
      this.isLogin = true;
    }
    this.isLogged.next(this.isLogin);
    return this._httlpClient.post(this.url, credential);
  }

  <!--This is the function where i need to retain data-->
  setSession(token: string) {
    localStorage.setItem('authToken', token);
  }

  getSession() {
    return localStorage.getItem('authToken');
  }
}
</code>```

after i logged in the profile page should be remained displayed until i logout, but when i refresh the page the profile page is already missing.

答:
In ngOnInit(), check the session status and update the BehaviorSubject
accordingly.

```<code>import { HttpClient } from '@angular/common/http';
    import { Component, OnInit, VERSION } from '@angular/core';
    import { BehaviorSubject, Subject } from 'rxjs';

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

      isLogin = false;
      isLogged = new BehaviorSubject<boolean>(false);

      constructor(private _httlpClient: HttpClient) {}

      ngOnInit() {
        if (this.getSession() !== null) {
          this.isLogin = true;
        }
        this.isLogged.next(this.isLogin);
      }

      login(credential: any): any {
        this.isLogin = false;
        if (credential != '') {
          this.isLogin = true;
        }
        this.isLogged.next(this.isLogin);
        return this._httlpClient.post(this.url, credential);
      }

      // This is the function where i need to retain data
      setSession(token: string) {
        localStorage.setItem('authToken', token);
      }

      getSession() {
        return localStorage.getItem('authToken');
      }
    }
</code>```

code snippet

Body:
  isLogin = false;
  isLogged = new Subject<boolean>();

  constructor(private _httlpClient: HttpClient) {}

  login(credential: any): any {
    this.isLogin = false;
    if (credential != '') {
      this.isLogin = true;
    }
    this.isLogged.next(this.isLogin);
    return this._httlpClient.post(this.url, credential);
  }

  setSession(token: string) {
    localStorage.setItem('authToken', token);
  }

  getSession() {
    return localStorage.getItem('authToken');
  }
}

after i logged in the profile page should be remained displayed until i logout, but when i refresh the page the profile page is already missing.

Body:
In ngOnInit(), check the session status and update the BehaviorSubject
accordingly.

import { HttpClient } from '@angular/common/http';
    import { Component, OnInit, VERSION } from '@angular/core';
    import { BehaviorSubject, Subject } from 'rxjs';

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

      isLogin = false;
      isLogged = new BehaviorSubject<boolean>(false);

      constructor(private _httlpClient: HttpClient) {}

      ngOnInit() {
        if (this.getSession() !== null) {
          this.isLogin = true;
        }
        this.isLogged.next(this.isLogin);
      }

      login(credential: any): any {
        this.isLogin = false;
        if (credential != '') {
          this.isLogin = true;
        }
        this.isLogged.next(this.isLogin);
        return this._httlpClient.post(this.url, credential);
      }

      // This is the function where i need to retain data
      setSession(token: string) {
        localStorage.setItem('authToken', token);
      }

      getSession() {
        return localStorage.getItem('authToken');
      }
    }

code snippet


问:
CSS - Make a Sidebar Box Sticky
I'm using TailwindCSS in my project. My page looks like below:

```<code><main class="max-w-7xl mx-auto mt-6 px-4">
  <div class="flex flex-col md:space-x-12 justify-center md:flex-row">
    <div class="w-full md:w-9/12 mb-8">
      <h1 class="text-3xl font-bold mt-2 mb-4">Title</h1>
      <p class="mb-4 uppercase text-gray-500">META DATA</p>
      <div class="prose lg:prose-lg post">
        <p class="bg-gray-200 p-5 h-36 m-3"></p>
        <p class="bg-gray-200 p-5 h-36 m-3"></p>
        <p class="bg-gray-200 p-5 h-36 m-3"></p>
        <p class="bg-gray-200 p-5 h-36 m-3"></p>
        <p class="bg-gray-200 p-5 h-36 m-3"></p>
        <p class="bg-gray-200 p-5 h-36 m-3"></p>
        <p class="bg-gray-200 p-5 h-36 m-3"></p>
        <p class="bg-gray-200 p-5 h-36 m-3"></p>
      </div>
      <hr class="mt-5" />
    </div>
    <div class="w-full md:w-3/12">
      <div class="mb-5 mx-auto" style="max-width:300px">
        <div class="rounded rounded-lg border">
          <p class="bg-blue-100 p-5 h-12 m-3"></p>
          <p class="bg-blue-100 p-5 h-12 m-3"></p>
          <p class="bg-blue-100 p-5 h-12 m-3"></p>
          <p class="bg-blue-100 p-5 h-12 m-3"></p>
        </div>

        <div class="rounded rounded-lg border mt-10 sticky self-auto top-20">
          <div class="p-20">Make this box sticky</div>
        </div>
      </div>
    </div>
  </div>
</main>
</code>```

I want to make the bottom box in the right sidebar sticky but it's not happening. I've seen many threads and followed advice like make it flex-start, but it doesn't work in this layout. Can you please help?

You can see the playground here - https://play.tailwindcss.com/MaFc2vXQRe

答:
Add display: unset; on the parent div of sticky div check below code.

```<code><div class="mb-5 mx-auto" style="max-width:300px; display: unset;">
</code>```

Let me know if you have to face any issue

Title: CSS - Make a Sidebar Box Sticky

Body:
I'm using TailwindCSS in my project. My page looks like below:

Title

META DATA

Make this box sticky

I want to make the bottom box in the right sidebar sticky but it's not happening. I've seen many threads and followed advice like make it flex-start, but it doesn't work in this layout. Can you please help?

You can see the playground here - https://play.tailwindcss.com/MaFc2vXQRe

Body:
Add display: unset; on the parent div of sticky div check below code.

<div class="mb-5 mx-auto" style="max-width:300px; display: unset;">

Let me know if you have to face any issue


问:
Export Google BigQuery data to Python Pandas dataframe
I've been researching how to export BigQuery data into Pandas.
There are two methods:

Export the file to a CVS and load it - https://cloud.google.com/bigquery/exporting-data-from-bigquery

Directly pull the data into a pandas frame. This doesn't seem to work but here is the method - pandas.io.gbq.read_gbq(query, project_id=None, index_col=None, col_order=None, reauth=False) .
It appears gbq has been discontinued?

Could someone please suggest the best and most efficient way to go about this?

Thank you.

答:
You can use the google cloud library and store it to dataframe</p>
```<code>from google.cloud import bigquery
import os

#Your credentials to google cloud
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]=r"C:\YourPath\to\credentials.json"

# Construct a BigQuery client object.
client = bigquery.Client()

#Select Your table in BQ
query = """
    SELECT *
    FROM `bigquery-public-data.usa_names.usa_1910_2013`
"""
query_job = client.query(query)  # Make an API request

result = query_job.to_dataframe()  # Stores your query results to dataframe
</code>```

Body:
You can use the google cloud library and store it to dataframe

from google.cloud import bigquery
import os

#Your credentials to google cloud
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]=r"C:\YourPath\to\credentials.json"

# Construct a BigQuery client object.
client = bigquery.Client()

#Select Your table in BQ
query = """
    SELECT *
    FROM `bigquery-public-data.usa_names.usa_1910_2013`
"""
query_job = client.query(query)  # Make an API request

result = query_job.to_dataframe()  # Stores your query results to dataframe


问:
Private Network Access problem w/ disabled web security: Request had no target IP address space, yet the resource is in address space local
We have a test environment on a public site. There we use --disable-web-security flag on chrome for the testers to bypass CORS errors for public service calls during manual test phase. And also we have localhost requests on the agent machine. However today with Chrome 98 update we started struggling with the network requests targeting localhost.

The error we get is for the localhost requests from a public site:

Access to XMLHttpRequest at 'https://localhost:3030/static/first.qjson' from origin 'https://....com' has been blocked by CORS policy: Request had no target IP address space, yet the resource is in address space `local`.

The site on localhost is configured to return Access-Control-Allow-* CORS headers including "Access-Control-Allow-Private-Network: true".

And also I do not see any preflight request. Just one GET request with CORS error on it.

We suspect this might be a side effect caused when you disable web security by --disable-web-security. It might be preventing obtaining of the target IP address space. Our assumption is based on the CORS preflight section on https://wicg.github.io/private-network-access/

3.1.2. CORS preflight

The HTTP fetch algorithm should be adjusted to ensure that a preflight is triggered for all private network requests initiated from secure contexts.

The main issue here is again that the response’s IP address space is not known until a connection is obtained in HTTP-network fetch, which is layered under CORS-preflight fetch.

So does anyone know any workaround for Private Network Access with --disable-web-security flag ?
Or maybe we are missing something. Thanks for the help.

答:
Below Steps can help to solve issue in chrome 98, for other browser like edge you need to do similar like chrome.

For MAC

Requestly with chrome version 98. You need to follow following steps :- Run this command on terminal

defaults write com.google.Chrome InsecurePrivateNetworkRequestsAllowed -bool true

Restart your Browser, Not work then restart your machine

For WINDOWS

Run 'regedit' to open windows registry (If permission issue came then run that command with Admin command prompt)

Go to Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome

Create new DWORD value with "InsecurePrivateNetworkRequestsAllowed" Name

Change Value to "1"

Restart your Browser


问:
Why does eclipse SOMETIMES prompt me which device to launch my app on?
Why does eclipse SOMETIMES prompt me which device to launch my app on when there is only 1 phone connected to my machine? Sometimes, it stays like this for months.... how to fix?

It says my target phone is 2.3.4    and there is a small yellow exclamation warning next to it.

答:
fix like this:

right click on your project->Run As->Run Configuration

there select target and select automatic and specify the VD there..


问:
how can I solve this error regarding the spacy version
This is the code:
nlp_model=spacy.load('nlp_model')

This is the error:
OSError: [E053] Could not read config.cfg from nlp_model\config.cfg

I am using a pre trained model from spacy v2 and my spacy model is 3.2.1. How can I use this model in my spacy version

答:
You can't use a model from spaCy v2 with spaCy v3. The major version (the first part of the version number) of spaCy and your model need to be the same.

You need to upgrade your model, or, if it's one you trained yourself, retrain it.


问:
How to delete multiple rows from MYSQL database with PHP no frameworks
I'm trying to handle a query to delete multiple items with checkboxes. I'm using react for my frontend and php for my backend.

My frontend sends the payload form data like this :
P.S My Primary Key is the SKU.

```<code>sku: DVD0004
sku: DVD0005
</code>```

I need to combine these values into 1 bracket like this (DVD0004,DVD0005) in order to put them in my query which is

My API

```<code>    public function deleteProduct($prdt_sku)
    {
        try {
            $this->db->query("DELETE FROM products WHERE product_sku = :sku");
            $this->db->bind(":sku", $prdt_sku);

            if ($this->db->execute()) {
                return true;
            } else {
                return false;
            }
        } catch (\Throwable) {
            header("HTTP/1.1 406 Error deleting product from database");
        }
    }
</code>```

*My actual form destination *

```<code>$response = array();

if (isset($_POST['sku'])) {

    $sku = $_POST['sku'];

    $result = $api->deleteProduct($sku);

    if ($result) {
        header("HTTP/1.1 200 OK");
        header("Location: http://localhost:3000/");
        exit();
    } else {
        header("HTTP/1.1 406 Error deleting product");
    }
} else {
    header("HTTP/1.1 499 Required parameters missing");
}
</code>```

答: To avoid running multiple delete queries, you can use WHERE IN (a, b, c) instead of deleting one record at a time. See this question for details.</p>

Body:
I'm trying to handle a query to delete multiple items with checkboxes. I'm using react for my frontend and php for my backend.

My frontend sends the payload form data like this :
P.S My Primary Key is the SKU.

sku: DVD0004
sku: DVD0005

I need to combine these values into 1 bracket like this (DVD0004,DVD0005) in order to put them in my query which is

My API

    public function deleteProduct($prdt_sku)
    {
        try {
            $this->db->query("DELETE FROM products WHERE product_sku = :sku");
            $this->db->bind(":sku", $prdt_sku);

            if ($this->db->execute()) {
                return true;
            } else {
                return false;
            }
        } catch (\Throwable) {
            header("HTTP/1.1 406 Error deleting product from database");
        }
    }

*My actual form destination *

$response = array();

if (isset($_POST['sku'])) {

    $sku = $_POST['sku'];

    $result = $api->deleteProduct($sku);

    if ($result) {
        header("HTTP/1.1 200 OK");
        header("Location: http://localhost:3000/");
        exit();
    } else {
        header("HTTP/1.1 406 Error deleting product");
    }
} else {
    header("HTTP/1.1 499 Required parameters missing");
}


问:
Add new contact in Xero using python FASTAPI
I am trying to add a new contact in Xero using python FASTAPI:

define a new contact

```<code>    contact = {
                "Contacts": [
                    {
                        "Name": "24 locks",
                        "FirstName": "Ben",
                        "LastName": "Bowden",
                        "EmailAddress": "ben.bowden@24locks.com",
                        "ContactPersons": [
                            {
                            "FirstName": "John",
                            "LastName": "Smith",
                            "EmailAddress": "john.smith@24locks.com",
                            "IncludeInEmails": "true"
                            }
                        ]
                    }
                ]
            }

</code>```

Call xero API

```<code>    get_url = 'https://api.xero.com/api.xro/2.0/Contacts'

    response = requests.post(get_url,
                           headers = {
                               'Authorization': 'Bearer ' + access_token,
                               'Xero-tenant-id': xero_tenant_id,
                               'Accept': 'application/json'
                           },
                           data = contact
                )

    json_response = response.json()
</code>```

I get the following error:

```<code>{'ErrorNumber': 17, 'Type': 'NoDataProcessedException', 'Message': 'No data has been processed for this endpoint. This endpoint is expecting Contact data to be specifed in the request body.'}
</code>```

Someone can help please ?

You can assume that access_token and xero_tenant_id are correct as I am using them for other methods and they works fine.

Thanks

答:
Try to use json = contact instead of data = contact or set header 'Content-Type': 'application/json'

Because

data for dict When not specified content-type, The default is application/x-www-form-urlencoded,

Body:
I am trying to add a new contact in Xero using python FASTAPI:

define a new contact

    contact = {
                "Contacts": [
                    {
                        "Name": "24 locks",
                        "FirstName": "Ben",
                        "LastName": "Bowden",
                        "EmailAddress": "ben.bowden@24locks.com",
                        "ContactPersons": [
                            {
                            "FirstName": "John",
                            "LastName": "Smith",
                            "EmailAddress": "john.smith@24locks.com",
                            "IncludeInEmails": "true"
                            }
                        ]
                    }
                ]
            }

Call xero API

    get_url = 'https://api.xero.com/api.xro/2.0/Contacts'

    response = requests.post(get_url,
                           headers = {
                               'Authorization': 'Bearer ' + access_token,
                               'Xero-tenant-id': xero_tenant_id,
                               'Accept': 'application/json'
                           },
                           data = contact
                )

    json_response = response.json()

I get the following error:

{'ErrorNumber': 17, 'Type': 'NoDataProcessedException', 'Message': 'No data has been processed for this endpoint. This endpoint is expecting Contact data to be specifed in the request body.'}

Someone can help please ?

You can assume that access_token and xero_tenant_id are correct as I am using them for other methods and they works fine.

Thanks


问:
Blurry Terminal in VS Code

I have been using Visual Studio Code for a few months, but for some reason, it just became blurry. The only thing I really changed was the theme. I set it to default but it is still blurry. Why is this occurring?

答:
Try changing editor font size and window zoom level:</p>
```<code>{
  "window.zoomLevel": -1,
  "editor.fontSize": 14,
  "terminal.integrated.fontSize": 12,
}
</code>```

Title: Blurry Terminal in VS Code

Body:
Try changing editor font size and window zoom level:

{
  "window.zoomLevel": -1,
  "editor.fontSize": 14,
  "terminal.integrated.fontSize": 12,
}


问:
Get Function name inside a loop pass
I am pretty amateur in LLVM. I am trying to write a loop pass in which I need to know which function I'm in. Is there any way to find that?
I want to do this in the following runOnLoop function:

```<code>virtual bool runOnLoop(Loop *L, LPPassManager &LPM) override {

 }
</code>```

答:
You need</p>
```<code>StringRef Name = L->getHeader()->getParent()->getName();
</code>```

Title: Get Function name inside a loop pass

Body:
I am pretty amateur in LLVM. I am trying to write a loop pass in which I need to know which function I'm in. Is there any way to find that?
I want to do this in the following runOnLoop function:

virtual bool runOnLoop(Loop *L, LPPassManager &LPM) override {

 }

Body:
You need

StringRef Name = L->getHeader()->getParent()->getName();


问:
Carbon (laravel) deal with invalid date
I have a quite simple problem.. I use the Carbon::parse($date) function with $date = '15.15.2015'. Of course it can not return a valid string because there is no 15th month. But how can i "ignore" the error message?
Great would be something like

```<code>if (Carbon::parse($date) != error) Carbon::parse($date);
else echo 'invalid date, enduser understands the error message';
</code>```

答:
Both try...catch... and validator is good. Sam's answer is good too.

In Laravel 8, I use following code:

```<code>// app/Exceptions/Handler.php

use Carbon\Exceptions\InvalidFormatException;

public function register()
{
    $this->renderable(function (InvalidFormatException $e, $request) {
        return response()->json([
            'message' => 'Invalid date format!.'
        ], 400);
    });
}
</code>```

When InvalidFormatException thrown, Laravel will return http status 400 and json with message.

If you don't want to use try...catch... at every Carbon::parse() section, this is a good way to handle exception.

Title: Carbon (laravel) deal with invalid date

Body:
I have a quite simple problem.. I use the Carbon::parse($date) function with $date = '15.15.2015'. Of course it can not return a valid string because there is no 15th month. But how can i "ignore" the error message?
Great would be something like

if (Carbon::parse($date) != error) Carbon::parse($date);
else echo 'invalid date, enduser understands the error message';

Body:
Both try...catch... and validator is good. Sam's answer is good too.

In Laravel 8, I use following code:

// app/Exceptions/Handler.php

use Carbon\Exceptions\InvalidFormatException;

public function register()
{
    $this->renderable(function (InvalidFormatException $e, $request) {
        return response()->json([
            'message' => 'Invalid date format!.'
        ], 400);
    });
}

When InvalidFormatException thrown, Laravel will return http status 400 and json with message.

If you don't want to use try...catch... at every Carbon::parse() section, this is a good way to handle exception.


答:
Run -> Run Configurations -> Choose current project in the list on the
  left -> Target -> Automatic

This will run the application automatically on a connected device. However, don't know how will it work if there are more then one device connected.

Title: Why does eclipse SOMETIMES prompt me which device to launch my app on?

Body:
Why does eclipse SOMETIMES prompt me which device to launch my app on when there is only 1 phone connected to my machine? Sometimes, it stays like this for months.... how to fix?

It says my target phone is 2.3.4    and there is a small yellow exclamation warning next to it.


答:
You have to compare with True, not "True" because "True" is str.

Also, it would be more recommended to use is when you compare with True or False rather than == (PEP 8: E712 comparison to True should be 'if cond is True:' or 'if cond:').

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'deal': [True, False, True, False]
})

df['madedeal'] = np.where(df['deal'] is True, 1, 0)
# df['madedeal'] = np.where(df['deal'], 1, 0 # This also works as @sammywemmy commented.

print(df)

#    deal  madedeal
#0   True         1
#1  False         0
#2   True         1
#3  False         0
```

Title: creating new column based on condition (Python)


问:
Finding the length of an integer in C
I would like to know how I can find the length of an integer in C.

For instance:

1 => 1

25 => 2

12512 => 5

0 => 1

and so on.

How can I do this in C?

答:
Hmm, maybe like this...?</p>
```<code>#define _LEN(x) (sizeof(#x)/sizeof(char)-1)
</code>```

Title: Finding the length of an integer in C

Body:
Hmm, maybe like this...?

#define _LEN(x) (sizeof(#x)/sizeof(char)-1)


问:
How to base64 encode a SHA256 hex character string
Hi I need help to get a base64 encoded column, what I got is a sha256 hashed column, I suppose to get 44 characters, but when I try this in python

[base64.b64encode(x.encode('utf-8')).decode() for x in xxx['yyy']]

it returns 88 character, anyone can help with this? Basically I want to achieve the steps showing in the pictures below in Python, thanks!

答:
This answer on the Cryptography Stack Exchange discusses why you're getting 64 characters. Basically, for historical reasons hashes are typically hex encoded even though this results in 64 characters while a base64 encoded hash would only be 44 characters. But if you need it base64 encoded there is a way of doing it. The following will give you a base64 encoded hash

```<code>from base64 import b64encode
from hashlib import sha256

email = 'user@example.com'
email_as_bytes = email.encode('utf-8')
hash_as_bytes = b64encode(sha256(email_as_bytes).digest())
hash = hash_as_bytes.decode('utf-8')
</code>```

Since b64encode and sha256 both operate on bytes, we can chain them together, and the resulting code isn't too terrible.

Body:
This answer on the Cryptography Stack Exchange discusses why you're getting 64 characters. Basically, for historical reasons hashes are typically hex encoded even though this results in 64 characters while a base64 encoded hash would only be 44 characters. But if you need it base64 encoded there is a way of doing it. The following will give you a base64 encoded hash

from base64 import b64encode
from hashlib import sha256

email = 'user@example.com'
email_as_bytes = email.encode('utf-8')
hash_as_bytes = b64encode(sha256(email_as_bytes).digest())
hash = hash_as_bytes.decode('utf-8')

Since b64encode and sha256 both operate on bytes, we can chain them together, and the resulting code isn't too terrible.


问:
Flutter Hybrid Composition and Keyboard Overlap
In my Flutter application I have a form which is encapsulated within a native view using hybrid composition. Tapping an input at the bottom of the form opens the keyboard. This causes the keyboard to overlap the focused form field.

How can I get the keyboard in Flutter to not overlap the form field in the native view component?

Below is my current layout:

    SingleChildScrollView(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Card(
            margin: const EdgeInsets.fromLTRB(0, 20, 0, 0),
            color: Colors.white,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(10)),
            ),
            child: Padding(
              padding: EdgeInsets.all(30),
              child: Container(
                height: 520,
                child: AddressDetailsNativeView(),
              ),
            ),
          ),
          SizedBox(height: 20),
        ],
      ),
    ),
```

答:
Take your column widget inside singlechildscroll view widget this will prevent the overlap of the keyboard.</p>
```<code>SinglechildscrollView(

child:Column(
 children:[
      TextField(),
      TextField()

          ]
</code>```

Body:
Take your column widget inside singlechildscroll view widget this will prevent the overlap of the keyboard.

SinglechildscrollView(

child:Column(
 children:[
      TextField(),
      TextField()

          ]


问:
How can I tell if a date is before a certain time in Java?
For example given a java.util.Date how could I test if the time was before 12.30 PM that day?</p>

答:
I think @Bohemian has the best answer if you don't want to add dependencies, but IMO you should save yourself some time and give up on the java classes and add joda-time to your project :)</p>

```<code>    static boolean isBefore1230(Date d) {
        return new DateTime(d).getMinuteOfDay() < 12 * 60 + 30;
    }
</code>```

Body:
I think @Bohemian has the best answer if you don't want to add dependencies, but IMO you should save yourself some time and give up on the java classes and add joda-time to your project :)

    static boolean isBefore1230(Date d) {
        return new DateTime(d).getMinuteOfDay() < 12 * 60 + 30;
    }


问:
How to set a max length on collection index in mongodb
Using Pymongo to set/query/insert in my mongodb database.

It is possible to indicate that a value should be a unique index in mongodb.

db.mycoll.create_index("sid", unique=True) # This is what I have so far
```
<p>Now, I want to make sure that the index has <strong>a minimum and maximum length</strong>. (3-20 chars).</p>
<p>I didn't find any information about adding length restrictions, is it possible with mongodb ?</p>
<p>I would expect something like this:</p>
<pre class="lang-py prettyprint-override"><code>db.mycoll.create_index("sid", unique=True, max_len=20, min_len=3) # Is there a way to do this ?
</code>```

If you need a bit more context, I have a collection in mongodb and for every document I need a SID (string ID). I would like to put a technical size limit on this value, so I can be sure on every side of my application that any string which doesn't match this size is not a proper id.

Thanks a lot

答:
You can use the MongoDB Schema Validation to specify the maximum and minimum length of a string type field. For example,

```<code>db.createCollection("mycoll", {
    validator: {
         $jsonSchema: {
             bsonType: "object",
             required: [ "name", "city" ],
             properties: {
                 name: {
                     bsonType: "string",
                     minLength: 3,
                     maxLength: 20,
                     description: "must be a string (3 to 20 chars) and is required"
                 },
                 city: {
                     bsonType: "string"
                 }
             }
        }
    }
} )
</code>```

The createCollection method has the validator option where you can specify the $jsonSchema to match the documents in the schema. Also, you can specify the validationAction (default is "error") and validationLevel (default is "strict") for the validator.

This means, if you try the following insert action, it will fail. The document will not be inserted, as the name field is only 2 characters in length.

```<code>db.mycoll.insertOne({name: 'mo', city: 'los angeles' })
</code>```

NOTE:

You still need to create a Unique Index on the name field to make sure it doesn't allow duplicate values.

Schema Validation is applied on the database server - just like the unique  index.

[EDIT ADD]
The PyMongo version:

```<code>client = pymongo.MongoClient()
db = client['test']
db.create_collection('pycoll', validator={
         '$jsonSchema': {
             'bsonType': 'object',
             'required': [ 'name' ],
             'properties': {
                 'name': {
                     'bsonType': 'string',
                     'minLength': 3,
                     'maxLength': 20,
                     'description': 'must be a string (3 to 20 chars) and is required'
                 }
             }
        }
    }
)

print('Collection created...')
</code>```

Body:
Using Pymongo to set/query/insert in my mongodb database.

It is possible to indicate that a value should be a unique index in mongodb.

db.mycoll.create_index("sid", unique=True) # This is what I have so far

Now, I want to make sure that the index has a minimum and maximum length. (3-20 chars).

I didn't find any information about adding length restrictions, is it possible with mongodb ?

I would expect something like this:

db.mycoll.create_index("sid", unique=True, max_len=20, min_len=3) # Is there a way to do this ?

If you need a bit more context, I have a collection in mongodb and for every document I need a SID (string ID). I would like to put a technical size limit on this value, so I can be sure on every side of my application that any string which doesn't match this size is not a proper id.

Thanks a lot

Body:
You can use the MongoDB Schema Validation to specify the maximum and minimum length of a string type field. For example,

db.createCollection("mycoll", {
    validator: {
         $jsonSchema: {
             bsonType: "object",
             required: [ "name", "city" ],
             properties: {
                 name: {
                     bsonType: "string",
                     minLength: 3,
                     maxLength: 20,
                     description: "must be a string (3 to 20 chars) and is required"
                 },
                 city: {
                     bsonType: "string"
                 }
             }
        }
    }
} )

The createCollection method has the validator option where you can specify the $jsonSchema to match the documents in the schema. Also, you can specify the validationAction (default is "error") and validationLevel (default is "strict") for the validator.

This means, if you try the following insert action, it will fail. The document will not be inserted, as the name field is only 2 characters in length.

db.mycoll.insertOne({name: 'mo', city: 'los angeles' })

NOTE:

You still need to create a Unique Index on the name field to make sure it doesn't allow duplicate values.

Schema Validation is applied on the database server - just like the unique  index.

[EDIT ADD]
The PyMongo version:

client = pymongo.MongoClient()
db = client['test']
db.create_collection('pycoll', validator={
         '$jsonSchema': {
             'bsonType': 'object',
             'required': [ 'name' ],
             'properties': {
                 'name': {
                     'bsonType': 'string',
                     'minLength': 3,
                     'maxLength': 20,
                     'description': 'must be a string (3 to 20 chars) and is required'
                 }
             }
        }
    }
)

print('Collection created...')


问:
How to find longest words in all files using ForkJoin
Using the resources of the Fork-Join framework, create an asynchronous multithreaded system to form a collection of words of maximum length from three text files.

How to find the longest words in all files?

In my case, I'm looking for each file separately, but I don't understand how to do it together, and I need to use ForkJoin framework.

```<code>import java.io.File;
import java.util.*;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.stream.Collectors;

public class loop {
    public static void main(String[] args) {

        File[] files = {
                new File("text"),
                new File("text2"),
                new File("text3")
        };

        MaxLengthWord sumOfDigits = new MaxLengthWord(files);

        ForkJoinPool pool = new ForkJoinPool();

        final List<String> maxWords = pool.invoke(sumOfDigits);
        System.out.println(maxWords);

    }
}

class MaxLengthWord extends RecursiveTask<List<String>> {
    File[] files;

    public MaxLengthWord(File[] files) {
        this.files = files;
    }

    @Override
    protected List<String> compute() {
        if (files.length > 1) {
            return ForkJoinTask.invokeAll(createSubtasks())
                    .stream()
                    .flatMap(maxLengthWord -> maxLengthWord.join().stream())
                    .collect(Collectors.toList());
        } else {
            return processing(files);
        }
    }

    private Collection<MaxLengthWord> createSubtasks() {
        List<MaxLengthWord> subTasks = new ArrayList<>();
        subTasks.add(new MaxLengthWord(
                Arrays.copyOfRange(files, 0, files.length / 2)));
        subTasks.add(new MaxLengthWord(
                Arrays.copyOfRange(files, files.length / 2, files.length)));
        return subTasks;
    }

    private List<String> processing(File[] files) {
        List<String> result = new ArrayList<>();
        String longest_word = "";
        try (Scanner sc = new Scanner(files[0])) {
            while (sc.hasNext()) {
                String word = sc.next();

                if (word.length() > longest_word.length()) {
                    longest_word = word;
                    result.clear();
                    result.add(longest_word);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(result + " " + Thread.currentThread() + " " + files[0]);
        return result;
    }
}
</code>```

答:
The basic algorithm of working with a RecusiveAction is the following:

check if the task is small enough, to be executed by a single thread (in this case - there has to be only one file in the array);

if the task has to be split create two subtasks;

invoke compute() on the first subtask (no need to fork both subtasks);

invoke fork() on the second subtask (task will be executed asynchronously on a different thread);

invoke join() on the second subtask (join() is a blocking call and must be done after the invocation of compute() on the first subtask).

I've substituted File with a Path in my example because File API is legacy and discouraged to be used. Method toFile() allows to use Path when an instance of the File is required.

RecursiveTask

```<code>    public class MaxLengthWord extends RecursiveTask<List<String>> {
        private final Path[] files;

        public MaxLengthWord(Path[] files) {
            this.files = files;
        }

        @Override
        protected List<String> compute() {
            if (files.length == 0) {
                return Collections.emptyList();
            }
            if (files.length == 1) {
                return getLongestWords(files[0]);
            }
            else {
                MaxLengthWord task1 = new MaxLengthWord(Arrays.copyOf(files, files.length - 1));
                MaxLengthWord task2 = new MaxLengthWord(new Path[]{files[files.length - 1]});
                task2.fork();
                List<String> result = task1.compute();
                result.addAll(task2.join());
                return result;
            }
        }

        private List<String> getLongestWords(Path file) {
            List<String> words = getAllWordsFromFile(file);

            int maxLen = words.stream()
                    .mapToInt(String::length)
                    .max().orElse(0);

            return words.stream()
                    .filter(word -> word.length() == maxLen)
                    .collect(Collectors.toList());
        }

        private List<String> getAllWordsFromFile(Path file) {
            Pattern wordBoundary = Pattern.compile("\\b");

            try(Stream<String> lines = Files.lines(file)) {
                return lines.flatMap(wordBoundary::splitAsStream)
                        .filter(word -> word.matches("\\p{L}+"))
                        .distinct()
                        .collect(Collectors.toList());
            }
            catch(IOException e) {
                e.printStackTrace();
            }
            return Collections.emptyList();
        }
    }
</code>```

main (don't forget to shutdown the pool)

```<code>    public static void main(String[] args) {
        Path[] files = new Path[] {
                Path.of("a.txt"),
                Path.of("b.txt"),
                Path.of("c.txt")
        };
        ForkJoinPool pool = ForkJoinPool.commonPool();
        List<String> words = pool.invoke(new MaxLengthWord(files));
        System.out.println(words);
        pool.shutdown();
    }
</code>```

output (all files are populated with quotes from Javadoc, these 4 words are happen to the longest)

```<code>[intermediate, Intermediate, intermediate, spliterator]
</code>```

Body:
Using the resources of the Fork-Join framework, create an asynchronous multithreaded system to form a collection of words of maximum length from three text files.

How to find the longest words in all files?

In my case, I'm looking for each file separately, but I don't understand how to do it together, and I need to use ForkJoin framework.

import java.io.File;
import java.util.*;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.stream.Collectors;

public class loop {
    public static void main(String[] args) {

        File[] files = {
                new File("text"),
                new File("text2"),
                new File("text3")
        };

        MaxLengthWord sumOfDigits = new MaxLengthWord(files);

        ForkJoinPool pool = new ForkJoinPool();

        final List<String> maxWords = pool.invoke(sumOfDigits);
        System.out.println(maxWords);

    }
}

class MaxLengthWord extends RecursiveTask<List<String>> {
    File[] files;

    public MaxLengthWord(File[] files) {
        this.files = files;
    }

    @Override
    protected List<String> compute() {
        if (files.length > 1) {
            return ForkJoinTask.invokeAll(createSubtasks())
                    .stream()
                    .flatMap(maxLengthWord -> maxLengthWord.join().stream())
                    .collect(Collectors.toList());
        } else {
            return processing(files);
        }
    }

    private Collection<MaxLengthWord> createSubtasks() {
        List<MaxLengthWord> subTasks = new ArrayList<>();
        subTasks.add(new MaxLengthWord(
                Arrays.copyOfRange(files, 0, files.length / 2)));
        subTasks.add(new MaxLengthWord(
                Arrays.copyOfRange(files, files.length / 2, files.length)));
        return subTasks;
    }

    private List<String> processing(File[] files) {
        List<String> result = new ArrayList<>();
        String longest_word = "";
        try (Scanner sc = new Scanner(files[0])) {
            while (sc.hasNext()) {
                String word = sc.next();

                if (word.length() > longest_word.length()) {
                    longest_word = word;
                    result.clear();
                    result.add(longest_word);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(result + " " + Thread.currentThread() + " " + files[0]);
        return result;
    }
}

Body:
The basic algorithm of working with a RecusiveAction is the following:

check if the task is small enough, to be executed by a single thread (in this case - there has to be only one file in the array);

if the task has to be split create two subtasks;

invoke compute() on the first subtask (no need to fork both subtasks);

invoke fork() on the second subtask (task will be executed asynchronously on a different thread);

invoke join() on the second subtask (join() is a blocking call and must be done after the invocation of compute() on the first subtask).

I've substituted File with a Path in my example because File API is legacy and discouraged to be used. Method toFile() allows to use Path when an instance of the File is required.

RecursiveTask

    public class MaxLengthWord extends RecursiveTask<List<String>> {
        private final Path[] files;

        public MaxLengthWord(Path[] files) {
            this.files = files;
        }

        @Override
        protected List<String> compute() {
            if (files.length == 0) {
                return Collections.emptyList();
            }
            if (files.length == 1) {
                return getLongestWords(files[0]);
            }
            else {
                MaxLengthWord task1 = new MaxLengthWord(Arrays.copyOf(files, files.length - 1));
                MaxLengthWord task2 = new MaxLengthWord(new Path[]{files[files.length - 1]});
                task2.fork();
                List<String> result = task1.compute();
                result.addAll(task2.join());
                return result;
            }
        }

        private List<String> getLongestWords(Path file) {
            List<String> words = getAllWordsFromFile(file);

            int maxLen = words.stream()
                    .mapToInt(String::length)
                    .max().orElse(0);

            return words.stream()
                    .filter(word -> word.length() == maxLen)
                    .collect(Collectors.toList());
        }

        private List<String> getAllWordsFromFile(Path file) {
            Pattern wordBoundary = Pattern.compile("\\b");

            try(Stream<String> lines = Files.lines(file)) {
                return lines.flatMap(wordBoundary::splitAsStream)
                        .filter(word -> word.matches("\\p{L}+"))
                        .distinct()
                        .collect(Collectors.toList());
            }
            catch(IOException e) {
                e.printStackTrace();
            }
            return Collections.emptyList();
        }
    }

main (don't forget to shutdown the pool)

    public static void main(String[] args) {
        Path[] files = new Path[] {
                Path.of("a.txt"),
                Path.of("b.txt"),
                Path.of("c.txt")
        };
        ForkJoinPool pool = ForkJoinPool.commonPool();
        List<String> words = pool.invoke(new MaxLengthWord(files));
        System.out.println(words);
        pool.shutdown();
    }

output (all files are populated with quotes from Javadoc, these 4 words are happen to the longest)

[intermediate, Intermediate, intermediate, spliterator]


问:
How can I change an image when I click on another image? (Without onclick)
I´m doing a landing page and wanted to make the main image change when I click on other images. I´ve tried with this

```
<pre class="lang-js prettyprint-override"><code>function imageChange() {
  let picDefault = document.getElementById("img");

  if ((picDefault = "img")) {
    picDefault.src = "./assets/img1.png";
  }
}
picDefault.addEventListener(click, imageChange);
</code>```

答:
Sample code for updating an image by clicking on another image. Use case might be completely different.

const thumps =  document.getElementsByClassName("thump"); // secondary images
const main =  document.getElementById("main");

for(let i = 0; i < thumps.length; i ++) {
  const el = thumps[i]
  el.addEventListener("click", function(e) { //  add click handler
    const elem = e.target;
    main.src = elem.src;
  })
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#main {
  max-width: 300px;
}

.thump {
  width: 100px;
  margin: 4px;
  padding: 2px;
  border: 1px solid #ccc;
  display: inline-block;
}</code>```

Main Image

Click Images below thumpnails to update main image

```

Body:
I´m doing a landing page and wanted to make the main image change when I click on other images. I´ve tried with this

function imageChange() {
  let picDefault = document.getElementById("img");

  if ((picDefault = "img")) {
    picDefault.src = "./assets/img1.png";
  }
}
picDefault.addEventListener(click, imageChange);

Body:
Sample code for updating an image by clicking on another image. Use case might be completely different.

const thumps =  document.getElementsByClassName("thump"); // secondary images
const main =  document.getElementById("main");

for(let i = 0; i < thumps.length; i ++) {
  const el = thumps[i]
  el.addEventListener("click", function(e) { //  add click handler
    const elem = e.target;
    main.src = elem.src;
  })
}

#main {
  max-width: 300px;
}

.thump {
  width: 100px;
  margin: 4px;
  padding: 2px;
  border: 1px solid #ccc;
  display: inline-block;
}

<div>
  <h5>Main Image</h5>
  <img src="https://images.unsplash.com/photo-1644243019151-0bb97ce1af84" id="main"/>
</div>

<h5>Click Images below thumpnails to update main image</h5>
<div class="row">
  <img src="https://images.unsplash.com/photo-1644235279538-4cc7cbdca6a8" class="thump">
  <img src="https://images.unsplash.com/photo-1643443026948-c17b9bb16758" class="thump">
  <img src="https://images.unsplash.com/photo-1644243019151-0bb97ce1af84" class="thump">
</div>


问:
Timer in Windows Service not firing ElapsedEventHandler
I have a windows service written in C# that executes a method correctly.  I added a timer to schedule the method execution and it doesn't seem to fire the ElapsedEventHandler event.

```<code>System.Timers.Timer timer = new System.Timers.Timer();

public LabelService()
        {
            InitializeComponent();
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
        }

public void SetTimer()
        {
            DateTime nextRunTime = GetNextRunTime();
            var ts = nextRunTime - DateTime.Now;
            timer.Interval = ts.TotalMilliseconds;
            timer.AutoReset = false;
            timer.Start();
        }

void timer_Elapsed(object source, ElapsedEventArgs e)
        {
           // ** never gets here **
            timer.Stop();
              // run some code
            SetTimer();
        }
</code>```

I can run and hit a breakpoint at  timer.Start();  so I know that's being done, but it never falls into the timer_Elapsed method.  (For testing I change ts.TotalMilliseconds to 1000)  Any ideas?

答:
From comments on the question you say you are calling it like this:

```<code>#if (!DEBUG)
    ServiceBase[] ServicesToRun;
    ServicesToRun = new ServiceBase[] { new LabelLoader() };
    ServiceBase.Run(ServicesToRun);
#else
    LabelLoader ll = new LabelLoader();
    ll.Start();
#endif
</code>```

If you are in debug mode that means your main method is this:

```<code>    LabelLoader ll = new LabelLoader();
    ll.Start();
</code>```

This means that once it has run these two lines the program finishes running and presumably exits. It doesn't matter what your timer is up to, the program has quit and thus your timer never fires.

I'd advise testing your ll with a better harness. Personally I use a winform type interface and just have a start button to mimic the service start (which will then have your code in the button click). Once I think I have that code running as I want I then test it in a service environment.

Body:
I have a windows service written in C# that executes a method correctly.  I added a timer to schedule the method execution and it doesn't seem to fire the ElapsedEventHandler event.

System.Timers.Timer timer = new System.Timers.Timer();

public LabelService()
        {
            InitializeComponent();
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
        }

public void SetTimer()
        {
            DateTime nextRunTime = GetNextRunTime();
            var ts = nextRunTime - DateTime.Now;
            timer.Interval = ts.TotalMilliseconds;
            timer.AutoReset = false;
            timer.Start();
        }

void timer_Elapsed(object source, ElapsedEventArgs e)
        {
           // ** never gets here **
            timer.Stop();
              // run some code
            SetTimer();
        }

I can run and hit a breakpoint at  timer.Start();  so I know that's being done, but it never falls into the timer_Elapsed method.  (For testing I change ts.TotalMilliseconds to 1000)  Any ideas?

Body:
From comments on the question you say you are calling it like this:

#if (!DEBUG)
    ServiceBase[] ServicesToRun;
    ServicesToRun = new ServiceBase[] { new LabelLoader() };
    ServiceBase.Run(ServicesToRun);
#else
    LabelLoader ll = new LabelLoader();
    ll.Start();
#endif

If you are in debug mode that means your main method is this:

    LabelLoader ll = new LabelLoader();
    ll.Start();

This means that once it has run these two lines the program finishes running and presumably exits. It doesn't matter what your timer is up to, the program has quit and thus your timer never fires.

I'd advise testing your ll with a better harness. Personally I use a winform type interface and just have a start button to mimic the service start (which will then have your code in the button click). Once I think I have that code running as I want I then test it in a service environment.


问:
How to align image to the left and text to the center on a Xamarin button in iOS?
I want to align my text in the center, but the image on the left. I have tried it with HorizontalAlignment, but it aligns both. How to do it?</p>

答:
I took the time to actually understand how "insets" work, and wrote my own solution.

```<code>
[assembly: ExportRenderer(typeof(Button), typeof(RingotanButtonRenderer))]
namespace MyAppNamespace
{
    public class MyButtonRenderer : ButtonRenderer
    {
        public override void LayoutSubviews()
        {
            base.LayoutSubviews();

            // Left-align the image and center the text
            // Taken from https://stackoverflow.com/a/71044012/238419
            if (Element.ContentLayout.Position == Button.ButtonContentLayout.ImagePosition.Left)
            {
                const int imageMargin = 20; // This might need to get multiplied by the screen density, not sure yet.  I'll update this later if it does.
                nfloat imageOffset = Control.ImageView.Frame.Left - imageMargin;
                Control.ImageEdgeInsets = new UIEdgeInsets(0, -imageOffset, 0, imageOffset);

                nfloat imageWidth = Control.ImageView.Frame.Width + imageMargin;
                nfloat textOffset = Control.TitleLabel.Frame.Left - (imageWidth + Control.Frame.Width - Control.TitleLabel.Frame.Width) / 2;
                Control.TitleEdgeInsets = new UIEdgeInsets(0, -textOffset, 0, textOffset);
            }
        }
    }
}
</code>```

Notes:

If you want the text to be centered on the overall button, rather than centered on the available remaining space, set imageWidth = 0

If you only want this to apply to some buttons, create a new class that extends Button and set the ExportRenderer to that new class.  Then only use that new class where you want the text centered.

This only works for left-aligned images, but similar math can be used for the other alignments

There seems to be a bug where Xamarin/iOS ignores the inset if you update the button's ImageSource or Text.  I haven't been able to find a workaround to this bug yet.

Body:
I took the time to actually understand how "insets" work, and wrote my own solution.

[assembly: ExportRenderer(typeof(Button), typeof(RingotanButtonRenderer))]
namespace MyAppNamespace
{
    public class MyButtonRenderer : ButtonRenderer
    {
        public override void LayoutSubviews()
        {
            base.LayoutSubviews();

            // Left-align the image and center the text
            // Taken from https://stackoverflow.com/a/71044012/238419
            if (Element.ContentLayout.Position == Button.ButtonContentLayout.ImagePosition.Left)
            {
                const int imageMargin = 20; // This might need to get multiplied by the screen density, not sure yet.  I'll update this later if it does.
                nfloat imageOffset = Control.ImageView.Frame.Left - imageMargin;
                Control.ImageEdgeInsets = new UIEdgeInsets(0, -imageOffset, 0, imageOffset);

                nfloat imageWidth = Control.ImageView.Frame.Width + imageMargin;
                nfloat textOffset = Control.TitleLabel.Frame.Left - (imageWidth + Control.Frame.Width - Control.TitleLabel.Frame.Width) / 2;
                Control.TitleEdgeInsets = new UIEdgeInsets(0, -textOffset, 0, textOffset);
            }
        }
    }
}

Notes:

If you want the text to be centered on the overall button, rather than centered on the available remaining space, set imageWidth = 0

If you only want this to apply to some buttons, create a new class that extends Button and set the ExportRenderer to that new class.  Then only use that new class where you want the text centered.

This only works for left-aligned images, but similar math can be used for the other alignments

There seems to be a bug where Xamarin/iOS ignores the inset if you update the button's ImageSource or Text.  I haven't been able to find a workaround to this bug yet.