问:
(ReactJS) Why do changes made in a component by its event handlers remain when the component is re-rendered?
I'm having a problem in React where if an event handler is triggered in a component, and it changes parts of the component (like style or textContent), those changes don't reset/revert when the component is re-rendered.

More specifics: I want to set up a basic forum/board page where you select a category from one drop down, and then select a topic from the second drop-down. Choosing the topic will fill an array with "post" objects, and the array is used to render the list of posts for it below. There's a search bar at the top which also renders posts through an array of post objects if it finds matches.

The posts that get rendered feature thumbs-up, thumbs-down and trash can icons. The thumbs icons have an onClick event that changes a "likes: " text on that post, while the trash can icon "deletes" the post (changes its display to none; only for visual effect).

UPDATED 12/7/22
The problem is, if I increase the likes/dislikes on a post or "delete" it and search a term, if a post from the results occupies the same position as the post I liked/disliked/deleted, the like/dislike number or the "deleted" effect remains and applies to that new post.

In other words, say the display shows 3 posts at first. The second post has 4 likes. I add a like so it updates to 5. Then I enter a search term that yields 5 posts that will render over the initial 3. By default, the second search result post is supposed to have 20 likes. But it's occupying the same position in the display as the one I modified; so the likes displayed shows 5 instead of 20. Note: The search bar is in a different component, parent to the component with the drop-downs. The component with the drop-downs is parent to the component where the posts display.

I tried:

Component with search bar (forumData and userData are unrelated)

```<code>(...)
function setSearchValue(e){
    if (e.key === "Enter"){
        setSearchQuery(e.target.value);
        setRenderSwitch(!renderSwitch);
    }
  }

    return (
        <>
            <header>
                <h1>Pseudo Forum</h1>
                <input type="text" id="postSearchBox" placeholder="search the entire forum" defaultValue={searchQuery} onKeyUp={setSearchValue}></input>
            </header>
            <section id="middle-section">
                <LeftColumn />
                <CenterColumn threads={forumData} searchQuery={searchQuery} renderSwitch={renderSwitch} />
                <RightColumn threads={forumData} users={userData} />
            </section>
        </>
    );
(...)
</code>```

Component with drop-downs

```<code>import React, { useEffect, useState } from 'react';
import './CenterColumn.css';
import Post from '../PostComponent/Post.jsx';

function CenterColumn(props) {
  const [topics, setTopics] = useState([]);
  const [posts, setPosts] = useState([]);
  const [topicVal, setTopicVal] = useState("");
  const [categoryVal, setCategoryVal] = useState(0);
  const [reSearch, setReSearch] = useState(false);

  useEffect(function(){
    setCategoryVal("");
    setPosts([]);
    setTopicVal("");
    setTopics([]);
    if (props.searchQuery !== ""){
        let allPosts = [];
        function getAllPosts(){
          let returnArray = [];
          for (let i = 0; i < props.threads.length; i++){
            for (let j = 0; j < props.threads[i].topicList.length; j++){
              for(let k = 0; k < props.threads[i].topicList[j].listPosts.length; k++){
                returnArray.push(props.threads[i].topicList[j].listPosts[k]);
              }
            }
          }

          return returnArray;
        }

        allPosts = getAllPosts();

        let searchResults = allPosts.filter(findResults);

        function findResults(eachPost){
          return (eachPost.text.toUpperCase().indexOf(props.searchQuery.toUpperCase()) > -1);
        }
        setPosts(searchResults);
        setReSearch(!reSearch);
    }

    else{
      setPosts([]);
    }
  }, [props.renderSwitch]);

  function assignTopics(e){
    setCategoryVal(parseInt(e.target.value));
    setPosts([]);
    setTopicVal("");

    setTopics(function(){
      if (e.target.value !== ""){
        return props.threads[(parseInt(e.target.value) - 1)].topicList;
      }

      return [];
    });
  }

  function assignPosts(e){
    setTopicVal(e.target.value);
    setPosts(function(){
      if (e.target.value !== ""){
        return props.threads[categoryVal - 1].topicList[(parseInt(e.target.value) -1)].listPosts;
      }

      return [];
    })
  }

  return (
        <section id="centerColumn">
              <section id="dropDownSection">
                <section id="categoryPair">
                    <label htmlFor="categoryDropDown">Choose Category</label>
                    <select id="categoryDropDown" onChange={assignTopics} value={categoryVal}>
                      <option value="">Select a Category</option>
                      {
                          props.threads.map(function(category){
                            return (<option value={category.id} key={category.id}>{category.name}</option>)
                      })}
                    </select>
                </section>
                <section id="topicPair">
                    <label htmlFor="topicDropDown">Choose Topic</label>
                    <select id="topicDropDown" onChange={assignPosts} value={topicVal}>
                      <option value="">Select a Thread</option>
                      {
                          topics.map(function(topic){
                            return (<option value={topic.id} key={topic.id}>{topic.topic_title}</option>)
                      })}
                    </select>
                </section>
              </section>
              <section id="postSection">
                {
                  posts.map(function(post){
                    return (<Post post={post} reSearch={reSearch} />)
                })}
              </section>
        </section>
    );
  }

  export default CenterColumn;
</code>```

Component with post display

```<code>import React from 'react';
import {useState, useRef} from 'react';
import './Post.css';
import {FaThumbsUp, FaThumbsDown, FaTrashAlt} from 'react-icons/fa';

function Post(props){
    let likeCounterRef = useRef(null);
    let deleteRef = useRef(null);

    function updateLikes(e){
        if (e.currentTarget.className === "thumbsUp"){
            let likesCount = parseInt(likeCounterRef.current.textContent.split(":")[1]);
            likesCount++;
            likeCounterRef.current.textContent= `likes:${likesCount}`;

        }
        else if (e.currentTarget.className === "thumbsDown"){
            let likesCount = parseInt(likeCounterRef.current.textContent.split(":")[1]);
            likesCount--;
            likeCounterRef.current.textContent = `likes:${likesCount}`;
        }
    }

    function deletePost(e){
        deleteRef.current.style.display="none";
    }

    return (
        <section className="wholePost" key={props.post.id} ref={deleteRef}>
            <section className="messageArea">
                <p className="message">{props.post.text}</p><p className="likes" ref={likeCounterRef}>likes:{props.post.like}</p><p className="thumbsUp" onClick={updateLikes}><FaThumbsUp style={{color: "green"}} /></p><p className="thumbsDown" onClick={updateLikes}><FaThumbsDown style={{color: "red"}} /></p>
            </section>
            <section className="metadata">
            <p className="author">by:{props.post.author}</p><p className="postDate">{props.post.date}</p><p className="replies">replies:{props.post.replies}</p><p className="trashCan"><FaTrashAlt style ={{cursor: "pointer"}} onClick={deletePost} /></p>
            </section>
        </section>
    );
}

export default Post;
</code>```

Expected:
The Post component would be completely re-rendered and the text reset/reverted whenever a different drop-down option is selected (or search term is entered that yields a post in the same position as the modified one). The likes count would reset and deleted posts would reappear.

Instead:
Changes to the likes count on a post carry over to whichever post newly occupies its position. Similarly, if I "delete" a post and change topic, that new topic's post in the same position/order will also be missing.

Outline of images (UPDATED):

1 - A list of posts. Didn't click on any likes yet. Likes is at 0 for first one:

First post in list, Likes 0 here

2 - Search yields different set of posts. Didn't click on any likes yet. Likes is at 22 for first:

Different first post, Likes 22 here

3 - Switched back to displaying first set of posts. Clicked the thumbs up on the first post. Likes is at 1.

Back to first set of posts, clicked thumbs up and likes is now 1

4 - Did previous search to get second set of results again. Look at the likes of the first post here, it went from 22 to 1.

First post in new set (thus, occupies the same position of the modified post from previous set)

Body:
I'm having a problem in React where if an event handler is triggered in a component, and it changes parts of the component (like style or textContent), those changes don't reset/revert when the component is re-rendered.

More specifics: I want to set up a basic forum/board page where you select a category from one drop down, and then select a topic from the second drop-down. Choosing the topic will fill an array with "post" objects, and the array is used to render the list of posts for it below. There's a search bar at the top which also renders posts through an array of post objects if it finds matches.

The posts that get rendered feature thumbs-up, thumbs-down and trash can icons. The thumbs icons have an onClick event that changes a "likes: " text on that post, while the trash can icon "deletes" the post (changes its display to none; only for visual effect).

UPDATED 12/7/22
The problem is, if I increase the likes/dislikes on a post or "delete" it and search a term, if a post from the results occupies the same position as the post I liked/disliked/deleted, the like/dislike number or the "deleted" effect remains and applies to that new post.

In other words, say the display shows 3 posts at first. The second post has 4 likes. I add a like so it updates to 5. Then I enter a search term that yields 5 posts that will render over the initial 3. By default, the second search result post is supposed to have 20 likes. But it's occupying the same position in the display as the one I modified; so the likes displayed shows 5 instead of 20. Note: The search bar is in a different component, parent to the component with the drop-downs. The component with the drop-downs is parent to the component where the posts display.

