问:
Mishandled Disposal of Agents in a NEAT algorithm
I have spent countless hours trying to come up with a solution but I just can't seem to find it.
This is in NodeJS using the tensorflow.js library for the neural networks of each agent:

```<code>function nextGeneration(agents) {
  return tf.tidy(()=>{
    calculateFitness(agents);

    const bestAgent = agents.reduce((best, agent) => agent.score > best.score ? agent : best, agents[0]);
    console.log("Best score: " + bestAgent.score);

    agents[0].brain = bestAgent.brain;
    agents[0].score = 1;
    agents[0].dead = false;

    let newAgents = [];

    for (let i = 1; i < agents.length; i++) {
      const parent = agents[pickOne(agents)];
      newAgents.push(new MathLearner(copyBrain(parent.brain)));
      newAgents[i - 1].mutate(0.5);
    }

    for(let i = 1; i < agents.length; i++) {
      agents[i].brain.dispose();
      agents[i] = newAgents[i - 1];
    }

    return agents;
  });

}
</code>```

If you ignore the newAgents for a moment, the code totally works, it picks from the best performing agents, copies their brain, and mutates it, while still keeping the best performing agent in each generation. But the code without newAgents, here it is:

```<code>for(let i = 1; i < agents.length; i++){
        let parent = agents[pickOne(agents)];
        agents[i].brain = copyBrain(parent.brain);
        agents[i].mutate(0.5);
        agents[i].score = 1;
        agents[i].dead = false;
}
</code>```

has a memory leak, so I was obligated to find a solution to dispose of the old agents while still being able to pick from the agents, so I went for the newAgents method, which basically saves the brains by reference then disposes of them after the mutations.
But now I am stuck, because this code creates this error: Error: Layer 'dense_Densexx' is already disposed. (xx being random digits) when the agents are evaluated, meaning one or a big part of them has their brain disposed, and not ready for prediction.
Here is the pickOne, copyBrain and evaluation function

```<code>function pickOne(agents) {
  let index = 0;
  let r = Math.random(1);
  while (r > 0) {
    r = r - agents[index].fitness;
    index++;
  }
  return index - 1;
}
</code>```
```<code>function copyBrain(brain) {
  return tf.tidy(()=>{
    const newBrain = tf.sequential();
    newBrain.add(
      tf.layers.dense({
        units: 16,
        inputShape: [2],
        activation: "sigmoid",
        useBias: true,
        kernelInitializer: "randomUniform",
      })
    );
    newBrain.add(
      tf.layers.dense({
        units: 1,
        activation: "sigmoid",
        useBias: true,
        kernelInitializer: "randomUniform",
      })
    );
    for (let i = 0; i < brain.layers.length; i++) {
      const layer = brain.layers[i];
      const originalWeights = layer.getWeights()[0];
      const originalBiases = layer.getWeights()[1];
      const weightsData = originalWeights.dataSync();
      const biasesData = originalBiases.dataSync();

      newBrain.layers[i].setWeights([
        tf.tensor(weightsData, originalWeights.shape),
        tf.tensor(biasesData, originalBiases.shape),
      ]);
    }
    return newBrain;
  })

}
</code>```
```<code>const MathLearner = require("./MathAgent.js");
const ga = require("./ga.js");
const v8 = require('v8');
const tf = require("@tensorflow/tfjs");
require("@tensorflow/tfjs-node");

const structuredClone = obj => {
    return v8.deserialize(v8.serialize(obj));
};

const getRandomNumbers = () => {
    let a = [];
    let b = [];
    for (let i = 0; i < 100; i++) {
        a.push(Math.floor(Math.random() * 11));
        b.push(Math.floor(Math.random() * 11));
    }
    return {a, b};
};

const createAgents = (numAgents) => {
    let agents = [];
    for (let i = 0; i < numAgents; i++) {
        agents.push(new MathLearner());
    }
    return agents;
};

const evaluateAgents = (agents, a, b) => {
    tf.tidy(() => {
        let counter = 0;
        const scores = agents.map((agent) => {
            if (!agent.dead) {
                let totalError = 0;

                for (let j = 0; j < 100; j++) {
                    // Predict the sum of two random numbers using the neural network
                    let prediction = agent.predict([a[j] / 10, b[j] / 10]) * 22;
                    // Calculate the error between the prediction and the actual sum
                    let error = prediction > (a[j] + b[j]) ? prediction - (a[j] + b[j]) : (a[j] + b[j]) - prediction;
                    // Add the error to the total error
                    totalError += error;
                }
                console.log("Agent " + counter);
                counter++;
                // Return the inverse of the total error (the higher the error, the lower the score)
                return 1 / totalError;
            }
        });
        agents.forEach((agent, i) => agent.score = scores[i]);
    });
};

const runSimulation = (numAgents) => {
    const {a, b} = getRandomNumbers();
    let agents = createAgents(numAgents);
    let iterations = 0;
    let generations = 0;
    let aliveCounter = 0;
    while (true) {
        evaluateAgents(agents, a, b);
        generations++;
        iterations = 0;
        console.log(`Generation ${generations} alive counter: ${aliveCounter}/${numAgents}`);
        aliveCounter = 0;
        agents = ga.nextGeneration(agents);
    }
};

runSimulation(10);
</code>```

The code is basically trying to evolve agents to be able to sum two numbers together. (it's just a basis upon I'll build other projects onto)

What did you try ?
I tried using tf.tidy in most places to minimize the memory leak, that worked for the most part in the evaluation function but it will not solve the problem I have with the copyBrain function and nextGeneration because there is still memory being leaked (can see it with console.log(tf.memory()) ).
I tried multiple ways of saving the brains (tf models) by reference to dispose of them later, but all of the ways I've tried result in the same Error: Layer 'dense_Densexx' is already disposed. error.

Body:
I have spent countless hours trying to come up with a solution but I just can't seem to find it.
This is in NodeJS using the tensorflow.js library for the neural networks of each agent:

function nextGeneration(agents) {
  return tf.tidy(()=>{
    calculateFitness(agents);

    const bestAgent = agents.reduce((best, agent) => agent.score > best.score ? agent : best, agents[0]);
    console.log("Best score: " + bestAgent.score);

    agents[0].brain = bestAgent.brain;
    agents[0].score = 1;
    agents[0].dead = false;

    let newAgents = [];

    for (let i = 1; i < agents.length; i++) {
      const parent = agents[pickOne(agents)];
      newAgents.push(new MathLearner(copyBrain(parent.brain)));
      newAgents[i - 1].mutate(0.5);
    }

    for(let i = 1; i < agents.length; i++) {
      agents[i].brain.dispose();
      agents[i] = newAgents[i - 1];
    }

    return agents;
  });

}

If you ignore the newAgents for a moment, the code totally works, it picks from the best performing agents, copies their brain, and mutates it, while still keeping the best performing agent in each generation. But the code without newAgents, here it is:

for(let i = 1; i < agents.length; i++){
        let parent = agents[pickOne(agents)];
        agents[i].brain = copyBrain(parent.brain);
        agents[i].mutate(0.5);
        agents[i].score = 1;
        agents[i].dead = false;
}

has a memory leak, so I was obligated to find a solution to dispose of the old agents while still being able to pick from the agents, so I went for the newAgents method, which basically saves the brains by reference then disposes of them after the mutations.
But now I am stuck, because this code creates this error: Error: Layer 'dense_Densexx' is already disposed. (xx being random digits) when the agents are evaluated, meaning one or a big part of them has their brain disposed, and not ready for prediction.
Here is the pickOne, copyBrain and evaluation function

function pickOne(agents) {
  let index = 0;
  let r = Math.random(1);
  while (r > 0) {
    r = r - agents[index].fitness;
    index++;
  }
  return index - 1;
}

function copyBrain(brain) {
  return tf.tidy(()=>{
    const newBrain = tf.sequential();
    newBrain.add(
      tf.layers.dense({
        units: 16,
        inputShape: [2],
        activation: "sigmoid",
        useBias: true,
        kernelInitializer: "randomUniform",
      })
    );
    newBrain.add(
      tf.layers.dense({
        units: 1,
        activation: "sigmoid",
        useBias: true,
        kernelInitializer: "randomUniform",
      })
    );
    for (let i = 0; i < brain.layers.length; i++) {
      const layer = brain.layers[i];
      const originalWeights = layer.getWeights()[0];
      const originalBiases = layer.getWeights()[1];
      const weightsData = originalWeights.dataSync();
      const biasesData = originalBiases.dataSync();

      newBrain.layers[i].setWeights([
        tf.tensor(weightsData, originalWeights.shape),
        tf.tensor(biasesData, originalBiases.shape),
      ]);
    }
    return newBrain;
  })

}

const MathLearner = require("./MathAgent.js");
const ga = require("./ga.js");
const v8 = require('v8');
const tf = require("@tensorflow/tfjs");
require("@tensorflow/tfjs-node");

const structuredClone = obj => {
    return v8.deserialize(v8.serialize(obj));
};

const getRandomNumbers = () => {
    let a = [];
    let b = [];
    for (let i = 0; i < 100; i++) {
        a.push(Math.floor(Math.random() * 11));
        b.push(Math.floor(Math.random() * 11));
    }
    return {a, b};
};

const createAgents = (numAgents) => {
    let agents = [];
    for (let i = 0; i < numAgents; i++) {
        agents.push(new MathLearner());
    }
    return agents;
};

const evaluateAgents = (agents, a, b) => {
    tf.tidy(() => {
        let counter = 0;
        const scores = agents.map((agent) => {
            if (!agent.dead) {
                let totalError = 0;

                for (let j = 0; j < 100; j++) {
                    // Predict the sum of two random numbers using the neural network
                    let prediction = agent.predict([a[j] / 10, b[j] / 10]) * 22;
                    // Calculate the error between the prediction and the actual sum
                    let error = prediction > (a[j] + b[j]) ? prediction - (a[j] + b[j]) : (a[j] + b[j]) - prediction;
                    // Add the error to the total error
                    totalError += error;
                }
                console.log("Agent " + counter);
                counter++;
                // Return the inverse of the total error (the higher the error, the lower the score)
                return 1 / totalError;
            }
        });
        agents.forEach((agent, i) => agent.score = scores[i]);
    });
};

