问:
I want to designate a type according to the conditions of the object property
There is organizational data with a hierarchical structure.

Organizational nodes are divided into Root, Dept, and User.

The object property type is assigned a type suitable for node data.

So, I hope that the node interface suitable for the object type will be attached conditionally.

To solve this problem, I tried Index Types and Conditional Types, but they were not successful.

Any help would be appreciated♂

```<code>export enum NodeType {
  root = "root",
  dept = "dept",
  user = "user",
}

interface Node {
  readonly nodeId: string;
  readonly type: NodeType;
  title: string;
  childNodes?: Node[];
}

interface RootNode extends Node {
  type: NodeType.root;
  childNodes?: (DeptNode | UserNode)[];
}

interface DeptNode extends Node {
  type: NodeType.dept;
  childNodes?: (DeptNode | UserNode)[];

  deptId: string;
  companyCode: string;
}

interface UserNode extends Node {
  type: NodeType.user;
  childNodes?: UserNode[];

  employeeNumber: string;
  userPrincipalName: string;
}

/**
 * from hierarchy data to flatting data
 */
function flatting(st: Node) {
  flatCompanyData.push(st);
  if (st.childNodes) {
    st.childNodes.forEach((x) => flatting(x));
  }
}

const companyData: RootNode = {
  nodeId: "0",
  type: NodeType.root,
  title: "Company 1",
  childNodes: [
    {
      nodeId: "0.0",
      type: NodeType.dept,
      title: "Department 1",
      deptId: "A1",
      companyCode: "557",
      childNodes: [
        {
          nodeId: "0.0.0",
          type: NodeType.user,
          title: "User 1",
          employeeNumber: "201911",
          userPrincipalName: "user01@test.com",
        },
        {
          nodeId: "0.0.1",
          type: NodeType.user,
          title: "User 2",
          employeeNumber: "201912",
          userPrincipalName: "user02@test.com",
        },
      ],
    },
    {
      nodeId: "0.1",
      type: NodeType.dept,
      title: "Department 2",
      deptId: "A2",
      companyCode: "558",
    },
  ],
};
let flatCompanyData: Node[] = [];

flatting(companyData);

// I want to be the type of DeptNode interface because the type of object property is NodeType.dept.
const selectDept = flatCompanyData.filter((x) => x.type === NodeType.dept);
selectDept.forEach((x) => {
  console.log({
    nodeId: x.nodeId,
    type: x.type,
    title: x.title,
    // The type is not affirmed in the node that fits the object property type, so you have to affirm the type yourself.
    deptId: (x as DeptNode).deptId,
    companyCode: (x as DeptNode).companyCode,
  });
});

// I want to be the type of UserNode interface because the type of object property is NodeType.user.
const selectUser = flatCompanyData.filter((x) => x.type === NodeType.user);
selectUser.forEach((x) => {
  console.log({
    nodeId: x.nodeId,
    type: x.type,
    title: x.title,
    // The type is not affirmed in the node that fits the object property type, so you have to affirm the type yourself.
    employeeNumber: (x as UserNode).employeeNumber,
    userPrincipalName: (x as UserNode).userPrincipalName,
  });
});
</code>```

答:
There's two problems in your code:

First of all, an element of type Node is not necessarily of type DeptNode just because it has NodeType.dept. Consider the following object:

```<code>{
  nodeId: '0',
  type: NodeType.dept,
  title: 'Company 1'
}
</code>```

This is a completely valid Node but not a valid DeptNode as it lacks the fields deptId and companyCode. So the compiler is in fact right when it does not treat it as a DeptNode. But there is a solution to this. Instead of using an array of Nodes you can define a union type of all possible node types and use it as type for flatCompanyData like this:

```<code>type NodeUnion = RootNode | DeptNode | UserNode;
let flatCompanyData: NodeUnion[];

// ...

const node = flatCompanyData[0];
if (node.type === NodeType.dept) {
  // x is correctly inferred as DeptNode in here
}
</code>```

With this type the compiler knows, the only way an element in the array could possibly have the type NodeType.dept is if it is a DeptNode and so the type is inferred correctly.

This still leaves us with the second problem. Even if you use this union type for flatCompanyData, your code will still not work. The reason is the Array.filter function. For an array of type T[] it will always return an array of type T[], no matter what you check inside.

But fortunately typescript comes with a handy solution for this: custom type guards. When defining a function (including an anonymous function) you can use a type predicate as its return type to tell the compiler that this function acts as a type guard.

```<code>function isDeptNode(node: NodeUnion): node is DeptNode {
  return node.type === NodeType.dept;
}
</code>```

And now you can use this function inside the filter to make typescript realize what you are doing.

```<code>const selectDept: DeptNode[] = flatCompanyData.filter(isDeptNode);
</code>```

It is also possible to specify a type predicate as the return type of an anonymous function without defining the isDeptNode function first.

```<code>const selectDept: DeptNode[] = flatCompanyData.filter(
  (x): x is DeptNode => x.type === NodeType.dept
);
</code>```

Body:
There is organizational data with a hierarchical structure.

Organizational nodes are divided into Root, Dept, and User.

The object property type is assigned a type suitable for node data.

So, I hope that the node interface suitable for the object type will be attached conditionally.

To solve this problem, I tried Index Types and Conditional Types, but they were not successful.

Any help would be appreciated♂

export enum NodeType {
  root = "root",
  dept = "dept",
  user = "user",
}

interface Node {
  readonly nodeId: string;
  readonly type: NodeType;
  title: string;
  childNodes?: Node[];
}

interface RootNode extends Node {
  type: NodeType.root;
  childNodes?: (DeptNode | UserNode)[];
}

interface DeptNode extends Node {
  type: NodeType.dept;
  childNodes?: (DeptNode | UserNode)[];

  deptId: string;
  companyCode: string;
}

interface UserNode extends Node {
  type: NodeType.user;
  childNodes?: UserNode[];

  employeeNumber: string;
  userPrincipalName: string;
}

/**
 * from hierarchy data to flatting data
 */
function flatting(st: Node) {
  flatCompanyData.push(st);
  if (st.childNodes) {
    st.childNodes.forEach((x) => flatting(x));
  }
}

const companyData: RootNode = {
  nodeId: "0",
  type: NodeType.root,
  title: "Company 1",
  childNodes: [
    {
      nodeId: "0.0",
      type: NodeType.dept,
      title: "Department 1",
      deptId: "A1",
      companyCode: "557",
      childNodes: [
        {
          nodeId: "0.0.0",
          type: NodeType.user,
          title: "User 1",
          employeeNumber: "201911",
          userPrincipalName: "user01@test.com",
        },
        {
          nodeId: "0.0.1",
          type: NodeType.user,
          title: "User 2",
          employeeNumber: "201912",
          userPrincipalName: "user02@test.com",
        },
      ],
    },
    {
      nodeId: "0.1",
      type: NodeType.dept,
      title: "Department 2",
      deptId: "A2",
      companyCode: "558",
    },
  ],
};
let flatCompanyData: Node[] = [];

flatting(companyData);

// I want to be the type of DeptNode interface because the type of object property is NodeType.dept.
const selectDept = flatCompanyData.filter((x) => x.type === NodeType.dept);
selectDept.forEach((x) => {
  console.log({
    nodeId: x.nodeId,
    type: x.type,
    title: x.title,
    // The type is not affirmed in the node that fits the object property type, so you have to affirm the type yourself.
    deptId: (x as DeptNode).deptId,
    companyCode: (x as DeptNode).companyCode,
  });
});

// I want to be the type of UserNode interface because the type of object property is NodeType.user.
const selectUser = flatCompanyData.filter((x) => x.type === NodeType.user);
selectUser.forEach((x) => {
  console.log({
    nodeId: x.nodeId,
    type: x.type,
    title: x.title,
    // The type is not affirmed in the node that fits the object property type, so you have to affirm the type yourself.
    employeeNumber: (x as UserNode).employeeNumber,
    userPrincipalName: (x as UserNode).userPrincipalName,
  });
});

Body:
There's two problems in your code:

First of all, an element of type Node is not necessarily of type DeptNode just because it has NodeType.dept. Consider the following object:

{
  nodeId: '0',
  type: NodeType.dept,
  title: 'Company 1'
}

This is a completely valid Node but not a valid DeptNode as it lacks the fields deptId and companyCode. So the compiler is in fact right when it does not treat it as a DeptNode. But there is a solution to this. Instead of using an array of Nodes you can define a union type of all possible node types and use it as type for flatCompanyData like this:

type NodeUnion = RootNode | DeptNode | UserNode;
let flatCompanyData: NodeUnion[];

// ...

const node = flatCompanyData[0];
if (node.type === NodeType.dept) {
  // x is correctly inferred as DeptNode in here
}

With this type the compiler knows, the only way an element in the array could possibly have the type NodeType.dept is if it is a DeptNode and so the type is inferred correctly.

This still leaves us with the second problem. Even if you use this union type for flatCompanyData, your code will still not work. The reason is the Array.filter function. For an array of type T[] it will always return an array of type T[], no matter what you check inside.

But fortunately typescript comes with a handy solution for this: custom type guards. When defining a function (including an anonymous function) you can use a type predicate as its return type to tell the compiler that this function acts as a type guard.

function isDeptNode(node: NodeUnion): node is DeptNode {
  return node.type === NodeType.dept;
}

And now you can use this function inside the filter to make typescript realize what you are doing.

const selectDept: DeptNode[] = flatCompanyData.filter(isDeptNode);

It is also possible to specify a type predicate as the return type of an anonymous function without defining the isDeptNode function first.

const selectDept: DeptNode[] = flatCompanyData.filter(
  (x): x is DeptNode => x.type === NodeType.dept
);


来源: stackexchange

问:
Python 3 - Deleting pictures from a folder that are under 1920x1080
I am using a subreddit scraper to download images from wallpaper subreddits. The problem I am having is that some images have a small resolution causing them to look awful when used as wallpapers. I have found that the minimum resolution needed for a good looking wallpaper is 1920x1080. I now need to make a constantly running script that scans the image folder, looks at each images resolution and decides whether to delete it or move on to the next image. I've been tinkering about in Python for an hour or so but feel I am going nowhere fast as I am only a beginner and have not used Python for a few months. Any help on this project would be awesome ;)! Cheers.

UPDATE: I am now stuck on how to get the program to run through a folder and look at each picture. Currently my code is;

```<code>import os
from PIL import Image
while True:
    for file in os.listdir(r"C:\\Users\\Barney\\Documents\\sam"):
        im = Image.open(file)
        x, y = im.size
        totalsize = x*y
        if totalsize < 2073600:
            os.remove(file)
</code>```

But this returns the error;

```<code>Traceback (most recent call last):
  File "C:\Users\Barney\Desktop\imagefilter.py", line 7, in <module>
    im = Image.open(file)
  File "C:\Python34\lib\site-packages\PIL\Image.py", line 2251, in open
    fp = builtins.open(fp, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'Car - 1971 Ford Mustang Mach 1 351 [2560X1600].jpg'
</code>```

Looking on the internet I see that there may be a problem from where I am opening the program?? Very confused as the program is looking into this folder and reading the contents as the file it says doesnt exist is in that folder? Any help?

