问:
How to update React state with a data object using hooks
I have a component with a date picker and a would like to change the value of the date picker in the state, using hooks, and also the date in the date picker itself, so you can select a date, or you can click a button to set a date, like 30 days ago.

this is what I tried so far:

```<code>const MyComp = () => {

  const [formData, setFormData] = useState({
    dateFrom: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
    dateTo: new Date()
  });

  const handleDateClick = interval => {
    setFormData({...formData, dateFrom: new Date(Date.now() - interval * 24 * 60 * 60 * 1000)});
    setFormData({...formData, dateTo: new Date()});
  };

  const handleOnChange = e => {
    setFormData({...formData, [e.target.name]: e.target.value});
  };

  return (
    <Button onClick={() => handleDateClick(30)} variant="secondary">30 days ago</Button>

    <DatePicker
      selected={formData.dateFrom}
      name="dateFrom"
      dateFormat="MMMM d, yyyy"
      onChange={value => handleOnChange({target: {name: "dateFrom", value}})}
    />
);

}
</code>```

clicking the button has no effect, not even displaying any error, the state is not updated and the value in the datepicker does not change? Any idea please?

答:
The reason why you're seeing a strange behavior is because your handleDateClick is calling setFormData twice in a row, which is a problem because setFormData it is asynchronous, meaning that it will not immediately reflect and update your state.

See this SO question for more details:

useState set method not reflecting change immediately

So, essentially what ends up happening is that you update dateFrom but then call setFormData again right after, and since it uses old state, you're never seeing an updated value for dateFrom.

const handleDateClick = interval => {
  setFormData({ ...formData, dateFrom: ... })

  // uses the value of `dateFrom` from the "old state"
  // when you do `...formData`, then updates `dateTo`
  setFormData({ ...formData, dateTo: ... })
}
```

<p>I suggest you combine all your updates inside <code>handleDateClick</code> into a single <code>setFormData</code> call. From what it looks like, there's no reason for you to have two separate calls.</p>

<p>Here's how you should approach this instead:</p>

<pre class="lang-js prettyprint-override"><code>function Button({ children, ...rest }) {
  return <button {...rest}>{children}</button>;
}

function MyComp() {
  const [formData, setFormData] = React.useState({
    dateFrom: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
    dateTo: new Date()
  });

  const handleDateClick = interval => {
    setFormData({
      dateTo: new Date(),
      dateFrom: new Date(Date.now() - interval * 24 * 60 * 60 * 1000)
    });
  };

  return (
    <>
      <Button onClick={() => handleDateClick(30)}>Click me!</Button>
      <p>
        <b>State:</b> {JSON.stringify(formData)}
      </p>
    </>
  );
}
</code>```

Here's a working example if you'd like to see:

CodeSandbox

Body:
I have a component with a date picker and a would like to change the value of the date picker in the state, using hooks, and also the date in the date picker itself, so you can select a date, or you can click a button to set a date, like 30 days ago.

this is what I tried so far:

const MyComp = () => {

  const [formData, setFormData] = useState({
    dateFrom: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
    dateTo: new Date()
  });

  const handleDateClick = interval => {
    setFormData({...formData, dateFrom: new Date(Date.now() - interval * 24 * 60 * 60 * 1000)});
    setFormData({...formData, dateTo: new Date()});
  };

  const handleOnChange = e => {
    setFormData({...formData, [e.target.name]: e.target.value});
  };

  return (
    <Button onClick={() => handleDateClick(30)} variant="secondary">30 days ago</Button>

    <DatePicker
      selected={formData.dateFrom}
      name="dateFrom"
      dateFormat="MMMM d, yyyy"
      onChange={value => handleOnChange({target: {name: "dateFrom", value}})}
    />
);

}

clicking the button has no effect, not even displaying any error, the state is not updated and the value in the datepicker does not change? Any idea please?

Body:
The reason why you're seeing a strange behavior is because your handleDateClick is calling setFormData twice in a row, which is a problem because setFormData it is asynchronous, meaning that it will not immediately reflect and update your state.

See this SO question for more details:

useState set method not reflecting change immediately

So, essentially what ends up happening is that you update dateFrom but then call setFormData again right after, and since it uses old state, you're never seeing an updated value for dateFrom.

const handleDateClick = interval => {
  setFormData({ ...formData, dateFrom: ... })

  // uses the value of `dateFrom` from the "old state"
  // when you do `...formData`, then updates `dateTo`
  setFormData({ ...formData, dateTo: ... })
}

I suggest you combine all your updates inside handleDateClick into a single setFormData call. From what it looks like, there's no reason for you to have two separate calls.

Here's how you should approach this instead:

function Button({ children, ...rest }) {
  return <button {...rest}>{children}</button>;
}

function MyComp() {
  const [formData, setFormData] = React.useState({
    dateFrom: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
    dateTo: new Date()
  });

  const handleDateClick = interval => {
    setFormData({
      dateTo: new Date(),
      dateFrom: new Date(Date.now() - interval * 24 * 60 * 60 * 1000)
    });
  };

  return (
    <>
      <Button onClick={() => handleDateClick(30)}>Click me!</Button>
      <p>
        <b>State:</b> {JSON.stringify(formData)}
      </p>
    </>
  );
}

Here's a working example if you'd like to see:

CodeSandbox


来源: stackexchange

问:
enhanced for with remove runs more efficiently
The following code is itself in an outer loop where oldChar is defined:

```<code>List<Character> modifiableCollection = new ArrayList<Character>(Arrays.asList(AlphabeticalStatistics.ALL_LETTERS));
for (int j = 0; j < modifiableCollection.size(); j++) {
    Character letterOfAlphabet = modifiableCollection.get(j);
    String loaAsString = letterOfAlphabet.toString();
    if (replaceLetters(Character.toString(oldChar), loaAsString)) {
        modifiableCollection.remove(j);
        System.out.println(oldChar + " was replaced with " + loaAsString);
        break;
    }
}
</code>```

I am trying to iterate through ALL_LETTERS as efficiently as possible. For each element, I want to check if replaceLetters() on that letter and another letter. If so, the letter will be replaced and I want to remove this from the modifiableCollection so the next time this is looped it won't look to replace that letter again.

However, what I am seeing is using an enhanced for loop WITH REMOVAL, the code runs AND is more efficient. I must not remove in an enhanced for:

```<code> for (Character letterOfAlphabet : modifiableCollection) {...remove()} // Compiles
</code>```

, but when I use a regular for loop, like above, the program takes longer to run; when I use iterator, the program takes even longer to run. Should I stick to the foreach loop?

Edit
replaceLetters() method:

```<code>protected boolean replaceLetters(String toReplace, String replacement, String toAdd, String toAdd2) {
        if (replacedLetters.contains(toAdd2) || solvedLetters.contains(toAdd))
            return false;
        return isCorrect(toReplace, replacement, toAdd, toAdd2);
    }

private boolean isCorrect(String toReplace, String replacement, String toAdd, String toAdd2) {
    String newText = getText().replace(toReplace,  replacement);
    if (Arrays.stream(newText.split(" "))
            .filter(w -> {
                return w.contains(replacement) && AlphabeticalStatistics.needsNoLetters(w);
            })
            .noneMatch(w -> {
                return !EnglishDeterminer.isWord(w);
            })
            ) {
        setText(newText);
        solvedLetters.add(toAdd);
        replacedLetters.add(toAdd2);
        return true;
    }
    return false;
}
</code>```

The purpose of this program is to decipher a substitution ciphertext.

答:
I seems faster with the indexed for loop (for int i=0; i<size; i++). Removal is probably faster by index as well since you dont have to compare your collection values to find the match. Maybe you should extract a variable for modifiableCollection.size() since it will be evaluated each iteration.