const runSimulation = (numAgents) => {
    const {a, b} = getRandomNumbers();
    let agents = createAgents(numAgents);
    let iterations = 0;
    let generations = 0;
    let aliveCounter = 0;
    while (true) {
        evaluateAgents(agents, a, b);
        generations++;
        iterations = 0;
        console.log(`Generation ${generations} alive counter: ${aliveCounter}/${numAgents}`);
        aliveCounter = 0;
        agents = ga.nextGeneration(agents);
    }
};

runSimulation(10);

The code is basically trying to evolve agents to be able to sum two numbers together. (it's just a basis upon I'll build other projects onto)

What did you try ?
I tried using tf.tidy in most places to minimize the memory leak, that worked for the most part in the evaluation function but it will not solve the problem I have with the copyBrain function and nextGeneration because there is still memory being leaked (can see it with console.log(tf.memory()) ).
I tried multiple ways of saving the brains (tf models) by reference to dispose of them later, but all of the ways I've tried result in the same Error: Layer 'dense_Densexx' is already disposed. error.


来源: stackexchange

问:
Firebase passwordless sign-up email address without localStorage
When using passwordless sign-up for web with Firebase the expectation for same-device sign-up is that you enter your email address, a magic link is sent to your email address, you click the magic link which returns you to the website with a parameter in the URL that should give Firebase almost enough information to finish the sign-up process.

However, as a safety check, if the device/browser used when clicking the link is not the same as the device/browser that was used to initiate the sign-up Firebase expects the user to re-confirm their email address. For same device/browser sign-ups, Firebase is supposed to remember the email address locally to skip/avoid this step.

In the past it seems Firebase has been able to skip over this extra email entry check by putting the email address on sign-up into localStorage, as per numerous references and documentation around the web and in their docs (see the localStorage.set). However, it seems Firebase doesn't use localStorage for this anymore, but instead stores the information in indexedDB.