答:
If you have many subfolders under a main folder you can use the following code:</p>
```<code>[for directory_path in glob.glob(r'F:\Data\Main_folder\*'):
    print(directory_path)
    for filename in os.listdir(directory_path):
        filepath = os.path.join(directory_path, filename)
        print(filepath)
        with Image.open(filepath) as im:
            x, y = im.size
        totalsize = x*y
        if totalsize < 50176:
            os.remove(filepath)][1]

</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using a subreddit scraper to download images from wallpaper subreddits. The problem I am having is that some images have a small resolution causing them to look awful when used as wallpapers. I have found that the minimum resolution needed for a good looking wallpaper is 1920x1080. I now need to make a constantly running script that scans the image folder, looks at each images resolution and decides whether to delete it or move on to the next image. I've been tinkering about in Python for an hour or so but feel I am going nowhere fast as I am only a beginner and have not used Python for a few months. Any help on this project would be awesome ;)! Cheers.

UPDATE: I am now stuck on how to get the program to run through a folder and look at each picture. Currently my code is;

import os
from PIL import Image
while True:
    for file in os.listdir(r"C:\\Users\\Barney\\Documents\\sam"):
        im = Image.open(file)
        x, y = im.size
        totalsize = x*y
        if totalsize < 2073600:
            os.remove(file)

But this returns the error;

Traceback (most recent call last):
  File "C:\Users\Barney\Desktop\imagefilter.py", line 7, in <module>
    im = Image.open(file)
  File "C:\Python34\lib\site-packages\PIL\Image.py", line 2251, in open
    fp = builtins.open(fp, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'Car - 1971 Ford Mustang Mach 1 351 [2560X1600].jpg'

Looking on the internet I see that there may be a problem from where I am opening the program?? Very confused as the program is looking into this folder and reading the contents as the file it says doesnt exist is in that folder? Any help?

Body:
If you have many subfolders under a main folder you can use the following code:

[for directory_path in glob.glob(r'F:\Data\Main_folder\*'):
    print(directory_path)
    for filename in os.listdir(directory_path):
        filepath = os.path.join(directory_path, filename)
        print(filepath)
        with Image.open(filepath) as im:
            x, y = im.size
        totalsize = x*y
        if totalsize < 50176:
            os.remove(filepath)][1]

ContentLicense: CC BY-SA 4.0


问:
Get text of a tag and the text of child tags
I have this HTML

        aquiline
         adj.
        of or like the eagle.

```

All this this node is wrapped by a div with class= field-item even

I would like to recive Aquiline adj. of or like the eagle.... Now i have this uncorrect xpath response.xpath('//div[@class="field-item even"]//descendant-or-self::p/text()').getall()

答:
Your xpath is almost correct. Replace p with * to select all text nodes and not only text nodes of paragraph tags. Also using normalize-space function you can get all the text as one string instead of a list. See below code snippet.

response.xpath('normalize-space(//div[@class="field-item even"]//descendant-or-self::*)').get()
```

Body:
I have this HTML

        aquiline
         adj.
        of or like the eagle.

All this this node is wrapped by a div with class= field-item even

I would like to recive Aquiline adj. of or like the eagle.... Now i have this uncorrect xpath response.xpath('//div[@class="field-item even"]//descendant-or-self::p/text()').getall()


问:
Can Pyramid's Built-in Authentication/Authorization Implement Complex Security Schemes?
It seems like the security model fits very small projects, but that it is probably not feasible to write all possible registered users' hashed passwords in security.py.  Do you know any examples of scaling up Pyramid's authentication, or are there any benefits to calling through Pyramid's security scheme into my own database of security information?</p>

答:
No idea what your needs are or what you mean by "scaling up security", but pyramids authentication policy is very flexible. You need to understand though that it doesn't maintain  users and passwords it merely provides a mechanism for obtaining a user identifier from the incoming request. For example, the AuthTktAuthenticationPolicy keeps track of the user id  by cookie that you set using the remember method.

What meaningful information you derive from that user id is totally up to you and is application specific.

So really the question you may want to ask is can your application "scale up security".

I can't show you code because it's proprietary but I've needed to support openid, http auth and your typical db backed user store on the same application, with the extra added complication that users are stored in different database shards and the shard can't be immediately determined. It takes very little code to support this.


问:
How can I clean html code data in a DataFrame?

I called an api, and put it in a DataFrame.

 There is a column with a lot of rows and the values are HTML code. I would like to clean the HTML code, only the wording itself. How can I do that?

Example:

```<code><p><span style="color: red;">家庭旅遊保險計劃</span><span style="font-size: 11.5pt;color: red;">包</span><span style="font-size: 11.5pt;color: red;">括</span><span style="color: red;">申請人及配偶，及<b>免費</b>最多其四名</span><span style="color: red;">18</span><span style="color: red;">歲以下之同行子女</span><span style="color: red;"></span></p><p>每人每次最高賠償額* (港元)</p><p><b>金計劃</b><span style="font-size: 11.5pt;color: black;"><br/> </span>醫療費用 $1,000,000<span style="font-size: 11.5pt;color: black;"><br/> </span>個人意外 $1,000,000<span style="font-size: 11.5pt;color: black;"><br/> </span>手機意外損毀或遺失 $3,000</p><p><b>銅計劃</b><span style="font-size: 11.5pt;color: black;"><br/> </span>醫療費用 $250,000<span style="font-size: 11.5pt;color: black;"><br/> </span>個人意外 $250,000</p><p>*18歲以下及75歲以上之受保人於計劃內的保障額將會減少<br/></p>
</code>```

答:
Firstly, run this in a terminal:

pip install beautifulsoup4

Afterwards, apply a proper function to the html column of your pandas dataframe (See below).

Code:

from bs4 import BeautifulSoup
import pandas as pd

# Create a sample dataframe
html = '
家庭旅遊保險計劃包括申請人及配偶，及免費最多其四名18歲以下之同行子女

每人每次最高賠償額* (港元)

金計劃
 醫療費用 $1,000,000
 個人意外 $1,000,000
 手機意外損毀或遺失 $3,000

銅計劃
 醫療費用 $250,000
 個人意外 $250,000

*18歲以下及75歲以上之受保人於計劃內的保障額將會減少

'
df = pd.DataFrame([{'html': html}])

# Extract text from html
df['extracted'] = df.html.apply(lambda s: BeautifulSoup(s).text)
```

Output:

html
extracted

0

家庭旅遊保險計劃包括申請人及配偶，及免費最多其四名18歲以下之同行子女

每人每次最高賠償額* (港元)

金計劃
 醫療費用 $1,000,000
 個人意外 $1,000,000
 手機意外損毀或遺失 $3,000

銅計劃
 醫療費用 $250,000
 個人意外 $250,000

*18歲以下及75歲以上之受保人於計劃內的保障額將會減少

家庭旅遊保險計劃包括申請人及配偶，及免費最多其四名18歲以下之同行子女每人每次最高賠償額* (港元)金計劃 醫療費用 $1,000,000 個人意外 $1,000,000 手機意外損毀或遺失 $3,000銅計劃 醫療費用 $250,000 個人意外 $250,000*18歲以下及75歲以上之受保人於計劃內的保障額將會減少

Body:
I called an api, and put it in a DataFrame.

 There is a column with a lot of rows and the values are HTML code. I would like to clean the HTML code, only the wording itself. How can I do that?

Example:

家庭旅遊保險計劃包括申請人及配偶，及免費最多其四名18歲以下之同行子女

每人每次最高賠償額* (港元)

金計劃
 醫療費用 $1,000,000
 個人意外 $1,000,000
 手機意外損毀或遺失 $3,000

銅計劃
 醫療費用 $250,000
 個人意外 $250,000

*18歲以下及75歲以上之受保人於計劃內的保障額將會減少

Body:
Firstly, run this in a terminal:

pip install beautifulsoup4

Afterwards, apply a proper function to the html column of your pandas dataframe (See below).

Code:

from bs4 import BeautifulSoup
import pandas as pd

# Create a sample dataframe
html = '<p><span style="color: red;">家庭旅遊保險計劃</span><span style="font-size: 11.5pt;color: red;">包</span><span style="font-size: 11.5pt;color: red;">括</span><span style="color: red;">申請人及配偶，及<b>免費</b>最多其四名</span><span style="color: red;">18</span><span style="color: red;">歲以下之同行子女</span><span style="color: red;"></span></p><p>每人每次最高賠償額* (港元)</p><p><b>金計劃</b><span style="font-size: 11.5pt;color: black;"><br/> </span>醫療費用 $1,000,000<span style="font-size: 11.5pt;color: black;"><br/> </span>個人意外 $1,000,000<span style="font-size: 11.5pt;color: black;"><br/> </span>手機意外損毀或遺失 $3,000</p><p><b>銅計劃</b><span style="font-size: 11.5pt;color: black;"><br/> </span>醫療費用 $250,000<span style="font-size: 11.5pt;color: black;"><br/> </span>個人意外 $250,000</p><p>*18歲以下及75歲以上之受保人於計劃內的保障額將會減少<br/></p>'
df = pd.DataFrame([{'html': html}])

# Extract text from html
df['extracted'] = df.html.apply(lambda s: BeautifulSoup(s).text)

Output:

html
extracted

0
<p><span style="color: red;">家庭旅遊保險計劃</span><span style="font-size: 11.5pt;color: red;">包</span><span style="font-size: 11.5pt;color: red;">括</span><span style="color: red;">申請人及配偶，及<b>免費</b>最多其四名</span><span style="color: red;">18</span><span style="color: red;">歲以下之同行子女</span><span style="color: red;"></span></p><p>每人每次最高賠償額* (港元)</p><p><b>金計劃</b><span style="font-size: 11.5pt;color: black;"><br/> </span>醫療費用 $1,000,000<span style="font-size: 11.5pt;color: black;"><br/> </span>個人意外 $1,000,000<span style="font-size: 11.5pt;color: black;"><br/> </span>手機意外損毀或遺失 $3,000</p><p><b>銅計劃</b><span style="font-size: 11.5pt;color: black;"><br/> </span>醫療費用 $250,000<span style="font-size: 11.5pt;color: black;"><br/> </span>個人意外 $250,000</p><p>*18歲以下及75歲以上之受保人於計劃內的保障額將會減少<br/></p>
家庭旅遊保險計劃包括申請人及配偶，及免費最多其四名18歲以下之同行子女每人每次最高賠償額* (港元)金計劃 醫療費用 $1,000,000 個人意外 $1,000,000 手機意外損毀或遺失 $3,000銅計劃 醫療費用 $250,000 個人意外 $250,000*18歲以下及75歲以上之受保人於計劃內的保障額將會減少


问:
Creating symmetric weight kernels for Dense layer tensorflow
I am trying to create a weight matrix in TensorFlow as shown below

```<code>[[a, b],
 [c, b],
 [a, d]]
</code>```

where a, b, c, d are Tf.Variable. The gradient flow should change only the variables a, b, c, d. If I initialize 3 variables separately like, and then create the weight matrix w as follows:

```<code>a = tf.Variable(1., name='a', trainable=True)
b = tf.Variable(1., name='b', trainable=True)
c = tf.Variable(1., name='c', trainable=True)
d = tf.Variable(1., name='d', trainable=True)
w = tf.Variable([[a, b], [c, b], [a, d]], name='w')
</code>```