```<code> public static final int ITERATIONS = 100000000;

 public static void main(String[] args) {
    List<Character> alphabetList = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmopqrstuvwxyz123456789".chars()
            .mapToObj(c -> Character.valueOf((char) c)).collect(Collectors.toList());
    ArrayList<Character> copy = new ArrayList<>(alphabetList);
    List<Character> unmodifiableAlphabetList = Collections.unmodifiableList(copy);

    double timeA = checkTime(ITERATIONS, () -> {
        List<Character> modifiableCollection = new ArrayList<>(alphabetList);
        modifiableCollection.removeIf(next -> checkRemove(next));
    });
    System.out.println("A : " + timeA);

    double timeB = checkTime(ITERATIONS, () -> {
        List<Character> modifiableCollection = new ArrayList<>(alphabetList);
        Iterator<Character> iterator = modifiableCollection.iterator();
        while (iterator.hasNext()) {
            if (checkRemove(iterator.next())) {
                iterator.remove();
                break;
            }
        }
    });
    System.out.println("B : " + timeB);

    double timeC = checkTime(ITERATIONS, () -> {
        List<Character> modifiableCollection = new ArrayList<>(alphabetList);
        int size = modifiableCollection.size();
        for (int i = 0; i < size; i++) {
            Character character = unmodifiableAlphabetList.get(i);
            if (checkRemove(character)) {
                modifiableCollection.remove(i);
                break;
            }
        }
    });
    System.out.println("C : " + timeC);

    double timeD = checkTime(ITERATIONS, () -> {
        List<Character> modifiableCollection = new ArrayList<>(alphabetList);
        for (Character c : unmodifiableAlphabetList) {
            if (checkRemove(c)) {
                modifiableCollection.remove(c);
                break;
            }
        }
    });
    System.out.println("D : " + timeD);
}

private static boolean checkRemove(Character next) {
    return next.equals('W');
}

private static double checkTime(long count, Runnable fn) {
    List<Long> diffs = new ArrayList<>();

    for (int i = 0; i < count; i++) {
        long now = System.nanoTime();
        fn.run();
        long after = System.nanoTime();
        long nanoDiff = after - now;
        diffs.add(nanoDiff);
    }
    double average = diffs.stream()
            .mapToLong(l -> l)
            .average()
            .orElse(0L);
    return average;
}

A : 247.68729885
B : 83.9981085
C : 63.98897325
D : 91.69348503
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The following code is itself in an outer loop where oldChar is defined:

List<Character> modifiableCollection = new ArrayList<Character>(Arrays.asList(AlphabeticalStatistics.ALL_LETTERS));
for (int j = 0; j < modifiableCollection.size(); j++) {
    Character letterOfAlphabet = modifiableCollection.get(j);
    String loaAsString = letterOfAlphabet.toString();
    if (replaceLetters(Character.toString(oldChar), loaAsString)) {
        modifiableCollection.remove(j);
        System.out.println(oldChar + " was replaced with " + loaAsString);
        break;
    }
}

I am trying to iterate through ALL_LETTERS as efficiently as possible. For each element, I want to check if replaceLetters() on that letter and another letter. If so, the letter will be replaced and I want to remove this from the modifiableCollection so the next time this is looped it won't look to replace that letter again.

However, what I am seeing is using an enhanced for loop WITH REMOVAL, the code runs AND is more efficient. I must not remove in an enhanced for:

 for (Character letterOfAlphabet : modifiableCollection) {...remove()} // Compiles

, but when I use a regular for loop, like above, the program takes longer to run; when I use iterator, the program takes even longer to run. Should I stick to the foreach loop?

Edit
replaceLetters() method:

protected boolean replaceLetters(String toReplace, String replacement, String toAdd, String toAdd2) {
        if (replacedLetters.contains(toAdd2) || solvedLetters.contains(toAdd))
            return false;
        return isCorrect(toReplace, replacement, toAdd, toAdd2);
    }

private boolean isCorrect(String toReplace, String replacement, String toAdd, String toAdd2) {
    String newText = getText().replace(toReplace,  replacement);
    if (Arrays.stream(newText.split(" "))
            .filter(w -> {
                return w.contains(replacement) && AlphabeticalStatistics.needsNoLetters(w);
            })
            .noneMatch(w -> {
                return !EnglishDeterminer.isWord(w);
            })
            ) {
        setText(newText);
        solvedLetters.add(toAdd);
        replacedLetters.add(toAdd2);
        return true;
    }
    return false;
}

The purpose of this program is to decipher a substitution ciphertext.

Body:
I seems faster with the indexed for loop (for int i=0; i<size; i++). Removal is probably faster by index as well since you dont have to compare your collection values to find the match. Maybe you should extract a variable for modifiableCollection.size() since it will be evaluated each iteration.

 public static final int ITERATIONS = 100000000;

 public static void main(String[] args) {
    List<Character> alphabetList = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmopqrstuvwxyz123456789".chars()
            .mapToObj(c -> Character.valueOf((char) c)).collect(Collectors.toList());
    ArrayList<Character> copy = new ArrayList<>(alphabetList);
    List<Character> unmodifiableAlphabetList = Collections.unmodifiableList(copy);

    double timeA = checkTime(ITERATIONS, () -> {
        List<Character> modifiableCollection = new ArrayList<>(alphabetList);
        modifiableCollection.removeIf(next -> checkRemove(next));
    });
    System.out.println("A : " + timeA);

    double timeB = checkTime(ITERATIONS, () -> {
        List<Character> modifiableCollection = new ArrayList<>(alphabetList);
        Iterator<Character> iterator = modifiableCollection.iterator();
        while (iterator.hasNext()) {
            if (checkRemove(iterator.next())) {
                iterator.remove();
                break;
            }
        }
    });
    System.out.println("B : " + timeB);

    double timeC = checkTime(ITERATIONS, () -> {
        List<Character> modifiableCollection = new ArrayList<>(alphabetList);
        int size = modifiableCollection.size();
        for (int i = 0; i < size; i++) {
            Character character = unmodifiableAlphabetList.get(i);
            if (checkRemove(character)) {
                modifiableCollection.remove(i);
                break;
            }
        }
    });
    System.out.println("C : " + timeC);

    double timeD = checkTime(ITERATIONS, () -> {
        List<Character> modifiableCollection = new ArrayList<>(alphabetList);
        for (Character c : unmodifiableAlphabetList) {
            if (checkRemove(c)) {
                modifiableCollection.remove(c);
                break;
            }
        }
    });
    System.out.println("D : " + timeD);
}

private static boolean checkRemove(Character next) {
    return next.equals('W');
}

private static double checkTime(long count, Runnable fn) {
    List<Long> diffs = new ArrayList<>();

    for (int i = 0; i < count; i++) {
        long now = System.nanoTime();
        fn.run();
        long after = System.nanoTime();
        long nanoDiff = after - now;
        diffs.add(nanoDiff);
    }
    double average = diffs.stream()
            .mapToLong(l -> l)
            .average()
            .orElse(0L);
    return average;
}

A : 247.68729885
B : 83.9981085
C : 63.98897325
D : 91.69348503


问:
Material edit text not rendering in android studio editor
My android sudio design editor don't render material TextInputLayouts. I already tried invalidate caches. Every other element is rendering correct also other material elements

```<code>                   <com.google.android.material.textfield.TextInputLayout
                    android:id="@+id/ti"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginTop="20dp"
                    android:layout_marginEnd="30dp"
                    android:layout_marginBottom="20dp"
                    android:hint="@string/street_number">

                    <com.google.android.material.textfield.TextInputEditText
                        android:layout_width="match_parent"
                        android:layout_height="50dp"
                        android:inputType="text"
                        android:text="@{vm.user.streetnumber}" />
                </com.google.android.material.textfield.TextInputLayout>
</code>```

答:
You have to change in build.gradle

implementation 'com.google.android.material:material:1.2.0-alpha02'

It seems newer versions are not rendered correctly.

See:how to solve render problem Path.op() not supported?

Body:
My android sudio design editor don't render material TextInputLayouts. I already tried invalidate caches. Every other element is rendering correct also other material elements

                   <com.google.android.material.textfield.TextInputLayout
                    android:id="@+id/ti"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginTop="20dp"
                    android:layout_marginEnd="30dp"
                    android:layout_marginBottom="20dp"
                    android:hint="@string/street_number">

                    <com.google.android.material.textfield.TextInputEditText
                        android:layout_width="match_parent"
                        android:layout_height="50dp"
                        android:inputType="text"
                        android:text="@{vm.user.streetnumber}" />
                </com.google.android.material.textfield.TextInputLayout>


问:
Integrating Microsoft Bot v4 with ServiceNow
I have office 365 account. Hence I get re-directed to ServiceNow portal without asking for user credentials.

Likewise, my Bot (v4) is hosted in MS Teams. What are the ways to initiate REST calls from Bot to ServiceNow without asking my credentials? Like SSO.

My ServiceNow instance does not allow client_credentials grant type and hence need to work on other grant-types which require user password.

Many thanks

答: There is no specific tutorial for integrating a bot with ServiceNow. You can make use of the REST API which is documented here to address your purpose. Refer to the following documentations as well to get more information about the ServiceNow SSO and Azure Bot Service authentication.</p>


问:
Find all possible Euler cycles
I have implemented an algorithm to find an Euler cycle for a given starting vertex in an undirected graph (using DFS and removing visited edges), but it always returns only one path. How do I modify the algorithm to search for all possible Euler cycles for a vertex?

Here is relevant code:

```<code>typedef int Graph[200][200]; // adjacency matrix
int v, e; // vertex count, edge count

......

void DFS(Graph &G, int x) {
    int i;
    Push(x);
    for (i = 0; i < v; i++)
        if (G[i][x] > 0) {
            G[i][x] = 0;
            G[x][i] = 0;
            DFS(G, i);
            break;
    }
</code>```

}

答:
After the recursive call, you should reinsert the edges you deleted before, and get rid of the break.

```<code>void DFS(Graph &G, int x)
{
    int i;
    Push(x);
    for (i = 0; i < v; i++)
        if (G[i][x] > 0)
        {
            G[i][x] *= -1;
            G[x][i] *= -1;
            DFS(G, i);
            G[i][x] *= -1;
            G[x][i] *= -1;
        }

}
</code>```

All you need now is a way to figure out when you've generated a full cycle so you can print it and move on to the next. That happens when you've eliminated every edge of your graph.

ContentLicense: CC BY-SA 3.0

Title: Find all possible Euler cycles

Body:
I have implemented an algorithm to find an Euler cycle for a given starting vertex in an undirected graph (using DFS and removing visited edges), but it always returns only one path. How do I modify the algorithm to search for all possible Euler cycles for a vertex?

Here is relevant code:

typedef int Graph[200][200]; // adjacency matrix
int v, e; // vertex count, edge count

......

void DFS(Graph &G, int x) {
    int i;
    Push(x);
    for (i = 0; i < v; i++)
        if (G[i][x] > 0) {
            G[i][x] = 0;
            G[x][i] = 0;
            DFS(G, i);
            break;
    }

}

Body:
After the recursive call, you should reinsert the edges you deleted before, and get rid of the break.

void DFS(Graph &G, int x)
{
    int i;
    Push(x);
    for (i = 0; i < v; i++)
        if (G[i][x] > 0)
        {
            G[i][x] *= -1;
            G[x][i] *= -1;
            DFS(G, i);
            G[i][x] *= -1;
            G[x][i] *= -1;
        }

}

All you need now is a way to figure out when you've generated a full cycle so you can print it and move on to the next. That happens when you've eliminated every edge of your graph.


问:
using jQuery (put at the bottom of the page) on specific page
Because of performance purposes I put loading of jQuery scripts at the bottom of the page (just before the closing body tag).

My question is how to enable page specific scripts? I don't want to put everything inside $(document).ready method (again because of performance purposes).

Update: I'm using a template system so I put jQuery loading in the template. That way jQuery calls don't get recognized even if I put them at the end of a specific page because jQuery is not loaded at that point.

答:
As I understand your issue:

jQuery is not available on the page before it loads.

You use templates and each has it's own js code to run when page loads

You want them to run with jQuery.

If I got you right, here is the solution:

In  define global task array:

```<code>    ...
    <script>
        const JQUERY_READY_TASKS = []
    </script>
</head>
</code>```

After you load jQuery and other scripts define:

```<code>    ...
    <script>
        jQuery(document).ready(() => {
            // Execute all tasks added by templates
            for (let n=0; n<JQUERY_READY_TASKS.length; n++)
                JQUERY_READY_TASKS[n](jQuery)
            }
        });
    </script>
</body>
</code>```

Wrap initialization code of your templates in functions:

```<code>    ...
    <script>
        // Within template
        JQUERY_READY_TASKS.push(($) => {
            // Template init code
            // You can use $ as jquery here
        })
    </script>
    ...
</code>```

ContentLicense: CC BY-SA 2.5

Body:
As I understand your issue:

jQuery is not available on the page before it loads.

You use templates and each has it's own js code to run when page loads

You want them to run with jQuery.

If I got you right, here is the solution:

In <head> define global task array:

    ...
    <script>
        const JQUERY_READY_TASKS = []
    </script>
</head>

After you load jQuery and other scripts define:

    ...
    <script>
        jQuery(document).ready(() => {
            // Execute all tasks added by templates
            for (let n=0; n<JQUERY_READY_TASKS.length; n++)
                JQUERY_READY_TASKS[n](jQuery)
            }
        });
    </script>
</body>

Wrap initialization code of your templates in functions:

    ...
    <script>
        // Within template
        JQUERY_READY_TASKS.push(($) => {
            // Template init code
            // You can use $ as jquery here
        })
    </script>
    ...


问:
Updating terraform (.tf) files using Python
I am trying to update terraform templates using python, although I am having some issues trying to find a module (like PyYAML to update yml files).

My aim is to update the terraform files present in a git repo, and create a pull request, which when merged would trigger a pipeline to implement the changes.

Example .tf file:

```<code>variable "variable_1" {}
variable "variable_2" {}

locals {
  temp_locals = 0
}

resource "aws_iam_role" "MY_AWS_ACCOUNT" {
  name = "MY_AWS_ACCOUNT"

  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Condition": {
        "Bool": {
          "aws:MultiFactorAuthPresent": "true"
        }
      },
      "Principal": {
        "AWS": [
          "arn:aws:iam::<AWS_ACCOUNT_ID>:user/user.name1"
        ]
      },
      "Effect": "Allow",
      "Sid": ""
    }
  ]
}
EOF
}