My issue is that when the user returns to the page in order to finish sign-up I need to call signInWithEmailLink(auth, email, window.location.href);, but I don't have the email parameter and there doesn't seem to be an API call in Firebase (unless I've missed it) to fetch this email address from indexedDB at this stage. I can see that it's stored there in the browser storage, but short of directly calling indexedDB APIs themselves (which runs the risk of breaking changes in future updates to firebase) I'm not sure how to retrieve this value.

There's some suggestion that the answer may be in implementing onAuthStateChanged, but this returns null at this stage (presumably because the user is not yet confirmed?).

Currently, this is leaving me in the position of having to re-prompt the user to enter their email address even on the same device, or to instead manually set localStorage, sessionStorage, or access indexedDB directly.

ContentLicense: CC BY-SA 4.0


问:
Django , map sql output with different values using dictionary and send them to template
I have a function that I use to show number of citizens and countries in charts.js

```<code>def Inbound_top_20(request):
    cursor1 = connections['default'].cursor()  # calling default database connection
    cursor1.execute("select citizens, countries from world")
    r1 = dictfetchall(cursor1)  # calling dictfetchall function , because I use raw sql

    D1 = {"1-1": "France", "2-2": "Spain", "3-3": "Germany", ...}  # a dictionary
    return render(request,'app_sins/countries .html', {"show1": r1, "D1": D1})
</code>```

output of query  are values of citizens, and name of countries, but countries are represented as strings: "1-1", "2-2", "3-3", etc.

I wish to map SQL output for countries using dictionary D1, to give them real names, not strings "1-1" or "2-2".

After that I need to visualize them through the charts.js. Below is extract from charts.js using column countries which works fine for strings ("1-1"  or "2-2" ...)

// ...
const ctx11 = document.getElementById('myChart11').getContext('2d');
const myChart11 = new Chart(ctx11, {
    type: 'line',
    data: {
        labels: [{% for show1 in show1%}
            '{{show1.countries}}',
        {% endfor %}],
    },
    // ...
});
// ...
```

How I can easily map SQL output strings ("1-1", "2-2", etc.) to real names  and put them in template tags?

Body:
I have a function that I use to show number of citizens and countries in charts.js

def Inbound_top_20(request):
    cursor1 = connections['default'].cursor()  # calling default database connection
    cursor1.execute("select citizens, countries from world")
    r1 = dictfetchall(cursor1)  # calling dictfetchall function , because I use raw sql

    D1 = {"1-1": "France", "2-2": "Spain", "3-3": "Germany", ...}  # a dictionary
    return render(request,'app_sins/countries .html', {"show1": r1, "D1": D1})

output of query  are values of citizens, and name of countries, but countries are represented as strings: "1-1", "2-2", "3-3", etc.

I wish to map SQL output for countries using dictionary D1, to give them real names, not strings "1-1" or "2-2".

After that I need to visualize them through the charts.js. Below is extract from charts.js using column countries which works fine for strings ("1-1"  or "2-2" ...)

// ...
const ctx11 = document.getElementById('myChart11').getContext('2d');
const myChart11 = new Chart(ctx11, {
    type: 'line',
    data: {
        labels: [{% for show1 in show1%}
            '{{show1.countries}}',
        {% endfor %}],
    },
    // ...
});
// ...

How I can easily map SQL output strings ("1-1", "2-2", etc.) to real names  and put them in template tags?


问:
Module not found: Error: Can't resolve error when importing custom NPM Module
I am attempting to create a NPM module that has all the Typescript Types for a service. It seems to be recognizing everything when importing the library. But when I run I get the error

Module not found: Error: Can't resolve '@[npm-package-name]'

I have tried a few different versions of the typescript declaration files. and they all have the same issue. Here is the code I have currently.

src/index.d.ts

```<code>import { Tag as tag } from './types/tag'

export = ModuleName;

declare module ModuleName {
  // Tag Types
  interface Tag extends tag { }

  // Commom Enums
  export enum EnumExample {
    Unknown = "unknown",
    Absolute = "absolute",
    Relative = "relative",
  }
}
</code>```

src/types/tag.d.ts

```<code>export interface Tag {
  Text: string;
}
</code>```

package.json

```<code>{
  "name": "[NPM-Name]",
  "version": "0.0.7",
  "description": "definition",
  "main": "src/index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git-url"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "git-url/issues"
  },
  "homepage": "git-url#readme",
  "devDependencies": {
    "@types/node": "^18.11.18",
    "typescript": "^4.9.4"
  },
  "dependencies": {
    "dayjs": "^1.11.7"
  }
}
</code>```

tsconfig.json

```<code>{
  "files": [
    "src/index.d.ts"
  ],
  "compilerOptions": {
    "module": "commonjs",
    "lib": [
      "es6",
      "dom"
    ],
    "noImplicitAny": true,
    "noImplicitThis": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "baseUrl": "../",
    "typeRoots": [
      "../"
    ],
    "types": [],
    "noEmit": true,
    "forceConsistentCasingInFileNames": true,
    "jsx": "preserve"
  }
}
</code>```

Body:
I am attempting to create a NPM module that has all the Typescript Types for a service. It seems to be recognizing everything when importing the library. But when I run I get the error

Module not found: Error: Can't resolve '@[npm-package-name]'

I have tried a few different versions of the typescript declaration files. and they all have the same issue. Here is the code I have currently.

src/index.d.ts

import { Tag as tag } from './types/tag'

export = ModuleName;

declare module ModuleName {
  // Tag Types
  interface Tag extends tag { }

  // Commom Enums
  export enum EnumExample {
    Unknown = "unknown",
    Absolute = "absolute",
    Relative = "relative",
  }
}

src/types/tag.d.ts

export interface Tag {
  Text: string;
}

package.json

{
  "name": "[NPM-Name]",
  "version": "0.0.7",
  "description": "definition",
  "main": "src/index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git-url"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "git-url/issues"
  },
  "homepage": "git-url#readme",
  "devDependencies": {
    "@types/node": "^18.11.18",
    "typescript": "^4.9.4"
  },
  "dependencies": {
    "dayjs": "^1.11.7"
  }
}

tsconfig.json

{
  "files": [
    "src/index.d.ts"
  ],
  "compilerOptions": {
    "module": "commonjs",
    "lib": [
      "es6",
      "dom"
    ],
    "noImplicitAny": true,
    "noImplicitThis": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "baseUrl": "../",
    "typeRoots": [
      "../"
    ],
    "types": [],
    "noEmit": true,
    "forceConsistentCasingInFileNames": true,
    "jsx": "preserve"
  }
}


问:
Incorrect output after returning elements between dates from a list
I'm working on a problem where I have to return postcodes from a list based on the time they have been added. For example, the user sets 12-2 then all the post codes added between 12 & 2 would be returned.

I've written a method, although currently the output is not as expected. The expected output is to be only the post code such as:

26-006
15-150
```
<p>Whereas now I have: <code>StringContainer{size=4, head=kod pocztowy kod pocztowy kod pocztowy kod pocztowy kod pocztowy kod pocztowy null 2023-01-09T21:34:44.197357200 2023-01-09T21:34:44.197357200 2023-01-09T21:34:44.197357200 2023-01-09T21:34:44.197357200 2023-01-09T21:34:44.197357200 null</code></p>
<p>It returns the postcodes + time etc.</p>
<p>Could you advise how to fix this?</p>
<p>Here is my current code:</p>
<pre class="lang-java prettyprint-override"><code>public class StringContainer {
    private int size = 0;
    private StringElement head = new StringElement(null);
    private Pattern pattern;

    public StringContainer(String regex) {
        clear();
        this.pattern = Pattern.compile(regex);
    }

    public void clear() {
        head.setNext(null);
        size = 0;
    }

    public void add(String value) {
        Matcher matcher = pattern.matcher(value);
        try {
            if (matcher.matches()) {
                if (head.getNext() == null) {
                    head.setNext(new StringElement(value, null, LocalDateTime.now()));
                }
                StringElement last = head.getNext();
                while (last.getNext() != null)
                    last = last.getNext();
                ++size;
                last.setNext(new StringElement(value, null, LocalDateTime.now()));
            } else {
                throw new InvalidStringContainerPatternException("Nie maczuje się");
            }
        } catch (InvalidStringContainerPatternException e) {
            e.printStackTrace();
        }
    }

    public boolean delete(Object o) {
        if (head.getNext() == null) return false;
        if (head.getNext().getValue().equals(o)) {
            head.setNext(head.getNext().getNext());
            size--;
            return true;
        }
        StringElement delete = head.getNext();
        while (delete != null && delete.getNext() != null) {
            if (delete.getNext().getValue().equals(o)) {
                delete.setNext(delete.getNext().getNext());
                size--;
                return true;
            }
            delete = delete.getNext();
        }
        return false;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public int getSize() {
        return size;
    }

    public Object get(int position) {
        if (position < 0 || position > size) {
            throw new IndexOutOfBoundsException();
        }
        StringElement find = head.getNext();
        for (int i = 0; i <= position; i++)
            find = find.getNext();
        return find.getValue();
    }

    public StringContainer getDataBetween(LocalDateTime dateFrom, LocalDateTime dateTo) {
        StringContainer result = new StringContainer(this.pattern.pattern());
        StringElement current = this.head.getNext();
        while (current != null) {
            StringElement currentWithDate = current;
            if (currentWithDate.getDateTime().isAfter(dateFrom) && currentWithDate.getDateTime().isBefore(dateTo)) {
                result.add((String) currentWithDate.getValue());
            }
            current = current.getNext();
        }
        return result;
    }

    @Override
    public String toString() {
        return "StringContainer{" +
                "size=" + size +
                ", head=" + head;
    }
}
</code>```

public class StringElement {
    private Object value;
    private StringElement next;
    private LocalDateTime dateTime;

    public StringElement(Object value, StringElement next, LocalDateTime dateTime) {
        this.value = value;
        this.next = next;
        this.dateTime = dateTime;
    }

    public StringElement(Object value) {
        this(value, null, null);
    }

    public Object getValue() {
        return value;
    }

    public StringElement getNext() {
        return next;
    }

    public void setNext(StringElement n) {
        next = n;
    }

    public boolean hasNext() {
        return next != null;
    }

    public void setValue(Object o) {
        value = o;
    }

    public LocalDateTime getDateTime() {
        return dateTime;
    }

    @Override
    public String toString() {
        return "kod pocztowy " + next + " " + getDateTime();
    }
```
<pre class="lang-java prettyprint-override"><code>public class Main {
    public static void main(String[] args) {
        StringContainer st = new StringContainer("\\d{2}[-]\\d{3}");

        st.add("02-495");
        st.add("01-120");
        st.add("05-123");
        st.add("00-000");
        st.add("Ala ma kota");
        st.add("Ala ma psa");

        for (int i = 0; i < st.getSize(); i++) {
            System.out.println("Kod pocztowy :" + st.get(i));
        }

        st.delete(0);  //usuwa "02-495"
        st.delete("00-000"); // usuwa "00-000"

        System.out.println();
        System.out.println("po usunieciu");
        for (int i = 0; i < st.getSize(); i++) {
            System.out.println("Kod pocztowy: " + st.get(i));

        }
        getDateTimeMethod(st);

    }

    private static void getDateTimeMethod(StringContainer st) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime dateFrom = now.minusHours(2);
        LocalDateTime dateTo = now.plusHours(2);
        StringContainer stBetween = st.getDataBetween(dateFrom,dateTo);
        System.out.println(stBetween);
    }
}
</code>```

Body:
I'm working on a problem where I have to return postcodes from a list based on the time they have been added. For example, the user sets 12-2 then all the post codes added between 12 & 2 would be returned.

I've written a method, although currently the output is not as expected. The expected output is to be only the post code such as:

26-006
15-150

Whereas now I have: StringContainer{size=4, head=kod pocztowy kod pocztowy kod pocztowy kod pocztowy kod pocztowy kod pocztowy null 2023-01-09T21:34:44.197357200 2023-01-09T21:34:44.197357200 2023-01-09T21:34:44.197357200 2023-01-09T21:34:44.197357200 2023-01-09T21:34:44.197357200 null

It returns the postcodes + time etc.

Could you advise how to fix this?

Here is my current code:

public class StringContainer {
    private int size = 0;
    private StringElement head = new StringElement(null);
    private Pattern pattern;

    public StringContainer(String regex) {
        clear();
        this.pattern = Pattern.compile(regex);
    }

    public void clear() {
        head.setNext(null);
        size = 0;
    }

    public void add(String value) {
        Matcher matcher = pattern.matcher(value);
        try {
            if (matcher.matches()) {
                if (head.getNext() == null) {
                    head.setNext(new StringElement(value, null, LocalDateTime.now()));
                }
                StringElement last = head.getNext();
                while (last.getNext() != null)
                    last = last.getNext();
                ++size;
                last.setNext(new StringElement(value, null, LocalDateTime.now()));
            } else {
                throw new InvalidStringContainerPatternException("Nie maczuje się");
            }
        } catch (InvalidStringContainerPatternException e) {
            e.printStackTrace();
        }
    }

    public boolean delete(Object o) {
        if (head.getNext() == null) return false;
        if (head.getNext().getValue().equals(o)) {
            head.setNext(head.getNext().getNext());
            size--;
            return true;
        }
        StringElement delete = head.getNext();
        while (delete != null && delete.getNext() != null) {
            if (delete.getNext().getValue().equals(o)) {
                delete.setNext(delete.getNext().getNext());
                size--;
                return true;
            }
            delete = delete.getNext();
        }
        return false;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public int getSize() {
        return size;
    }

    public Object get(int position) {
        if (position < 0 || position > size) {
            throw new IndexOutOfBoundsException();
        }
        StringElement find = head.getNext();
        for (int i = 0; i <= position; i++)
            find = find.getNext();
        return find.getValue();
    }

    public StringContainer getDataBetween(LocalDateTime dateFrom, LocalDateTime dateTo) {
        StringContainer result = new StringContainer(this.pattern.pattern());
        StringElement current = this.head.getNext();
        while (current != null) {
            StringElement currentWithDate = current;
            if (currentWithDate.getDateTime().isAfter(dateFrom) && currentWithDate.getDateTime().isBefore(dateTo)) {
                result.add((String) currentWithDate.getValue());
            }
            current = current.getNext();
        }
        return result;
    }

    @Override
    public String toString() {
        return "StringContainer{" +
                "size=" + size +
                ", head=" + head;
    }
}

public class StringElement {
    private Object value;
    private StringElement next;
    private LocalDateTime dateTime;

    public StringElement(Object value, StringElement next, LocalDateTime dateTime) {
        this.value = value;
        this.next = next;
        this.dateTime = dateTime;
    }

    public StringElement(Object value) {
        this(value, null, null);
    }

    public Object getValue() {
        return value;
    }

    public StringElement getNext() {
        return next;
    }

    public void setNext(StringElement n) {
        next = n;
    }

    public boolean hasNext() {
        return next != null;
    }

    public void setValue(Object o) {
        value = o;
    }

    public LocalDateTime getDateTime() {
        return dateTime;
    }

    @Override
    public String toString() {
        return "kod pocztowy " + next + " " + getDateTime();
    }

public class Main {
    public static void main(String[] args) {
        StringContainer st = new StringContainer("\\d{2}[-]\\d{3}");

        st.add("02-495");
        st.add("01-120");
        st.add("05-123");
        st.add("00-000");
        st.add("Ala ma kota");
        st.add("Ala ma psa");

        for (int i = 0; i < st.getSize(); i++) {
            System.out.println("Kod pocztowy :" + st.get(i));
        }

        st.delete(0);  //usuwa "02-495"
        st.delete("00-000"); // usuwa "00-000"

        System.out.println();
        System.out.println("po usunieciu");
        for (int i = 0; i < st.getSize(); i++) {
            System.out.println("Kod pocztowy: " + st.get(i));

        }
        getDateTimeMethod(st);

    }

    private static void getDateTimeMethod(StringContainer st) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime dateFrom = now.minusHours(2);
        LocalDateTime dateTo = now.plusHours(2);
        StringContainer stBetween = st.getDataBetween(dateFrom,dateTo);
        System.out.println(stBetween);
    }
}


问:
VB.Net ComboBox - Enums and Limiting Values Based on Selection in Another ComboBox
The project I'm working on makes extensive use of Enum's to hold unit symbols. Like this...

```<code>Public Enum AreaSym
    unknown = 0
    in2
    mm2
End Enum
</code>```

My Problems began when I realized that my Enum names didn't make good names for the drop downs on my ComboBoxes.  I found and implemented a TypeConverter from this C# CodeProject http://www.codeproject.com/KB/cs/LocalizingEnums.aspx?msg=3746572 ...  It allows you to assign the Enum Values friendly names in a .Resx file, and it overloads the GetValues function so that it returns the Enums friendly names from the .Resx file.  This works well as I can then assign the combobox data source directly to the enum.

```<code>ComboBox1.DataSource = System.Enum.GetValues(GetType(AreaSym))
</code>```

However, I realized that when using a Datasource in this manner, I have to manipulate the data source to create a change in the ComboBox.  Such as, if I don't want to display unknown to the user, I'd need another way to load my ComboBoxes.  This is when I decided to make a List(Of KeyValuePair(AreaSym, String))

```<code>Public Function AreaSymbols() As List(Of KeyValuePair(Of AreaSym, String))
    AreaSymbols = New List(Of KeyValuePair(Of AreaSym, String))
    AreaSymbols.Add(New KeyValuePair(Of AreaSym, String)(AreaSym.in2, "in²"))
    AreaSymbols.Add(New KeyValuePair(Of AreaSym, String)(AreaSym.mm2, "mm²"))
    Return AreaSymbols
End Function
</code>```

This is great because now I can control exactly what goes into the combo box using the list.

```<code>ComboBox1.DataSource = UnitNameList.AreaSymbols
ComboBox1.DisplayMember = "Value"
ComboBox1.ValueMember = "Key"
</code>```

However, I've found that using a DataSource has stopped me from doing two things.

When the form loads, I want the ComboBox itself to show as either empty with no text, or to show the Text I've input in the Text Property.  Currently using the DataSource, it always is populated with the first item in the list.

I'd like to be able to easily limit the items in the list, based on the selection of items in another list.   Classic example would be two ComboBoxes filled with the exact same values (1,2,3) & (1,2,3).  When you choose 1 in ComboBox one, only (2,3) are available for selection in ComboBox 2.

I realize that I could probably easily do that if I was using Items, instead of a data source, I'm just not sure what the best way to do that would be because of my need to have the key, value pair of enums and strings...

ContentLicense: CC BY-SA 3.0

Body:
The project I'm working on makes extensive use of Enum's to hold unit symbols. Like this...

Public Enum AreaSym
    unknown = 0
    in2
    mm2
End Enum

My Problems began when I realized that my Enum names didn't make good names for the drop downs on my ComboBoxes.  I found and implemented a TypeConverter from this C# CodeProject http://www.codeproject.com/KB/cs/LocalizingEnums.aspx?msg=3746572 ...  It allows you to assign the Enum Values friendly names in a .Resx file, and it overloads the GetValues function so that it returns the Enums friendly names from the .Resx file.  This works well as I can then assign the combobox data source directly to the enum.

ComboBox1.DataSource = System.Enum.GetValues(GetType(AreaSym))

However, I realized that when using a Datasource in this manner, I have to manipulate the data source to create a change in the ComboBox.  Such as, if I don't want to display unknown to the user, I'd need another way to load my ComboBoxes.  This is when I decided to make a List(Of KeyValuePair(AreaSym, String))

Public Function AreaSymbols() As List(Of KeyValuePair(Of AreaSym, String))
    AreaSymbols = New List(Of KeyValuePair(Of AreaSym, String))
    AreaSymbols.Add(New KeyValuePair(Of AreaSym, String)(AreaSym.in2, "in²"))
    AreaSymbols.Add(New KeyValuePair(Of AreaSym, String)(AreaSym.mm2, "mm²"))
    Return AreaSymbols
End Function

This is great because now I can control exactly what goes into the combo box using the list.

ComboBox1.DataSource = UnitNameList.AreaSymbols
ComboBox1.DisplayMember = "Value"
ComboBox1.ValueMember = "Key"

However, I've found that using a DataSource has stopped me from doing two things.

When the form loads, I want the ComboBox itself to show as either empty with no text, or to show the Text I've input in the Text Property.  Currently using the DataSource, it always is populated with the first item in the list.

I'd like to be able to easily limit the items in the list, based on the selection of items in another list.   Classic example would be two ComboBoxes filled with the exact same values (1,2,3) & (1,2,3).  When you choose 1 in ComboBox one, only (2,3) are available for selection in ComboBox 2.

I realize that I could probably easily do that if I was using Items, instead of a data source, I'm just not sure what the best way to do that would be because of my need to have the key, value pair of enums and strings...


问:
Loops bug with ERR_TOO_MANY_REDIRECTS
Hello i help an friend to move his website and i have this bug ERR_TOO_MANY_REDIRECTS on the web page i think is the .htaccess file but not sure

here is the .htaccess

```<code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !\/resource.*$
RewriteRule ^((?!index\.php).+)$ /index.php [L]
FallbackResource /index.php
</code>```

I think ist the fallbackResource but not not sure .
did you have somes idea how this loop is caused ?

Title: Loops bug with ERR_TOO_MANY_REDIRECTS

Body:
Hello i help an friend to move his website and i have this bug ERR_TOO_MANY_REDIRECTS on the web page i think is the .htaccess file but not sure

here is the .htaccess

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !\/resource.*$
RewriteRule ^((?!index\.php).+)$ /index.php [L]
FallbackResource /index.php

I think ist the fallbackResource but not not sure .
did you have somes idea how this loop is caused ?


问:
replace special characters in a column in postgresql using pgadmin
I am trying to replace a column with these characters --> "{,

I tried using both replace and regex_replace, I am getting the following error.

```<code>update mytable
   set address = replace(address, ',','_');
</code>```

this is the error I get.

```<code>ERROR:  function replace(character varying[], unknown, unknown) does not exist
LINE 1: select replace(address,',','_') from mytable.
               ^
HINT:  No function matches the given name and argument types.
You might need to add explicit type casts.
SQL state: 42883
Character: 8
</code>```

Body:
I am trying to replace a column with these characters --> "{,

I tried using both replace and regex_replace, I am getting the following error.

update mytable
   set address = replace(address, ',','_');

this is the error I get.

ERROR:  function replace(character varying[], unknown, unknown) does not exist
LINE 1: select replace(address,',','_') from mytable.
               ^
HINT:  No function matches the given name and argument types.
You might need to add explicit type casts.
SQL state: 42883
Character: 8


问:
How to encode "
” into an XML element?
I have an XML file that I'm trying to update. The section in question is text intended for consumption by humans. In order to improve readability it needs to have paragraphs and, for that, carriage returns / line feeeds.

In the original file, a carriage return / line feed is represented by the following characters - "
". These characters seem to be required by this XML file's application in order to display the content accurately.

XML File

Without the right characters in the XML, the content paragraphs just all run on and create a big block of text that isn't easy to consume.

I'm working with Microsoft Word VBA. I'm puling the content for the XML file from a Content Control (which I think is irrelevant because it's simply returning a string).

Despite the content in the content control having paragraphs, the content in the application has no CR/LF in it.

Text in Word Application

Text in the XML application

To date, I've tried simply adding the characters (ie "
") into the string, but that didn't work. I've tried to add chr(10) and chr(13) directly into string, and a host of other options, but to no avail.

Thank you in advance for any support, tips or ideas that you can provide.

Title:
How to encode "
” into an XML element?


问:
How to plot discontinuous function in Python
I have a discontinuous function I_v(P) in which the equation changes when P => 1. How do I successfully generate I_v values so I can make a plot?

```<code>P = np.linspace(1e-3,1e+1,1000)
if P < 1:
    I_v = P*math.e**(P)*(a_0 + a_1*P + a_2*P**2 + a_3*P**3 + a_4*P**4 + a_5*P**5 - math.log(P))
else:
    I_v = (P**4 + e_1*P**3 + e_2*P**2 + e_3*P + e_4)/(P**4 + f_1*P**3 + f_2*P**2 + f_3*P + f_4)
</code>```
```<code>Error: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
</code>```

I want the P values to evaluated one at a time, not as an array.

Body:
I have a discontinuous function I_v(P) in which the equation changes when P => 1. How do I successfully generate I_v values so I can make a plot?

P = np.linspace(1e-3,1e+1,1000)
if P < 1:
    I_v = P*math.e**(P)*(a_0 + a_1*P + a_2*P**2 + a_3*P**3 + a_4*P**4 + a_5*P**5 - math.log(P))
else:
    I_v = (P**4 + e_1*P**3 + e_2*P**2 + e_3*P + e_4)/(P**4 + f_1*P**3 + f_2*P**2 + f_3*P + f_4)

Error: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I want the P values to evaluated one at a time, not as an array.


问:
Disassembling Code inside of a C++ program
objdump -D file.o will output something like

```<code>  2b:   47                      rex.RXB
  2c:   43                      rex.XB
  2d:   43 3a 20                rex.XB cmp (%r8),%spl
</code>```

In my program I have a pointer to the instruction and need to disassemble the first instruction found (not the whole file).  What would be the easiest way to do that?  For example

```<code>uint8_t * inst_ptr = memory_location
std::string human_readable = get_disassembly(instr_ptr)
</code>```

human_readable = "43 3a 20 rex.XB cmp (%r8),%spl"

Is there linux headers/includes that do this already?

Ive been googling but havent found a good, straight forward solution.

Body:
objdump -D file.o will output something like

  2b:   47                      rex.RXB
  2c:   43                      rex.XB
  2d:   43 3a 20                rex.XB cmp (%r8),%spl

In my program I have a pointer to the instruction and need to disassemble the first instruction found (not the whole file).  What would be the easiest way to do that?  For example

uint8_t * inst_ptr = memory_location
std::string human_readable = get_disassembly(instr_ptr)

human_readable = "43 3a 20 rex.XB cmp (%r8),%spl"

Is there linux headers/includes that do this already?

Ive been googling but havent found a good, straight forward solution.


问:
Touchend not allowed to play media element on iOS
According to this article https://webkit.org/blog/6784/new-video-policies-for-ios/ touchend should be able to trigger a play event on iOS. However in the example below a press on the element fires the action and starts the audio playback. A touch drag fires the action but returns a promise rejection and does not start the audio playback. Any idea on how to work around this?</p>
```<code> el.addEventListener("touchend", stb.task.dragEnd );
 el.addEventListener("mousedown", stb.task.dragEnd );
</code>```

Body:
According to this article https://webkit.org/blog/6784/new-video-policies-for-ios/ touchend should be able to trigger a play event on iOS. However in the example below a press on the element fires the action and starts the audio playback. A touch drag fires the action but returns a promise rejection and does not start the audio playback. Any idea on how to work around this?

 el.addEventListener("touchend", stb.task.dragEnd );
 el.addEventListener("mousedown", stb.task.dragEnd );


问:
How to use the SCIP protocol in ReactNative for Android app running on PHILIPS 10BDL3051T
I am looking into creating an Android app using ReactNative for a PHILIPS 10BDL3051T tablet running Android 4.4

To use the hardware LED strips on the tablet, you need to use the SCIP socket for communication.

I have found this repo in .NET C# where the connection is archived and the ability to set LED colors: https://github.com/aolde/philips-signage-display-sicp

Does anybody have experience with making such an app and is able to provide hints or links?

Or am I forced to create the app with XAMARIN in order to use the NuGet package, if that is even possible?

Thanks a lot in advance


问:
GTM Preview Error: JavaScript Compiler Error
I am getting the below error in GTM when I select preview:

enter image description here

I ran my script through JS Lint to make sure there were no errors, additionally I haven't changed anything to the line / character it is calling out so I'm not entirely sure what the fix is.

Here is a sample of what my script looks like:

```<code>function() {
    // Set inputVariable to the input you want to assess
    var inputVariable = {{Page URL}};
    // Set defaultVal to what you want to return if no match is made
    var defaultVal = undefined;
    // Add rows as two-cell Arrays within the Array "table".
    // The first cell contains the RegExp you want to match
    // the inputVariable with, the second cell contains the
    // return value if a match is made. The third cell (optional),
    // contains any RegEx flags you want to use.
    //
    // The return value can be another GTM variable or any
    // supported JavaScript type.
    //
    // Remember, no comma after the last row in the table Array,
    // and remember to double escape reserved characters: \\?
    // Row 1 is master, row 2 is staging.  Repeat for every app
    var table = [
//Website Name
      ["URL", "GA4 Lookup Reference Name"],
];  **<----- THIS IS THE LINE THAT IS GIVING ME ISSUES**
    // Go through all the rows in the table, do the tests,
    // and return the return value of the FIRST successful
    // match.
    for (var i = 0, len = table.length; i < len; i += 1) {
        var regex = new RegExp(table[i][0], table[i][2]);
        if (regex.test(inputVariable)) {
            return table[i][1];
        }
    }
    return defaultVal;
}
</code>```

Any ideas what the fix is here?

I tried correcting the error by adding in an additional ','. I also looked at previous versions which worked and did not see any differences aside from some new URL's I've added in.

Body:
I am getting the below error in GTM when I select preview:

enter image description here

I ran my script through JS Lint to make sure there were no errors, additionally I haven't changed anything to the line / character it is calling out so I'm not entirely sure what the fix is.

Here is a sample of what my script looks like:

function() {
    // Set inputVariable to the input you want to assess
    var inputVariable = {{Page URL}};
    // Set defaultVal to what you want to return if no match is made
    var defaultVal = undefined;
    // Add rows as two-cell Arrays within the Array "table".
    // The first cell contains the RegExp you want to match
    // the inputVariable with, the second cell contains the
    // return value if a match is made. The third cell (optional),
    // contains any RegEx flags you want to use.
    //
    // The return value can be another GTM variable or any
    // supported JavaScript type.
    //
    // Remember, no comma after the last row in the table Array,
    // and remember to double escape reserved characters: \\?
    // Row 1 is master, row 2 is staging.  Repeat for every app
    var table = [
//Website Name
      ["URL", "GA4 Lookup Reference Name"],
];  **<----- THIS IS THE LINE THAT IS GIVING ME ISSUES**
    // Go through all the rows in the table, do the tests,
    // and return the return value of the FIRST successful
    // match.
    for (var i = 0, len = table.length; i < len; i += 1) {
        var regex = new RegExp(table[i][0], table[i][2]);
        if (regex.test(inputVariable)) {
            return table[i][1];
        }
    }
    return defaultVal;
}

Any ideas what the fix is here?

I tried correcting the error by adding in an additional ','. I also looked at previous versions which worked and did not see any differences aside from some new URL's I've added in.


问:
Bing webmaster tool is unable to fetch robots.txt of my website while google is able to fetch
When I am checking my robots.txt file in Bing webmaster tool robots.txt Tester it's showing an error
robots.txt is not found.

While my robots.txt is available in the root directory and accessible in the browser as well as accessible in google etc. Then why is bing showing such an error? Here is a screenshot of error saying "robots.txt is not found"

I had checked my robots.txt permission and all but was not able to fetch it in the bing robots.txt tester.


问:
How to blacklist a nested property using redux-persist that is inside of an array?
My redux store looks like this:

```<code>{
"stationsReducer":{
      "origin":"something",
      "dest":"something-else",
      "bookmarks":[
         {
            "trip":{
               "origin":"trip-something",
               "legs":[
                  {
                     "train":{
                        "train_id":"123",
                        "details":{
                           "headsign":"blah blah",
                           "polyline":"some String"
                        }
                     }
                  }
               ]
            }
         }
      ]
   }
}
</code>```

Using the examples given in the redux-persist repo, I can blacklist objects that I can directly access for eg: I can blacklist the entire bookmark array. But I can't seem to blacklist something that is inside the array. I want to blacklist polyline property which is inside 2 arrays.

How can I go about doing it or is it even possible ?

Body:
My redux store looks like this:

{
"stationsReducer":{
      "origin":"something",
      "dest":"something-else",
      "bookmarks":[
         {
            "trip":{
               "origin":"trip-something",
               "legs":[
                  {
                     "train":{
                        "train_id":"123",
                        "details":{
                           "headsign":"blah blah",
                           "polyline":"some String"
                        }
                     }
                  }
               ]
            }
         }
      ]
   }
}

Using the examples given in the redux-persist repo, I can blacklist objects that I can directly access for eg: I can blacklist the entire bookmark array. But I can't seem to blacklist something that is inside the array. I want to blacklist polyline property which is inside 2 arrays.

How can I go about doing it or is it even possible ?


问:
How can i check user interaction on a post, to notify user about his own reaction
I am working on a social media app and facing an issue, I want to mark liked posts, so the user see his own reaction a normal behavior like Facebook or and social media app,
what I do now is I send all the post reaction to the client side, loop throw them and if (user_id == post.user_id) then I know that client liked a post, and show something to tell user that he already liked that post.
I believe this will lead to bad performance because of the huge amount of reaction, my issue as I said it's all about detection of client reaction on posts when refreshing or loading posts.
I am using nodejs and SQL</p>


问:
certificate is invalid for Net Core 3.1 running under macos
I have a net core 3.1 app trying to call an HTTPS endpoint. This HTTPS endpoint uses a self-signed certificate which I have the CA certificate installed in my machine under /etc/ssl/cert/pem, I tried call it via curl and worked.

Well, in my coworker's machine (windows) it works normally, but in my MacOS Monterey:

```<code>The SSL connection could not be established, see inner exception.
System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception.
 ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
</code>```

Well, I tried some things but nothing worked:

added this env variable "SSL_CERT_DIR" : "/etc/ssl"

added this env variable "SSL_CERT_FILE": "/etc/ssl/cert.pem"

I don't want to change anything in the code because it works normally on other machines (not macos). I'm pretty sure that this error happens because for some reason the .Net Core is note using my CA cert somehow.

Any tips here?

Body:
I have a net core 3.1 app trying to call an HTTPS endpoint. This HTTPS endpoint uses a self-signed certificate which I have the CA certificate installed in my machine under /etc/ssl/cert/pem, I tried call it via curl and worked.

Well, in my coworker's machine (windows) it works normally, but in my MacOS Monterey:

The SSL connection could not be established, see inner exception.
System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception.
 ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.

Well, I tried some things but nothing worked:

added this env variable "SSL_CERT_DIR" : "/etc/ssl"

added this env variable "SSL_CERT_FILE": "/etc/ssl/cert.pem"

I don't want to change anything in the code because it works normally on other machines (not macos). I'm pretty sure that this error happens because for some reason the .Net Core is note using my CA cert somehow.

Any tips here?


问:
Attempts to update state in react not working correctly
I have a menu handling component in React.

It receives props.choices as an object (which is turn passed as props from another parent component which is in turn rendered from its parent App.js following a useState call), along with a setstate function setChoices, similarly inherited as props.

After setChoices is called, the props object appears to update correctly using the component view developer tools BUT the console log still shows the original default initialized value. This is problematic because I'd like to check that the first and second choices are not the same.

The rendered values in the return JSX update correctly, and furthermore other components that use the same state as props are updating correctly. Component view in developer tools also shows that the state is being correctly updated.

The problem I have therefore appears to be accessing the newly updated state (which would allow me to compare the first and second choices).

Thanks for suggestions - this is driving me only slightly mad.

```<code>import React from 'react';

export function ConfirmChoices(props) {

    // destructure props
    const {
        selectedMenuOption,
        selectedMenuSubOption,
        choices,
        setChoices
    } = props;

    //TODO: choice handling, including updating choices state in App.js
    function handleSetChoicesClick(event) {

        if (event.target.id === 'firstChoiceButton') {
            setChoices({...choices, first: selectedMenuSubOption, firstOption: selectedMenuOption});

            // THIS DOES NOT RETURN THE CORRECT VALUE - BUT IT DOES RENDER CORRECTLY IN THE RETURN FUNCTION <P> BELOW
            console.log(choices.first);
        }

        if (event.target.id === 'secondChoiceButton') {
            setChoices({...choices, second: selectedMenuSubOption, secondOption: selectedMenuOption});
        }

    }

    // do not render anything if a suboption has not been selected
    if (selectedMenuSubOption === '') {
        return null;
    }

    return (
        <div>
                        <button id="firstChoiceButton"
                                onClick={handleSetChoicesClick}
                        >Set as first choice</button>
                        <button id="secondChoiceButton"
                                onClick={handleSetChoicesClick}
                        >Set as second choice</button>
                        <p>{choices.firstOption} - {choices.first}</p>
        </div>
    );
}
</code>```

What I was expecting If the selected first choice option from the menu is 'Meeting' and suboption is 'Team', I would expect the console.log statement to result in 'Team', instead it returns the default value when the state was initialized in the parent component with useState ('not yet selected').

The
 block in the returned JSX expression does indeed render correctly and results in 'Meeting - Team'

What I would like to be able to do Check the suboptions for equality (choices.first and choices.second) after the new state has been set by handleSetChoicesClick and blank out the other option to avoid duplicate first and second choices using something like this:

```<code>// If first choice button selected, immediately after console.log statement in previous code

            if (choices.first === choices.second) {
                setChoices({...choices, second: '', secondOption: ''});
            }

</code>```

The solution
State updates are only reflected in the next re-render of the component, which means trying to use them for logical operations before this can be problematic.
The solution is to add a useEffect hook with a dependency array which includes the state variable.

See this answer here: The useState set method is not reflecting a change immediately

Here is my (now working) code:

```<code>import React, { useEffect } from 'react';

export function ConfirmChoices(props) {

    // destructure props
    const {
        selectedMenuOption,
        selectedMenuSubOption,
        choices,
        setChoices
    } = props;

    let lastClicked = '';

    useEffect(() => {

        console.log(choices.first);
        console.log(choices.second);

        if (choices.first === choices.second && choices.first !== '(Not yet selected)') {

            console.log(lastClicked);
            lastClicked === 'firstChoiceButton' ? setChoices({...choices, second: '', secondOption: ''}) : setChoices({...choices, first: '', firstOption: ''});

        }

    }, [choices]);

    //TODO: choice handling, including updating choices state in App.js
    function handleSetChoicesClick(event) {

        lastClicked = event.target.id;

        if (event.target.id === 'firstChoiceButton') {
            setChoices({...choices, first: selectedMenuSubOption, firstOption: selectedMenuOption});
        }

        if (event.target.id === 'secondChoiceButton') {
            setChoices({...choices, second: selectedMenuSubOption, secondOption: selectedMenuOption});
        }

        console.log(lastClicked);
    }

    // do not render anything if a suboption has not been selected
    if (selectedMenuSubOption === '') {
        return null;
    }

    return (
        <div>
                        <button id="firstChoiceButton"
                                onClick={handleSetChoicesClick}
                        >Set as first choice</button>
                        <button id="secondChoiceButton"
                                onClick={handleSetChoicesClick}
                        >Set as second choice</button>
        </div>
    );
}
</code>```

Body:
I have a menu handling component in React.

It receives props.choices as an object (which is turn passed as props from another parent component which is in turn rendered from its parent App.js following a useState call), along with a setstate function setChoices, similarly inherited as props.

After setChoices is called, the props object appears to update correctly using the component view developer tools BUT the console log still shows the original default initialized value. This is problematic because I'd like to check that the first and second choices are not the same.

The rendered values in the return JSX update correctly, and furthermore other components that use the same state as props are updating correctly. Component view in developer tools also shows that the state is being correctly updated.

The problem I have therefore appears to be accessing the newly updated state (which would allow me to compare the first and second choices).

Thanks for suggestions - this is driving me only slightly mad.

import React from 'react';

export function ConfirmChoices(props) {

    // destructure props
    const {
        selectedMenuOption,
        selectedMenuSubOption,
        choices,
        setChoices
    } = props;

    //TODO: choice handling, including updating choices state in App.js
    function handleSetChoicesClick(event) {

        if (event.target.id === 'firstChoiceButton') {
            setChoices({...choices, first: selectedMenuSubOption, firstOption: selectedMenuOption});

            // THIS DOES NOT RETURN THE CORRECT VALUE - BUT IT DOES RENDER CORRECTLY IN THE RETURN FUNCTION
 BELOW
            console.log(choices.first);
        }

        if (event.target.id === 'secondChoiceButton') {
            setChoices({...choices, second: selectedMenuSubOption, secondOption: selectedMenuOption});
        }

    }

    // do not render anything if a suboption has not been selected
    if (selectedMenuSubOption === '') {
        return null;
    }

    return (

                        <button id="firstChoiceButton"
                                onClick={handleSetChoicesClick}
                        >Set as first choice</button>
                        <button id="secondChoiceButton"
                                onClick={handleSetChoicesClick}
                        >Set as second choice</button>

{choices.firstOption} - {choices.first}

    );
}

What I was expecting If the selected first choice option from the menu is 'Meeting' and suboption is 'Team', I would expect the console.log statement to result in 'Team', instead it returns the default value when the state was initialized in the parent component with useState ('not yet selected').

The
 block in the returned JSX expression does indeed render correctly and results in 'Meeting - Team'

What I would like to be able to do Check the suboptions for equality (choices.first and choices.second) after the new state has been set by handleSetChoicesClick and blank out the other option to avoid duplicate first and second choices using something like this:

// If first choice button selected, immediately after console.log statement in previous code

            if (choices.first === choices.second) {
                setChoices({...choices, second: '', secondOption: ''});
            }

The solution
State updates are only reflected in the next re-render of the component, which means trying to use them for logical operations before this can be problematic.
The solution is to add a useEffect hook with a dependency array which includes the state variable.

See this answer here: The useState set method is not reflecting a change immediately

Here is my (now working) code:

import React, { useEffect } from 'react';

export function ConfirmChoices(props) {

    // destructure props
    const {
        selectedMenuOption,
        selectedMenuSubOption,
        choices,
        setChoices
    } = props;

    let lastClicked = '';

    useEffect(() => {

        console.log(choices.first);
        console.log(choices.second);

        if (choices.first === choices.second && choices.first !== '(Not yet selected)') {

            console.log(lastClicked);
            lastClicked === 'firstChoiceButton' ? setChoices({...choices, second: '', secondOption: ''}) : setChoices({...choices, first: '', firstOption: ''});

        }

    }, [choices]);

    //TODO: choice handling, including updating choices state in App.js
    function handleSetChoicesClick(event) {

        lastClicked = event.target.id;

        if (event.target.id === 'firstChoiceButton') {
            setChoices({...choices, first: selectedMenuSubOption, firstOption: selectedMenuOption});
        }

        if (event.target.id === 'secondChoiceButton') {
            setChoices({...choices, second: selectedMenuSubOption, secondOption: selectedMenuOption});
        }

        console.log(lastClicked);
    }

    // do not render anything if a suboption has not been selected
    if (selectedMenuSubOption === '') {
        return null;
    }

    return (

                        <button id="firstChoiceButton"
                                onClick={handleSetChoicesClick}
                        >Set as first choice</button>
                        <button id="secondChoiceButton"
                                onClick={handleSetChoicesClick}
                        >Set as second choice</button>

    );
}


问:
How do I create a favorites button that will add the div to an html page called "My Watchlist"?
I'm trying to create a streaming service that has a custom watchlist that stores whatever the user marks as their favorite. On each card, there would be a play button and a favorites button. The favorites button would (if clicked) add that specific movie/tv show to their watchlist (which is on another page in the same website0 and save both the status of the favorites button to localstorage and save the movie/tv show to localstorage until they remove it. Can someone help me?

I haven't tried anything yet, which is why I need help.


问:
Supervisor "spawn error" : I'm stuck... how can I know the reason for the error?
I have a Django REST API running on an UBUNTU 20.04 server, with a sqlite database.

Everything has been working for weeks with no issue.

Today, after pulling small changes to my code (changes in my settings.py file), I've tried to restart the GUNICORN server with SUPERVISOR as usual with:

```<code>sudo supervisorctl restart <MyAppName>
</code>```

but I get an error message :

```<code><MyAppName>-gunicorn: ERROR (spawn error)
</code>```

In /var/log/supervisor.supervisor.log, I can only see that error message :

```<code>exited: <MyApp>-gunicorn (exit status 3; not expected)
</code>```

I can find no way to have it working again (I've even tried to restart the server).
The strange thing is that when I manually launch gunicorn with :

```<code>/home/<myname>/env/bin/gunicorn <MyApp>.wsgi
</code>```

I have no error message and my server works perfectly(requests are served to my app).

How can I know the reason for the supervisor spawn error ?

Body:
I have a Django REST API running on an UBUNTU 20.04 server, with a sqlite database.

Everything has been working for weeks with no issue.

Today, after pulling small changes to my code (changes in my settings.py file), I've tried to restart the GUNICORN server with SUPERVISOR as usual with:

sudo supervisorctl restart <MyAppName>

but I get an error message :

<MyAppName>-gunicorn: ERROR (spawn error)

In /var/log/supervisor.supervisor.log, I can only see that error message :

exited: <MyApp>-gunicorn (exit status 3; not expected)

I can find no way to have it working again (I've even tried to restart the server).
The strange thing is that when I manually launch gunicorn with :

/home/<myname>/env/bin/gunicorn <MyApp>.wsgi

I have no error message and my server works perfectly(requests are served to my app).

How can I know the reason for the supervisor spawn error ?


问:
How to prevent a text from bouncing in collapsible custom cell?
I'm attempting to create a custom UICollectionViewCell. The cell includes a subtitle label, which should expand and contract in response to the user's interaction with a show more button. However, when the subtitle label expands,the subtitlelabel appears to bounce. I tried changing the constraints on the subtitlabel and the container view of the cell, but the problem persists. I tried to expand the size of the container view to make space for it bottom it didn't work. I also added a maximum width to subtitlabel to allow it to expand without causing other views to move but that didn't work also. How can I resolve this? GIF

```<code>lazy var container: UIStackView = setupContainer()
lazy var subtitleLabel: UILabel = setupSubtitleLabel()

 private func setupView() {
        container.addArrangedSubview(titleView)

        titleView.snp.makeConstraints { make in
            make.height.equalTo(34)
            make.left.right.equalTo(container).inset(16)
        }

        let titleSeparator = HorizontalSeparatorView(height: 0.5)

        container.addArrangedSubview(titleSeparator)

        titleSeparator.snp.makeConstraints { make in
            make.left.right.equalTo(contentView)
        }

        container.addArrangedSubview(subtitleLabel)

        subtitleLabel.snp.makeConstraints { make in
            make.left.right.equalTo(container).inset(16)
        }

        container.addArrangedSubview(thumbnail)

        thumbnail.snp.makeConstraints { make in
            make.height.equalTo(220)
            make.left.right.equalTo(container).inset(16)
        }
    }

    private func setupContainer() -> UIStackView {
        let stackView = UIStackView(frame: .zero,
                                    alignment: .center,
                                    axis: .vertical,
                                    distribution: .fill,
                                    spacing: 30)

        contentView.addSubview(stackView)

        stackView.snp.makeConstraints { make -> Void in
            make.left.right.bottom.equalTo(contentView)
            make.top.equalTo(contentView).inset(24)

        }

        return stackView
    }

private func setupSubtitleLabel() -> UILabel {
    let label = UILabel()
    label.numberOfLines = 0
    label.textColor = .label
    label.font = .systemFont(ofSize: 30, weight: .regular)

    return label
}
</code>```

My attempts:
1: Expanding bottom spacing of the container:

```<code> stackView.snp.makeConstraints { make -> Void in
            make.left.right.bottom.equalTo(contentView)
            make.top.equalTo(contentView).inset(24)
            make.bottom.equalTo(contentView).inset(24)
            make.height.greaterThanOrEqualTo(400)
        }
</code>```

Allowing the subtitlabel to expand:

subtitleLabel.snp.makeConstraints { make in
make.centerX.equalTo(container)
make.width.lessThanOrEqualTo(container).multipliedBy(0.8)
}

Body:
I'm attempting to create a custom UICollectionViewCell. The cell includes a subtitle label, which should expand and contract in response to the user's interaction with a show more button. However, when the subtitle label expands,the subtitlelabel appears to bounce. I tried changing the constraints on the subtitlabel and the container view of the cell, but the problem persists. I tried to expand the size of the container view to make space for it bottom it didn't work. I also added a maximum width to subtitlabel to allow it to expand without causing other views to move but that didn't work also. How can I resolve this? GIF

lazy var container: UIStackView = setupContainer()
lazy var subtitleLabel: UILabel = setupSubtitleLabel()

 private func setupView() {
        container.addArrangedSubview(titleView)

        titleView.snp.makeConstraints { make in
            make.height.equalTo(34)
            make.left.right.equalTo(container).inset(16)
        }

        let titleSeparator = HorizontalSeparatorView(height: 0.5)

        container.addArrangedSubview(titleSeparator)

        titleSeparator.snp.makeConstraints { make in
            make.left.right.equalTo(contentView)
        }

        container.addArrangedSubview(subtitleLabel)

        subtitleLabel.snp.makeConstraints { make in
            make.left.right.equalTo(container).inset(16)
        }

        container.addArrangedSubview(thumbnail)

        thumbnail.snp.makeConstraints { make in
            make.height.equalTo(220)
            make.left.right.equalTo(container).inset(16)
        }
    }

    private func setupContainer() -> UIStackView {
        let stackView = UIStackView(frame: .zero,
                                    alignment: .center,
                                    axis: .vertical,
                                    distribution: .fill,
                                    spacing: 30)

        contentView.addSubview(stackView)

        stackView.snp.makeConstraints { make -> Void in
            make.left.right.bottom.equalTo(contentView)
            make.top.equalTo(contentView).inset(24)

        }

        return stackView
    }

private func setupSubtitleLabel() -> UILabel {
    let label = UILabel()
    label.numberOfLines = 0
    label.textColor = .label
    label.font = .systemFont(ofSize: 30, weight: .regular)

    return label
}

My attempts:
1: Expanding bottom spacing of the container:

 stackView.snp.makeConstraints { make -> Void in
            make.left.right.bottom.equalTo(contentView)
            make.top.equalTo(contentView).inset(24)
            make.bottom.equalTo(contentView).inset(24)
            make.height.greaterThanOrEqualTo(400)
        }

Allowing the subtitlabel to expand:

subtitleLabel.snp.makeConstraints { make in
make.centerX.equalTo(container)
make.width.lessThanOrEqualTo(container).multipliedBy(0.8)
}


问:
how to use SSL pining in every Api request using http plugin fllutter
I am new to SSL pinning, I was asked to use SSL pinning in every API request. I checked some resources but I didn't get the idea of how to call it in my API request.
I am using HTTP/HTTP plugin and not Dio, if anyone can provide me an example of how to use it in the API request? or how to use it?

Thank you in advance


问:
Can you set `Go to declaration or usages` to not go to the type declaration in PhpStorm?
I am often going to methods via the GoTo Declaration or Usages shortcut (mouse scroll click).

This works totally fine for any normal JS / PHP method, but when using TypeScript its always going to the type / interface.

I don't want that, I want to go to the method.  Is that possible to change / is there another go to that would work better in this situation?

Edit

Including some examples

Mouse scroll click on relationship

I want it to go here (actual method)

But it goes here (type declaration)


问:
Finding child Documents from parent modal - mongodb
I have User Schema and View Schema such that each user have multiple view documents
Here is my views schema

```<code>  var ViewsSchema = mongoose.Schema(
    {
       userId: {
         type: mongoose.Schema.Types.ObjectId,
         ref: 'User',
       },
    })
</code>```

Now I am fetching all users and i want to fetch each user view as well in one query. I tried to use virtual property in User schema something like this

```<code>  UserSchema.virtual('views').get(function () {
          return Views.find({ userId: this._id });
    });
</code>```

But it does not create any property for views in each user document.
I also tried this way

```<code> UserSchema.virtual('views', {
         ref: 'Views',
         foreignField: 'userId',
         localField: '_id',
    });
   let doc = await User.find({}).populate('views');
</code>```

But this also does not works. Anyone can tell me what are best possible ways to find Each user view in one query?

Body:
I have User Schema and View Schema such that each user have multiple view documents
Here is my views schema

  var ViewsSchema = mongoose.Schema(
    {
       userId: {
         type: mongoose.Schema.Types.ObjectId,
         ref: 'User',
       },
    })

Now I am fetching all users and i want to fetch each user view as well in one query. I tried to use virtual property in User schema something like this

  UserSchema.virtual('views').get(function () {
          return Views.find({ userId: this._id });
    });

But it does not create any property for views in each user document.
I also tried this way

 UserSchema.virtual('views', {
         ref: 'Views',
         foreignField: 'userId',
         localField: '_id',
    });
   let doc = await User.find({}).populate('views');

But this also does not works. Anyone can tell me what are best possible ways to find Each user view in one query?


问:
webpack style-loader not converting css-loader output to style tags
im attempting to make a simple webpack project with typescript and scss that will output a single html file that contains all the JS in a script tag, and all the CSS in a style tag. i cannot figure out how to properly config webpack to do this. i can get as far as outputting evertyhign onto a single index.html page but my styles show up something like this (before minification):

```<code>var ___CSS_LOADER_EXPORT___ = \_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((\_node_modules_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push(\[module.id, "\* {\\n  border: 0;\\n  font: inherit;\\n  font-size: 100%;\\n  margin: 0;\\n  outline: 0;\\n  padding: 0;\\n  vertical-align: baseline;\\n}\\n\\nbody {\\n  background-color: #ff0;\\n  display: flex;\\n  flex-direction: column;\\n  font-size: 14px;\\n  line-height: 150%;\\n  min-height: 100vh;\\n  color: #000;\\n  overscroll-behavior: none;\\n}\\n\\n.form {\\n  background-color: #f0f;\\n  padding: 20px;\\n  max-width: 80vw;\\n  box-sizing: content-box;\\n}\\n\\n.textInput {\\n  flex-shrink: 0;\\n  border: thin solid #000;\\n  padding: 5px;\\n  width: 130px;\\n  box-sizing: border-box;\\n}\\n.textInput + .textInput {\\n  margin-left: 5px;\\n}\\n\\n.button {\\n  background-color: #f00;\\n  padding: 5px;\\n  font-weight: 600;\\n  transition: background-color 0.1s;\\n  cursor: pointer;\\n  flex-grow: 0;\\n}\\n.button:hover {\\n  background-color: #00f;\\n}", ""\]);
// Exports
/\* harmony default export \*/ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);
</code>```

i have been playing with my webpack config for days. currently looks like this:

```<code>const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const HtmlInlineScriptPlugin = require("html-inline-script-webpack-plugin");

module.exports = {
  entry: "./src/index.ts",
  mode: "development",
  output: {
    filename: "main.js",
    path: path.resolve(__dirname, "dist"),
    clean: true,
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "src/index.html",
      inject: "body",
    }),
    new HtmlInlineScriptPlugin(),
  ],
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: "ts-loader",
        exclude: /node_modules/,
      },
      {
        test: /\.html$/,
        loader: "html-loader",
      },
      {
        test: /\.scss$/i,
        use: [
          {
            loader: "style-loader",
          },
          {
            loader: "css-loader",
            // options: {
              // importLoaders: 1,
              // modules: {
              //   mode: "icss",
              // },
              // esModule: false,
            // },
          },
          {
            loader: "sass-loader",
          },
        ],
      },
    ],
  },
  resolve: {
    extensions: [".ts", "..."],
  },
};