I tried:

Component with search bar (forumData and userData are unrelated)

(...)
function setSearchValue(e){
    if (e.key === "Enter"){
        setSearchQuery(e.target.value);
        setRenderSwitch(!renderSwitch);
    }
  }

    return (
        <>

Pseudo Forum

                <input type="text" id="postSearchBox" placeholder="search the entire forum" defaultValue={searchQuery} onKeyUp={setSearchValue}></input>

                <LeftColumn />
                <CenterColumn threads={forumData} searchQuery={searchQuery} renderSwitch={renderSwitch} />
                <RightColumn threads={forumData} users={userData} />

        </>
    );
(...)

Component with drop-downs

import React, { useEffect, useState } from 'react';
import './CenterColumn.css';
import Post from '../PostComponent/Post.jsx';

function CenterColumn(props) {
  const [topics, setTopics] = useState([]);
  const [posts, setPosts] = useState([]);
  const [topicVal, setTopicVal] = useState("");
  const [categoryVal, setCategoryVal] = useState(0);
  const [reSearch, setReSearch] = useState(false);

  useEffect(function(){
    setCategoryVal("");
    setPosts([]);
    setTopicVal("");
    setTopics([]);
    if (props.searchQuery !== ""){
        let allPosts = [];
        function getAllPosts(){
          let returnArray = [];
          for (let i = 0; i < props.threads.length; i++){
            for (let j = 0; j < props.threads[i].topicList.length; j++){
              for(let k = 0; k < props.threads[i].topicList[j].listPosts.length; k++){
                returnArray.push(props.threads[i].topicList[j].listPosts[k]);
              }
            }
          }

          return returnArray;
        }

        allPosts = getAllPosts();

        let searchResults = allPosts.filter(findResults);

        function findResults(eachPost){
          return (eachPost.text.toUpperCase().indexOf(props.searchQuery.toUpperCase()) > -1);
        }
        setPosts(searchResults);
        setReSearch(!reSearch);
    }

    else{
      setPosts([]);
    }
  }, [props.renderSwitch]);

  function assignTopics(e){
    setCategoryVal(parseInt(e.target.value));
    setPosts([]);
    setTopicVal("");

    setTopics(function(){
      if (e.target.value !== ""){
        return props.threads[(parseInt(e.target.value) - 1)].topicList;
      }

      return [];
    });
  }

  function assignPosts(e){
    setTopicVal(e.target.value);
    setPosts(function(){
      if (e.target.value !== ""){
        return props.threads[categoryVal - 1].topicList[(parseInt(e.target.value) -1)].listPosts;
      }

      return [];
    })
  }

  return (

                    Choose Category
                    <select id="categoryDropDown" onChange={assignTopics} value={categoryVal}>
                      <option value="">Select a Category</option>
                      {
                          props.threads.map(function(category){
                            return (<option value={category.id} key={category.id}>{category.name}</option>)
                      })}
                    </select>

                    Choose Topic
                    <select id="topicDropDown" onChange={assignPosts} value={topicVal}>
                      <option value="">Select a Thread</option>
                      {
                          topics.map(function(topic){
                            return (<option value={topic.id} key={topic.id}>{topic.topic_title}</option>)
                      })}
                    </select>

                {
                  posts.map(function(post){
                    return (<Post post={post} reSearch={reSearch} />)
                })}

    );
  }

  export default CenterColumn;

Component with post display

import React from 'react';
import {useState, useRef} from 'react';
import './Post.css';
import {FaThumbsUp, FaThumbsDown, FaTrashAlt} from 'react-icons/fa';

function Post(props){
    let likeCounterRef = useRef(null);
    let deleteRef = useRef(null);

    function updateLikes(e){
        if (e.currentTarget.className === "thumbsUp"){
            let likesCount = parseInt(likeCounterRef.current.textContent.split(":")[1]);
            likesCount++;
            likeCounterRef.current.textContent= `likes:${likesCount}`;

        }
        else if (e.currentTarget.className === "thumbsDown"){
            let likesCount = parseInt(likeCounterRef.current.textContent.split(":")[1]);
            likesCount--;
            likeCounterRef.current.textContent = `likes:${likesCount}`;
        }
    }

    function deletePost(e){
        deleteRef.current.style.display="none";
    }

    return (

{props.post.text}

likes:{props.post.like}

<FaThumbsUp style={{color: "green"}} />

<FaThumbsDown style={{color: "red"}} />

by:{props.post.author}

{props.post.date}

replies:{props.post.replies}

<FaTrashAlt style ={{cursor: "pointer"}} onClick={deletePost} />

    );
}

export default Post;

Expected:
The Post component would be completely re-rendered and the text reset/reverted whenever a different drop-down option is selected (or search term is entered that yields a post in the same position as the modified one). The likes count would reset and deleted posts would reappear.

Instead:
Changes to the likes count on a post carry over to whichever post newly occupies its position. Similarly, if I "delete" a post and change topic, that new topic's post in the same position/order will also be missing.

Outline of images (UPDATED):

1 - A list of posts. Didn't click on any likes yet. Likes is at 0 for first one:

First post in list, Likes 0 here

2 - Search yields different set of posts. Didn't click on any likes yet. Likes is at 22 for first:

Different first post, Likes 22 here

3 - Switched back to displaying first set of posts. Clicked the thumbs up on the first post. Likes is at 1.

Back to first set of posts, clicked thumbs up and likes is now 1

4 - Did previous search to get second set of results again. Look at the likes of the first post here, it went from 22 to 1.

First post in new set (thus, occupies the same position of the modified post from previous set)


来源: stackexchange

问:
React text editor with mentioned functionality
Anyone know any good react js text editor which have good functionality and can work with mentions too like we mention people in our chat applications?</p>

ContentLicense: CC BY-SA 4.0


问:
sometime Not enough replicas available for query at consistency ONE (1 required but only 0 alive) error
when insert date into cassandra, I use spark structured stream kafka-cassandra. data insert no problem. but when i load data. sometime occurred error, SQL Error: com.datastax.driver.core.exceptions.UnavailableException: Not enough replicas available for query at consistency ONE (1 required but only 0 alive)

my spark-submit code

```<code>spark-submit --packages org.apache.spark:spark-sql-kafka-0-10_2.12:3.1.2,com.datastax.spark:spark-cassandra-connector_2.12:3.2.0,com.github.jnr:jnr-posix:3.1.15 --conf spark.dynamicAllocation.enabled=false --conf com.datastax.spark:spark.cassandra.connectiohost=172.16.10    .6,spark.sql.extensions=com.datastax.spark.connector.CassandraSparkExtensions
</code>```

source code

```<code># Spark Bridge local to spark_master
spark = SparkSession.builder \
    .master(_connSession)\
    .appName("Spark_Streaming+kafka+cassandra") \
    .config('spark.cassandra.connection.host', _connCassandraHost) \
    .config('spark.cassandra.connection.port', _connCassandraPort) \
    .getOrCreate()

# readStream From DATA_SOC at DB Server
df = spark.readStream \
  .format("kafka") \
  .option("kafka.bootstrap.servers", _connKafka) \
  .option('startingOffsets','earliest') \
  .option("subscribe", _topic) \
  .option('failOnDataLoss', False) \
  .load() \
  .select(from_json(col("value").cast("String"), schema).alias("parsed_value")) \
  .select("parsed_value.*")

df = df.withColumn("create_dt",date_format(current_date(),"yyyyMM"))
df = df.withColumn("max",df.attributes.getItem("max"))
df = df.withColumn("min",df.attributes.getItem("min"))
df = df.withColumn("avg",df.attributes.getItem("avg"))
df = df.drop("attributes")

df.printSchema()

# writeStream at cassandra in Spark master VM
ds = df.writeStream \
  .trigger(processingTime='15 seconds') \
  .format("org.apache.spark.sql.cassandra") \
  .option("checkpointLocation","/home/jeju/jeju_sensor_collector/src/checkPoint") \
  .options(table=_table,keyspace=_keySpace) \
  .outputMode('append') \
  .start()

ds.awaitTermination()
</code>```

application Desigh Pattern is Master-Slave, 1master-3slave.

why auto off spark-cassandra??

Body:
when insert date into cassandra, I use spark structured stream kafka-cassandra. data insert no problem. but when i load data. sometime occurred error, SQL Error: com.datastax.driver.core.exceptions.UnavailableException: Not enough replicas available for query at consistency ONE (1 required but only 0 alive)

my spark-submit code

spark-submit --packages org.apache.spark:spark-sql-kafka-0-10_2.12:3.1.2,com.datastax.spark:spark-cassandra-connector_2.12:3.2.0,com.github.jnr:jnr-posix:3.1.15 --conf spark.dynamicAllocation.enabled=false --conf com.datastax.spark:spark.cassandra.connectiohost=172.16.10    .6,spark.sql.extensions=com.datastax.spark.connector.CassandraSparkExtensions