resource "aws_iam_role_policy_attachment" "aws_iam_role_policy_attachment" {
}
</code>```

Want to add arn of user.name2 in this file.

答:
There is currently no Python implementation of Terraform's underlying syntax HCL which can support surgical modification to an existing file, because that requires preserving information that a typical HCL parser will not retain, such as comments and the ordering of arguments within blocks.

Another option is to use a lesser-used feature of Terraform called Override Files, which allow you to write a new file that overrides part of an existing file. This mechanism exists specifically for this sort of situation where you want to use the content from a file written by humans but override part of it with content generated by a machine.

If you take your given example code as example.tf then you can put another file on disk next to it called example_override.tf.json with the following content:

```<code>{
  "resource": {
    "aws_iam_role": {
      "MY_AWS_ACCOUNT": {
        "assume_role_policy": "{\n\t\"Version\": \"2012-10-17\",\n\t\"Statement\": [\n\t  {\n\t\t\"Action\": \"sts:AssumeRole\",\n\t\t\"Condition\": {\n\t\t  \"Bool\": {\n\t\t\t\"aws:MultiFactorAuthPresent\": \"true\"\n\t\t  }\n\t\t},\n\t\t\"Principal\": {\n\t\t  \"AWS\": [\n\t\t\t\"arn:aws:iam::<AWS_ACCOUNT_ID>:user/user.name2\"\n\t\t  ]\n\t\t},\n\t\t\"Effect\": \"Allow\",\n\t\t\"Sid\": \"\"\n\t  }\n\t]\n  }"
      }
    }
  }
}
</code>```

Because this additional file uses Terraform's alternative JSON syntax, it is easy to generate from any language that has a JSON serializer available, including Python. Terraform itself will read both files and take the assume_role_policy from the override file as overriding the corresponding one in the base file, as described in Merging Behavior. You can then leave the original HCL file unmodified, avoiding issues with interfering with human-oriented formatting decisions in that file.

The Go implementation of HCL, which is the canonical one and the one that Terraform itself uses, has a package hclwrite which is a specialized API for directly modifying existing HCL source code while preserving all of the unmodified tokens and their ordering. Therefore a program written in Go could potentially achieve a result like what you were looking for using that package:

package main

import (
    "fmt"
    "log"

    hcl "github.com/hashicorp/hcl/v2"
    "github.com/hashicorp/hcl/v2/hclwrite"
    "github.com/zclconf/go-cty/cty"
)

func main() {
    // In a real program, use ioutil.ReadFile to read a file from disk.
    // But for this example, I will use a const string.
    src := []byte(oldSource)
    f, diags := hclwrite.ParseConfig(src, "example.tf", hcl.Pos{Line: 1, Column: 1})
    if diags.HasErrors() {
        log.Fatal(diags)
    }

    for _, block := range f.Body().Blocks() {
        if block.Type() != "resource" {
            continue
        }
        if labels := block.Labels(); len(labels) < 2 || labels[0] != "aws_iam_role" || labels[1] != "MY_AWS_ACCOUNT" {
            continue
        }

        block.Body().SetAttributeValue("assume_role_policy", cty.StringVal(newPolicy))
    }

    // In a real program, maybe write these bytes to a file on disk.
    fmt.Println(string(f.Bytes()))
}

const oldSource = `
variable "variable_1" {}
variable "variable_2" {}

locals {
  temp_locals = 0
}

resource "aws_iam_role" "MY_AWS_ACCOUNT" {
  name = "MY_AWS_ACCOUNT"

  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Condition": {
        "Bool": {
          "aws:MultiFactorAuthPresent": "true"
        }
      },
      "Principal": {
        "AWS": [
          "arn:aws:iam::<AWS_ACCOUNT_ID>:user/user.name1"
        ]
      },
      "Effect": "Allow",
      "Sid": ""
    }
  ]
}
EOF
}

resource "aws_iam_role_policy_attachment" "aws_iam_role_policy_attachment" {
}
`

const newPolicy = `
{
    "Version": "2012-10-17",
    "Statement": [
      {
        "Action": "sts:AssumeRole",
        "Condition": {
          "Bool": {
            "aws:MultiFactorAuthPresent": "true"
          }
        },
        "Principal": {
          "AWS": [
            "arn:aws:iam::<AWS_ACCOUNT_ID>:user/user.name2"
          ]
        },
        "Effect": "Allow",
        "Sid": ""
      }
    ]
  }
`
```

<p>The output of this program does, however, demonstrate one of the limitations of automatic generation of a language that's primarily designed to be written and read by humans:</p>

```variable "variable_1" {}
variable "variable_2" {}

locals {
  temp_locals = 0
}

resource "aws_iam_role" "MY_AWS_ACCOUNT" {
  name = "MY_AWS_ACCOUNT"

  assume_role_policy = "\n{\n\t\"Version\": \"2012-10-17\",\n\t\"Statement\": [\n\t  {\n\t\t\"Action\": \"sts:AssumeRole\",\n\t\t\"Condition\": {\n\t\t  \"Bool\": {\n\t\t\t\"aws:MultiFactorAuthPresent\": \"true\"\n\t\t  }\n\t\t},\n\t\t\"Principal\": {\n\t\t  \"AWS\": [\n\t\t\t\"arn:aws:iam::<AWS_ACCOUNT_ID>:user/user.name2\"\n\t\t  ]\n\t\t},\n\t\t\"Effect\": \"Allow\",\n\t\t\"Sid\": \"\"\n\t  }\n\t]\n  }\n"
}

resource "aws_iam_role_policy_attachment" "aws_iam_role_policy_attachment" {
}
```

As humans, we can make subjective decisions about how to format things for readability, but hclwrite has just defaulted to using the quoted string form for this string, which in this case is a poor choice that a human author would likely not have made.

Body:
I am trying to update terraform templates using python, although I am having some issues trying to find a module (like PyYAML to update yml files).

My aim is to update the terraform files present in a git repo, and create a pull request, which when merged would trigger a pipeline to implement the changes.

Example .tf file:

variable "variable_1" {}
variable "variable_2" {}

locals {
  temp_locals = 0
}

resource "aws_iam_role" "MY_AWS_ACCOUNT" {
  name = "MY_AWS_ACCOUNT"

  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Condition": {
        "Bool": {
          "aws:MultiFactorAuthPresent": "true"
        }
      },
      "Principal": {
        "AWS": [
          "arn:aws:iam::<AWS_ACCOUNT_ID>:user/user.name1"
        ]
      },
      "Effect": "Allow",
      "Sid": ""
    }
  ]
}
EOF
}

resource "aws_iam_role_policy_attachment" "aws_iam_role_policy_attachment" {
}

Want to add arn of user.name2 in this file.

Body:
There is currently no Python implementation of Terraform's underlying syntax HCL which can support surgical modification to an existing file, because that requires preserving information that a typical HCL parser will not retain, such as comments and the ordering of arguments within blocks.

Another option is to use a lesser-used feature of Terraform called Override Files, which allow you to write a new file that overrides part of an existing file. This mechanism exists specifically for this sort of situation where you want to use the content from a file written by humans but override part of it with content generated by a machine.

If you take your given example code as example.tf then you can put another file on disk next to it called example_override.tf.json with the following content:

{
  "resource": {
    "aws_iam_role": {
      "MY_AWS_ACCOUNT": {
        "assume_role_policy": "{\n\t\"Version\": \"2012-10-17\",\n\t\"Statement\": [\n\t  {\n\t\t\"Action\": \"sts:AssumeRole\",\n\t\t\"Condition\": {\n\t\t  \"Bool\": {\n\t\t\t\"aws:MultiFactorAuthPresent\": \"true\"\n\t\t  }\n\t\t},\n\t\t\"Principal\": {\n\t\t  \"AWS\": [\n\t\t\t\"arn:aws:iam::<AWS_ACCOUNT_ID>:user/user.name2\"\n\t\t  ]\n\t\t},\n\t\t\"Effect\": \"Allow\",\n\t\t\"Sid\": \"\"\n\t  }\n\t]\n  }"
      }
    }
  }
}

Because this additional file uses Terraform's alternative JSON syntax, it is easy to generate from any language that has a JSON serializer available, including Python. Terraform itself will read both files and take the assume_role_policy from the override file as overriding the corresponding one in the base file, as described in Merging Behavior. You can then leave the original HCL file unmodified, avoiding issues with interfering with human-oriented formatting decisions in that file.

The Go implementation of HCL, which is the canonical one and the one that Terraform itself uses, has a package hclwrite which is a specialized API for directly modifying existing HCL source code while preserving all of the unmodified tokens and their ordering. Therefore a program written in Go could potentially achieve a result like what you were looking for using that package:

package main

import (
    "fmt"
    "log"

    hcl "github.com/hashicorp/hcl/v2"
    "github.com/hashicorp/hcl/v2/hclwrite"
    "github.com/zclconf/go-cty/cty"
)

func main() {
    // In a real program, use ioutil.ReadFile to read a file from disk.
    // But for this example, I will use a const string.
    src := []byte(oldSource)
    f, diags := hclwrite.ParseConfig(src, "example.tf", hcl.Pos{Line: 1, Column: 1})
    if diags.HasErrors() {
        log.Fatal(diags)
    }

    for _, block := range f.Body().Blocks() {
        if block.Type() != "resource" {
            continue
        }
        if labels := block.Labels(); len(labels) < 2 || labels[0] != "aws_iam_role" || labels[1] != "MY_AWS_ACCOUNT" {
            continue
        }

        block.Body().SetAttributeValue("assume_role_policy", cty.StringVal(newPolicy))
    }

    // In a real program, maybe write these bytes to a file on disk.
    fmt.Println(string(f.Bytes()))
}

const oldSource = `
variable "variable_1" {}
variable "variable_2" {}

locals {
  temp_locals = 0
}

resource "aws_iam_role" "MY_AWS_ACCOUNT" {
  name = "MY_AWS_ACCOUNT"

  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Condition": {
        "Bool": {
          "aws:MultiFactorAuthPresent": "true"
        }
      },
      "Principal": {
        "AWS": [
          "arn:aws:iam::<AWS_ACCOUNT_ID>:user/user.name1"
        ]
      },
      "Effect": "Allow",
      "Sid": ""
    }
  ]
}
EOF
}

resource "aws_iam_role_policy_attachment" "aws_iam_role_policy_attachment" {
}
`

const newPolicy = `
{
    "Version": "2012-10-17",
    "Statement": [
      {
        "Action": "sts:AssumeRole",
        "Condition": {
          "Bool": {
            "aws:MultiFactorAuthPresent": "true"
          }
        },
        "Principal": {
          "AWS": [
            "arn:aws:iam::<AWS_ACCOUNT_ID>:user/user.name2"
          ]
        },
        "Effect": "Allow",
        "Sid": ""
      }
    ]
  }
`

The output of this program does, however, demonstrate one of the limitations of automatic generation of a language that's primarily designed to be written and read by humans:

variable "variable_1" {}
variable "variable_2" {}

locals {
  temp_locals = 0
}

resource "aws_iam_role" "MY_AWS_ACCOUNT" {
  name = "MY_AWS_ACCOUNT"

  assume_role_policy = "\n{\n\t\"Version\": \"2012-10-17\",\n\t\"Statement\": [\n\t  {\n\t\t\"Action\": \"sts:AssumeRole\",\n\t\t\"Condition\": {\n\t\t  \"Bool\": {\n\t\t\t\"aws:MultiFactorAuthPresent\": \"true\"\n\t\t  }\n\t\t},\n\t\t\"Principal\": {\n\t\t  \"AWS\": [\n\t\t\t\"arn:aws:iam::<AWS_ACCOUNT_ID>:user/user.name2\"\n\t\t  ]\n\t\t},\n\t\t\"Effect\": \"Allow\",\n\t\t\"Sid\": \"\"\n\t  }\n\t]\n  }\n"
}

resource "aws_iam_role_policy_attachment" "aws_iam_role_policy_attachment" {
}

As humans, we can make subjective decisions about how to format things for readability, but hclwrite has just defaulted to using the quoted string form for this string, which in this case is a poor choice that a human author would likely not have made.