</code>```

and heres my entry .ts file where i import the styles:

```<code>import "./styles.scss";

document.forms[0].onsubmit = onManageSubmit;

function onManageSubmit(evt: SubmitEvent) {
  evt.preventDefault();
  console.log('hello');
}

</code>```

Body:
im attempting to make a simple webpack project with typescript and scss that will output a single html file that contains all the JS in a script tag, and all the CSS in a style tag. i cannot figure out how to properly config webpack to do this. i can get as far as outputting evertyhign onto a single index.html page but my styles show up something like this (before minification):

var ___CSS_LOADER_EXPORT___ = \_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((\_node_modules_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push(\[module.id, "\* {\\n  border: 0;\\n  font: inherit;\\n  font-size: 100%;\\n  margin: 0;\\n  outline: 0;\\n  padding: 0;\\n  vertical-align: baseline;\\n}\\n\\nbody {\\n  background-color: #ff0;\\n  display: flex;\\n  flex-direction: column;\\n  font-size: 14px;\\n  line-height: 150%;\\n  min-height: 100vh;\\n  color: #000;\\n  overscroll-behavior: none;\\n}\\n\\n.form {\\n  background-color: #f0f;\\n  padding: 20px;\\n  max-width: 80vw;\\n  box-sizing: content-box;\\n}\\n\\n.textInput {\\n  flex-shrink: 0;\\n  border: thin solid #000;\\n  padding: 5px;\\n  width: 130px;\\n  box-sizing: border-box;\\n}\\n.textInput + .textInput {\\n  margin-left: 5px;\\n}\\n\\n.button {\\n  background-color: #f00;\\n  padding: 5px;\\n  font-weight: 600;\\n  transition: background-color 0.1s;\\n  cursor: pointer;\\n  flex-grow: 0;\\n}\\n.button:hover {\\n  background-color: #00f;\\n}", ""\]);
// Exports
/\* harmony default export \*/ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);

i have been playing with my webpack config for days. currently looks like this:

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const HtmlInlineScriptPlugin = require("html-inline-script-webpack-plugin");

module.exports = {
  entry: "./src/index.ts",
  mode: "development",
  output: {
    filename: "main.js",
    path: path.resolve(__dirname, "dist"),
    clean: true,
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "src/index.html",
      inject: "body",
    }),
    new HtmlInlineScriptPlugin(),
  ],
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: "ts-loader",
        exclude: /node_modules/,
      },
      {
        test: /\.html$/,
        loader: "html-loader",
      },
      {
        test: /\.scss$/i,
        use: [
          {
            loader: "style-loader",
          },
          {
            loader: "css-loader",
            // options: {
              // importLoaders: 1,
              // modules: {
              //   mode: "icss",
              // },
              // esModule: false,
            // },
          },
          {
            loader: "sass-loader",
          },
        ],
      },
    ],
  },
  resolve: {
    extensions: [".ts", "..."],
  },
};

and heres my entry .ts file where i import the styles:

import "./styles.scss";

document.forms[0].onsubmit = onManageSubmit;

function onManageSubmit(evt: SubmitEvent) {
  evt.preventDefault();
  console.log('hello');
}


问:
changing the color the tkinter title bar on macOS
I have an app and want to change the color of the title bar. I can do that on windows with the following code:

```<code>import tkinter as tk
from ctypes import windll, byref, sizeof, c_int