The gradient flow is not tied to the variable and tape.gradient tells None for a, b, c, d, whereas it shows gradient for w. You can check the gradients by

```<code>x = [[1., 2., 3.]]
with tf.GradientTape(persistent=True) as tape:
    y = x @ w
    loss = y
print(tape.gradient(loss, [w, a, b, c, d]))
</code>```

Is there some way to initialize the weight matrix with such constraints?

答:
Try using a list instead of tf.Variable for w, since the nested variables do not seem to be recognized:

```<code>import tensorflow as tf

a = tf.Variable(1., name='a', trainable=True)
b = tf.Variable(1., name='b', trainable=True)
c = tf.Variable(1., name='c', trainable=True)
d = tf.Variable(1., name='d', trainable=True)
w = [[a, b], [c, b], [a, d]]

x = tf.constant([[1., 2., 3.]])
with tf.GradientTape(persistent=True) as tape:
    y = x @ w
    loss = y
print(*tape.gradient(loss, w), sep='\n')
</code>```
```<code>[<tf.Tensor: shape=(), dtype=float32, numpy=4.0>, <tf.Tensor: shape=(), dtype=float32, numpy=3.0>]
[<tf.Tensor: shape=(), dtype=float32, numpy=2.0>, <tf.Tensor: shape=(), dtype=float32, numpy=3.0>]
[<tf.Tensor: shape=(), dtype=float32, numpy=4.0>, <tf.Tensor: shape=(), dtype=float32, numpy=3.0>]
</code>```

Body:
I am trying to create a weight matrix in TensorFlow as shown below

[[a, b],
 [c, b],
 [a, d]]

where a, b, c, d are Tf.Variable. The gradient flow should change only the variables a, b, c, d. If I initialize 3 variables separately like, and then create the weight matrix w as follows:

a = tf.Variable(1., name='a', trainable=True)
b = tf.Variable(1., name='b', trainable=True)
c = tf.Variable(1., name='c', trainable=True)
d = tf.Variable(1., name='d', trainable=True)
w = tf.Variable([[a, b], [c, b], [a, d]], name='w')

The gradient flow is not tied to the variable and tape.gradient tells None for a, b, c, d, whereas it shows gradient for w. You can check the gradients by

x = [[1., 2., 3.]]
with tf.GradientTape(persistent=True) as tape:
    y = x @ w
    loss = y
print(tape.gradient(loss, [w, a, b, c, d]))

Is there some way to initialize the weight matrix with such constraints?

Body:
Try using a list instead of tf.Variable for w, since the nested variables do not seem to be recognized:

import tensorflow as tf

a = tf.Variable(1., name='a', trainable=True)
b = tf.Variable(1., name='b', trainable=True)
c = tf.Variable(1., name='c', trainable=True)
d = tf.Variable(1., name='d', trainable=True)
w = [[a, b], [c, b], [a, d]]

x = tf.constant([[1., 2., 3.]])
with tf.GradientTape(persistent=True) as tape:
    y = x @ w
    loss = y
print(*tape.gradient(loss, w), sep='\n')

[<tf.Tensor: shape=(), dtype=float32, numpy=4.0>, <tf.Tensor: shape=(), dtype=float32, numpy=3.0>]
[<tf.Tensor: shape=(), dtype=float32, numpy=2.0>, <tf.Tensor: shape=(), dtype=float32, numpy=3.0>]
[<tf.Tensor: shape=(), dtype=float32, numpy=4.0>, <tf.Tensor: shape=(), dtype=float32, numpy=3.0>]


问:
It's possible to use an array of property on "item-text" in Vuetify?
```<code> <v-autocomplete
   v-model="friends"
   :disabled="isUpdating"
   :items="people"
   label="Select"
   item-text="name" <!-- use here Array ['name', 'id', 'value'] -->
   item-value="name"
  >
</code>```

It's possible to use an array of property on "text-item" in Vuetify?

答:
You can try sometime like that :

```<code>:item-text="item => `${item.name} - ${item.id} - ${item.value}`"
</code>```

Body:
 <v-autocomplete
   v-model="friends"
   :disabled="isUpdating"
   :items="people"
   label="Select"
   item-text="name"
   item-value="name"
  >

It's possible to use an array of property on "text-item" in Vuetify?

Body:
You can try sometime like that :

:item-text="item => `${item.name} - ${item.id} - ${item.value}`"


问:
Finding maximum

Given an integer n and array a. Finding maximum of (a[i]+a[j])*(j-i) with 1<=i<=n-1 and i+1<=j<=n

Example:

Input

```<code>5
1 3 2 5 4
</code>```

Output

```<code>21
</code>```

Explanation :With i=2 and j=5, we have the maximum of (a[i]+a[j])*(j-i) is (3+4)*(5-2)=21

Constraints:

```<code>n<=10^6
a[i]>0 with 1<=i<=n
</code>```

I can solve this problem with n<=10^4, but what should I do if n is too large, like the constraints?

答:
Note: Some notation for variables and the Result class in the code have been copied from @selbie's excellent answer.

Here's another O(n^2) worst-case solution with (likely provable) O(n) expected performance on random permutations and room for optimization.

Suppose [i, j] are our array bounds for an optimal pair. By the problem definition, this means all elements left of i must be strictly less than A[i], and all elements right of j must be strictly less than A[j].

This means we can compute the left-maxima of A: all elements strictly greater than all previous elements, as well as the right-maxima of A. Then, we only need to consider left endpoints from the left-maxima and right endpoints from the right-maxima.

I don't know the expectation of the product of the sizes of left and right maxima sets, but we can get an upper bound. The size of left maxima is at most the size of the longest increasing subsequence (LIS) of A. The right maxima are at most the size of the longest decreasing subsequence. These aren't independent, but I'm taking as an (unproven) assumption that the LIS and LDS lengths are inversely correlated with each other for random permutations. The right-maxima must start after the left-maxima end, so this seems like a safe assumption.

The length of the LIS for random permutations follows the Tracy-Widom distribution, so it has mean sqrt(2N) and standard deviation N^(-1/6). The expected square of the size is therefore 2N + 1/(N^1/3) so ~2N. This isn't exactly the proof we wanted, since you'd need to sum over the partial density function to be rigorous, but the LIS is already an upper bound on the left-maxima size, so I think the conclusion is still true.