问:
Discord: Stop Exception Error from being printed in Python Console
I am sure I am missing something very simple but I just can not find it. I have made a error handle for a command that I made and it responds to the user. The problem is I would like the console of my bot python script to be clean so I am looking for a way to eliminate the large errors that get printed in the console. Even though I handled it, it still prints the exception in the console which is what I am ask to block. Any and all help given is very appreciated.

Code:

```<code>    @bal.error
    async def bal_error(self, ctx, error):
        if isinstance(error, discord.ext.commands.BadArgument):
            await ctx.send('Balance: Please specify a user. Syntax (!bal {mention})')
        raise error #I am pretty sure there is no need for this.
</code>```

Error that I am trying to avoid being printed to the console:

```<code>Ignoring exception in on_command_error
Traceback (most recent call last):
  File "C:\Users\gunzb\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 270, in _run
_event
    await coro(*args, **kwargs)
  File "C:\Users\gunzb\Desktop\AfterClap Bot\bot.py", line 37, in on_command_error
    raise error
  File "C:\Users\gunzb\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 86
3, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\gunzb\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 7
21, in invoke
    await self.prepare(ctx)
  File "C:\Users\gunzb\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 6
85, in prepare
    await self._parse_arguments(ctx)
  File "C:\Users\gunzb\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 6
08, in _parse_arguments
    kwargs[name] = await self.transform(ctx, param)
  File "C:\Users\gunzb\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 4
55, in transform
    return await self.do_conversion(ctx, converter, argument, param)
  File "C:\Users\gunzb\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 4
08, in do_conversion
    return await self._actual_conversion(ctx, converter, argument, param)
  File "C:\Users\gunzb\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 3
54, in _actual_conversion
    ret = await instance.convert(ctx, argument)
  File "C:\Users\gunzb\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\converter.py", l
ine 132, in convert
    raise BadArgument('Member "{}" not found'.format(argument))
discord.ext.commands.errors.BadArgument: Member "n" not found
</code>```

答:
Return the error to prevent it from printing the error message on the console.</p>

```<code>@bal.error
async def bal_error(self, ctx, error):
    if isinstance(error, discord.ext.commands.BadArgument):
        await ctx.send('Balance: Please specify a user. Syntax (!bal {mention})')
        return error
    else:
        raise error
</code>```

Body:
I am sure I am missing something very simple but I just can not find it. I have made a error handle for a command that I made and it responds to the user. The problem is I would like the console of my bot python script to be clean so I am looking for a way to eliminate the large errors that get printed in the console. Even though I handled it, it still prints the exception in the console which is what I am ask to block. Any and all help given is very appreciated.

Code:

    @bal.error
    async def bal_error(self, ctx, error):
        if isinstance(error, discord.ext.commands.BadArgument):
            await ctx.send('Balance: Please specify a user. Syntax (!bal {mention})')
        raise error #I am pretty sure there is no need for this.

Error that I am trying to avoid being printed to the console:

Ignoring exception in on_command_error
Traceback (most recent call last):
  File "C:\Users\gunzb\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 270, in _run
_event
    await coro(*args, **kwargs)
  File "C:\Users\gunzb\Desktop\AfterClap Bot\bot.py", line 37, in on_command_error
    raise error
  File "C:\Users\gunzb\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 86
3, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\gunzb\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 7
21, in invoke
    await self.prepare(ctx)
  File "C:\Users\gunzb\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 6
85, in prepare
    await self._parse_arguments(ctx)
  File "C:\Users\gunzb\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 6
08, in _parse_arguments
    kwargs[name] = await self.transform(ctx, param)
  File "C:\Users\gunzb\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 4
55, in transform
    return await self.do_conversion(ctx, converter, argument, param)
  File "C:\Users\gunzb\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 4
08, in do_conversion
    return await self._actual_conversion(ctx, converter, argument, param)
  File "C:\Users\gunzb\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 3
54, in _actual_conversion
    ret = await instance.convert(ctx, argument)
  File "C:\Users\gunzb\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\converter.py", l
ine 132, in convert
    raise BadArgument('Member "{}" not found'.format(argument))
discord.ext.commands.errors.BadArgument: Member "n" not found

Body:
Return the error to prevent it from printing the error message on the console.

@bal.error
async def bal_error(self, ctx, error):
    if isinstance(error, discord.ext.commands.BadArgument):
        await ctx.send('Balance: Please specify a user. Syntax (!bal {mention})')
        return error
    else:
        raise error


问:
signalling inside php
hi when implementing a connection that stays open for a long time ( comet ),
how would i implement signalling between php proses(outstanding requests)??

example timeline:

request 1 start

request 1 makes action

request 1 sleeps

request 2 start

request 2 makes action

request 2 notifies request 1 and go's to sleep

request 1 wakes up and sends the new data

request 1 sleeps agen

i was wandering if ther was a methode whitch use less(noting?) cpu prosessing

答:
If your platform is Linux/Unix, you can use queues.

request 1 start

request 1 makes action

request 1 sleeps and reading queue (sleep(1) and read queue)

request 2 start

request 2 makes action

request 2 sending message to queue

request 1 receives message from queue, wakes up and sends the new data

request 1 sleeps again

Whith semaphores you can do this without sleep() even, but it will be more difficult to code.

Title: signalling inside php


问:
Distribution plot is showing flat pdf
I tried to plot the Probability Density Function (PDF) plot of my data after finding the best parameters, but the plot is showing a flat line instead of a curve.

Is it a matter of scaling?

Is it a problem of Continuous or Discrete data? Data file is available here

The purpose here is to get the best distribution fittings and then plot PDF function.

My data values are so small like: 0.21, 1.117 .etc. The data statistics and PDF plots are shown below:

My script is given below:

```<code>from time import time
from datetime import datetime
start_time = datetime.now()
import pandas as pd
pd.options.display.float_format = '{:.4f}'.format
import numpy as np
import pickle
import scipy
import scipy.stats
import matplotlib.pyplot as plt

data= pd.read_csv("line_RXC_data.csv",usecols=['R'],parse_dates=True, squeeze=True)
df=data

y_std=df
# del yy

import warnings
warnings.filterwarnings("ignore")

# Create an index array (x) for data

y=df
#
# Create an index array (x) for data

x = np.arange(len(y))
size = len(y)

#simple visualisation of the data
plt.hist(y)
plt.title("Histogram of resistance ")
plt.xlabel("Resistance data visualization ")
plt.ylabel("Frequency")
plt.show()

y_df = pd.DataFrame(y)
tt=y_df.describe()
print(tt)

dist_names = [
                'foldcauchy',
                'beta',
                'expon',
                  'exponnorm',
                'norm',
                'lognorm',
                  'dweibull',
                'pareto',
                  'gamma'
]

x = np.arange(len(df))
size = len(df)
y_std = df
y=df
chi_square = []
p_values = []

# Set up 50 bins for chi-square test
# Observed data will be approximately evenly distrubuted aross all bins
percentile_bins = np.linspace(0,100,51)
percentile_cutoffs = np.percentile(y_std, percentile_bins)
observed_frequency, bins = (np.histogram(y_std, bins=percentile_cutoffs))
cum_observed_frequency = np.cumsum(observed_frequency)

# Loop through candidate distributions

for distribution in dist_names:
    s1 = time()
    # Set up distribution and get fitted distribution parameters
    dist = getattr(scipy.stats, distribution)
    # print("1")
    param = dist.fit(y_std)
    # print("2")
    # Obtain the KS test P statistic, round it to 5 decimal places
    p = scipy.stats.kstest(y_std, distribution, args=param)[1]
    p = np.around(p, 5)
    p_values.append(p)
    # print("3")
    # Get expected counts in percentile bins
    # This is based on a 'cumulative distrubution function' (cdf)
    cdf_fitted = dist.cdf(percentile_cutoffs, *param[:-2], loc=param[-2],
                          scale=param[-1])
    # print("4")
    expected_frequency = []
    for bin in range(len(percentile_bins)-1):
        expected_cdf_area = cdf_fitted[bin+1] - cdf_fitted[bin]
        expected_frequency.append(expected_cdf_area)

    # calculate chi-squared
    expected_frequency = np.array(expected_frequency) * size
    cum_expected_frequency = np.cumsum(expected_frequency)
    ss = sum (((cum_expected_frequency - cum_observed_frequency) ** 2) / cum_observed_frequency)
    chi_square.append(ss)
    print(f"chi_square {distribution} time: {time() - s1}")

#    print("std of predicted probability : ", np.std(cum_observed_frequency))

# Collate results and sort by goodness of fit (best at top)

results = pd.DataFrame()
results['Distribution'] = dist_names
results['chi_square'] = chi_square
results['p_value'] = p_values
results.sort_values(['chi_square'], inplace=True)

# Report results

print ('\nDistributions sorted by goodness of fit:')
print ('----------------------------------------')
print (results)

#%%

# Divide the observed data into 100 bins for plotting (this can be changed)
number_of_bins = 100
bin_cutoffs = np.linspace(np.percentile(y,0), np.percentile(y,99),number_of_bins)

# Create the plot
plt.figure(figsize=(7, 4))
h = plt.hist(y, bins = bin_cutoffs, color='0.70')

# Get the top three distributions from the previous phase
number_distributions_to_plot = 5
dist_names = results['Distribution'].iloc[0:number_distributions_to_plot]

#%%
# Create an empty list to stroe fitted distribution parameters
parameters = []

# Loop through the distributions ot get line fit and paraemters

for dist_name in dist_names:
    # Set up distribution and store distribution paraemters
    dist = getattr(scipy.stats, dist_name)
    param = dist.fit(y)
    parameters.append(param)

    # Get line for each distribution (and scale to match observed data)
    pdf_fitted = dist.pdf(x, *param[:-2], loc=param[-2], scale=param[-1])
    scale_pdf = np.trapz (h[0], h[1][:-1]) / np.trapz (pdf_fitted, x)
    pdf_fitted *= scale_pdf

    # Add the line to the plot
    plt.plot(pdf_fitted, label=dist_name)

    # Set the plot x axis to contain 99% of the data
    # This can be removed, but sometimes outlier data makes the plot less clear
    plt.xlim(0,np.percentile(y,99))

# Add legend and display plotfig = plt.figure(figsize=(8,5))

plt.legend()
plt.title(u'Data distribution charateristics) \n' )
plt.xlabel(u'Resistance')
plt.ylabel('Frequency )')
plt.show()

# Store distribution paraemters in a dataframe (this could also be saved)
dist_parameters = pd.DataFrame()
dist_parameters['Distribution'] = (
        results['Distribution'].iloc[0:number_distributions_to_plot])
dist_parameters['Distribution parameters'] = parameters

# Print parameter results
print ('\nDistribution parameters:')
print ('------------------------')

for index, row in dist_parameters.iterrows():
    print ('\nDistribution:', row[0])
    print ('Parameters:', row[1] )
</code>```

答: If you look at the following categorical frequency analysis, you'll see that you have only 15 distinct values spread across the range with large gaps in between—not a continuum of values.  Half the observations have the value 0.211, with another ~36% occurring at the value 1.117, ~8% at 0.194, and ~4% at 0.001. I think it's a mistake to treat this as continuous data.

Title: Distribution plot is showing flat pdf

Body:
I tried to plot the Probability Density Function (PDF) plot of my data after finding the best parameters, but the plot is showing a flat line instead of a curve.

Is it a matter of scaling?

Is it a problem of Continuous or Discrete data? Data file is available here

The purpose here is to get the best distribution fittings and then plot PDF function.

My data values are so small like: 0.21, 1.117 .etc. The data statistics and PDF plots are shown below:

My script is given below:

from time import time
from datetime import datetime
start_time = datetime.now()
import pandas as pd
pd.options.display.float_format = '{:.4f}'.format
import numpy as np
import pickle
import scipy
import scipy.stats
import matplotlib.pyplot as plt

data= pd.read_csv("line_RXC_data.csv",usecols=['R'],parse_dates=True, squeeze=True)
df=data

y_std=df
# del yy

import warnings
warnings.filterwarnings("ignore")

# Create an index array (x) for data

y=df
#
# Create an index array (x) for data

x = np.arange(len(y))
size = len(y)

#simple visualisation of the data
plt.hist(y)
plt.title("Histogram of resistance ")
plt.xlabel("Resistance data visualization ")
plt.ylabel("Frequency")
plt.show()

y_df = pd.DataFrame(y)
tt=y_df.describe()
print(tt)

dist_names = [
                'foldcauchy',
                'beta',
                'expon',
                  'exponnorm',
                'norm',
                'lognorm',
                  'dweibull',
                'pareto',
                  'gamma'
]

x = np.arange(len(df))
size = len(df)
y_std = df
y=df
chi_square = []
p_values = []

# Set up 50 bins for chi-square test
# Observed data will be approximately evenly distrubuted aross all bins
percentile_bins = np.linspace(0,100,51)
percentile_cutoffs = np.percentile(y_std, percentile_bins)
observed_frequency, bins = (np.histogram(y_std, bins=percentile_cutoffs))
cum_observed_frequency = np.cumsum(observed_frequency)

# Loop through candidate distributions

for distribution in dist_names:
    s1 = time()
    # Set up distribution and get fitted distribution parameters
    dist = getattr(scipy.stats, distribution)
    # print("1")
    param = dist.fit(y_std)
    # print("2")
    # Obtain the KS test P statistic, round it to 5 decimal places
    p = scipy.stats.kstest(y_std, distribution, args=param)[1]
    p = np.around(p, 5)
    p_values.append(p)
    # print("3")
    # Get expected counts in percentile bins
    # This is based on a 'cumulative distrubution function' (cdf)
    cdf_fitted = dist.cdf(percentile_cutoffs, *param[:-2], loc=param[-2],
                          scale=param[-1])
    # print("4")
    expected_frequency = []
    for bin in range(len(percentile_bins)-1):
        expected_cdf_area = cdf_fitted[bin+1] - cdf_fitted[bin]
        expected_frequency.append(expected_cdf_area)

    # calculate chi-squared
    expected_frequency = np.array(expected_frequency) * size
    cum_expected_frequency = np.cumsum(expected_frequency)
    ss = sum (((cum_expected_frequency - cum_observed_frequency) ** 2) / cum_observed_frequency)
    chi_square.append(ss)
    print(f"chi_square {distribution} time: {time() - s1}")

#    print("std of predicted probability : ", np.std(cum_observed_frequency))

# Collate results and sort by goodness of fit (best at top)

results = pd.DataFrame()
results['Distribution'] = dist_names
results['chi_square'] = chi_square
results['p_value'] = p_values
results.sort_values(['chi_square'], inplace=True)

# Report results

print ('\nDistributions sorted by goodness of fit:')
print ('----------------------------------------')
print (results)

#%%

# Divide the observed data into 100 bins for plotting (this can be changed)
number_of_bins = 100
bin_cutoffs = np.linspace(np.percentile(y,0), np.percentile(y,99),number_of_bins)

# Create the plot
plt.figure(figsize=(7, 4))
h = plt.hist(y, bins = bin_cutoffs, color='0.70')

# Get the top three distributions from the previous phase
number_distributions_to_plot = 5
dist_names = results['Distribution'].iloc[0:number_distributions_to_plot]

#%%
# Create an empty list to stroe fitted distribution parameters
parameters = []

# Loop through the distributions ot get line fit and paraemters

for dist_name in dist_names:
    # Set up distribution and store distribution paraemters
    dist = getattr(scipy.stats, dist_name)
    param = dist.fit(y)
    parameters.append(param)

    # Get line for each distribution (and scale to match observed data)
    pdf_fitted = dist.pdf(x, *param[:-2], loc=param[-2], scale=param[-1])
    scale_pdf = np.trapz (h[0], h[1][:-1]) / np.trapz (pdf_fitted, x)
    pdf_fitted *= scale_pdf

    # Add the line to the plot
    plt.plot(pdf_fitted, label=dist_name)

    # Set the plot x axis to contain 99% of the data
    # This can be removed, but sometimes outlier data makes the plot less clear
    plt.xlim(0,np.percentile(y,99))

# Add legend and display plotfig = plt.figure(figsize=(8,5))

plt.legend()
plt.title(u'Data distribution charateristics) \n' )
plt.xlabel(u'Resistance')
plt.ylabel('Frequency )')
plt.show()

# Store distribution paraemters in a dataframe (this could also be saved)
dist_parameters = pd.DataFrame()
dist_parameters['Distribution'] = (
        results['Distribution'].iloc[0:number_distributions_to_plot])
dist_parameters['Distribution parameters'] = parameters

# Print parameter results
print ('\nDistribution parameters:')
print ('------------------------')

for index, row in dist_parameters.iterrows():
    print ('\nDistribution:', row[0])
    print ('Parameters:', row[1] )


问:
Why don't translate(${x},${y}) and translate(${-x},${-y}) cancel out?
This is a snippet from https://observablehq.com/@d3/non-contiguous-cartogram , which controls the transformation of the shape of states.

```<code>function transform(d, year) {
  const [x, y] = path.centroid(d);
  return `
    translate(${x},${y})
    scale(${Math.sqrt(data.get(d.id)[year])})
    translate(${-x},${-y})
  `;
}
</code>```

Since x and y are constants, shouldn't translate(${x},${y}) and translate(${-x},${-y}) cancel out?

Further, why does this mechanism secure the centroid in its old position?

答:
It is important to understand that SVG transformations are applied consecutively, i.e. order does matter. You cannot just add up numbers to consolidate a list of various transform definitions. In the words of the spec:

The value of the ‘transform’ attribute is a <transform-list>, which is defined as a list of transform definitions, which are applied in the order provided.

Each transform definition of that list manipulates the coordinate system that is the basis for all following transformations. Although, in your example, the translations are nominally of the same amount in opposing directions they do not cancel out because the scaling that happens in between changes the coordinate system along the way. Thus, the second translation does not cover the same distance as the first one.

To understand why those transformations keep the centroid in place it is helpful to write them down a bit more formally. Given the centroid's coodinates (xc, yc) and the scaling factor k we can write them as:

x ↦ xc + k (x − xc)

  y ↦ yc + k (y − yc)

Every original point (x, y) is mapped to the centroid (first terms) and then moved outwards to its original position, yet it is only moved a scaled down portion of the original distance (second terms).

Plugging the centroid itself into these rules shows the second terms cancelling out which keeps the centroid in its original place whereby centering the whole transformation on the centroid:

xc ↦ xc + k (xc − xc) = xc

  yc ↦ yc + k (yc − yc) = yc

Body:
This is a snippet from https://observablehq.com/@d3/non-contiguous-cartogram , which controls the transformation of the shape of states.

function transform(d, year) {
  const [x, y] = path.centroid(d);
  return `
    translate(${x},${y})
    scale(${Math.sqrt(data.get(d.id)[year])})
    translate(${-x},${-y})
  `;
}

Since x and y are constants, shouldn't translate(${x},${y}) and translate(${-x},${-y}) cancel out?

Further, why does this mechanism secure the centroid in its old position?


答:
Here is my solution to your question with just using basic functions in R:</p>

```<code>#step 1: read data from file
d <- read.csv("dt.csv", header = TRUE)
d
   ID           WearStart             WearEnd
1  1 2018-05-14 09:00:00 2018-05-14 20:00:00
2  1 2018-05-14 21:30:00 2018-05-15 02:00:00
3  1 2018-05-15 07:00:00 2018-05-16 22:30:00
4  1 2018-05-16 23:00:00 2018-05-16 23:40:00
5  1 2018-05-17 01:00:00 2018-05-19 15:00:00
6  2 2018-05-16 11:30:00 2018-05-16 11:40:00
7  2 2018-05-16 22:05:00 2018-05-22 22:42:00

#step 2: change class of WearStart and WearEnd to POSIlct
d$WearStart <- as.POSIXlt(d$WearStart, tryFormats = "%Y-%m-%d %H:%M")
d$WearEnd   <- as.POSIXlt(d$WearEnd, tryFormats = "%Y-%m-%d %H:%M")

#step 3: calculate time interval (days and hours) for each record
timeInt <- function(d) {
        WearStartDay  <- as.Date(d$WearStart, "%Y/%m/%d")
        Interval_days <- as.numeric(difftime(d$WearEnd,d$WearStart, units = "days"))
        Days <- WearStartDay + seq(0, Interval_days,1)
        N_FullBTWDays <- length(Days) - 2

        if (N_FullBTWDays >= 0) {
           sd   <- d$WearStart
           sd_h <- 24 - sd$hour -1
           sd_m <- (60 - sd$min)/60
           sd_total <- sd_h + sd_m
           hours <- sd_total
           hours <- c(hours, rep(24,N_FullBTWDays))
           ed   <- d$WearEnd
           ed_h <- ed$hour
           ed_m <- ed$min/60
           ed_total <- ed_h + ed_m
           hours <- c(hours,ed_total)
        } else {
         hours <- as.numeric(difftime(d$WearEnd,d$WearStart, units = "hours"))
        }
  df <- data.frame(id = rep(d$ID, length(Days)), days = Days, hours = hours)
  return(df)
  }

  df <- data.frame(matrix(ncol = 3, nrow = 0))
  colnames(df) <- c("id", "days", "hours")
  for ( i in 1:nrow(d)) {
   df <- rbind(df,timeInt(d[i,]))
  }

id       days      hours
1   1 2018-05-14 11.0000000
2   1 2018-05-14  4.5000000
3   1 2018-05-15 17.0000000
4   1 2018-05-16 22.5000000
5   1 2018-05-16  0.6666667
6   1 2018-05-17 23.0000000
7   1 2018-05-18 24.0000000
8   1 2018-05-19 15.0000000
9   2 2018-05-16  0.1666667
10  2 2018-05-16  1.9166667
11  2 2018-05-17 24.0000000
12  2 2018-05-18 24.0000000
13  2 2018-05-19 24.0000000
14  2 2018-05-20 24.0000000
15  2 2018-05-21 24.0000000
16  2 2018-05-22 22.7000000

#daily usage of device for each customer
res <- as.data.frame(tapply(df$hours, list(df$days,df$id), sum))
res[is.na(res)] <- 0
res$date <- rownames(res)
res
                  1         2       date
2018-05-14 15.50000  0.000000 2018-05-14
2018-05-15 17.00000  0.000000 2018-05-15
2018-05-16 23.16667  2.083333 2018-05-16
2018-05-17 23.00000 24.000000 2018-05-17
2018-05-18 24.00000 24.000000 2018-05-18
2018-05-19 15.00000 24.000000 2018-05-19
2018-05-20  0.00000 24.000000 2018-05-20
2018-05-21  0.00000 24.000000 2018-05-21
2018-05-22  0.00000 22.700000 2018-05-22
</code>```

Title: R: how can I split one row of a time period into multiple rows based on day and time

Body:
I am trying to split rows in an excel file based on day and time. The data is from a study which participants will need to wear a tracking watch. Each row of the data set is started with participants put on the watch (Variable: 'Wear Time Start ') and ended with them taking off the device (Variable: 'Wear Time End').