root = tk.Tk()
root.update()

HWND = windll.user32.GetParent(root.winfo_id())
DWMWA_ATTRIBUTE = 35
COLOR = 0x000000FF # hex order: 0x00bbggrr

windll.dwmapi.DwmSetWindowAttribute(HWND, DWMWA_ATTRIBUTE, byref(c_int(COLOR)), sizeof(c_int))

root.mainloop()
</code>```

Now I want to do the same for macOS. Sadly, windll.user32 only exists on windows, so is there a mac specific way of approaching this?

(I know I can hide the title bar with overrideredirect but I don't want to use that because it causes other weird behavior)

Body:
I have an app and want to change the color of the title bar. I can do that on windows with the following code:

import tkinter as tk
from ctypes import windll, byref, sizeof, c_int

root = tk.Tk()
root.update()

HWND = windll.user32.GetParent(root.winfo_id())
DWMWA_ATTRIBUTE = 35
COLOR = 0x000000FF # hex order: 0x00bbggrr

windll.dwmapi.DwmSetWindowAttribute(HWND, DWMWA_ATTRIBUTE, byref(c_int(COLOR)), sizeof(c_int))

root.mainloop()

Now I want to do the same for macOS. Sadly, windll.user32 only exists on windows, so is there a mac specific way of approaching this?

(I know I can hide the title bar with overrideredirect but I don't want to use that because it causes other weird behavior)


问:
Casting from cv::Vec2d to cv::Vec2i through ceil/floor
I'd need to either ceil- or floor-off an OpenCV vector of doubles.

With the following code, I got a conversion performed through rounding:

```<code>#include <opencv2/core.hpp>
#include <vector>
#include <iostream>
using namespace std;