C++ code (Result class and some variable names taken from selbie's post, as mentioned):

struct Result
{
    size_t i;
    size_t j;
    int64_t value;
};

Result find_best_sum_size_product(const std::vector<int>& nums)
{
    /* Given: list of positive integers nums
       Returns: Tuple with (best_i, best_j, best_product)
       where best_i and best_j maximize the product
      (nums[i]+nums[j])*(j-i) over 0 <= i < j < n

       Runtime: O(n^2) worst case,
       O(n) average on random permutations.
    */

    int n = nums.size();

    if (n < 2)
    {
        return {0,0,INT64_MIN};
    }

    std::vector<int> left_maxima_indices;
    left_maxima_indices.push_back(0);

    for (int i = 1; i < n; i++){
        if (nums.at(i) > nums.at(left_maxima_indices.back())) {
            left_maxima_indices.push_back(i);
        }
    }

    std::vector<int> right_maxima_indices;
    right_maxima_indices.push_back(n-1);

    for (int i = n-1; i >= 0; i--){
        if (nums.at(i) > nums.at(right_maxima_indices.back())) {
            right_maxima_indices.push_back(i);
        }
    }

    size_t best_i = 0;
    size_t best_j = 0;
    int64_t best_product = INT64_MIN;
    int i = 0;
    int j = 0;

    for (size_t left_idx = 0;
         left_idx < left_maxima_indices.size();
         left_idx++)
    {
        i = left_maxima_indices.at(left_idx);

        for (size_t right_idx = 0;
            right_idx < right_maxima_indices.size();
            right_idx++)
        {
            j = right_maxima_indices.at(right_idx);
            if (i == j) continue;

            int64_t value = (nums.at(i) + (int64_t)nums.at(j)) * (j - i);
            if (value > best_product)
            {
                best_product = value;
                best_i = i;
                best_j = j;
            }
        }
    }

    return { best_i, best_j, best_product };
}
```

Title: Finding maximum

Body:
Given an integer n and array a. Finding maximum of (a[i]+a[j])*(j-i) with 1<=i<=n-1 and i+1<=j<=n

Example:

Input

5
1 3 2 5 4

Output

21

Explanation :With i=2 and j=5, we have the maximum of (a[i]+a[j])*(j-i) is (3+4)*(5-2)=21

Constraints:

n<=10^6
a[i]>0 with 1<=i<=n

I can solve this problem with n<=10^4, but what should I do if n is too large, like the constraints?


问:
Print Current Module Name in Swift
How can I print the module name for a class in swift?

self.dynamicType prints only the class name without the module. How can I print the module?

答:
And yet another way to print the current module name... in Swift.

let module = String(String(reflecting: MY_SUBJECT.self).prefix { $0 != "." })
```

Title: Print Current Module Name in Swift


问:
VIM - FuzzyFinder closes on Backspace, why?
I use FuzzyFinder in VIM (cannot switch to Command-T, no Ruby support on my server). It works well, except for one issue: Whenever I hit backspace (for example, after making a typo), the entire FuzzyFinder buffer just closes.

This doesn't happen every time, only right after entering a directory. For example:

FILE>filename -- I can hit backspace just fine, and get FILE>filenam

FILE>folder/ -- if I hit backspace now, the buffer just closes. It's as if I can't navigate backwards in the hierarchy after entering a directory.

I have no idea why this happens, and it's driving me crazy. Any advice would be appreciated.

This also happens when I press Ctrl+w as it says in the fuf documentation.

答:
I've been using FuzzyFinder for a while and never faced this problem.

Possible you have some mapping that may be interfering with FuzzyFinder. You could try :map <bs> to find out if there is any mapping on backspace key, and :10verbose map <bs> to find out where such mapping was set.

You also could try :unmap <bs> and :unmap! <bs> to remove any mappings from backspace and check if the issue still exists.

If the above doesn't solve the problem you might consider contacting the plugin author, as the issue could also be related to some other mapping, as stated on FuzzyFinder changelog, :h fuf-changelog:

```<code>  - Fixed the bug that it did not work correctly when a user have mapped <C-p>
    or <Down>.
</code>```

Body:
I've been using FuzzyFinder for a while and never faced this problem.

Possible you have some mapping that may be interfering with FuzzyFinder. You could try :map <bs> to find out if there is any mapping on backspace key, and :10verbose map <bs> to find out where such mapping was set.

You also could try :unmap <bs> and :unmap! <bs> to remove any mappings from backspace and check if the issue still exists.

If the above doesn't solve the problem you might consider contacting the plugin author, as the issue could also be related to some other mapping, as stated on FuzzyFinder changelog, :h fuf-changelog:

  - Fixed the bug that it did not work correctly when a user have mapped <C-p>
    or <Down>.


问:
How to get the sentence / string with the matched substring
If the following content is given in a text file,

Text1.txt

Registered : [10-01-21]       Left : [12-02-21]

Approved : [03-03-21]         Name : Ann

Ann submitted documents. Ann checked [12-04-21]

```<code>I need to get the output as :

Registered : [10-01-21]
Left : [12-02-21]
Approved : [03-03-21]
checked [12-04-21]

As the substring, we can give a regex to validate the date format.
</code>```
```<code>import re
f1= open("Text1.txt")
string=f1.read()

found_p1=re.findall(r"(.*)\[[0-9]{2}[-][0-9][2][-][0-9]{2}\](.*)" ,string)
k=[ ]
for i in found_p1:
    i=re.sub(r"|',|'(|)", "", str(i))
</code>```

答:
try this:</p>
```<code>import re

f = open("Text1.txt")
string = f.read()

pattern = re.compile("(\w+\s\[\d{2}[-]\d{2}[-]\d{2}\]|\w+\s[:][\s]\[\d{2}[-]\d{2}[-]\d{2}\])")
m = pattern.findall(string)
for i in m:
    print(i)
</code>```

Body:
If the following content is given in a text file,

Text1.txt

Registered : [10-01-21]       Left : [12-02-21]

Approved : [03-03-21]         Name : Ann

Ann submitted documents. Ann checked [12-04-21]

I need to get the output as :

Registered : [10-01-21]
Left : [12-02-21]
Approved : [03-03-21]
checked [12-04-21]

As the substring, we can give a regex to validate the date format.

import re
f1= open("Text1.txt")
string=f1.read()

found_p1=re.findall(r"(.*)\[[0-9]{2}[-][0-9][2][-][0-9]{2}\](.*)" ,string)
k=[ ]
for i in found_p1:
    i=re.sub(r"|',|'(|)", "", str(i))

Body:
try this:

import re

f = open("Text1.txt")
string = f.read()

pattern = re.compile("(\w+\s\[\d{2}[-]\d{2}[-]\d{2}\]|\w+\s[:][\s]\[\d{2}[-]\d{2}[-]\d{2}\])")
m = pattern.findall(string)
for i in m:
    print(i)


问:
Why is my independent t-test different in SPSS or Excel?

I want to compare the output of my simulation model to the observed data in various ways, like using an independent t-test to compare the means. However, when I do the independent t-test in SPSS, I get a different result than the independent t-test in Excel. I don't know why so I don't know which one I should use. Can anybody tell me why the results are different?

Here is the independent t-test in SPSS (with t-value 0,181 and p-value 0,857):

Here is the t-test: Two-Sample Assuming Equal Variances in Excel (also the t-test assuming unequal variances is different than the one in SPSS):

答:
After running the TTest on your original data in SPSS, with the FULL data, I got perfectly matching results from spss and excel (see below).

The problem you had has to do with one case seemingly missing from your "observed" set (as noted by @TomSharpe).

This could be due to a simple error in copying the data to SPSS. In SPSS you had to have the two ranges in the same column - you may have done this manually with an error - in which case you should learn to use restructure commands, namely varstocases, to avoid such mistakes.

On the other hand, if the data is full but still a case seems to be missing from the analysis, you should check if the data is weighted by another variable. Weighted data can change the apparent number of observarions in the analysis, and of course change the results.
.


问:
How can I prevent Text suggestions in an Entry in Xamarin Forms?
Is it possible to disable text suggestions for a Xamarin.Forms entry? I expected that this is done by IsTextPredictionEnabled = false, but this value seems to have no affect on the Entry, at least as of Xamarin Forms 5.0.0.2291.

I have created a test screen with the following code:

```<code>var entry1 = new Entry();
entry1.Text = "Default";
entry1.WidthRequest = 300;
entry1.IsSpellCheckEnabled = true;
entry1.IsTextPredictionEnabled = true;
absoluteLayout.Children.Add(entry1);

var entry2 = new Entry();
entry2.IsSpellCheckEnabled = false;
entry2.IsTextPredictionEnabled = false;
entry2.Text = "No SpellCheck/Prediction";
entry2.WidthRequest = 300;
entry2.Margin = new Thickness (0, 60, 0, 0);
absoluteLayout.Children.Add(entry2);

</code>```

This produces the following behavior. Notice that both entries behave the same regardless of the IsSpellCheckEnabled or IsTextPredictionEnabled values.

According to the documentation here, this should work: https://learn.microsoft.com/en-us/dotnet/api/xamarin.forms.entry.istextpredictionenabled?view=xamarin-forms

Also here:
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/text/entry

Nothing came up in my searches to indicate that this is broken, so maybe I'm doing something wrong?

答:
Use custom renderer and try to set InputTypes as TextVariationVisiblePassword,this works well on my side.Below is the code snippets for your reference.

```<code>        Content = new StackLayout
        {
            Children = {

            new MyEntry {
                Text = "No SpellCheck/Prediction",
                IsSpellCheckEnabled= false,
                IsTextPredictionEnabled = false,
                WidthRequest=300
                }
        },
            VerticalOptions = LayoutOptions.CenterAndExpand,
            HorizontalOptions = LayoutOptions.CenterAndExpand,
        };
</code>```

MyRenderer class:

```<code>[assembly: ExportRenderer(typeof(Entry), typeof(MyRenderer))]
namespace AppTestEntry.Droid
{
class MyRenderer : EntryRenderer
{
    public MyRenderer(Context context) : base(context)
    {

    }
    protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
    {
        base.OnElementChanged(e);
        if (Control != null)
        {
            Control.InputType = Android.Text.InputTypes.TextVariationVisiblePassword;
        }
      }
    }
}
</code>```

Document for custom renderer for your reference:https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/custom-renderer/entry

Body:
Is it possible to disable text suggestions for a Xamarin.Forms entry? I expected that this is done by IsTextPredictionEnabled = false, but this value seems to have no affect on the Entry, at least as of Xamarin Forms 5.0.0.2291.

I have created a test screen with the following code:

var entry1 = new Entry();
entry1.Text = "Default";
entry1.WidthRequest = 300;
entry1.IsSpellCheckEnabled = true;
entry1.IsTextPredictionEnabled = true;
absoluteLayout.Children.Add(entry1);

var entry2 = new Entry();
entry2.IsSpellCheckEnabled = false;
entry2.IsTextPredictionEnabled = false;
entry2.Text = "No SpellCheck/Prediction";
entry2.WidthRequest = 300;
entry2.Margin = new Thickness (0, 60, 0, 0);
absoluteLayout.Children.Add(entry2);

This produces the following behavior. Notice that both entries behave the same regardless of the IsSpellCheckEnabled or IsTextPredictionEnabled values.

According to the documentation here, this should work: https://learn.microsoft.com/en-us/dotnet/api/xamarin.forms.entry.istextpredictionenabled?view=xamarin-forms

Also here:
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/text/entry

Nothing came up in my searches to indicate that this is broken, so maybe I'm doing something wrong?

Body:
Use custom renderer and try to set InputTypes as TextVariationVisiblePassword,this works well on my side.Below is the code snippets for your reference.

        Content = new StackLayout
        {
            Children = {

            new MyEntry {
                Text = "No SpellCheck/Prediction",
                IsSpellCheckEnabled= false,
                IsTextPredictionEnabled = false,
                WidthRequest=300
                }
        },
            VerticalOptions = LayoutOptions.CenterAndExpand,
            HorizontalOptions = LayoutOptions.CenterAndExpand,
        };

MyRenderer class:

[assembly: ExportRenderer(typeof(Entry), typeof(MyRenderer))]
namespace AppTestEntry.Droid
{
class MyRenderer : EntryRenderer
{
    public MyRenderer(Context context) : base(context)
    {

    }
    protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
    {
        base.OnElementChanged(e);
        if (Control != null)
        {
            Control.InputType = Android.Text.InputTypes.TextVariationVisiblePassword;
        }
      }
    }
}

Document for custom renderer for your reference:https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/custom-renderer/entry


问:
nginx returning index.html for js with 304 response
I have an nginx server that is showing a 200 response in my browser for requests like

https://server.com/app/static/js/2.8cc049f3.chunk.js

and showing a 304 on the server logs

"GET /static/js/2.8cc049f3.chunk.js HTTP/1.1" 304 0 "https://server.com/app"

There is another nginx in front of the nginx running on server.com that is removing the app from the path. Based on the nginx logs on server.com this is working correctly. The static folder is in my root /usr/share/nginx/html/.

The content my browser receives for the js file is the index.html. However when I login to the server and run

curl http://localhost/static/js/2.8cc049f3.chunk.js

I get the correct js content in response and in the logs the server prints 200

"GET /static/js/2.8cc049f3.chunk.js HTTP/1.1" 200 1570391 "-" "curl/7.80.0" "-"

Here is my nginx.conf

```<code>server {
    listen  80;
    root    /usr/share/nginx/html/;
    index   index.html;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    location / {
        try_files $uri $uri/ /index.html;
    }

    location ~ ^/(static)/  {
        gzip_static on;
        gzip_types
            text/plain
            text/xml
            text/css
            text/comma-separated-values
            text/javascript application/x-javascript
            application/atom+xml;
        expires max;
    }
}
</code>```

I've read that a 304 means the file hasn't changed and tells your browser to use its local cache, so I cleared my browser cache. I also restarted nginx, thinking that the first request would give a 200 response on the server but it was still a 304.

Based on the local curl request being successful I don't think there is anything wrong with my nginx.conf. I don't know if nginx somehow has the index.html cached as the content of my js, or if I didn't clear my browser cache correctly.

I'm also confused why the response code is 304 on the server but 200 in my browser.

答:
The HTTP 304 says "Not-Modified". This is because you are using another NGINX Proxy server in front of the NGINX Server we are talking about.

The 1st NGINX is requesting a resource on the 2nd NGINX and this one answers "Hey that file was not modified since the last time you have asked".

In this case it would be very helpful to check the configuration of the 1st NGINX Proxy instance or your turn of the caching in the first one and proxy_cache off; and check the result.

Body:
I have an nginx server that is showing a 200 response in my browser for requests like

https://server.com/app/static/js/2.8cc049f3.chunk.js

and showing a 304 on the server logs

"GET /static/js/2.8cc049f3.chunk.js HTTP/1.1" 304 0 "https://server.com/app"

There is another nginx in front of the nginx running on server.com that is removing the app from the path. Based on the nginx logs on server.com this is working correctly. The static folder is in my root /usr/share/nginx/html/.

The content my browser receives for the js file is the index.html. However when I login to the server and run

curl http://localhost/static/js/2.8cc049f3.chunk.js

I get the correct js content in response and in the logs the server prints 200

"GET /static/js/2.8cc049f3.chunk.js HTTP/1.1" 200 1570391 "-" "curl/7.80.0" "-"

Here is my nginx.conf

server {
    listen  80;
    root    /usr/share/nginx/html/;
    index   index.html;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    location / {
        try_files $uri $uri/ /index.html;
    }

    location ~ ^/(static)/  {
        gzip_static on;
        gzip_types
            text/plain
            text/xml
            text/css
            text/comma-separated-values
            text/javascript application/x-javascript
            application/atom+xml;
        expires max;
    }
}

I've read that a 304 means the file hasn't changed and tells your browser to use its local cache, so I cleared my browser cache. I also restarted nginx, thinking that the first request would give a 200 response on the server but it was still a 304.

Based on the local curl request being successful I don't think there is anything wrong with my nginx.conf. I don't know if nginx somehow has the index.html cached as the content of my js, or if I didn't clear my browser cache correctly.

I'm also confused why the response code is 304 on the server but 200 in my browser.


问:
Setting INDETERMINATE STATE on SVELTE TREEVIEW Component with CHECKBOXES?
hope you can help me figuring out this problem I have :)