I need to calculate how many hours of each participant wearing the device on each day (NOT each time period in one row).

Data set before split:

   ID          WearStart                WearEnd
1  01           2018-05-14 09:00:00      2018-05-14 20:00:00
2  01           2018-05-14 21:30:00      2018-05-15 02:00:00
3  01           2018-05-15 07:00:00      2018-05-16 22:30:00
4  01           2018-05-16 23:00:00      2018-05-16 23:40:00
5  01           2018-05-17 01:00:00      2018-05-19 15:00:00
6  02           ...

Some explanation about the data set before split:  the data type of 'WearStart' and 'WearEnd' are POSIXlt.

Desired output after split:

  ID         WearStart                WearEnd                Interval
1 01         2018-05-14 09:00:00      2018-05-14 20:00:00    11
2 01         2018-05-14 21:30:00      2018-05-15 00:00:00    2.5
3 01         2018-05-15 00:00:00      2018-05-15 02:00:00    2
4 01         2018-05-15 07:00:00      2018-05-16 00:00:00    17
5 01         2018-05-16 00:00:00      2018-05-16 22:30:00    22.5
4 01         2018-05-16 23:00:00      2018-05-16 23:40:00    0.4
5 01         2018-05-17 01:00:00      2018-05-18 00:00:00    23
6 01         2018-05-18 00:00:00      2018-05-19 00:00:00    24
7 01         2018-05-19 00:00:00      2018-05-19 15:00:00    15

Then I need to accumulate hours based on day:

  ID         Wear_Day        Total_Hours
1 01         2018-05-14      13.5
2 01         2018-05-15      19
3 01         2018-05-16      22.9
4 01         2018-05-17      23
5 01         2018-05-18      24
4 01         2018-05-19      15

Body:
Here is my solution to your question with just using basic functions in R:

#step 1: read data from file
d <- read.csv("dt.csv", header = TRUE)
d
   ID           WearStart             WearEnd
1  1 2018-05-14 09:00:00 2018-05-14 20:00:00
2  1 2018-05-14 21:30:00 2018-05-15 02:00:00
3  1 2018-05-15 07:00:00 2018-05-16 22:30:00
4  1 2018-05-16 23:00:00 2018-05-16 23:40:00
5  1 2018-05-17 01:00:00 2018-05-19 15:00:00
6  2 2018-05-16 11:30:00 2018-05-16 11:40:00
7  2 2018-05-16 22:05:00 2018-05-22 22:42:00

#step 2: change class of WearStart and WearEnd to POSIlct
d$WearStart <- as.POSIXlt(d$WearStart, tryFormats = "%Y-%m-%d %H:%M")
d$WearEnd   <- as.POSIXlt(d$WearEnd, tryFormats = "%Y-%m-%d %H:%M")

#step 3: calculate time interval (days and hours) for each record
timeInt <- function(d) {
        WearStartDay  <- as.Date(d$WearStart, "%Y/%m/%d")
        Interval_days <- as.numeric(difftime(d$WearEnd,d$WearStart, units = "days"))
        Days <- WearStartDay + seq(0, Interval_days,1)
        N_FullBTWDays <- length(Days) - 2

        if (N_FullBTWDays >= 0) {
           sd   <- d$WearStart
           sd_h <- 24 - sd$hour -1
           sd_m <- (60 - sd$min)/60
           sd_total <- sd_h + sd_m
           hours <- sd_total
           hours <- c(hours, rep(24,N_FullBTWDays))
           ed   <- d$WearEnd
           ed_h <- ed$hour
           ed_m <- ed$min/60
           ed_total <- ed_h + ed_m
           hours <- c(hours,ed_total)
        } else {
         hours <- as.numeric(difftime(d$WearEnd,d$WearStart, units = "hours"))
        }
  df <- data.frame(id = rep(d$ID, length(Days)), days = Days, hours = hours)
  return(df)
  }

  df <- data.frame(matrix(ncol = 3, nrow = 0))
  colnames(df) <- c("id", "days", "hours")
  for ( i in 1:nrow(d)) {
   df <- rbind(df,timeInt(d[i,]))
  }

id       days      hours
1   1 2018-05-14 11.0000000
2   1 2018-05-14  4.5000000
3   1 2018-05-15 17.0000000
4   1 2018-05-16 22.5000000
5   1 2018-05-16  0.6666667
6   1 2018-05-17 23.0000000
7   1 2018-05-18 24.0000000
8   1 2018-05-19 15.0000000
9   2 2018-05-16  0.1666667
10  2 2018-05-16  1.9166667
11  2 2018-05-17 24.0000000
12  2 2018-05-18 24.0000000
13  2 2018-05-19 24.0000000
14  2 2018-05-20 24.0000000
15  2 2018-05-21 24.0000000
16  2 2018-05-22 22.7000000

#daily usage of device for each customer
res <- as.data.frame(tapply(df$hours, list(df$days,df$id), sum))
res[is.na(res)] <- 0
res$date <- rownames(res)
res
                  1         2       date
2018-05-14 15.50000  0.000000 2018-05-14
2018-05-15 17.00000  0.000000 2018-05-15
2018-05-16 23.16667  2.083333 2018-05-16
2018-05-17 23.00000 24.000000 2018-05-17
2018-05-18 24.00000 24.000000 2018-05-18
2018-05-19 15.00000 24.000000 2018-05-19
2018-05-20  0.00000 24.000000 2018-05-20
2018-05-21  0.00000 24.000000 2018-05-21
2018-05-22  0.00000 22.700000 2018-05-22


问:
Scala Option[(A, B)] pattern matching
I am writing a Java code generator.

I have an immutable Map that contains a mapping from java.sql.Types [Int] to a tuple of (String, String) where the first value is a Java type and the second a Java package from which to import the type if it is not imported by default (java.lang):

```<code>val SqlTypesToJavaTypeNames =
    Map(Types.BIGINT -> ("Long", None),
        Types.BINARY -> ("byte[]", None),
        Types.BIT -> ("Boolean", None),
        Types.BOOLEAN -> ("Boolean", None),
        Types.CHAR -> ("String", None),
        Types.DATE -> ("Date", Some("java.sql.Date")),
        Types.DECIMAL -> ("BigDecimal", Some("java.math.BigDecimal")),
        Types.DOUBLE -> ("Double", None),
        Types.FLOAT -> ("Float", None),
        Types.INTEGER -> ("Integer", None),
        Types.LONGNVARCHAR -> ("String", None),
        Types.LONGVARCHAR -> ("String", None),
        Types.NCHAR -> ("String", None),
        Types.NUMERIC -> ("BigDecimal", None),
        Types.NVARCHAR -> ("String", None),
        Types.REAL -> ("Float", None),
        Types.SMALLINT -> ("Short", None),
        Types.SQLXML -> ("String", None),
        Types.TIME -> ("Time", Some("java.sql.Time")),
        Types.TIMESTAMP -> ("Timestamp", Some("java.sql.Timestamp")),
        Types.TINYINT -> ("Byte", None),
        Types.VARCHAR -> ("String", None))
</code>```

I am trying to pattern match on a search of this map, where dataType is the java.sql.Types value from a database metadata:

```<code>val (javaType, importType) =
  SqlTypesToJavaTypeNames.get(dataType) match {
    case Some(jType, Some(iType)) => (jType, iType)
    case Some(jType, None) => (jType, null)
    case None => throw new IllegalStateException("Unknown translation to Java type for SQL type " + dataType)
  }
</code>```

The compiler is giving me an error on the first case (starts with case Some(jType, Some(iType))): error: wrong number of arguments for <none>: (x: (java.lang.String, Option[java.lang.String]))Some[(java.lang.String, Option[java.lang.String])]

I'm not sure what is wrong.