source code

# Spark Bridge local to spark_master
spark = SparkSession.builder \
    .master(_connSession)\
    .appName("Spark_Streaming+kafka+cassandra") \
    .config('spark.cassandra.connection.host', _connCassandraHost) \
    .config('spark.cassandra.connection.port', _connCassandraPort) \
    .getOrCreate()

# readStream From DATA_SOC at DB Server
df = spark.readStream \
  .format("kafka") \
  .option("kafka.bootstrap.servers", _connKafka) \
  .option('startingOffsets','earliest') \
  .option("subscribe", _topic) \
  .option('failOnDataLoss', False) \
  .load() \
  .select(from_json(col("value").cast("String"), schema).alias("parsed_value")) \
  .select("parsed_value.*")

df = df.withColumn("create_dt",date_format(current_date(),"yyyyMM"))
df = df.withColumn("max",df.attributes.getItem("max"))
df = df.withColumn("min",df.attributes.getItem("min"))
df = df.withColumn("avg",df.attributes.getItem("avg"))
df = df.drop("attributes")

df.printSchema()

# writeStream at cassandra in Spark master VM
ds = df.writeStream \
  .trigger(processingTime='15 seconds') \
  .format("org.apache.spark.sql.cassandra") \
  .option("checkpointLocation","/home/jeju/jeju_sensor_collector/src/checkPoint") \
  .options(table=_table,keyspace=_keySpace) \
  .outputMode('append') \
  .start()

ds.awaitTermination()

application Desigh Pattern is Master-Slave, 1master-3slave.

why auto off spark-cassandra??


问:
Selenium JS : can't get rid of exception unexpected alert open: {Alert text : xxx}
I have a page in which an alert box may appear randomly if I click on a button. I auto click on this button every 5 seconds. I want to get rid/ignore all possible alerts but it the exception unexpected alert open: {Alert text : xxx} won't disappear despite I tried this :

Solution (1) that I tried

```<code>// Add --disable-notifications to chrome options
let options = new chrome.Options();
options.addArguments("--disable-notifications")
const driver = new
webdriver.Builder().forBrowser("chrome").setChromeOptions(options).build();
</code>```

Solution (2) that I tried :

```<code>// set the driver capabilities to accept silently all dialogs
// I double-checked the key/values strings of the capabilities
const capabilities = await driver.getCapabilities()
await capabilities.set('unhandledPromptBehavior', 'accept')
</code>```

Any idea ?

Body:
I have a page in which an alert box may appear randomly if I click on a button. I auto click on this button every 5 seconds. I want to get rid/ignore all possible alerts but it the exception unexpected alert open: {Alert text : xxx} won't disappear despite I tried this :

Solution (1) that I tried

// Add --disable-notifications to chrome options
let options = new chrome.Options();
options.addArguments("--disable-notifications")
const driver = new
webdriver.Builder().forBrowser("chrome").setChromeOptions(options).build();

Solution (2) that I tried :

// set the driver capabilities to accept silently all dialogs
// I double-checked the key/values strings of the capabilities
const capabilities = await driver.getCapabilities()
await capabilities.set('unhandledPromptBehavior', 'accept')

Any idea ?


问:
Loading UIImage's on background thread solves SceneKit memory problems. Why?
Consider the following code:

```<code>let img = UIImage(named: "myString")
if let img = img {
    mySCNMaterial.diffuse.contents = img
}
</code>```

I was using this to load images in a SceneKit project. Specifically, I was doing this from inside my UIViewController's viewDidLoad.

As long as I was doing it this way, my project was leaking memory like crazy (restarting a level in the game would bump memory consumption up by something like 30mb each time, and that memory would never be reclaimed). However, Instruments found no memory leaks, and enabling my project scheme's Zombie Objects gave results that were...literally unbelievable, with something like 1000+ zombies from all kinds of sources.

At some point, I learned about the difference between UIImage(named:) and UIImage(contentsOfFile:), with the system caching the former, but not the latter.

So, now I've got this:

```<code>let path = Bundle.main.path(forResource: "myString", ofType: "png")!
let img = UIImage(contentsOfFile: path)!
mySCNMaterial.diffuse.contents = img
</code>```

I theorized that this would improve memory usage in my own game, but the gains were minimal at best.

But today I decided to try explicitly running the previous bit of code on a background thread (UIImage is thread-safe, according to the documentation) -- and my game stopped leaking memory entirely, as determined by the Instruments Allocations template.

So, now I've got this:

```<code>DispatchQueue.global(qos: .background).async {
    let path = Bundle.main.path(forResource: "myString", ofType: "png")!
    let img = UIImage(contentsOfFile: path)!
    mySCNMaterial.diffuse.contents = img
}
</code>```

While I'm very glad to have stumbled upon this fix, I'd like to better understand what's going on.

Question: Why might these changes solve my SceneKit game's memory usage problems?

Body:
Consider the following code:

let img = UIImage(named: "myString")
if let img = img {
    mySCNMaterial.diffuse.contents = img
}

I was using this to load images in a SceneKit project. Specifically, I was doing this from inside my UIViewController's viewDidLoad.

As long as I was doing it this way, my project was leaking memory like crazy (restarting a level in the game would bump memory consumption up by something like 30mb each time, and that memory would never be reclaimed). However, Instruments found no memory leaks, and enabling my project scheme's Zombie Objects gave results that were...literally unbelievable, with something like 1000+ zombies from all kinds of sources.

At some point, I learned about the difference between UIImage(named:) and UIImage(contentsOfFile:), with the system caching the former, but not the latter.

So, now I've got this:

let path = Bundle.main.path(forResource: "myString", ofType: "png")!
let img = UIImage(contentsOfFile: path)!
mySCNMaterial.diffuse.contents = img

I theorized that this would improve memory usage in my own game, but the gains were minimal at best.

But today I decided to try explicitly running the previous bit of code on a background thread (UIImage is thread-safe, according to the documentation) -- and my game stopped leaking memory entirely, as determined by the Instruments Allocations template.

So, now I've got this:

DispatchQueue.global(qos: .background).async {
    let path = Bundle.main.path(forResource: "myString", ofType: "png")!
    let img = UIImage(contentsOfFile: path)!
    mySCNMaterial.diffuse.contents = img
}

While I'm very glad to have stumbled upon this fix, I'd like to better understand what's going on.

Question: Why might these changes solve my SceneKit game's memory usage problems?


问:
Issue in creating DKIM key with RSA digest
Trying to create DKIM keys using PHP code mentioned below.

```<code><?php

//Set these to match your domain and chosen DKIM selector
$domain = 'example.com';
$selector = 'phpmailer';

//Private key filename for this selector
$privatekeyfile = $selector . '_dkim_private.pem';
//Public key filename for this selector
$publickeyfile = $selector . '_dkim_public.pem';

if (file_exists($privatekeyfile)) {
    echo "Using existing keys - if you want to generate new keys, delete old key files first.\n\n";
    $privatekey = file_get_contents($privatekeyfile);
    $publickey = file_get_contents($publickeyfile);
} else {
    //Create a 2048-bit RSA key with an SHA256 digest
    $pk = openssl_pkey_new(
        [
            'digest_alg' => 'sha256',
            'private_key_bits' => 2048,
            'private_key_type' => OPENSSL_KEYTYPE_RSA,
        ]
    );
    //Save private key

    var_dump($pk);
    //exit;
    openssl_pkey_export_to_file($pk, $privatekeyfile);
    //Save public key
    $pubKey = openssl_pkey_get_details($pk);
    $publickey = $pubKey['key'];
    file_put_contents($publickeyfile, $publickey);

    $privatekey = file_get_contents($privatekeyfile);
}
echo "```"."Private key (keep this private!):\n\n" . $privatekey;
echo "\n\nPublic key:\n\n" . $publickey;

//Prepare public key for DNS, e.g.
//phpmailer._domainkey.example.com IN TXT "v=DKIM1; h=sha256; t=s; p=" "MIIBIjANBg...oXlwIDAQAB"...
$dnskey = "$selector._domainkey.$domain IN TXT";
$dnsvalue = '"v=DKIM1; h=sha256; t=s; p=" ';
//Some DNS servers don't like ;(semi colon) chars unless backslash-escaped
$dnsvalue2 = '"v=DKIM1\; h=sha256\; t=s\; p=" ';