Hi have a nested directory tree object that is structured in this way:

{name: 'root_folder', files: Array(6), val: true}

and if you check files you would see something like that:

```<code>0: {name: 'sub_folder1', files: Array(3), val: true}
1: {name: 'sub_folder2', files: Array(2), val: true}
2: {name: 'sub_folder3', files: Array(9), val: true}
3: {name: 'sub_folder4', files: Array(1), val: true}
4: {name: 'sub_folder5', files: Array(1), val: true}
5: {name: 'sub_folder6', files: Array(1), val: true}
</code>```

and so on and so forth until you get to "no-folder" files (of course there could also be no folder s inside this structure).

I'm developing a web app using Svelte and I could render this structure using a Treeview Component taken from here: https://v5.framework7.io/svelte/treeview.html#:~:text=%3CBlockTitle%3EWith%20checkboxes%3C/BlockTitle%3E

and what I wrote is the following:

```<code><!-- Tree_component.svelte -->

<Treeview>
{#each files as file}
    {#if file.files}
      <TreeviewItem label={file.name} iconF7="folder_fill">
        <span slot="content-start">
          <Checkbox
            indeterminate = {?????? *boolean value* ????}
            checked={file.val}
            onChange={async(e) => {

              const auto_check = (node) => {

                if(node.files){
                  node.files.forEach(obj => auto_check(obj));

                }

                node.val = e.target.checked;
              }

              file.val = e.target.checked;
              file.files.forEach(obj => auto_check(obj));
              files = files;
            }}
          />
        </span>
        <svelte:self {...file}/>

      </TreeviewItem>
      {:else}
      <TreeviewItem label={file.name1} iconF7="chevron_left_slash_chevron_right">
        <span slot="content-start">
          <Checkbox
            checked={file.val}
            onChange={(e) => {
              file['val'] = e.target.checked;
            }}
          />
        </span>
      </TreeviewItem>
    {/if}
{/each}
</Treeview>
</code>```

As you can see I could recursively set the check value  all the way through the structure using recursively the auto_check  function.

I'm having some issues to set the "indeterminate" state of the folder checkboxes when I have only a few element of the structure checked, wether they are the last files or the folder in between the structure.

Could someone help me to solve this problem? Thank you in advance :D

答:
You would need to check if any children but not all are checked. Something along these lines:

let indeterminate
$: {
  // Get the number of files that is checked
  const count = file.files.filter(f => f.val).length;
  indeterminate = count != 0 && count != file.files.length;
}
```

I would advice to put this in the script block to not clutter your markup, it might be a good idea to the same with your event handler to improve readability.

Body:
hope you can help me figuring out this problem I have :)

Hi have a nested directory tree object that is structured in this way:

{name: 'root_folder', files: Array(6), val: true}

and if you check files you would see something like that:

0: {name: 'sub_folder1', files: Array(3), val: true}
1: {name: 'sub_folder2', files: Array(2), val: true}
2: {name: 'sub_folder3', files: Array(9), val: true}
3: {name: 'sub_folder4', files: Array(1), val: true}
4: {name: 'sub_folder5', files: Array(1), val: true}
5: {name: 'sub_folder6', files: Array(1), val: true}

and so on and so forth until you get to "no-folder" files (of course there could also be no folder s inside this structure).

I'm developing a web app using Svelte and I could render this structure using a Treeview Component taken from here: https://v5.framework7.io/svelte/treeview.html#:~:text=%3CBlockTitle%3EWith%20checkboxes%3C/BlockTitle%3E

and what I wrote is the following:

<Treeview>
{#each files as file}
    {#if file.files}
      <TreeviewItem label={file.name} iconF7="folder_fill">

          <Checkbox
            indeterminate = {?????? *boolean value* ????}
            checked={file.val}
            onChange={async(e) => {

              const auto_check = (node) => {

                if(node.files){
                  node.files.forEach(obj => auto_check(obj));

                }

                node.val = e.target.checked;
              }

              file.val = e.target.checked;
              file.files.forEach(obj => auto_check(obj));
              files = files;
            }}
          />

        <svelte:self {...file}/>

      </TreeviewItem>
      {:else}
      <TreeviewItem label={file.name1} iconF7="chevron_left_slash_chevron_right">

          <Checkbox
            checked={file.val}
            onChange={(e) => {
              file['val'] = e.target.checked;
            }}
          />

      </TreeviewItem>
    {/if}
{/each}
</Treeview>

As you can see I could recursively set the check value  all the way through the structure using recursively the auto_check  function.

I'm having some issues to set the "indeterminate" state of the folder checkboxes when I have only a few element of the structure checked, wether they are the last files or the folder in between the structure.

Could someone help me to solve this problem? Thank you in advance :D

Body:
You would need to check if any children but not all are checked. Something along these lines:

let indeterminate
$: {
  // Get the number of files that is checked
  const count = file.files.filter(f => f.val).length;
  indeterminate = count != 0 && count != file.files.length;
}

I would advice to put this in the script block to not clutter your markup, it might be a good idea to the same with your event handler to improve readability.


问:
Why can't I create an array of automatic variables?
In C++0x (ohh! read C++11), we have automatic type inference. One thing which made me curious was that I can't create an array of auto variables. For example:

```<code>auto A[] = {1, 2, 3, 4}; // Error!
</code>```

Any ideas why this might have been disallowed?

答: Because {1, 2, 3, 4} is purely a syntactic construct- it is not an expression and does not have a type. Therefore, auto cannot deduce its type from it.

Body:
In C++0x (ohh! read C++11), we have automatic type inference. One thing which made me curious was that I can't create an array of auto variables. For example:

auto A[] = {1, 2, 3, 4}; // Error!

Any ideas why this might have been disallowed?


问:
Detect click on text in contenteditable div
I would like to allow editing of text when actual text is clicked. The rest of the white space I need for a dragging functionality.

Is there any way to detect when mouse clicks on text instead of white space in a contenteditable div?

Is there maybe some CSS I can add to a div that would wrap around the text and not the whitespace? Or is there some Javascript that can tell when user clicked on text.

```<code>      <div class="container">
        <div class="textbox" contenteditable="true"></div>
      </div>
</code>```
```<code>            .container{
              min-width: 100px;
              width: min-content;
              height: min-content;
              padding: 10px;
              border: 1px solid black;
            }

            .textbox{
              min-width: 100px;
              width: min-content;
            }
</code>```

答:
One solution would be to insert each text in a
 tag. The
 will extend on the whole with of the container. Inside
, i would wrap each part of text in a  tag. So whenever the users clicks on the text, the target of the event would be the span element, and when the users clicks on the whitespace, the target of the event would be a p element.

```<code>document.querySelector(".container").addEventListener("click", function(e){
  if(e.target.localName == "p") {
    //whitespace
  }
  if(e.target.localName == "span") {
    //text
 }
});
</code>```

Body:
I would like to allow editing of text when actual text is clicked. The rest of the white space I need for a dragging functionality.

Is there any way to detect when mouse clicks on text instead of white space in a contenteditable div?

Is there maybe some CSS I can add to a div that would wrap around the text and not the whitespace? Or is there some Javascript that can tell when user clicked on text.

            .container{
              min-width: 100px;
              width: min-content;
              height: min-content;
              padding: 10px;
              border: 1px solid black;
            }

            .textbox{
              min-width: 100px;
              width: min-content;
            }

Body:
One solution would be to insert each text in a <p> tag. The <p> will extend on the whole with of the container. Inside <p>, i would wrap each part of text in a <span> tag. So whenever the users clicks on the text, the target of the event would be the span element, and when the users clicks on the whitespace, the target of the event would be a p element.

document.querySelector(".container").addEventListener("click", function(e){
  if(e.target.localName == "p") {
    //whitespace
  }
  if(e.target.localName == "span") {
    //text
 }
});


问:
Azure DevOps API Authentication
I would like to use the Azure DevOps API to create a PAT for my user. But I'm unable to authenticate yet. In this document from Microsoft, they state that authentication is possible with a PAT, but it is not true. I'm getting a HTTP 203 with a Sign In page in response.

PS: I'm using Postman to test the API requests.

答:
I think the security section of this REST API is misleading.

In fact, this REST API cannot be authenticated with PAT, as mentioned in another document:

To use the API, you must authenticate with an Azure AD token.

Unlike other Azure DevOps Services APIs, users must provide an Azure AD access token to use this API instead of a PAT token. Azure AD tokens are a safer authentication mechanism than using PATs. Given this API’s ability to create and revoke PATs, we want to ensure that such powerful functionality is given to allowed users only.

This document also explains how to use this REST API in detail, which you can refer to.

Title: Azure DevOps API Authentication


问:
Speed up solving time of this function
This function is working fine but it takes too much time to solve. Please suggest me how to improve the solving time.

```<code>from sympy.solvers import solve
from sympy import Symbol

QD = 25.45
CDI = 0.65
AIN = 33.6
GTL = 10
GTSELV = 2300.1
CDGT = 1.9

def fun(HWE):
    TWE = Symbol('TWE')
    expression = (CDI*AIN*(2*9.81*(HWE-TWE))**0.5) - (CDGT*GTL*(TWE-GTSELV)**1.5)-QD
    solution = solve(expression)
    return solution