答:
You are missing the inner parens (because you have an Option[(A, B)]:

```<code>case Some( (jType, Some(iType)) ) =>
case Some( (jType, _) )           =>
case None                         =>
</code>```

From the looks of your method, it seems like you could simplify even more:

```<code>SqlTypesToJavaTypeNames.get(dataType) map { case (jType, maybeIType) => jType -> maybeIType.orNull } getOrElse error("Unmapped : " + dataType)
</code>```

Title: Scala Option[(A, B)] pattern matching

Body:
I am writing a Java code generator.

I have an immutable Map that contains a mapping from java.sql.Types [Int] to a tuple of (String, String) where the first value is a Java type and the second a Java package from which to import the type if it is not imported by default (java.lang):

val SqlTypesToJavaTypeNames =
    Map(Types.BIGINT -> ("Long", None),
        Types.BINARY -> ("byte[]", None),
        Types.BIT -> ("Boolean", None),
        Types.BOOLEAN -> ("Boolean", None),
        Types.CHAR -> ("String", None),
        Types.DATE -> ("Date", Some("java.sql.Date")),
        Types.DECIMAL -> ("BigDecimal", Some("java.math.BigDecimal")),
        Types.DOUBLE -> ("Double", None),
        Types.FLOAT -> ("Float", None),
        Types.INTEGER -> ("Integer", None),
        Types.LONGNVARCHAR -> ("String", None),
        Types.LONGVARCHAR -> ("String", None),
        Types.NCHAR -> ("String", None),
        Types.NUMERIC -> ("BigDecimal", None),
        Types.NVARCHAR -> ("String", None),
        Types.REAL -> ("Float", None),
        Types.SMALLINT -> ("Short", None),
        Types.SQLXML -> ("String", None),
        Types.TIME -> ("Time", Some("java.sql.Time")),
        Types.TIMESTAMP -> ("Timestamp", Some("java.sql.Timestamp")),
        Types.TINYINT -> ("Byte", None),
        Types.VARCHAR -> ("String", None))

I am trying to pattern match on a search of this map, where dataType is the java.sql.Types value from a database metadata:

val (javaType, importType) =
  SqlTypesToJavaTypeNames.get(dataType) match {
    case Some(jType, Some(iType)) => (jType, iType)
    case Some(jType, None) => (jType, null)
    case None => throw new IllegalStateException("Unknown translation to Java type for SQL type " + dataType)
  }

The compiler is giving me an error on the first case (starts with case Some(jType, Some(iType))): error: wrong number of arguments for <none>: (x: (java.lang.String, Option[java.lang.String]))Some[(java.lang.String, Option[java.lang.String])]

I'm not sure what is wrong.

Body:
You are missing the inner parens (because you have an Option[(A, B)]:

case Some( (jType, Some(iType)) ) =>
case Some( (jType, _) )           =>
case None                         =>

From the looks of your method, it seems like you could simplify even more:

SqlTypesToJavaTypeNames.get(dataType) map { case (jType, maybeIType) => jType -> maybeIType.orNull } getOrElse error("Unmapped : " + dataType)


问:
How to validate JWT Token using JWKS in Dot Net Core
In C#, I need to validate the Bearer Token against the JWKS (Json object which represent the set of keys like below)</p>

```<code>{
   "keys":[
      {
         "e":"AQAB",
         "kid":"unique key",
         "kty":"RSA",
         "n":"some value"
      }
   ]
}
</code>```

答:
You can do this using Microsoft's Nuget packages Microsoft.IdentityModel.Tokens and System.IdentityModel.Tokens.Jwt

Use following code to create token validator:

private static bool ValidateToken(string token, TokenValidationParameters validationParameters)
{
    var tokenHandler = new JwtSecurityTokenHandler();
    try
    {
        tokenHandler.ValidateToken(token, validationParameters, out var validatedToken);
        return validatedToken != null;
    }
    catch (Exception)
    {
        return false;
    }
}
```

<p>And for usage you have to load JWKS and select a key for validation parameters:</p>

<pre class="lang-cs prettyprint-override"><code>var jwksJson = @"
    {
       ""keys"":[
          {
             ""e"":""AQAB"",
             ""kid"":""unique key"",
             ""kty"":""RSA"",
             ""n"":""some value""
          }
       ]
    }";

var token = "eyJhb...";
var jwks = new JsonWebKeySet(jwksJson);
var jwk = jwks.Keys.First();

var validationParameters = new TokenValidationParameters
{
    IssuerSigningKey = jwk,
    ValidAudience = "", // Your API Audience, can be disabled via ValidateAudience = false
    ValidIssuer = ""  // Your token issuer, can be disabled via ValidateIssuer = false
};

var isValid = ValidateToken(token, validationParameters);
</code>```

Body:
In C#, I need to validate the Bearer Token against the JWKS (Json object which represent the set of keys like below)

{
   "keys":[
      {
         "e":"AQAB",
         "kid":"unique key",
         "kty":"RSA",
         "n":"some value"
      }
   ]
}

Body:
You can do this using Microsoft's Nuget packages Microsoft.IdentityModel.Tokens and System.IdentityModel.Tokens.Jwt

Use following code to create token validator:

private static bool ValidateToken(string token, TokenValidationParameters validationParameters)
{
    var tokenHandler = new JwtSecurityTokenHandler();
    try
    {
        tokenHandler.ValidateToken(token, validationParameters, out var validatedToken);
        return validatedToken != null;
    }
    catch (Exception)
    {
        return false;
    }
}

And for usage you have to load JWKS and select a key for validation parameters:

var jwksJson = @"
    {
       ""keys"":[
          {
             ""e"":""AQAB"",
             ""kid"":""unique key"",
             ""kty"":""RSA"",
             ""n"":""some value""
          }
       ]
    }";

var token = "eyJhb...";
var jwks = new JsonWebKeySet(jwksJson);
var jwk = jwks.Keys.First();

var validationParameters = new TokenValidationParameters
{
    IssuerSigningKey = jwk,
    ValidAudience = "", // Your API Audience, can be disabled via ValidateAudience = false
    ValidIssuer = ""  // Your token issuer, can be disabled via ValidateIssuer = false
};

var isValid = ValidateToken(token, validationParameters);


问:
Writing an brokerless AMQP to MQTT adaptor
I want to implement an amqp to mqtt adapter, which would receive amqp messages, take their payload and publish it as mqtt messages to my mqtt broker.
Therefore the adapter must be able to

listen on a port

confirm connect requests

receive amqp messages

acknowledge them

publish with mqtt

In my ecosystem I want to provide different protocols for incoming messages, but I want to run only one mqtt broker. I want to avoid any other broker.
I read here that amqp "1.0 permits brokerless point-to-point communication". I guess that would be the right thing for my use case (Although amqp 0-9-1 would be nice).

I have trouble coming up with a approach for this. The rabbitmq client library seems to be only for client to broker communication.

I have also gone through the qpid repo. With their broker library I'm able to start an embedded broker in my own project like shown here. That's a nice gimmick, but is not what I need.

The mqtt stuff is no problem for me. What bothers me is the "wait for amqp messages" part.

I have been researching for a couple hours. Am I blind here? Or is it really that uncommon/complex?

I would really appreciate any advice on possible libraries or examples from you or the web.

Thank you.

答:
Depending on the language you are using you can use either the Qpid proton-c or proton-j protocol engine and implement your own in memory AMQP 1.0 server style component that can listen on a server socket and then accept incoming AMQP 1.0 connections and deal with the messages as you see fit.  This does require you to have a pretty deep understanding of the protocol though and implement a fair bit of logic to deal with the variety of client behaviours you might see given the general flexibility of the AMQP 1.0 protocol.  </p>

<p>You might save yourself a fair bit of effort by using one of the many multi protocol brokers like ActiveMQ Artemis or some such to handle all that for you.  I think you might be able to leverage some of the higher level code in the proton C++ or C clients to help if you wanted to go your own way but it will still be a fair bit of work.  </p>

Body:
Depending on the language you are using you can use either the Qpid proton-c or proton-j protocol engine and implement your own in memory AMQP 1.0 server style component that can listen on a server socket and then accept incoming AMQP 1.0 connections and deal with the messages as you see fit.  This does require you to have a pretty deep understanding of the protocol though and implement a fair bit of logic to deal with the variety of client behaviours you might see given the general flexibility of the AMQP 1.0 protocol.

You might save yourself a fair bit of effort by using one of the many multi protocol brokers like ActiveMQ Artemis or some such to handle all that for you.  I think you might be able to leverage some of the higher level code in the proton C++ or C clients to help if you wanted to go your own way but it will still be a fair bit of work.


问:
Dialect needs to be explicitly supplied as of v4.0.0
I have been working on a NodeJS project which uses PostgreSQL database.
I am trying to implement migration to the database. Also, using Sequelize. After setting up the migration folder and config, it throws error while running db:migrate

The error is:
"Dialect needs to be explicitly supplied as of v4.0.0"

答:
This error can also be caused if there is an error in your model schema.

I had:

```<code>middle_name: {
    type: Sequelize.Sequelize,
    allowNull: false,
}
</code>```

Which should had been:

```<code>middle_name: {
    type: Sequelize.STRING,
    allowNull: false,
}
</code>```

Body:
This error can also be caused if there is an error in your model schema.

I had:

middle_name: {
    type: Sequelize.Sequelize,
    allowNull: false,
}

Which should had been:

middle_name: {
    type: Sequelize.STRING,
    allowNull: false,
}


问:
Do we need to specifically call previous state to retain previous values?
I currently have a state like so:

```<code>  const [startDate, setStartDate] = useState({
    bDay: new Date(),
    anniversary: new Date(),
  });
</code>```

Let us suppose I want to retain bDay and change anniversary date would I need to copy the previous state to change only part of it?

Like so:

```<code>    setDropdowns(prevState => ({
    ...prevState,
    anniversary: new Date(datefrom4yearsago)
  }))
</code>```

or can I just set the state for only the one I want and the state will be kept the same for all other object entries?

```<code>setDropdowns({anniversary: new Date(datefrom4yearsago)})
</code>```

答: With hooks one doesn't merge state anymore as in the case of this.setState, one overrides the state. So you have to use prevState if you only want to change one property of your state object.

Body:
I currently have a state like so:

  const [startDate, setStartDate] = useState({
    bDay: new Date(),
    anniversary: new Date(),
  });

Let us suppose I want to retain bDay and change anniversary date would I need to copy the previous state to change only part of it?

Like so:

    setDropdowns(prevState => ({
    ...prevState,
    anniversary: new Date(datefrom4yearsago)
  }))

or can I just set the state for only the one I want and the state will be kept the same for all other object entries?

setDropdowns({anniversary: new Date(datefrom4yearsago)})


问:
JavaScript add and remove class function on click
Basically I have this problem. I have an accordion that toggles one heading open at a time and I am having a problem adding in the open/close image that sits to the right of the heading.

I have it so far so that once you click a heading it removes the 'open' image and toggles another class for the 'close' image. Now I need to basically swap out these classes again so that if you toggle another heading it removes the other image and goes back to the original.

Here is the code I am using.

JavaScript

```<code><SCRIPT>
    $("#accordion > li").click(function () {
        $("#accordian li").removeClass("faq-header");
        $(this).addClass("faq-header2");
        if (false == $(this).next().is(':visible')) {
            $('#accordion > ul').slideUp(250);
            $('#accordion > ul').addClass('faq-header');
            $(this).removeClass("faq-header");
        }
        $(this).next().slideToggle(300);
    });

    $('#accordion > ul:eq(0)').show();
</SCRIPT>
</code>```

CSS

```<code>#accordion {
    list-style: none;
    margin-left:-38px;
}
#accordion ul:eq {
    background-image:url(../img/faq-open.gif);
    background-repeat:no-repeat;
    background-position:right;
    padding-right:20px;
}
#accordion li{
    display: block;
    background-color: #FFF;
    font-weight: bold;
    cursor: pointer;
}
.faq-header {
    text-align:left;
    background-image:url(../img/faq-close.gif);
    background-repeat:no-repeat;
    background-position:right;
    margin-right:20px;
}
.faq-header2 {
    text-align:left;
    background-image:url(../img/faq-open.gif);
    background-repeat:no-repeat;
    background-position:right;
    margin-right:20px;
}
#accordion ul {
    list-style: none;
    display: none;
}
#accordion ul li{
    font-weight: normal;
    cursor: auto;
    background-color: #fff;
    border-bottom:1px solid #999;
    margin-left:-38px !important;
}
</code>```

I have removed one class and added another class as you can see $("#accordian li").removeClass("faq-header"); and added the following $(this).addClass("faq-header2");

But I need to now remove .faq-header2 and add back .faq-header after it is no longer the section selected. It doesn't seem too hard to me but i just can't figure out how to code it. Should be a basic if function I would think...

答:
I think that toggle() function is a bit not intuitive. I usually use my pwn method replaceClass() to do as you want:

```<code>void replaceClass(Object classList, String surrogateClass, String classToReplace);
</code>```

defined as follow

```<code>function replaceClass(elementClassList, firstClass, secondClass) {
 if(elementClassList.contains(firstClass)){
 {
  elementClassList.remove(firstClass);
elementClassList.add(secondClass);
}
}
</code>```

Body:
Basically I have this problem. I have an accordion that toggles one heading open at a time and I am having a problem adding in the open/close image that sits to the right of the heading.

I have it so far so that once you click a heading it removes the 'open' image and toggles another class for the 'close' image. Now I need to basically swap out these classes again so that if you toggle another heading it removes the other image and goes back to the original.

Here is the code I am using.

JavaScript

CSS

#accordion {
    list-style: none;
    margin-left:-38px;
}
#accordion ul:eq {
    background-image:url(../img/faq-open.gif);
    background-repeat:no-repeat;
    background-position:right;
    padding-right:20px;
}
#accordion li{
    display: block;
    background-color: #FFF;
    font-weight: bold;
    cursor: pointer;
}
.faq-header {
    text-align:left;
    background-image:url(../img/faq-close.gif);
    background-repeat:no-repeat;
    background-position:right;
    margin-right:20px;
}
.faq-header2 {
    text-align:left;
    background-image:url(../img/faq-open.gif);
    background-repeat:no-repeat;
    background-position:right;
    margin-right:20px;
}
#accordion ul {
    list-style: none;
    display: none;
}
#accordion ul li{
    font-weight: normal;
    cursor: auto;
    background-color: #fff;
    border-bottom:1px solid #999;
    margin-left:-38px !important;
}

I have removed one class and added another class as you can see $("#accordian li").removeClass("faq-header"); and added the following $(this).addClass("faq-header2");

But I need to now remove .faq-header2 and add back .faq-header after it is no longer the section selected. It doesn't seem too hard to me but i just can't figure out how to code it. Should be a basic if function I would think...

Body:
I think that toggle() function is a bit not intuitive. I usually use my pwn method replaceClass() to do as you want:

void replaceClass(Object classList, String surrogateClass, String classToReplace);

defined as follow