//Strip and split the key into smaller parts and format for DNS
//Many DNS systems don't like long TXT entries
//but are OK if it's split into 255-char chunks
//Remove PEM wrapper
$publickey = preg_replace('/^-+.*?-+$/m', '', $publickey);
//Strip line breaks
$publickey = str_replace(["\r", "\n"], '', $publickey);
//Split into chunks
$keyparts = str_split($publickey, 253); //Becomes 255 when quotes are included
//Quote each chunk
foreach ($keyparts as $keypart) {
    $dnsvalue .= '"' . trim($keypart) . '" ';
    $dnsvalue2 .= '"' . trim($keypart) . '" ';
}
echo "\n\nDNS key:\n\n" . trim($dnskey);
echo "\n\nDNS value:\n\n" . trim($dnsvalue);
echo "\n\nDNS value (with escaping):\n\n" . trim($dnsvalue2);
?>
```

Here in this code we are using 2048-bit RSA key with an SHA256 digest, but our DNS provider supports 1024 bit with RSA digest.
key size I can manage 'private_key_bits' => 1024, please suggest how can this key can be created using RSA digest.

Body:
Trying to create DKIM keys using PHP code mentioned below.

<?php

//Set these to match your domain and chosen DKIM selector
$domain = 'example.com';
$selector = 'phpmailer';

//Private key filename for this selector
$privatekeyfile = $selector . '_dkim_private.pem';
//Public key filename for this selector
$publickeyfile = $selector . '_dkim_public.pem';

if (file_exists($privatekeyfile)) {
    echo "Using existing keys - if you want to generate new keys, delete old key files first.\n\n";
    $privatekey = file_get_contents($privatekeyfile);
    $publickey = file_get_contents($publickeyfile);
} else {
    //Create a 2048-bit RSA key with an SHA256 digest
    $pk = openssl_pkey_new(
        [
            'digest_alg' => 'sha256',
            'private_key_bits' => 2048,
            'private_key_type' => OPENSSL_KEYTYPE_RSA,
        ]
    );
    //Save private key

    var_dump($pk);
    //exit;
    openssl_pkey_export_to_file($pk, $privatekeyfile);
    //Save public key
    $pubKey = openssl_pkey_get_details($pk);
    $publickey = $pubKey['key'];
    file_put_contents($publickeyfile, $publickey);

    $privatekey = file_get_contents($privatekeyfile);
}
echo "
"."Private key (keep this private!):\n\n" . $privatekey;
echo "\n\nPublic key:\n\n" . $publickey;

//Prepare public key for DNS, e.g.
//phpmailer._domainkey.example.com IN TXT "v=DKIM1; h=sha256; t=s; p=" "MIIBIjANBg...oXlwIDAQAB"...
$dnskey = "$selector._domainkey.$domain IN TXT";
$dnsvalue = '"v=DKIM1; h=sha256; t=s; p=" ';
//Some DNS servers don't like ;(semi colon) chars unless backslash-escaped
$dnsvalue2 = '"v=DKIM1\; h=sha256\; t=s\; p=" ';

//Strip and split the key into smaller parts and format for DNS
//Many DNS systems don't like long TXT entries
//but are OK if it's split into 255-char chunks
//Remove PEM wrapper
$publickey = preg_replace('/^-+.*?-+$/m', '', $publickey);
//Strip line breaks
$publickey = str_replace(["\r", "\n"], '', $publickey);
//Split into chunks
$keyparts = str_split($publickey, 253); //Becomes 255 when quotes are included
//Quote each chunk
foreach ($keyparts as $keypart) {
    $dnsvalue .= '"' . trim($keypart) . '" ';
    $dnsvalue2 .= '"' . trim($keypart) . '" ';
}
echo "\n\nDNS key:\n\n" . trim($dnskey);
echo "\n\nDNS value:\n\n" . trim($dnsvalue);
echo "\n\nDNS value (with escaping):\n\n" . trim($dnsvalue2);
?>

Here in this code we are using 2048-bit RSA key with an SHA256 digest, but our DNS provider supports 1024 bit with RSA digest.
key size I can manage 'private_key_bits' => 1024, please suggest how can this key can be created using RSA digest.


问:
Server code in *.server.ts getting bundled in Remix JS Client
I am building a Remix JS / Prisma app, following the Remix Jokes App tutorial by Kent C Dodds.

I am getting an error that says:

```<code>PrismaClient is unable to be run in the browser.
</code>```

even though PrismaClient is being run inside a *.server.ts file which means the Remix compiler should be excluding it from the client bundle.

Here is my route file:

// app/routes/auth/login.tsx

import {
  type ActionFunction,
  json
} from "@remix-run/cloudflare";
import LoginScreen from "~/screens/LoginScreen"
import { login } from "~/utils/session.server"; // Import from .server file
import { useActionData } from "@remix-run/react";

const badRequest = (data: ActionData) =>
  json(data, { status: 400 });

export const action: ActionFunction = async ({
  request,
}) => {
  // Get and validate input [Omitted]

  const user = await login({ email, password }); // <-- Problematic code path
  if (!user) {
   return badRequest({
     fields,
     formError: `Incorrect username or password.`,
   });
  }
  // Redirect user into the app [Omitted]
}

export const loader = () => null;

export default function LoginRoute() {
  const data = useActionData();
  return (
    <LoginScreen formError={data?.formError} fieldErrors={data?.fieldErrors}/>
  )
}
```
<p><strong>Here is my <code>session.server.ts</code> file, where I define the <code>login</code> function:</strong></p>
<pre class="lang-js prettyprint-override"><code>// app/utils/session.server.ts

import bcrypt from "bcryptjs";
import { db } from "./db.server";

export async function login({
  email,
  password,
}) {
  const user = await db.user.findUnique({ where: { email } }); // <-- Problematic code path

  if (!user) return null;
  const isCorrectPassword = await bcrypt.compare(
    password,
    user.passwordHash
  );
  if (!isCorrectPassword) return null;
  return { id: user.id, email };
}
</code>```

Here is where I defined PrimsaClient:

// app/utils/db.server.ts

import { PrismaClient } from "@prisma/client";

let db: PrismaClient;

declare global {
  var __db: PrismaClient | undefined;
}

// This is needed because in development we don't want to restart
// the server with every change, but we want to make sure we don't
// create a new connection to the DB with every change either.
if (process.env.NODE_ENV === "production") {
  db = new PrismaClient();
} else {
  if (!global.__db) {
    global.__db = new PrismaClient(); <-- This is where the exception is happening
  }
  db = global.__db;
}

export { db };
```

Why is Primsa being run in the client given that it's inside *.server.ts?

Body:
I am building a Remix JS / Prisma app, following the Remix Jokes App tutorial by Kent C Dodds.

I am getting an error that says:

PrismaClient is unable to be run in the browser.

even though PrismaClient is being run inside a *.server.ts file which means the Remix compiler should be excluding it from the client bundle.

Here is my route file:

// app/routes/auth/login.tsx

import {
  type ActionFunction,
  json
} from "@remix-run/cloudflare";
import LoginScreen from "~/screens/LoginScreen"
import { login } from "~/utils/session.server"; // Import from .server file
import { useActionData } from "@remix-run/react";

const badRequest = (data: ActionData) =>
  json(data, { status: 400 });

export const action: ActionFunction = async ({
  request,
}) => {
  // Get and validate input [Omitted]

  const user = await login({ email, password }); // <-- Problematic code path
  if (!user) {
   return badRequest({
     fields,
     formError: `Incorrect username or password.`,
   });
  }
  // Redirect user into the app [Omitted]
}

export const loader = () => null;

export default function LoginRoute() {
  const data = useActionData();
  return (
    <LoginScreen formError={data?.formError} fieldErrors={data?.fieldErrors}/>
  )
}

Here is my session.server.ts file, where I define the login function:

// app/utils/session.server.ts

import bcrypt from "bcryptjs";
import { db } from "./db.server";

export async function login({
  email,
  password,
}) {
  const user = await db.user.findUnique({ where: { email } }); // <-- Problematic code path

  if (!user) return null;
  const isCorrectPassword = await bcrypt.compare(
    password,
    user.passwordHash
  );
  if (!isCorrectPassword) return null;
  return { id: user.id, email };
}

Here is where I defined PrimsaClient:

// app/utils/db.server.ts

import { PrismaClient } from "@prisma/client";

let db: PrismaClient;

declare global {
  var __db: PrismaClient | undefined;
}

// This is needed because in development we don't want to restart
// the server with every change, but we want to make sure we don't
// create a new connection to the DB with every change either.
if (process.env.NODE_ENV === "production") {
  db = new PrismaClient();
} else {
  if (!global.__db) {
    global.__db = new PrismaClient(); <-- This is where the exception is happening
  }
  db = global.__db;
}

export { db };

Why is Primsa being run in the client given that it's inside *.server.ts?


问:
Override Django Slug
I have a blog in wagtail. Wagtail's default Page model already has a slug field defined. Full Example is here

```<code>slug = models.SlugField(
        verbose_name=_("slug"),
</code>```

I have a Subclass AddStory of the Page class, so I am unable to define slug there. And I am getting a clashing error.

Problem:

The slug field automatically generates a slug from the Title. So There are some kind of event whose title will be same always. Like Jokes of the day, So for the first 10 or 20 days, editors will know that they have added 20 posts with day_1,day_2... at the end of the slug and when these days will increase it will be impossible for them to remember how many they have entered?!