int main() {
    cv::Vec2d v(1.3, 1.3);
    cout << v[0] << ";" << v[1] << endl;
    cv::Vec2i vi = cv::Vec2i(v);

    cout << vi[0] << ";" << vi[1] << endl; // Print "1;1"

    v = cv::Vec2d(1.7,1.7);
    vi = cv::Vec2i(v);
    cout << vi[0] << ";" << vi[1] << endl; // Print "2;2"
    return 0;
}
</code>```

How could I directly obtain a conversion to an integer vector through ceiling (Print "2;2" in both cases) or flooring (Print "1;1" in both cases)? By directly I mean without the need for a loop to access each element.

Body:
I'd need to either ceil- or floor-off an OpenCV vector of doubles.

With the following code, I got a conversion performed through rounding:

#include <opencv2/core.hpp>
#include <vector>
#include <iostream>
using namespace std;

int main() {
    cv::Vec2d v(1.3, 1.3);
    cout << v[0] << ";" << v[1] << endl;
    cv::Vec2i vi = cv::Vec2i(v);

    cout << vi[0] << ";" << vi[1] << endl; // Print "1;1"

    v = cv::Vec2d(1.7,1.7);
    vi = cv::Vec2i(v);
    cout << vi[0] << ";" << vi[1] << endl; // Print "2;2"
    return 0;
}

How could I directly obtain a conversion to an integer vector through ceiling (Print "2;2" in both cases) or flooring (Print "1;1" in both cases)? By directly I mean without the need for a loop to access each element.


问:
Altair legend not showing gradient range as quantitative variable
I have a map that I am trying to create a gradient legend based on values in column "pct_chg". When I assign the variable as quantitative, I get a gradient legend like I want but the points on the graph aren't correctly colored. How can I create a gradient legend like in graph A but with the colored scatter points like in plot B?

Plot A:

Plot B:

Code:

```<code>states = alt.topo_feature(data.us_10m.url, feature='states')