function replaceClass(elementClassList, firstClass, secondClass) {
 if(elementClassList.contains(firstClass)){
 {
  elementClassList.remove(firstClass);
elementClassList.add(secondClass);
}
}


问:
Generating random points out of a triangle
I have the following code to generate random points on a given map. I want to avoid having points in the lake area (top right corner). I sort of divided the lake into a rectangle and a triangle. For the rectangle, I could figure out how to avoid having points in there. But, for the triangle (shown with the red line), I couldn't find a solution. Any suggestion? You can find the "Map.png" below the code.

```<code>import numpy as np
import matplotlib.pyplot as plt

def point_generator(number):
    xlist,ylist = [], []
    for i in range(number):
        x = np.random.uniform(BBox[0],BBox[1])
        y = np.random.uniform(BBox[2],BBox[3])
        while x>-87.8 and y>42.25:
            x = np.random.uniform(BBox[0],BBox[1])
            y = np.random.uniform(BBox[2],BBox[3])
        xlist.append(x); ylist.append(y)
    return(xlist,ylist)

BBox = ((-89.541239, -87.541239,
         40.773460, 42.498943))
im = plt.imread('Map.png')

fig, ax = plt.subplots(figsize = (15,15))
ax.set_xlim(BBox[0],BBox[1])
ax.set_ylim(BBox[2],BBox[3])

plt.plot([-87.8,-87.8],[42.25,42.498943],'-k')
plt.plot([-87.8,-87.541239],[42.25,42.25],'-k')
plt.plot([-87.8,-87.541239],[42.25,41.75],'-r')

xs,ys = point_generator(1500)
plt.plot(xs,ys, '.b')
ax.imshow(im, zorder=0, extent = BBox, aspect= 'equal',alpha=0.5)
</code>```

答:
You can use the underlying color from the image to check if your points are legit.

```<code>import numpy as np
import matplotlib.pyplot as plt
from PIL import Image

def bBoxPointToColor(px,w,h,BBox,point):
    row = int(((BBox[3]-point[1])/(BBox[3]-BBox[2]))*h)
    col = int(((point[0]-BBox[0])/(BBox[1]-BBox[0]))*w)
    return sum(abs(k[0]-k[1]) for k in zip(px[col,row],(159, 214, 255))) < 10

def point_generator(number,BBox):
    img = Image.open('Chicago.jpg')
    px = img.load()
    xlist,ylist = [], []
    for i in range(number):
        x = np.random.uniform(BBox[0],BBox[1])
        y = np.random.uniform(BBox[2],BBox[3])
        while bBoxPointToColor(px,img.width,img.height,BBox,[x,y]):
            x = np.random.uniform(BBox[0],BBox[1])
            y = np.random.uniform(BBox[2],BBox[3])
        xlist.append(x); ylist.append(y)
    return(xlist,ylist)

BBox = ((-89.541239, -87.541239,
         40.773460, 42.498943))

im = plt.imread('Chicago.jpg')

fig, ax = plt.subplots(figsize = (15,15))
ax.set_xlim(BBox[0],BBox[1])
ax.set_ylim(BBox[2],BBox[3])

xs,ys = point_generator(1500,BBox)
plt.plot(xs,ys, '.b')
ax.imshow(im, zorder=0, extent = BBox, aspect= 'equal',alpha=0.5)
plt.show()
</code>```

you can see the issue is that where there is a label on top of the water the point get's drawn on the label... But the benefit is that with this approach you don't have to do custom geometry for new map sections.

Body:
I have the following code to generate random points on a given map. I want to avoid having points in the lake area (top right corner). I sort of divided the lake into a rectangle and a triangle. For the rectangle, I could figure out how to avoid having points in there. But, for the triangle (shown with the red line), I couldn't find a solution. Any suggestion? You can find the "Map.png" below the code.

import numpy as np
import matplotlib.pyplot as plt

def point_generator(number):
    xlist,ylist = [], []
    for i in range(number):
        x = np.random.uniform(BBox[0],BBox[1])
        y = np.random.uniform(BBox[2],BBox[3])
        while x>-87.8 and y>42.25:
            x = np.random.uniform(BBox[0],BBox[1])
            y = np.random.uniform(BBox[2],BBox[3])
        xlist.append(x); ylist.append(y)
    return(xlist,ylist)

BBox = ((-89.541239, -87.541239,
         40.773460, 42.498943))
im = plt.imread('Map.png')

fig, ax = plt.subplots(figsize = (15,15))
ax.set_xlim(BBox[0],BBox[1])
ax.set_ylim(BBox[2],BBox[3])

plt.plot([-87.8,-87.8],[42.25,42.498943],'-k')
plt.plot([-87.8,-87.541239],[42.25,42.25],'-k')
plt.plot([-87.8,-87.541239],[42.25,41.75],'-r')

xs,ys = point_generator(1500)
plt.plot(xs,ys, '.b')
ax.imshow(im, zorder=0, extent = BBox, aspect= 'equal',alpha=0.5)

Body:
You can use the underlying color from the image to check if your points are legit.

import numpy as np
import matplotlib.pyplot as plt
from PIL import Image

def bBoxPointToColor(px,w,h,BBox,point):
    row = int(((BBox[3]-point[1])/(BBox[3]-BBox[2]))*h)
    col = int(((point[0]-BBox[0])/(BBox[1]-BBox[0]))*w)
    return sum(abs(k[0]-k[1]) for k in zip(px[col,row],(159, 214, 255))) < 10

def point_generator(number,BBox):
    img = Image.open('Chicago.jpg')
    px = img.load()
    xlist,ylist = [], []
    for i in range(number):
        x = np.random.uniform(BBox[0],BBox[1])
        y = np.random.uniform(BBox[2],BBox[3])
        while bBoxPointToColor(px,img.width,img.height,BBox,[x,y]):
            x = np.random.uniform(BBox[0],BBox[1])
            y = np.random.uniform(BBox[2],BBox[3])
        xlist.append(x); ylist.append(y)
    return(xlist,ylist)

BBox = ((-89.541239, -87.541239,
         40.773460, 42.498943))

im = plt.imread('Chicago.jpg')

fig, ax = plt.subplots(figsize = (15,15))
ax.set_xlim(BBox[0],BBox[1])
ax.set_ylim(BBox[2],BBox[3])

xs,ys = point_generator(1500,BBox)
plt.plot(xs,ys, '.b')
ax.imshow(im, zorder=0, extent = BBox, aspect= 'equal',alpha=0.5)
plt.show()

you can see the issue is that where there is a label on top of the water the point get's drawn on the label... But the benefit is that with this approach you don't have to do custom geometry for new map sections.


问:
Is it possible to get reference to comment element/block by JavaScript?
This sounds a little crazy, but I'm wondering whether possible to get reference to comment element so that I can dynamically replace it other content with JavaScript.

```<code><html>
<head>
</head>
<body>
<div id="header"></div>
<div id="content"></div>
<!-- sidebar place holder: some id-->
</body>
</html>
</code>```

In above page, can I get reference to the comment block and replace it with some content in local storage?

I know that I can have a div place holder. Just wondering whether it applies to comment block.
Thanks.

答:
If you just want to get an array of all comments from a document or part of a document, then this is the most efficient way I've found to do that in modern JavaScript.

```<code>function getComments (root) {

    var treeWalker = document.createTreeWalker(
        root,
        NodeFilter.SHOW_COMMENT,
        {
            "acceptNode": function acceptNode (node) {
                return NodeFilter.FILTER_ACCEPT;
            }
        }
    );

    // skip the first node which is the node specified in the `root`
    var currentNode = treeWalker.nextNode();

    var nodeList = [];
    while (currentNode) {

        nodeList.push(currentNode);
        currentNode = treeWalker.nextNode();

    }

    return nodeList;

}
</code>```

I am getting over 50,000 operations per second in Chrome 80 and the stack and recursion methods both get less than 5,000 operations per second in Chrome 80. I had tens of thousands of complex documents to process in node.js and this worked the best for me.

https://jsperf.com/getcomments/6

Body:
This sounds a little crazy, but I'm wondering whether possible to get reference to comment element so that I can dynamically replace it other content with JavaScript.

In above page, can I get reference to the comment block and replace it with some content in local storage?

I know that I can have a div place holder. Just wondering whether it applies to comment block.
Thanks.

Body:
If you just want to get an array of all comments from a document or part of a document, then this is the most efficient way I've found to do that in modern JavaScript.

function getComments (root) {

    var treeWalker = document.createTreeWalker(
        root,
        NodeFilter.SHOW_COMMENT,
        {
            "acceptNode": function acceptNode (node) {
                return NodeFilter.FILTER_ACCEPT;
            }
        }
    );

    // skip the first node which is the node specified in the `root`
    var currentNode = treeWalker.nextNode();

    var nodeList = [];
    while (currentNode) {

        nodeList.push(currentNode);
        currentNode = treeWalker.nextNode();

    }

    return nodeList;

}

I am getting over 50,000 operations per second in Chrome 80 and the stack and recursion methods both get less than 5,000 operations per second in Chrome 80. I had tens of thousands of complex documents to process in node.js and this worked the best for me.

https://jsperf.com/getcomments/6


问:
Using table() function from base with dplyr pipe-syntax?
I enjoy the syntax of dplyr, but I'm struggling with easily obtaining a contingency table in the same way that I can get with the base R table() function. table() is OK, but I can't figure out how to incorporate it into the dplyr pipe syntax.

Thank you for your help.

Here is some example data that has the output I'm trying to get to.

```<code>df <- tibble(id=c(rep("A",100),rep("B",100),rep("C",100)),
               val=c(rnorm(300,mean=500,sd=100))) %>%
  mutate(val_bin=cut(val,breaks=5))

table(df$id,df$val_bin)
</code>```

Output:

```<code>    (210,325] (325,440] (440,554] (554,669] (669,784]
  A         4        22        55        18         1
  B         6        19        46        24         5
  C         3        23        44        22         8
</code>```

答:
One option is to use with:

df %>%
  with(., table(id, val_bin))
#    val_bin
# id  (228,327] (327,426] (426,525] (525,624] (624,723]
#   A         4        19        39        22        16
#   B         5        15        41        32         7
#   C         5        14        44        25        12
```

<p>Technically, the <code>.</code> is not required,</p>

<pre class="lang-r prettyprint-override"><code>df %>%
  with(table(id, val_bin))
</code>```

but I find it is perhaps a little clearer in situations where it might be easy to confuse where the data is going (within with or table). (Hint: it's just about always the first function, with here.)

Body:
I enjoy the syntax of dplyr, but I'm struggling with easily obtaining a contingency table in the same way that I can get with the base R table() function. table() is OK, but I can't figure out how to incorporate it into the dplyr pipe syntax.

Thank you for your help.

Here is some example data that has the output I'm trying to get to.

df <- tibble(id=c(rep("A",100),rep("B",100),rep("C",100)),
               val=c(rnorm(300,mean=500,sd=100))) %>%
  mutate(val_bin=cut(val,breaks=5))

table(df$id,df$val_bin)

Output:

    (210,325] (325,440] (440,554] (554,669] (669,784]
  A         4        22        55        18         1
  B         6        19        46        24         5
  C         3        23        44        22         8

Body:
One option is to use with:

df %>%
  with(., table(id, val_bin))
#    val_bin
# id  (228,327] (327,426] (426,525] (525,624] (624,723]
#   A         4        19        39        22        16
#   B         5        15        41        32         7
#   C         5        14        44        25        12

Technically, the . is not required,

df %>%
  with(table(id, val_bin))

but I find it is perhaps a little clearer in situations where it might be easy to confuse where the data is going (within with or table). (Hint: it's just about always the first function, with here.)