</code>```

Function fun(2303) gives [2302.23386564786] which is correct but solving time is about 30 seconds. I need to run this for many arguments.

答:
The dReal system can handle these sorts of problems, using the notion of delta-satisfiability. (See http://dreal.github.io for details.)

This is how your program is coded using dReal's Python interface (To install, see the notes at https://github.com/dreal/dreal4#python-binding):

from dreal import *

QD     = 25.45
CDI    = 0.65
AIN    = 33.6
GTL    = 10
GTSELV = 2300.1
CDGT   = 1.9

def fun(HWE):
    TWE = Variable("TWE")
    expression = (CDI*AIN*(2*9.81*(HWE-TWE))**0.5) - (CDGT*GTL*(TWE-GTSELV)**1.5)-QD
    return (expression == 0)

result = CheckSatisfiability(fun(2303), 0.001)
print(result)
```
<p>When I run it on my now 3 year old computer, I get:</p>
```$ time python a.py
TWE : [2302.2338656478555, 2302.2338656478582]
python3 a.py  0.03s user 0.01s system 92% cpu 0.044 total
```
<p>So, it takes about 0.044 seconds to go through, which does include loading the entire Python echo-system. (So, if you run many problems one after another, each instance should go even faster.)</p>
<p>Note that dReal shows you an interval for the acceptable solution, within a user-specified numerical error bound. The bound is the second argument to <code>CheckSatisfiability</code>, which we set at <code>0.001</code> for this problem. You can increase this precision at the cost of potentially more computation time, but looks like <code>0.001</code> seems to be doing quite well in this case. Also note that you get an "interval" for the solution for each variable. If you increase the precision, this interval might get smaller. For instance, when I change the call to:</p>
<pre class="lang-py prettyprint-override"><code>result = CheckSatisfiability(fun(2303), 0.0000000000001)
</code>```

I get:

```<code>$ time python a.py
TWE : [2302.2338656478569, 2302.2338656478569]
python3 a.py  0.03s user 0.01s system 84% cpu 0.050 total
</code>```

where the interval has reduced to a single-point, but the program took slightly longer to run. For each problem, you should experiment with an appropriate delta to make sure the interval you get for the results is reasonable.

Title: Speed up solving time of this function

Body:
This function is working fine but it takes too much time to solve. Please suggest me how to improve the solving time.

from sympy.solvers import solve
from sympy import Symbol

QD = 25.45
CDI = 0.65
AIN = 33.6
GTL = 10
GTSELV = 2300.1
CDGT = 1.9

def fun(HWE):
    TWE = Symbol('TWE')
    expression = (CDI*AIN*(2*9.81*(HWE-TWE))**0.5) - (CDGT*GTL*(TWE-GTSELV)**1.5)-QD
    solution = solve(expression)
    return solution

Function fun(2303) gives [2302.23386564786] which is correct but solving time is about 30 seconds. I need to run this for many arguments.

Body:
The dReal system can handle these sorts of problems, using the notion of delta-satisfiability. (See http://dreal.github.io for details.)

This is how your program is coded using dReal's Python interface (To install, see the notes at https://github.com/dreal/dreal4#python-binding):

from dreal import *

QD     = 25.45
CDI    = 0.65
AIN    = 33.6
GTL    = 10
GTSELV = 2300.1
CDGT   = 1.9

def fun(HWE):
    TWE = Variable("TWE")
    expression = (CDI*AIN*(2*9.81*(HWE-TWE))**0.5) - (CDGT*GTL*(TWE-GTSELV)**1.5)-QD
    return (expression == 0)

result = CheckSatisfiability(fun(2303), 0.001)
print(result)

When I run it on my now 3 year old computer, I get:

$ time python a.py
TWE : [2302.2338656478555, 2302.2338656478582]
python3 a.py  0.03s user 0.01s system 92% cpu 0.044 total

So, it takes about 0.044 seconds to go through, which does include loading the entire Python echo-system. (So, if you run many problems one after another, each instance should go even faster.)

Note that dReal shows you an interval for the acceptable solution, within a user-specified numerical error bound. The bound is the second argument to CheckSatisfiability, which we set at 0.001 for this problem. You can increase this precision at the cost of potentially more computation time, but looks like 0.001 seems to be doing quite well in this case. Also note that you get an "interval" for the solution for each variable. If you increase the precision, this interval might get smaller. For instance, when I change the call to:

result = CheckSatisfiability(fun(2303), 0.0000000000001)

I get:

$ time python a.py
TWE : [2302.2338656478569, 2302.2338656478569]
python3 a.py  0.03s user 0.01s system 84% cpu 0.050 total

where the interval has reduced to a single-point, but the program took slightly longer to run. For each problem, you should experiment with an appropriate delta to make sure the interval you get for the results is reasonable.


问:
Migrating from Provider to Riverpod
I am stuck using Provider and came across Riverpod which is just the next gen of Provider. I am trying to create a StreamProvider using Riverpod but I am getting an error.

Here is the code for creating the StreamProvider:

```<code>final trxnStreamProvider = StreamProvider.autoDispose<List<Trxns>>((ref) {
  final stream = firestoreService.getAgencyTrxns();
  return stream.map((snapshot) => snapshot.docs.map((doc) => Trxns.fromFirestore(doc.data)).toList());
});
</code>```

The error I get marks the code "doc.data". Here is the error text:

```<code>The argument type 'Object? Function()' can't be assigned to the parameter type 'Map<String, dynamic>'.
</code>```

Here is the code for "Trxns.fromFirestore(doc.data)":

```<code>Trxns.fromFirestore(Map<String, dynamic> firestore)
      : clientFName = firestore['clientFName'],
        clientLName = firestore['clientLName'];
</code>```

I'm still new to this and am having a hard time understanding the error message. Is it saying that "doc.data" is not the right type? If so, how do I fix this? If not, what is wrong and how do I fix it?

答:
```<code>Map<String, dynamic> data() => dartify(jsObject.data());
</code>```

data is a method so you need to call it:

```<code>doc.data()
</code>```

doc.data mean you want to pass a function

Title: Migrating from Provider to Riverpod

Body:
I am stuck using Provider and came across Riverpod which is just the next gen of Provider. I am trying to create a StreamProvider using Riverpod but I am getting an error.

Here is the code for creating the StreamProvider:

final trxnStreamProvider = StreamProvider.autoDispose<List<Trxns>>((ref) {
  final stream = firestoreService.getAgencyTrxns();
  return stream.map((snapshot) => snapshot.docs.map((doc) => Trxns.fromFirestore(doc.data)).toList());
});

The error I get marks the code "doc.data". Here is the error text:

The argument type 'Object? Function()' can't be assigned to the parameter type 'Map<String, dynamic>'.

Here is the code for "Trxns.fromFirestore(doc.data)":

Trxns.fromFirestore(Map<String, dynamic> firestore)
      : clientFName = firestore['clientFName'],
        clientLName = firestore['clientLName'];

I'm still new to this and am having a hard time understanding the error message. Is it saying that "doc.data" is not the right type? If so, how do I fix this? If not, what is wrong and how do I fix it?

Body:
Map<String, dynamic> data() => dartify(jsObject.data());

data is a method so you need to call it:

doc.data()

doc.data mean you want to pass a function


问:
How to execute a command when clicking a button (discord.net)?
I want to execute my Task "test1", when the Button "Spieler moven" is clicked. How do i do that? Currently you write !test1 and than it executes.
So a player clicks the button "Spieler moven" and the task "test1" gets executed.

```<code>[Command("spawner")]
        public async Task Spawn()
        {
            var builder = new ComponentBuilder()
                .WithButton("Spieler moven", "1", ButtonStyle.Success);

        await ReplyAsync("Welche Option willst du ausführen?", components: builder.Build());

    }

 public async Task Test1()
    {

        var user = Context.User as SocketGuildUser;

        var Queuelist = Context.Guild.GetVoiceChannel(936628853340778506).Users; //Checke ob jemand in der Warteschlange ist
        bool Queue = false; //Standardmäßig Niemand in der Queue
        foreach (var u in Queuelist)
        {
            Queue = true;
        }
        if (Queue == true)
        {

               var VoiceUsers = Context.Guild.GetVoiceChannel(936628853340778507).Users; // Checke ob Support 1 besetzt ist
            bool sup1 = false;
            foreach (var u in VoiceUsers)
            {
            bool supporter = u.Equals(Context.User); // Checke ob der Supporter selbst in Support 1 ist
                if (supporter == false)
                    sup1 = true;

            }

            if (sup1 == false)
            {
                await user.ModifyAsync(x => { x.ChannelId = 936628853340778507; }); //Move zu Support 1
            }
            else
            {
                await user.ModifyAsync(x => { x.ChannelId = 936628853340778508; }); //Support 1 ist voll, move zu Support 2
            }

        } else
            await ReplyAsync("" + Context.Message.Author.Mention + ", es befindet sich niemand bei Tränix :c");

    }
</code>```

Thanks beforehand

答:
You can listen to the InteractionCreated Event and then trigger your Task from there on.

I'm handling my buttons this way, but there might be an easier solution today as this code was made about 3 months ago.

        public HandlingService(IServiceProvider services)
        {
            _client = services.GetRequiredService<DiscordSocketClient>();

            _client.InteractionCreated += HandleInteractionCreated;
        }

```
<pre class="lang-cs prettyprint-override"><code>        private async Task HandleInteractionCreated(SocketInteraction interaction)
        {
            switch (interaction.Type)
            {
                case InteractionType.ApplicationCommand:
                    //Handle SlashCommands
                    break;
                case InteractionType.ApplicationCommandAutocomplete:
                    //Handle Autocomplete
                    break;
                case InteractionType.MessageComponent:
                    MessageComponentHandlingService.MessageComponentHandler(interaction)
                    break;
                default: // We dont support it
                    Console.WriteLine("Unsupported interaction type: " + interaction.Type);
                    break;
            }
        }

</code>```

    class MessageComponentHandlingService
    {
        public static async Task MessageComponentHandler(SocketInteraction interaction)
        {
             var parsedArg = (SocketMessageComponent)interaction;
             switch (parsedArg.Data.CustomId)
             {
                  case "Spieler moven": //maybe also "spieler moven" Here you have to insert the costom ID of the button
                  await Test1()
                      break;
             }
        }
    }
```

Body:
I want to execute my Task "test1", when the Button "Spieler moven" is clicked. How do i do that? Currently you write !test1 and than it executes.
So a player clicks the button "Spieler moven" and the task "test1" gets executed.

[Command("spawner")]
        public async Task Spawn()
        {
            var builder = new ComponentBuilder()
                .WithButton("Spieler moven", "1", ButtonStyle.Success);

        await ReplyAsync("Welche Option willst du ausführen?", components: builder.Build());

    }

 public async Task Test1()
    {

        var user = Context.User as SocketGuildUser;

        var Queuelist = Context.Guild.GetVoiceChannel(936628853340778506).Users; //Checke ob jemand in der Warteschlange ist
        bool Queue = false; //Standardmäßig Niemand in der Queue
        foreach (var u in Queuelist)
        {
            Queue = true;
        }
        if (Queue == true)
        {

               var VoiceUsers = Context.Guild.GetVoiceChannel(936628853340778507).Users; // Checke ob Support 1 besetzt ist
            bool sup1 = false;
            foreach (var u in VoiceUsers)
            {
            bool supporter = u.Equals(Context.User); // Checke ob der Supporter selbst in Support 1 ist
                if (supporter == false)
                    sup1 = true;

            }

            if (sup1 == false)
            {
                await user.ModifyAsync(x => { x.ChannelId = 936628853340778507; }); //Move zu Support 1
            }
            else
            {
                await user.ModifyAsync(x => { x.ChannelId = 936628853340778508; }); //Support 1 ist voll, move zu Support 2
            }

        } else
            await ReplyAsync("" + Context.Message.Author.Mention + ", es befindet sich niemand bei Tränix :c");

    }

Thanks beforehand

Body:
You can listen to the InteractionCreated Event and then trigger your Task from there on.

I'm handling my buttons this way, but there might be an easier solution today as this code was made about 3 months ago.

        public HandlingService(IServiceProvider services)
        {
            _client = services.GetRequiredService<DiscordSocketClient>();

            _client.InteractionCreated += HandleInteractionCreated;
        }

        private async Task HandleInteractionCreated(SocketInteraction interaction)
        {
            switch (interaction.Type)
            {
                case InteractionType.ApplicationCommand:
                    //Handle SlashCommands
                    break;
                case InteractionType.ApplicationCommandAutocomplete:
                    //Handle Autocomplete
                    break;
                case InteractionType.MessageComponent:
                    MessageComponentHandlingService.MessageComponentHandler(interaction)
                    break;
                default: // We dont support it
                    Console.WriteLine("Unsupported interaction type: " + interaction.Type);
                    break;
            }
        }

    class MessageComponentHandlingService
    {
        public static async Task MessageComponentHandler(SocketInteraction interaction)
        {
             var parsedArg = (SocketMessageComponent)interaction;
             switch (parsedArg.Data.CustomId)
             {
                  case "Spieler moven": //maybe also "spieler moven" Here you have to insert the costom ID of the button
                  await Test1()
                      break;
             }
        }
    }


问:
which authentication encryption type is recommanded?
from the dev document, i got that opengauss support several encryption type for cleint authentication:

md5

sha256 (as default)

local is a Unix domain socket. host is a common or SSL-encrypted TCP/IP socket. hostssl is an SSL-encrypted TCP/IP socket. hostnossl is a TCP/IP-only socket.
authmehod-options is an optional parameter. Value range:

As i know that md5 is not safe enough?
so why opengauss still support it, which authentication encryption type is recommanded ?

答:
for your question, i guess openGauss have to sovle compatibility issue.
that is there are many old version deploying in customer's env, they may use the md5 encryption type.

so that openGauss can not delete the type directly.

then use sha256 authentication encryption as default for secure;
use md5 for compatibility, but better make sure use it in trusted network.


问:
Problem with "this" in JS
Consider the following code:

```<code>    var table = function () {

        return {
            _init: function (tableId) {
                this.tableId = tableId;
                this.table = $("#" + tableId);
            },

            removeStripes: function() {
                this.table.find(".alt").removeClass("alt");
            },

            addStripes: function () {
                this.table.find("tbody tr:even").addClass("alt");
            },

            resetStripes: function() {
                this.removeStripes();
                this.addStripes();
            },

            sort: function (options) {
                this.table.tablesorter(options);
                this.table.bind("sortEnd", this.resetStripes);
            },

        }

    }

var newTable = new table();
newTable._init("tableId");
var options = {};
newTable.sort(options);
</code>```

The browser says this.removeStripes called by this.resetStripes, on one of the last lines) is not a function. I guess there is some error with this, but I can't figure out where it is. Any idea, anyone?

答: Try removing coma (,) after declaration of sort function. This will probably not solve your problem, but it will 'compile' under ie<7.</p>

Title: Problem with "this" in JS

Body:
Consider the following code:

    var table = function () {

        return {
            _init: function (tableId) {
                this.tableId = tableId;
                this.table = $("#" + tableId);
            },

            removeStripes: function() {
                this.table.find(".alt").removeClass("alt");
            },

            addStripes: function () {
                this.table.find("tbody tr:even").addClass("alt");
            },

            resetStripes: function() {
                this.removeStripes();
                this.addStripes();
            },

            sort: function (options) {
                this.table.tablesorter(options);
                this.table.bind("sortEnd", this.resetStripes);
            },

        }

    }

var newTable = new table();
newTable._init("tableId");
var options = {};
newTable.sort(options);

The browser says this.removeStripes called by this.resetStripes, on one of the last lines) is not a function. I guess there is some error with this, but I can't figure out where it is. Any idea, anyone?


问:
Rails 6 + Webpacker + jQuery + jGrowl is not working
I am using Rails 6. I am having problems with getting js plugins working. I am trying to add jGrowl.

This what I have tried:

```<code>yarn install jgrowl
</code>```

This is how my application.js file looks like:

```<code>import 'jquery'
import 'jgrowl'
</code>```

This is how my environment.js file looks like:

```<code>const { environment } = require('@rails/webpacker');

const webpack = require('webpack');
environment.plugins.append('Provide', new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery'
}));

module.exports = environment;
</code>```

What am I missing?

答:
You need to initialize jQuery. Add the following code to application.js

import jQuery from 'jquery'
window.$ = jQuery
window.jQuery = jQuery```

Body:
I am using Rails 6. I am having problems with getting js plugins working. I am trying to add jGrowl.

This what I have tried:

yarn install jgrowl

This is how my application.js file looks like:

import 'jquery'
import 'jgrowl'

This is how my environment.js file looks like:

const { environment } = require('@rails/webpacker');

const webpack = require('webpack');
environment.plugins.append('Provide', new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery'
}));

module.exports = environment;

What am I missing?


问:
How to compare large text files?
I have a general question on your opinion about my "technique".

There are 2 textfiles (file_1 and file_2) that need to be compared to each other. Both are very huge (3-4 gigabytes, from 30,000,000 to 45,000,000 lines each).
My idea is to read several lines (as many as possible) of file_1 to the memory, then compare those to all lines of file_2. If there's a match, the lines from both files that match shall be written to a new file. Then go on with the next 1000 lines of file_1 and also compare those to all lines of file_2 until I went through file_1 completely.

But this sounds actually really, really time consuming and complicated to me.
Can you think of any other method to compare those two files?

How long do you think the comparison could take?
For my program, time does not matter that much. I have no experience in working with such huge files, therefore I have no idea how long this might take. It shouldn't take more than a day though. ;-) But I am afraid my technique could take forever...

Antoher question that just came to my mind: how many lines would you read into the memory? As many as possible? Is there a way to determine the number of possible lines before actually trying it?
I want to read as many as possible (because I think that's faster) but I've ran out of memory quite often.

Thanks in advance.

EDIT
I think I have to explain my problem a bit more.

The purpose is not to see if the two files in general are identical (they are not).
There are some lines in each file that share the same "characteristic".
Here's an example:
file_1 looks somewhat like this:

```<code>mat1 1000 2000 TEXT      //this means the range is from 1000 - 2000
mat1 2040 2050 TEXT
mat3 10000 10010 TEXT
mat2 20 500 TEXT
</code>```

file_2looks like this:

```<code>mat3 10009 TEXT
mat3 200 TEXT
mat1 999 TEXT
</code>```

TEXT refers to characters and digits that are of no interest for me, mat can go from mat1 - mat50 and are in no order; also there can be 1000x mat2 (but the numbers in the next column are different). I need to find the fitting lines in a way that: matX is the same in both compared lines an the number mentioned in file_2 fits into the range mentioned in file_1.
So in my example I would find one match: line 3 of file_1and line 1 of file_2 (because both are mat3 and 10009 is between 10000 and 10010).
I hope this makes it clear to you!

So my question is: how would you search for the matching lines?

Yes, I use Java as my programming language.

EDIT
I now divided the huge files first so that I have no problems with being out of memory. I also think it is faster to compare (many) smaller files to each other than those two huge files. After that I can compare them the way I mentioned above. It may not be the perfect way, but I am still learning ;-)
Nonentheless all your approaches were very helpful to me, thank you for your replies!

答: No sure how good an answer this would be - but have a look at this page: http://c2.com/cgi/wiki?DiffAlgorithm - it summarises a few diff algorithms.  Hunt-McIlroy algorithm is probably the better implementation.  From that page there's also a link to a java implementation of the GNU diff. However, I think an implementation in C/C++ and compiled into native code will be much faster.  If you're stuck with java, you may want to consider JNI.</p>

Title: How to compare large text files?

Body:
I have a general question on your opinion about my "technique".

There are 2 textfiles (file_1 and file_2) that need to be compared to each other. Both are very huge (3-4 gigabytes, from 30,000,000 to 45,000,000 lines each).
My idea is to read several lines (as many as possible) of file_1 to the memory, then compare those to all lines of file_2. If there's a match, the lines from both files that match shall be written to a new file. Then go on with the next 1000 lines of file_1 and also compare those to all lines of file_2 until I went through file_1 completely.

But this sounds actually really, really time consuming and complicated to me.
Can you think of any other method to compare those two files?

How long do you think the comparison could take?
For my program, time does not matter that much. I have no experience in working with such huge files, therefore I have no idea how long this might take. It shouldn't take more than a day though. ;-) But I am afraid my technique could take forever...

Antoher question that just came to my mind: how many lines would you read into the memory? As many as possible? Is there a way to determine the number of possible lines before actually trying it?
I want to read as many as possible (because I think that's faster) but I've ran out of memory quite often.

Thanks in advance.

EDIT
I think I have to explain my problem a bit more.

The purpose is not to see if the two files in general are identical (they are not).
There are some lines in each file that share the same "characteristic".
Here's an example:
file_1 looks somewhat like this:

mat1 1000 2000 TEXT      //this means the range is from 1000 - 2000
mat1 2040 2050 TEXT
mat3 10000 10010 TEXT
mat2 20 500 TEXT

file_2looks like this:

mat3 10009 TEXT
mat3 200 TEXT
mat1 999 TEXT

TEXT refers to characters and digits that are of no interest for me, mat can go from mat1 - mat50 and are in no order; also there can be 1000x mat2 (but the numbers in the next column are different). I need to find the fitting lines in a way that: matX is the same in both compared lines an the number mentioned in file_2 fits into the range mentioned in file_1.
So in my example I would find one match: line 3 of file_1and line 1 of file_2 (because both are mat3 and 10009 is between 10000 and 10010).
I hope this makes it clear to you!

So my question is: how would you search for the matching lines?

Yes, I use Java as my programming language.

EDIT
I now divided the huge files first so that I have no problems with being out of memory. I also think it is faster to compare (many) smaller files to each other than those two huge files. After that I can compare them the way I mentioned above. It may not be the perfect way, but I am still learning ;-)
Nonentheless all your approaches were very helpful to me, thank you for your replies!


问:
AlarmManager + Dynamic broadcast cannot be received

The dynamic registration broadcast in the code cannot be received, why?why?why?

Register the broadcast in AndroidManifest.xml and receive it normally

```<code>AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
Intent i = new Intent(context, MyReceiver.class);
i.setAction("test_action");
PendingIntent pIntent = PendingIntent.getBroadcast(context, PendingIntent.FLAG_UPDATE_CURRENT, i, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 10 * 6000, pIntent);
</code>```

答:
ELAPSED_REALTIME_WAKEUP flag determines time when alarm will be triggered - in your case 10 * 6000 millis after device boot! your code is running probably after this moment, so you are setting alarm in the past...

try to add current SystemClock.elapsedRealtime() to your 10 * 6000 for getting moment in the future (1 min after code execution and alarm set up)

```<code>alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
    SystemClock.elapsedRealtime() + 60 * 1000, pIntent);
</code>```

Body:
The dynamic registration broadcast in the code cannot be received, why?why?why?

Register the broadcast in AndroidManifest.xml and receive it normally

AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
Intent i = new Intent(context, MyReceiver.class);
i.setAction("test_action");
PendingIntent pIntent = PendingIntent.getBroadcast(context, PendingIntent.FLAG_UPDATE_CURRENT, i, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 10 * 6000, pIntent);

Body:
ELAPSED_REALTIME_WAKEUP flag determines time when alarm will be triggered - in your case 10 * 6000 millis after device boot! your code is running probably after this moment, so you are setting alarm in the past...

try to add current SystemClock.elapsedRealtime() to your 10 * 6000 for getting moment in the future (1 min after code execution and alarm set up)

alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
    SystemClock.elapsedRealtime() + 60 * 1000, pIntent);


问:
Visual Studio Code is changing HTML after saving (React)
I started to  learn react. A few minutes later messed up. I was looking for a setting and somehow I come where else where i selected a different choice(something like NodeJS)...now my problem is:

First Image

Second Image

First image is what I wrote. Second image is what it became after saving(CTRL + S).

Third Image

This third image is the changed original template...

I tried to reinstall VS Code and deleting the settings(user/json) file nothing has changed. Does anyone know how to fix this problem.

Any help is appreciated :P

答: I got that error too try renaming js files to jsx or


问:
How to predictably run shell script in unknown user environment?

Summary

How can I guarantee that my shell scripts will do what I expect, regardless of the environment?

(Let's assume that people have alias'd and function'd everything they can, but that they haven't touched any system binaries eg. /bin/ls)

Explanation

I am distributing shell scripts as part of an app. These shell scripts are executed in the user's environment - this cannot be changed.

This means users may have aliases for anything and functions redefining "standard" behavior. There have already been a few cases when normal shell keywords have been redefined (eg. local), causing unexpected side effects and crashes.

The only tokens that cannot be defined as functions are as follows:

Bash:

!  [[  ]]  case  coproc  do  done  elif  else  esac  fi  for  function  if  in  select  then  time  until  while  {  }
```
<p>ZSH:</p>
```!  [[  case  coproc  do  done  elif  else  end  esac  fi  for  foreach  function  if  nocorrect  repeat  select  then  time  until  while  { }
```