Probable Solution

So if I can automate the slug as it will generate a slug from random ids or strings and it will be unique.

I tried this in the subclass AddStory

```<code>def pre_save(self):
    def randomid1(self):
        return(get_random_string(length=10))
    self.slug = randomid1
</code>```

How can I define that it will not generate slug from the title instead it will generate a slug from given random strings?

Title: Override Django Slug

Body:
I have a blog in wagtail. Wagtail's default Page model already has a slug field defined. Full Example is here

slug = models.SlugField(
        verbose_name=_("slug"),

I have a Subclass AddStory of the Page class, so I am unable to define slug there. And I am getting a clashing error.

Problem:

The slug field automatically generates a slug from the Title. So There are some kind of event whose title will be same always. Like Jokes of the day, So for the first 10 or 20 days, editors will know that they have added 20 posts with day_1,day_2... at the end of the slug and when these days will increase it will be impossible for them to remember how many they have entered?!

Probable Solution

So if I can automate the slug as it will generate a slug from random ids or strings and it will be unique.

I tried this in the subclass AddStory

def pre_save(self):
    def randomid1(self):
        return(get_random_string(length=10))
    self.slug = randomid1

How can I define that it will not generate slug from the title instead it will generate a slug from given random strings?


问:
Authentication with Private Key does not work
I try to connect SFTP Server using Jsch Library. It works when i use username/password, but with private/public key does not work. i have been read all questions about this theme in Stackoverflow and in other Site webs, but i did not find what i search for.

To test my private key, i have used Terminal(also WinSCP), it works fine, but with Java Code i get this " Auth fail"

This is an Example:

```<code> public static void main(String[] args) throws JSchException, SftpException, IOException {
        JSch jsch = new JSch();
        Properties config=new Properties();
        config.put("StrictHostKeyChecking", "no");
        jsch.addIdentity("path_to_private_key");
        Session session;
        session = jsch.getSession("user", "host", 22);

        session.setConfig(config);
//        session.setPassword("pass");
        session.connect();
        System.out.println("CONNECT !!! ");
        session.disconnect();
    }
</code>```

.  I have generated keys using this command: ssh-keygen -C "" -m PEM id_rsa
.  past public key in /.ssh/authorized_keys

Any help please?

Body:
I try to connect SFTP Server using Jsch Library. It works when i use username/password, but with private/public key does not work. i have been read all questions about this theme in Stackoverflow and in other Site webs, but i did not find what i search for.

To test my private key, i have used Terminal(also WinSCP), it works fine, but with Java Code i get this " Auth fail"

This is an Example:

 public static void main(String[] args) throws JSchException, SftpException, IOException {
        JSch jsch = new JSch();
        Properties config=new Properties();
        config.put("StrictHostKeyChecking", "no");
        jsch.addIdentity("path_to_private_key");
        Session session;
        session = jsch.getSession("user", "host", 22);

        session.setConfig(config);
//        session.setPassword("pass");
        session.connect();
        System.out.println("CONNECT !!! ");
        session.disconnect();
    }

.  I have generated keys using this command: ssh-keygen -C "" -m PEM id_rsa
.  past public key in /.ssh/authorized_keys

Any help please?


问:
Test if objRecordSet exists. In Powershell
My script is connecting to a MS Access Database using $objRecordSet / Microsoft.Jet.OLEDB.4.0. And then deleting something with SQL command.
In the end I want to check if the object in the Database was really deleted. And there is my problem.

The code I am using:
`

```<code>$Pathtest="H:\Dokumente\Datenbank\test.csv"
$CsvContant=import-csv -path $Pathtest -Delimiter ";"
$strDB="H:\Dokumente\Datenbank\fdms18.mdb"
$strTable="Services"
$objCon=New-Object -comobject ADODB.Connection
$objRecordSet=New-Object -comobject ADODB.Recordset
$objCon.Open("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = $strDB")

foreach ($item in $CsvContant){

 $ID = $item.ID

$objRecordSet.Open("SELECT * FROM example WHERE exampleID=$ID",$objCon,3,3)
$objRecordSet.delete()

$objRecordSet.close()

$objRecordSet.Open("SELECT * FROM example WHERE exampleID=$ID",$objCon,3,3)

if ($objRecordSet -eq $null){
    write-host("It dont exist")
}

}

$objCon.close()

</code>```

`

And this part don't work
`

```<code>if ($objRecordSet -eq $null){
    write-host("It dont exist")
}
</code>```

`

I hope some powershell genius, know how to solve my problem.
Thanks in advance.

PS: My code runs on powershell x86 because i didnt want to install another framework.

~Luca

Body:
My script is connecting to a MS Access Database using $objRecordSet / Microsoft.Jet.OLEDB.4.0. And then deleting something with SQL command.
In the end I want to check if the object in the Database was really deleted. And there is my problem.

The code I am using:
`

$Pathtest="H:\Dokumente\Datenbank\test.csv"
$CsvContant=import-csv -path $Pathtest -Delimiter ";"
$strDB="H:\Dokumente\Datenbank\fdms18.mdb"
$strTable="Services"
$objCon=New-Object -comobject ADODB.Connection
$objRecordSet=New-Object -comobject ADODB.Recordset
$objCon.Open("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = $strDB")

foreach ($item in $CsvContant){

 $ID = $item.ID

$objRecordSet.Open("SELECT * FROM example WHERE exampleID=$ID",$objCon,3,3)
$objRecordSet.delete()

$objRecordSet.close()

$objRecordSet.Open("SELECT * FROM example WHERE exampleID=$ID",$objCon,3,3)

if ($objRecordSet -eq $null){
    write-host("It dont exist")
}

}

$objCon.close()

`

And this part don't work
`

if ($objRecordSet -eq $null){
    write-host("It dont exist")
}

`

I hope some powershell genius, know how to solve my problem.
Thanks in advance.

PS: My code runs on powershell x86 because i didnt want to install another framework.

~Luca


问:
How to to check the cycles count in time series data using Python
I have a battery voltage data with respect to Datetime, collected data for one month I need to find out the number of cycles of battery hers is my data https://docs.google.com/spreadsheets/d/1K0XspcrpO94mv2wFgW45DzSjAO0Af1uSwmoHHVxDJwI/edit?usp=sharing
since I used peak detection algorithm it is not detecting the cycles correctly is there any way to find the cycles data
here is my code I used

```<code>import numpy as np
op_col = []
for i in df["voltage"]:
 op_col.append(i)
np.set_printoptions(threshold=np.inf)
x = np.array(op_col)
from scipy.signal import find_peaks
peak, _ = find_peaks(x, width=800,prominence=1,height=51)
fig= plt.figure(figsize=(19,8))
plt.plot(x)
plt.xlim(0,45000)
plt.plot(peak, x[peak], "x", color = 'r')
</code>```

here is my out put

how can I do it in another way any suggestions.
thanks in advance

Body:
I have a battery voltage data with respect to Datetime, collected data for one month I need to find out the number of cycles of battery hers is my data https://docs.google.com/spreadsheets/d/1K0XspcrpO94mv2wFgW45DzSjAO0Af1uSwmoHHVxDJwI/edit?usp=sharing
since I used peak detection algorithm it is not detecting the cycles correctly is there any way to find the cycles data
here is my code I used

import numpy as np
op_col = []
for i in df["voltage"]:
 op_col.append(i)
np.set_printoptions(threshold=np.inf)
x = np.array(op_col)
from scipy.signal import find_peaks
peak, _ = find_peaks(x, width=800,prominence=1,height=51)
fig= plt.figure(figsize=(19,8))
plt.plot(x)
plt.xlim(0,45000)
plt.plot(peak, x[peak], "x", color = 'r')

here is my out put

how can I do it in another way any suggestions.
thanks in advance


问:
Optimize the PostgreSQL query
I have a table likes the below.

```<code>id       session_id     start_time                   answer_time
1          111          2022-12-06 13:40:50          2022-12-06 13:40:55
2          111          2022-12-06 13:40:51          Null
3          111          2022-12-06 13:40:57          Null
4          222          2022-12-06 13:40:58          Null
5          222          2022-12-06 13:41:10          Null
6          222          2022-12-06 13:41:10          Null
7          333          2022-12-06 13:46:10         2022-12-06 13:46:15
8          333          2022-12-06 13:46:18         2022-12-06 13:46:20
</code>```

There are three sessions in the table, with session ids 111, 222, and 333; Each session has multiple records, but the session_id is the same; and the session is successful or unsuccessfulis depends on answer_time is Null or not of the smallest id record of that session.

The id 1 and id 4 and id 7 records in the above sample table determine whether a session is successful or unsuccessful.

I have the below SQL to query it, and it works well.

```<code>WITH t AS
(
    SELECT DISTINCT ON (session_id)  start_time, answer_time
    FROM logs
            WHERE ((SELECT NOW() AT TIME ZONE 'UTC') - start_time < interval '24 HOURS')
    ORDER BY logs.session_id, id
)
SELECT
       COUNT(*) FILTER (WHERE (answer_time IS NOT NULL)) AS sccess_count,
       COUNT(*) FILTER (WHERE (answer_time IS NULL)) AS fail_count
FROM t;

</code>```

But if the DB table have about 50M records, the query taken 20 seconds, this is unacceptable in the production environment, how can I optimize it? My goal is less than 1 second for the 50M records.

Edit, the below is the table SQL file:

```<code>/*
 Navicat PostgreSQL Data Transfer

 Source Server         : Test Server
 Source Server Type    : PostgreSQL
 Source Server Version : 140004 (140004)
 Source Host           : localhost:5832
 Source Catalog        : pserver1
 Source Schema         : public

 Target Server Type    : PostgreSQL
 Target Server Version : 140004 (140004)
 File Encoding         : 65001

 Date: 07/12/2022 19:53:07
*/

-- ----------------------------
-- Table structure for logs
-- ----------------------------
DROP TABLE IF EXISTS "public"."logs";
CREATE TABLE "public"."logs" (
  "id" int8 NOT NULL,
  "company_id" int8 NOT NULL,
  "session_id" int8 NOT NULL,
  "start_time" timestamp(6) NOT NULL,
  "answer_time" timestamp(6)
)
;

-- ----------------------------
-- Indexes structure for table logs
-- ----------------------------
CREATE INDEX "calllog_start_time_idx_copy1" ON "public"."logs" USING btree (
  "start_time" "pg_catalog"."timestamp_ops" DESC NULLS FIRST
);
CREATE INDEX "idx_calllog_session_id_copy1" ON "public"."logs" USING btree (
  "session_id" "pg_catalog"."int8_ops" ASC NULLS LAST
);

-- ----------------------------
-- Triggers structure for table logs
-- ----------------------------
CREATE TRIGGER "ts_insert_blocker" BEFORE INSERT ON "public"."logs"
FOR EACH ROW
EXECUTE PROCEDURE "_timescaledb_internal"."insert_blocker"();

-- ----------------------------
-- Primary Key structure for table logs
-- ----------------------------
ALTER TABLE "public"."logs" ADD CONSTRAINT "calllog_copy1_pkey" PRIMARY KEY ("id", "start_time");

</code>```

Title: Optimize the PostgreSQL query

Body:
I have a table likes the below.

id       session_id     start_time                   answer_time
1          111          2022-12-06 13:40:50          2022-12-06 13:40:55
2          111          2022-12-06 13:40:51          Null
3          111          2022-12-06 13:40:57          Null
4          222          2022-12-06 13:40:58          Null
5          222          2022-12-06 13:41:10          Null
6          222          2022-12-06 13:41:10          Null
7          333          2022-12-06 13:46:10         2022-12-06 13:46:15
8          333          2022-12-06 13:46:18         2022-12-06 13:46:20

There are three sessions in the table, with session ids 111, 222, and 333; Each session has multiple records, but the session_id is the same; and the session is successful or unsuccessfulis depends on answer_time is Null or not of the smallest id record of that session.

The id 1 and id 4 and id 7 records in the above sample table determine whether a session is successful or unsuccessful.

I have the below SQL to query it, and it works well.

WITH t AS
(
    SELECT DISTINCT ON (session_id)  start_time, answer_time
    FROM logs
            WHERE ((SELECT NOW() AT TIME ZONE 'UTC') - start_time < interval '24 HOURS')
    ORDER BY logs.session_id, id
)
SELECT
       COUNT(*) FILTER (WHERE (answer_time IS NOT NULL)) AS sccess_count,
       COUNT(*) FILTER (WHERE (answer_time IS NULL)) AS fail_count
FROM t;

But if the DB table have about 50M records, the query taken 20 seconds, this is unacceptable in the production environment, how can I optimize it? My goal is less than 1 second for the 50M records.

Edit, the below is the table SQL file:

/*
 Navicat PostgreSQL Data Transfer

 Source Server         : Test Server
 Source Server Type    : PostgreSQL
 Source Server Version : 140004 (140004)
 Source Host           : localhost:5832
 Source Catalog        : pserver1
 Source Schema         : public

 Target Server Type    : PostgreSQL
 Target Server Version : 140004 (140004)
 File Encoding         : 65001

 Date: 07/12/2022 19:53:07
*/

-- ----------------------------
-- Table structure for logs
-- ----------------------------
DROP TABLE IF EXISTS "public"."logs";
CREATE TABLE "public"."logs" (
  "id" int8 NOT NULL,
  "company_id" int8 NOT NULL,
  "session_id" int8 NOT NULL,
  "start_time" timestamp(6) NOT NULL,
  "answer_time" timestamp(6)
)
;

-- ----------------------------
-- Indexes structure for table logs
-- ----------------------------
CREATE INDEX "calllog_start_time_idx_copy1" ON "public"."logs" USING btree (
  "start_time" "pg_catalog"."timestamp_ops" DESC NULLS FIRST
);
CREATE INDEX "idx_calllog_session_id_copy1" ON "public"."logs" USING btree (
  "session_id" "pg_catalog"."int8_ops" ASC NULLS LAST
);

-- ----------------------------
-- Triggers structure for table logs
-- ----------------------------
CREATE TRIGGER "ts_insert_blocker" BEFORE INSERT ON "public"."logs"
FOR EACH ROW
EXECUTE PROCEDURE "_timescaledb_internal"."insert_blocker"();

-- ----------------------------
-- Primary Key structure for table logs
-- ----------------------------
ALTER TABLE "public"."logs" ADD CONSTRAINT "calllog_copy1_pkey" PRIMARY KEY ("id", "start_time");


问:
EKS Pod folder contents overwritten after mounting EFS volume
We have created a deployment in the EKS cluster. Underlying pods are supposed to have existing content inside a particular directory which was created through the Dockerfile copy command. But when the pod is created an external EFS volume is mounted on the same directory path due to some application requirements. When we login to the pod and check the contents we found that the existing files have been overwritten by the EFS volume contents. We would like to have both the file contents in place once the EFS volume is mounted on the Pod. Please help us to achieve this.</p>


问:
Output Movie in Python cannnot by played
I want to convert a network camera video to grayscale and save it as an another video file.
I wrote the following code, but it does not work well.
However detect.avi is output, I can not play this file.
What is the problem?

```<code>rtsp_path = f"rtsp://{userid}:{pwd}@{ip_address}:{rtsp_port}/ipcam_h264.sdp"
video = cv2.VideoCapture(rtsp_path )
savepath = "detect.avi"
frame_Rate = video.get(cv2.CAP_PROP_FPS)
height, width, dim = frame.shape
rec = cv2.VideoWriter(savepath, cv2.VideoWriter_fourcc(*'DIVX'), frame_Rate, (int(width), int(height)))

while (video.isOpened()):

    ret, frame = video.read()
    if frame is None:
        break

    img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    rec.write(img)

    if cv2.waitKey(30) & 0xFF == ord('q'):
        video.release()
        rec.release()
        cv2.destroyAllWindows()
        break

cv2.destroyAllWindows()
video.release()
rec.release()

</code>```

I got the error message as below:

```<code>OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\videoio\src\cap_images.cpp:267: error: (-215:Assertion failed) number < max_number in function 'cv::icvExtractPattern'
</code>```

I got an error about CISCO OPENH264.
I put  openh264-1.8.0-win64.dll in python directory.
However , I got another errors as below.

```<code>    OpenH264 Video Codec provided by Cisco Systems, Inc.

[libopenh264 @ 000001b9e01c4700] [OpenH264] this = 0x000001B9DA5EC4D0, Error:MaxSpatialBitrate (288000000) should be larger than SpatialBitrate (536870911), considering it as error setting
[libopenh264 @ 000001b9e01c4700] [OpenH264] this = 0x000001B9DA5EC4D0, Error:WelsInitEncoderExt(), ParamValidationExt failed return 16.
[libopenh264 @ 000001b9e01c4700] [OpenH264] this = 0x000001B9DA5EC4D0, Error:CWelsH264SVCEncoder::Initialize(), WelsInitEncoderExt failed.
[libopenh264 @ 000001b9e01c4700] Initialize failed
[ERROR:0@15.734] global /build/opencv/modules/videoio/src/cap_ffmpeg_impl.hpp (2985) open Could not open codec libopenh264, error: Unspecified error (-1313558101)
[ERROR:0@15.734] global /build/opencv/modules/videoio/src/cap_ffmpeg_impl.hpp (3002) open VIDEOIO/FFMPEG: Failed to initialize VideoWriter
[ERROR:0@24.573] global D:\a\opencv-python\opencv-python\opencv\modules\videoio\src\cap.cpp (597) cv::VideoWriter::open VIDEOIO(CV_IMAGES): raised OpenCV exception:

OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\videoio\src\cap_images.cpp:267: error: (-215:Assertion failed) number < max_number in function 'cv::icvExtractPattern'
</code>```

Body:
I want to convert a network camera video to grayscale and save it as an another video file.
I wrote the following code, but it does not work well.
However detect.avi is output, I can not play this file.
What is the problem?

rtsp_path = f"rtsp://{userid}:{pwd}@{ip_address}:{rtsp_port}/ipcam_h264.sdp"
video = cv2.VideoCapture(rtsp_path )
savepath = "detect.avi"
frame_Rate = video.get(cv2.CAP_PROP_FPS)
height, width, dim = frame.shape
rec = cv2.VideoWriter(savepath, cv2.VideoWriter_fourcc(*'DIVX'), frame_Rate, (int(width), int(height)))

while (video.isOpened()):

    ret, frame = video.read()
    if frame is None:
        break

    img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    rec.write(img)

    if cv2.waitKey(30) & 0xFF == ord('q'):
        video.release()
        rec.release()
        cv2.destroyAllWindows()
        break

cv2.destroyAllWindows()
video.release()
rec.release()

I got the error message as below:

OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\videoio\src\cap_images.cpp:267: error: (-215:Assertion failed) number < max_number in function 'cv::icvExtractPattern'

I got an error about CISCO OPENH264.
I put  openh264-1.8.0-win64.dll in python directory.
However , I got another errors as below.

    OpenH264 Video Codec provided by Cisco Systems, Inc.

[libopenh264 @ 000001b9e01c4700] [OpenH264] this = 0x000001B9DA5EC4D0, Error:MaxSpatialBitrate (288000000) should be larger than SpatialBitrate (536870911), considering it as error setting
[libopenh264 @ 000001b9e01c4700] [OpenH264] this = 0x000001B9DA5EC4D0, Error:WelsInitEncoderExt(), ParamValidationExt failed return 16.
[libopenh264 @ 000001b9e01c4700] [OpenH264] this = 0x000001B9DA5EC4D0, Error:CWelsH264SVCEncoder::Initialize(), WelsInitEncoderExt failed.
[libopenh264 @ 000001b9e01c4700] Initialize failed
[ERROR:0@15.734] global /build/opencv/modules/videoio/src/cap_ffmpeg_impl.hpp (2985) open Could not open codec libopenh264, error: Unspecified error (-1313558101)
[ERROR:0@15.734] global /build/opencv/modules/videoio/src/cap_ffmpeg_impl.hpp (3002) open VIDEOIO/FFMPEG: Failed to initialize VideoWriter
[ERROR:0@24.573] global D:\a\opencv-python\opencv-python\opencv\modules\videoio\src\cap.cpp (597) cv::VideoWriter::open VIDEOIO(CV_IMAGES): raised OpenCV exception:

OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\videoio\src\cap_images.cpp:267: error: (-215:Assertion failed) number < max_number in function 'cv::icvExtractPattern'


问:
Do I need to use std::move(...) when returning string result from std::stringstream?
For my implementation of the std-lib the str() implementation for std::stringstream has a str() && version, making it possible to move the string out of the stream without copying it.

My question is, when returning from a function, do you need to specify std::move(...) or is it assumed automatically and can be left out?

Toy example:

#include <sstream>
#include <iostream>

std::string f() {
    auto ss = std::ostringstream{};

    ss << std::string(10000000, '*');

    // return std::move(ss.str()); // Is move() required here?
    // return ss.str() // or does this use the str() && implementation?
    return std::move(ss).str(); // Syntax suggested by ALX23z
}

int main() {
    auto x = f();
    std::cout << x << "\n";
}

```

Edit:
Updated to show that my question does not have to do with SSO.

Edit:
The answers marked as duplicates does not answer the question I am asking with member functions, and if you were to use the answers given in the "duplicate" questions you would get worse performance. (it's now reopened)

Body:
For my implementation of the std-lib the str() implementation for std::stringstream has a str() && version, making it possible to move the string out of the stream without copying it.

My question is, when returning from a function, do you need to specify std::move(...) or is it assumed automatically and can be left out?

Toy example:

#include <sstream>
#include <iostream>

std::string f() {
    auto ss = std::ostringstream{};

    ss << std::string(10000000, '*');

    // return std::move(ss.str()); // Is move() required here?
    // return ss.str() // or does this use the str() && implementation?
    return std::move(ss).str(); // Syntax suggested by ALX23z
}

int main() {
    auto x = f();
    std::cout << x << "\n";
}

Edit:
Updated to show that my question does not have to do with SSO.

Edit:
The answers marked as duplicates does not answer the question I am asking with member functions, and if you were to use the answers given in the "duplicate" questions you would get worse performance. (it's now reopened)


问:
Solving VScode Angular installation issue
```<code>ng : File C:\Users\unknown\AppData\Roaming\npm\ng.ps1 cannot be loaded. The file C:\Users\unknown\AppData\Roaming\npm\ng.ps1 is not digitally signed. You cannot run this script on the current
system. For more information about running scripts and setting execution policy, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ ng
+ ~~
    + CategoryInfo          : SecurityError: (:) [], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess
</code>```

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

//execute the above command and restart the VSCode again, and retry, it should work well

Body:
ng : File C:\Users\unknown\AppData\Roaming\npm\ng.ps1 cannot be loaded. The file C:\Users\unknown\AppData\Roaming\npm\ng.ps1 is not digitally signed. You cannot run this script on the current
system. For more information about running scripts and setting execution policy, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ ng
+ ~~
    + CategoryInfo          : SecurityError: (:) [], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

//execute the above command and restart the VSCode again, and retry, it should work well


问:
can CORS set by client?
I know that CORS will pass by servers, but as I did a ticket for this to my API provider, they said " You can try to set the request header Origin to https://api-swap-rest.bingbon.pro. "

How should I do this in React via AXIOS?

I Tested this but didn't workout :

axios.defaults.headers.common['Access-Control-Allow-Origin'] = "https://api-swap-rest.bingbon.pro"

axios.get(`https://api-swap-rest.bingbon.pro/api/v1/market/getLatestFunding?symbol=BTC-USDT`).then((data) => console.log(data)).catch((err) => console.log(err))
```

Title: can CORS set by client?


问:
Flutter: How to implement a list returned by Future and show the subtotal after refresh?
What's the best way to implement the following scenario using the stacked package?
I have a list of items with price. This list is returned from a future. I also have a datepicker. By changing the date, the list is refreshed with new data. Every time the list gets refreshed, I want to show the subtotal value in the app bar of the page. I tried to wrap the page in the FutureViewModel class and it works to refresh the list. But I am not sure how to update the subtotal. Should subtotal have a separate modelview? I think the subtotal should be calculated where the list of items exists. I am not sure how to implement this.


问:
Multinominal logistic regression in R from a 2x2 table
Sorry, a bit new to all this.

I want to do logistic regression in R with multiple dependent variables. However, all I have access to are the 2x2 tables as follows:

How do I plug these into a glm model?

Dataset is as follows:

```<code>        Disease
        No  Yes
Var1 No 41  21
    Yes 65  42

Var2 No 55  26
    Yes 66  46

Var3 No 99  50
    Yes 22  22
</code>```

Would I have to de-aggregate or reverse-summarise the dataset and revert the data set back to a non-count observation state? Not sure how to go about this though.

I really appreciate any help you can provide. Thanks!

Body:
Sorry, a bit new to all this.

I want to do logistic regression in R with multiple dependent variables. However, all I have access to are the 2x2 tables as follows:

How do I plug these into a glm model?

Dataset is as follows:

        Disease
        No  Yes
Var1 No 41  21
    Yes 65  42

Var2 No 55  26
    Yes 66  46

Var3 No 99  50
    Yes 22  22

Would I have to de-aggregate or reverse-summarise the dataset and revert the data set back to a non-count observation state? Not sure how to go about this though.

I really appreciate any help you can provide. Thanks!


问:
boost regex symbol reference error on g++ 8.3
I'm trying to use boost::regex_search in my application. Compiling with g++ 8.3 version gives me a symbol referencing error as below

```<code>boost::re_detail_106600::perl_matcher<__gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<boost::sub_match<__gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::construct_init(boost::basic_regex<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > > const&, boost::regex_constants::_match_flags)
</code>```
```<code>std::string url = "A4B3CD";
boost::regex exp("4");
boost::smatch match;
if (boost::regex_search(url, match, exp))
</code>```

P.S :: When the same is compiled with g++ 8.5 it works fine.
Machine details : Red Hat Enterprise Linux release 8.6

Body:
I'm trying to use boost::regex_search in my application. Compiling with g++ 8.3 version gives me a symbol referencing error as below

boost::re_detail_106600::perl_matcher<__gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<boost::sub_match<__gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::construct_init(boost::basic_regex<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > > const&, boost::regex_constants::_match_flags)

std::string url = "A4B3CD";
boost::regex exp("4");
boost::smatch match;
if (boost::regex_search(url, match, exp))

P.S :: When the same is compiled with g++ 8.5 it works fine.
Machine details : Red Hat Enterprise Linux release 8.6


问:
How to disable animation of marker rotation using animarker package
I am using flutter_animarker: ^3.4.0-beta.1 package.

my code:

```<code>void newLocationUpdate(LocationObj obj) {
    var marker = RippleMarker(
        markerId: markerId,
        position: obj.latlng,
        ripple: false,
        alpha: 1,
        rotation: obj.rotat,
        icon: sourceIcon,
        anchor: const Offset(0.5, 0.5),
        onTap: () {
          // print('Tapped! $obj');
        });
    setState(() => markers[markerId] = marker);
  }
</code>```

widget using:

```<code>Animarker(
          curve: Curves.linear,
          useRotation: true,
          rippleRadius: 0.5,
          angleThreshold: 1.5,
          duration: duration,
          runExpressAfter: 1,
          rippleDuration: const Duration(seconds: 2),
          mapId: controller.future.then<int>((value) => value.mapId),
          markers: markers.values.toSet(),
          child: GoogleMap(
              polylines: {
                Polyline(
                    width: 2,
                    polylineId: const PolylineId('HTPolyline'),
                    points: locArr.map((element) => element.latlng).toList(),
                    color: const Color.fromARGB(179, 62, 191, 208)),
              },
              mapType: MapType.normal,
              initialCameraPosition: startPosition,
              onMapCreated: (gController) {
                getPositionsHistory().then((latlng) {
                  if (latlng.latitude > 0) {
                    gController.animateCamera(CameraUpdate.newCameraPosition(
                        CameraPosition(target: latlng, zoom: 14.5)));
                  }
                  stream.forEach((value) => newLocationUpdate(value));
                  controller.complete(gController);
                });
              }),
        )
</code>```

In this image you can see the 360 degree animated rotation.

I tried the useRotation to false and also custom bearing functions but now I just want to disable the animation when marker is rotating.

Body:
I am using flutter_animarker: ^3.4.0-beta.1 package.

my code:

void newLocationUpdate(LocationObj obj) {
    var marker = RippleMarker(
        markerId: markerId,
        position: obj.latlng,
        ripple: false,
        alpha: 1,
        rotation: obj.rotat,
        icon: sourceIcon,
        anchor: const Offset(0.5, 0.5),
        onTap: () {
          // print('Tapped! $obj');
        });
    setState(() => markers[markerId] = marker);
  }

widget using:

Animarker(
          curve: Curves.linear,
          useRotation: true,
          rippleRadius: 0.5,
          angleThreshold: 1.5,
          duration: duration,
          runExpressAfter: 1,
          rippleDuration: const Duration(seconds: 2),
          mapId: controller.future.then<int>((value) => value.mapId),
          markers: markers.values.toSet(),
          child: GoogleMap(
              polylines: {
                Polyline(
                    width: 2,
                    polylineId: const PolylineId('HTPolyline'),
                    points: locArr.map((element) => element.latlng).toList(),
                    color: const Color.fromARGB(179, 62, 191, 208)),
              },
              mapType: MapType.normal,
              initialCameraPosition: startPosition,
              onMapCreated: (gController) {
                getPositionsHistory().then((latlng) {
                  if (latlng.latitude > 0) {
                    gController.animateCamera(CameraUpdate.newCameraPosition(
                        CameraPosition(target: latlng, zoom: 14.5)));
                  }
                  stream.forEach((value) => newLocationUpdate(value));
                  controller.complete(gController);
                });
              }),
        )

In this image you can see the 360 degree animated rotation.

I tried the useRotation to false and also custom bearing functions but now I just want to disable the animation when marker is rotating.


问:
How can I get headers of the URL from chrome-php
I am using chrome-php
I want to get the header from the response
Is there any way I can get it?
Here is how I am trying to implement the functionality ...

```<code>$browserFactory = new BrowserFactory('chromium-browser');

// starts headless chrome
$browser = $browserFactory->createBrowser([
    'noSandbox' => true,
    'debugLogger' => 'php://stdout',
]);

try {

    $page = $browser->createPage();
    $page->navigate($url)->waitForNavigation();

    info([$page->getHtml()]);

finally {
    $browser->close();
}
</code>```

Body:
I am using chrome-php
I want to get the header from the response
Is there any way I can get it?
Here is how I am trying to implement the functionality ...

$browserFactory = new BrowserFactory('chromium-browser');

// starts headless chrome
$browser = $browserFactory->createBrowser([
    'noSandbox' => true,
    'debugLogger' => 'php://stdout',
]);

try {

    $page = $browser->createPage();
    $page->navigate($url)->waitForNavigation();

    info([$page->getHtml()]);

finally {
    $browser->close();
}


问:
Flutter Textfield cursor focus moves to another textfield when new widget appears with provider watch
Video

As shown in video, with provider watch, textfield cursor focus moves to the upper textfield when new Text widgets appear above the textfields.

This doesn't happen when Text widget appears below the textfield widgets.

Replacing if (testPvd.showA) with Visibility widget does prevent the cursor from moving, however I still don't understand this happening.

Can anyone explain why this happens?

```<code>import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class TestWidget extends StatefulWidget {
  const TestWidget({Key? key}) : super(key: key);

  @override
  State<TestWidget> createState() => _TestWidgetState();
}

class _TestWidgetState extends State<TestWidget> {
  var controller1 = TextEditingController();
  var controller2 = TextEditingController();
  var controller3 = TextEditingController();
  var controller4 = TextEditingController();

  @override
  Widget build(BuildContext context) {
    TestProvider testPvd = context.watch<TestProvider>();

    return Scaffold(
      body: ListView(
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        padding: EdgeInsets.symmetric(vertical: 50, horizontal: 20),
        children: [
          Row(
            children: [
              InkWell(
                child: Text('showA'),
                onTap: () {
                  testPvd.updateToggleButton('A');
                },
              ),
              SizedBox(width: 20),
              InkWell(
                child: Text('showB'),
                onTap: () {
                  testPvd.updateToggleButton('B');
                },
              ),
            ],
          ),
          SizedBox(height: 20),
          if (testPvd.showA) Text('A'),
          if (testPvd.showB) Text('B'),
          SizedBox(height: 20),
          TextField(controller: controller1),
          TextField(controller: controller2),
          TextField(controller: controller3),
          TextField(controller: controller4),
          // if (testPvd.showA) Text('A'),
          // if (testPvd.showB) Text('B'),
        ],
      ),
    );
  }
}

class TestProvider with ChangeNotifier {
  bool showA = false;
  bool showB = false;

  updateToggleButton(String value) {
    if (value == 'A') showA = !showA;
    if (value == 'B') showB = !showB;

    notifyListeners();
  }
}

</code>```

Expected the cursor to stay on current textfield.

Body:
Video

As shown in video, with provider watch, textfield cursor focus moves to the upper textfield when new Text widgets appear above the textfields.

This doesn't happen when Text widget appears below the textfield widgets.

Replacing if (testPvd.showA) with Visibility widget does prevent the cursor from moving, however I still don't understand this happening.

Can anyone explain why this happens?

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class TestWidget extends StatefulWidget {
  const TestWidget({Key? key}) : super(key: key);

  @override
  State<TestWidget> createState() => _TestWidgetState();
}

class _TestWidgetState extends State<TestWidget> {
  var controller1 = TextEditingController();
  var controller2 = TextEditingController();
  var controller3 = TextEditingController();
  var controller4 = TextEditingController();

  @override
  Widget build(BuildContext context) {
    TestProvider testPvd = context.watch<TestProvider>();

    return Scaffold(
      body: ListView(
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        padding: EdgeInsets.symmetric(vertical: 50, horizontal: 20),
        children: [
          Row(
            children: [
              InkWell(
                child: Text('showA'),
                onTap: () {
                  testPvd.updateToggleButton('A');
                },
              ),
              SizedBox(width: 20),
              InkWell(
                child: Text('showB'),
                onTap: () {
                  testPvd.updateToggleButton('B');
                },
              ),
            ],
          ),
          SizedBox(height: 20),
          if (testPvd.showA) Text('A'),
          if (testPvd.showB) Text('B'),
          SizedBox(height: 20),
          TextField(controller: controller1),
          TextField(controller: controller2),
          TextField(controller: controller3),
          TextField(controller: controller4),
          // if (testPvd.showA) Text('A'),
          // if (testPvd.showB) Text('B'),
        ],
      ),
    );
  }
}

class TestProvider with ChangeNotifier {
  bool showA = false;
  bool showB = false;

  updateToggleButton(String value) {
    if (value == 'A') showA = !showA;
    if (value == 'B') showB = !showB;

    notifyListeners();
  }
}

Expected the cursor to stay on current textfield.