background = alt.Chart(states).mark_geoshape(
    fill='lightgray',
    stroke='white'
    ).project('albersUsa').properties(
    width=500,
    height=300
)

points = alt.Chart(locations).mark_circle().encode(
    longitude='Long:Q',
    latitude='Lat:Q',
    size=alt.value(10),
    color=alt.Color('pct_chg:Q',
                    sort="ascending",
                    scale=alt.Scale(scheme='plasma'),#, domain = [-0.999125,41.548309]),
                    legend=alt.Legend(title="Percent Change",
                                      tickCount=10)
                   )
)

chart = background + points
</code>```

Body:
I have a map that I am trying to create a gradient legend based on values in column "pct_chg". When I assign the variable as quantitative, I get a gradient legend like I want but the points on the graph aren't correctly colored. How can I create a gradient legend like in graph A but with the colored scatter points like in plot B?

Plot A:

Plot B:

Code:

states = alt.topo_feature(data.us_10m.url, feature='states')

background = alt.Chart(states).mark_geoshape(
    fill='lightgray',
    stroke='white'
    ).project('albersUsa').properties(
    width=500,
    height=300
)

points = alt.Chart(locations).mark_circle().encode(
    longitude='Long:Q',
    latitude='Lat:Q',
    size=alt.value(10),
    color=alt.Color('pct_chg:Q',
                    sort="ascending",
                    scale=alt.Scale(scheme='plasma'),#, domain = [-0.999125,41.548309]),
                    legend=alt.Legend(title="Percent Change",
                                      tickCount=10)
                   )
)

chart = background + points


问:
How to inherit and initialize a parent class method
I want to use the FTestAnovaPower.solve_power function from the parent class and get some values and them do some additional evaluation in the PwrAnalysis class. but im having trouble passing the arguments to the parent class. i'm trying to inherit a function with the below code.

```<code>import statsmodels.stats.power
class PwrAnalysis(statsmodels.stats.power.FTestAnovaPower):