I am aware that:

You can escape a word to skip alias lookup

You can use builtin to always run a builtin

You can use command to always run a command

However, builtin and command can be redefined, so \builtin <command> may not always do what I expect.

答:
Aliases are not expanded in bash scripts (unless you explicitly request this), and functions are usually not inherited by child processes. The caller of your script just has to avoid sourcing it. Problems could be environment variables and file handles.

It is difficult to make a script completely self-containing. For instance, I have seen cases where even standard programs (ls, cat,....) are stored in different locations, which means that if you set up your own PATH and don't know anything about the target platform, you have to apply some heuristics (searching a list of "commonly known directories") and hope that your search is correct.

A more reliable way would be to require from the user of the script to provide a certain minimal configuration (typically containing the basic definition for a PATH) and pass this configuration as parameter to your script.

There is one problem pointed out in the comment by Renaud Pacalet, in that bash allows functions to be exported (using export -f), and in bash, you would have to find out which functions exist, and explicitly remove their definitions (similarily as you would do it with environment variables). However, I see that you have tagged your question by bash and zsh, and if you don't mind, which script language you are using, writing the script in zsh would be perhaps better, because zsh does not have exported functions.

One point to keep in mind is, that every shell, bash and zsh, processes on startup certain files, before the commands in your script have any chance to run. For instance, no matter how you start your zsh, it will always process /etc/zshenv.  For instance, if your script at one point invokes a zsh child script too, it would again run /etc/zshenv.

Of course, those startup files could set up functions, and in zsh, aliases are (AFIK) even expanded inside scripts. The strategy would be therefore to initially loop over your environment variables, the currently defined functions, the currently defined aliases (in zsh), and remove those definitions. Then you set up your own definitions (functions, variables).

Body:
Summary

How can I guarantee that my shell scripts will do what I expect, regardless of the environment?

(Let's assume that people have alias'd and function'd everything they can, but that they haven't touched any system binaries eg. /bin/ls)

Explanation

I am distributing shell scripts as part of an app. These shell scripts are executed in the user's environment - this cannot be changed.

This means users may have aliases for anything and functions redefining "standard" behavior. There have already been a few cases when normal shell keywords have been redefined (eg. local), causing unexpected side effects and crashes.

The only tokens that cannot be defined as functions are as follows:

Bash:

!  [[  ]]  case  coproc  do  done  elif  else  esac  fi  for  function  if  in  select  then  time  until  while  {  }

ZSH:

!  [[  case  coproc  do  done  elif  else  end  esac  fi  for  foreach  function  if  nocorrect  repeat  select  then  time  until  while  { }

I am aware that:

You can escape a word to skip alias lookup

You can use builtin to always run a builtin

You can use command to always run a command

However, builtin and command can be redefined, so \builtin <command> may not always do what I expect.


问:
How to fix wrong link in CONTRIBUTING.md in a github repository?
When you have a github repository you might have a file CONTRIBUTING.md which describes how users can contribute to this project.

In a file CONTRIBUTING.md in one of our groups repositories the following raw text

```<code>Please do not hesitate to raise an issue on [github project page][github].
</code>```

creates the text

```<code>Please do not hesitate to raise an issue on github project page.
</code>```

where github project page is a link that leads to a different github repository!

So the internal link [github] (or what this is) leads to a different repository. I also do not understand what the two square brackets together mean

```<code>[github project page][github]
</code>```

as a link usually is created with a normal and a square bracket

```<code>[GitHub Pages](https://pages.github.com/)
</code>```

The project has been renamed, but the link leads to a completely different github repository.

How can I fix this? How can I change the link of the internal link [github]? Or where can I find documentation about this feature?

答:
It turns out it is a kind of reference defined at the end of the file!

So for the above example you can define this reference at the end of your file as follows:

```<code>[github]: https://github.com/YourGroup/YourRepo
</code>```

Not sure this is documented.

Body:
When you have a github repository you might have a file CONTRIBUTING.md which describes how users can contribute to this project.

In a file CONTRIBUTING.md in one of our groups repositories the following raw text

Please do not hesitate to raise an issue on [github project page][github].

creates the text

Please do not hesitate to raise an issue on github project page.

where github project page is a link that leads to a different github repository!

So the internal link [github] (or what this is) leads to a different repository. I also do not understand what the two square brackets together mean

[github project page][github]

as a link usually is created with a normal and a square bracket

[GitHub Pages](https://pages.github.com/)

The project has been renamed, but the link leads to a completely different github repository.

How can I fix this? How can I change the link of the internal link [github]? Or where can I find documentation about this feature?

Body:
It turns out it is a kind of reference defined at the end of the file!

So for the above example you can define this reference at the end of your file as follows:

[github]: https://github.com/YourGroup/YourRepo

Not sure this is documented.


问:
MonoTouch: Default.png not being added to .app bundle
Using MonoTouch 4.0.4.1 and MonoDevelop 2.6b3

Our Default.png file is marked as "Content"

When we build the app, the resulting .app file when viewed using "Show Contents" in finder does not contain the Default.png.

The png is 320x480 32 bit

In previous versions the Default.png was being added correctly.

Has something changed?

答: There is a bug in the MonoDevelop beta releases that will not copy the content in root over to output. You can either use a post-build command to copy (and then resign!!!) the content or you can use the stable version of MonoDevelop (2.4.x)</p>


问:
np.arange producing elements with many decimals
I have the following loop.

```<code>x_array = []

for x in np.arange(0.01, 0.1, 0.01 ):

    x_array.append(x)
</code>```

Why are some of the elements in x_array in so many decimals?

```<code>[0.01,
 0.02,
 0.03,
 0.04,
 0.05,
 0.060000000000000005,
 0.06999999999999999,
 0.08,
 0.09]
</code>```

答:
If you want your list of numbers without "additional" digits in the
fractional part, try the following code:

```<code>x_array = np.arange(0.01, 0.1, 0.01).round(2).tolist()
</code>```

As you see, you don't even need any explicit loop.

The result is just what you want, i.e.:

```<code>[0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09]
</code>```

Another choice is:

```<code>x_array = (np.arange(1, 10) / 100).tolist()
</code>```

Body:
I have the following loop.

x_array = []

for x in np.arange(0.01, 0.1, 0.01 ):

    x_array.append(x)

Why are some of the elements in x_array in so many decimals?

[0.01,
 0.02,
 0.03,
 0.04,
 0.05,
 0.060000000000000005,
 0.06999999999999999,
 0.08,
 0.09]

Body:
If you want your list of numbers without "additional" digits in the
fractional part, try the following code:

x_array = np.arange(0.01, 0.1, 0.01).round(2).tolist()

As you see, you don't even need any explicit loop.

The result is just what you want, i.e.:

[0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09]

Another choice is:

x_array = (np.arange(1, 10) / 100).tolist()


问:
How to differentiate SD card and External Hard Drive storage paths on Android Xamarin?
My tablet has an SD card and external hard drive. I am calling GetExternalFilesDirs to get all shared/external storage devices where the application can place persistent files it owns.

Here is my code:

```<code>var ctx = Android.App.Application.Context;
Java.IO.File[] storagePaths = ctx.GetExternalFilesDirs(null);
</code>```

storagePaths contains 3 files:

/storage/emulated/0/path_to_app_data (emulated storage)

/storage/0123-4567/path_to_app_data (SD card)

/storage/285B-DFC6/path_to_app_data (USB hard drive)

How could I programmatically confirm which one of these (path 2 or path 3) is the USB storage device?

答:
The path for mounting a USB device to an Android device varies with Android devices from different vendors.

You can register a BroadcastReceiver to listen to the mounted event in your app.
Once the USB hard drive is mounted with the android device, we can recieve a BroadcastReceiver.

And in the BroadcastReceiver ,we can get the path of the of the USB hard drive.
Once we get the path of the hard storage, we can distinguish which path is the one we need.

You can refer to the following code snippet:

```<code>public class USBBroadCastReceiver : BroadcastReceiver
{
    string TAG = "USBBroadCastReceiver";
    public override void OnReceive(Context context, Intent intent)
    {

        String action = intent.Action;

        if (Intent.ActionMediaMounted.Equals(action))
        {

                UsbDevice device = (UsbDevice)intent.GetParcelableExtra(UsbManager.ExtraDevice);

                if (intent.GetBooleanExtra(UsbManager.ExtraPermissionGranted, false))
                {

                    if (device != null)
                    {
                        // call method to set up device communication

                        Log.Debug(TAG, "onReceive: " + intent.Extras.ToString());
                        Log.Debug(TAG, "onReceive: " + intent.Data);

                        // here you can get the path of your USB hard drive
                        String path = intent.Data.Path;

                        Log.Debug(TAG, "onReceive: path of device received from intent: " + path);

                    }
                }

        }
    }
</code>```

Body:
My tablet has an SD card and external hard drive. I am calling GetExternalFilesDirs to get all shared/external storage devices where the application can place persistent files it owns.

Here is my code:

var ctx = Android.App.Application.Context;
Java.IO.File[] storagePaths = ctx.GetExternalFilesDirs(null);

storagePaths contains 3 files:

/storage/emulated/0/path_to_app_data (emulated storage)

/storage/0123-4567/path_to_app_data (SD card)

/storage/285B-DFC6/path_to_app_data (USB hard drive)

How could I programmatically confirm which one of these (path 2 or path 3) is the USB storage device?

Body:
The path for mounting a USB device to an Android device varies with Android devices from different vendors.

You can register a BroadcastReceiver to listen to the mounted event in your app.
Once the USB hard drive is mounted with the android device, we can recieve a BroadcastReceiver.

And in the BroadcastReceiver ,we can get the path of the of the USB hard drive.
Once we get the path of the hard storage, we can distinguish which path is the one we need.

You can refer to the following code snippet:

public class USBBroadCastReceiver : BroadcastReceiver
{
    string TAG = "USBBroadCastReceiver";
    public override void OnReceive(Context context, Intent intent)
    {

        String action = intent.Action;

        if (Intent.ActionMediaMounted.Equals(action))
        {

                UsbDevice device = (UsbDevice)intent.GetParcelableExtra(UsbManager.ExtraDevice);

                if (intent.GetBooleanExtra(UsbManager.ExtraPermissionGranted, false))
                {

                    if (device != null)
                    {
                        // call method to set up device communication

                        Log.Debug(TAG, "onReceive: " + intent.Extras.ToString());
                        Log.Debug(TAG, "onReceive: " + intent.Data);

                        // here you can get the path of your USB hard drive
                        String path = intent.Data.Path;

                        Log.Debug(TAG, "onReceive: path of device received from intent: " + path);

                    }
                }

        }
    }