def __init__(self,effect_size, nobs, alpha, power, k_groups):
    statsmodels.stats.power.FTestAnovaPower.__init__(self,effect_size, nobs, alpha, power, k_groups)
</code>```

when i try to run
c=PwrAnalysis.solve_power(effect_size=0.33, nobs=None, alpha=0.04, power=0.8, k_groups=3)
i get "solve_power() missing 1 required positional argument: 'self'"

for reference the below code runs fine:

```<code>x = statsmodels.stats.power.FTestAnovaPower()
g = x.solve_power(effect_size=0.33, nobs=None, alpha=0.04, power=0.8, k_groups=3)
</code>```

i am passing the self argument, i dont understand why its asking me to pass self again

Body:
I want to use the FTestAnovaPower.solve_power function from the parent class and get some values and them do some additional evaluation in the PwrAnalysis class. but im having trouble passing the arguments to the parent class. i'm trying to inherit a function with the below code.

import statsmodels.stats.power
class PwrAnalysis(statsmodels.stats.power.FTestAnovaPower):

def __init__(self,effect_size, nobs, alpha, power, k_groups):
    statsmodels.stats.power.FTestAnovaPower.__init__(self,effect_size, nobs, alpha, power, k_groups)

when i try to run
c=PwrAnalysis.solve_power(effect_size=0.33, nobs=None, alpha=0.04, power=0.8, k_groups=3)
i get "solve_power() missing 1 required positional argument: 'self'"

for reference the below code runs fine:

x = statsmodels.stats.power.FTestAnovaPower()
g = x.solve_power(effect_size=0.33, nobs=None, alpha=0.04, power=0.8, k_groups=3)

i am passing the self argument, i dont understand why its asking me to pass self again


问:
Transport-Level error when running Invoke-Sqlcmd query, but only when launching from within another function?
I get the error below when running the following query to get the name of my AG. "SELECT TOP 1 AG.name FROM sys.availability_groups AG", but only when launching it from within another module.

A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 0 - The specified network name is no longer available.)
Msg 64, Level 20, State 0, Procedure , Line 0.
Error in Line:      Invoke-Sqlcmd -ServerInstance $ServerName -Query $query | Select-Object -expand Name

When I call to the .psm that runs this standalone, it runs without fail, but when I call to it from within another .psm it has run twice out of the >50 attempts I have made today.  Any advice or ideas are much appreciated!


问:
build exact debian kernel
I'm searching a way to compile this debian kernel from netinstall image :
https://gemmei.ftp.acc.umu.se/debian-cd/current/amd64/iso-cd/debian-11.6.0-amd64-netinst.iso

the version is 5.10.0-20-amd64 smp debian 5.10.158-2 (2022-12-13)

do you know where to search or can i do it ?

i try to search the version in https://cdn.kernel.org/pub/linux/kernel/v5.x/
but can-t find it ...

Title: build exact debian kernel