问:
execution of same code in nodeJS gives different output from browser, can one explain
Executing this piece of code is different in the browser to the nodeJs.

```<code>let abc = (() => {
  function xyz() {
    this.man = "XYZ"
  }
  xyz();
  this.man = "ABC";
})()
console.log(man);
</code>```

The answer expected is XYZ as produced in node but found ABC in the browser.

答:
First, a couple points:

You should not write code like this that depends upon some implicit value of this that is inherited from the environment.  If you mean to access the global object, then write code that explicitly references the global object.

If you run this code in strict mode which was designed to prevent common programming mistakes and problems, this code will not run.  It will throw an exception.  This is a further hint that you shouldn't be writing code like this.

This code depends upon two defaults for the value of this.

First, it depends upon the top level value of this.  In a browser that will be the window object.  In a nodejs module, that will be the module.exports object for the current module.

Second, it depends upon what the value of this will be in your function call xyz().  In sloppy mode in the browser, that will be window.  In sloppy mode in nodejs, that will be the global object.  So, this.man = "XYZ" is setting a property on the global object.  In strict mode, the value of this inside the xyz() function will be undefined.

Third, your assignment of this.man = "ABC" depends upon what the lexical value of this at the point of definition of your top level arrow function.  In the browser, that will also be window.  In nodejs, that will be module.exports.

So, in a browser, your xyz() function sets window.man to "XYZ", then it sets window.man to "ABC".

In nodejs, your xyz() function sets global.man to "XYZ" and then your arrow function sets module.exports.man to "ABC".

Lastly, run this in strict mode by inserting:

```<code>"use strict";
</code>```

As the first line of code in the file and you will get an error:

```<code>TypeError: Cannot set properties of undefined (setting 'man')
</code>```

because this inside of the xyz() function will be undefined (as it should be) and trying to set a property on undefined is a TypeError.  You set properties on objects.

It is a great idea to run all your code in strict mode.  More and more features in the language are automatically run in strict mode such as class methods because it's just better to run your code in strict mode.  It doesn't prevent you from doing anything that there isn't a better way to do.  It just prevents you from doing things (often accidentally) that you shouldn't be doing.

For a good illustration in nodejs, run this:

```<code>let abc = (() => {
    function xyz() {
        this.man = "XYZ";    // sets global.man
    }
    xyz();
    this.man = "ABC";        // sets module.exports.man
})()
console.log(this == module.exports);
console.log(module.exports.man);
console.log(global.man)
</code>```

You will get this output:

```<code>true
ABC
XYZ
</code>```

One other point here is that when you call a function such as xyz(), the value of this inside the execution of xyz() is determined by how the function is called.  You can see an explanation of the various ways a function can be called here and how that affects the value of this inside the function.

Calling it as just a plain function xyz() in sloppy mode will set the value of this inside that function to the global object.  Calling it as a plain function in strict mode will set the value of this inside that function to undefined.

Body:
Executing this piece of code is different in the browser to the nodeJs.

let abc = (() => {
  function xyz() {
    this.man = "XYZ"
  }
  xyz();
  this.man = "ABC";
})()
console.log(man);

The answer expected is XYZ as produced in node but found ABC in the browser.

Body:
First, a couple points:

You should not write code like this that depends upon some implicit value of this that is inherited from the environment.  If you mean to access the global object, then write code that explicitly references the global object.

If you run this code in strict mode which was designed to prevent common programming mistakes and problems, this code will not run.  It will throw an exception.  This is a further hint that you shouldn't be writing code like this.

This code depends upon two defaults for the value of this.

First, it depends upon the top level value of this.  In a browser that will be the window object.  In a nodejs module, that will be the module.exports object for the current module.

Second, it depends upon what the value of this will be in your function call xyz().  In sloppy mode in the browser, that will be window.  In sloppy mode in nodejs, that will be the global object.  So, this.man = "XYZ" is setting a property on the global object.  In strict mode, the value of this inside the xyz() function will be undefined.

Third, your assignment of this.man = "ABC" depends upon what the lexical value of this at the point of definition of your top level arrow function.  In the browser, that will also be window.  In nodejs, that will be module.exports.

So, in a browser, your xyz() function sets window.man to "XYZ", then it sets window.man to "ABC".

In nodejs, your xyz() function sets global.man to "XYZ" and then your arrow function sets module.exports.man to "ABC".

Lastly, run this in strict mode by inserting:

"use strict";

As the first line of code in the file and you will get an error:

TypeError: Cannot set properties of undefined (setting 'man')

because this inside of the xyz() function will be undefined (as it should be) and trying to set a property on undefined is a TypeError.  You set properties on objects.

It is a great idea to run all your code in strict mode.  More and more features in the language are automatically run in strict mode such as class methods because it's just better to run your code in strict mode.  It doesn't prevent you from doing anything that there isn't a better way to do.  It just prevents you from doing things (often accidentally) that you shouldn't be doing.

For a good illustration in nodejs, run this:

let abc = (() => {
    function xyz() {
        this.man = "XYZ";    // sets global.man
    }
    xyz();
    this.man = "ABC";        // sets module.exports.man
})()
console.log(this == module.exports);
console.log(module.exports.man);
console.log(global.man)

You will get this output:

true
ABC
XYZ

One other point here is that when you call a function such as xyz(), the value of this inside the execution of xyz() is determined by how the function is called.  You can see an explanation of the various ways a function can be called here and how that affects the value of this inside the function.

Calling it as just a plain function xyz() in sloppy mode will set the value of this inside that function to the global object.  Calling it as a plain function in strict mode will set the value of this inside that function to undefined.


来源: stackexchange

问:
Decompressing a file like 7zip with Java
I need to open a compresed file (zml, i don't couldn't find information about that extension) like 7zip does it with java.

I have a zml file, if I open it with 7zip it asks me for the password, then I put the password and can open the file.

I need to do the same with java, could anyone give me an advice for this?

Best regards.

Juan

答:
Below function will extract your 7zip file and return the list of files which are extracted.</p>
```<code>public static List<String> unSevenZipFile(String zipFilePath, String unzipDestination, String attachmentPassword) {

    List<String> extractedFilesList=new ArrayList<String>();

    // Get 7zip file
    try (SevenZFile sevenZFile = new SevenZFile(new File(zipFilePath),attachmentPassword.toCharArray())) {

        SevenZArchiveEntry entry;
        while ((entry = sevenZFile.getNextEntry()) != null) {

            File file = new File(unzipDestination+ entry.getName());
            System.out.println("Un seven zipping - " + file);
            byte[] content = new byte[(int) entry.getSize()];
            sevenZFile.read(content);
            Files.write(file.toPath(), content);
            extractedFilesList.add(unzipDestination+ entry.getName());

        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return extractedFilesList;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Below function will extract your 7zip file and return the list of files which are extracted.

public static List<String> unSevenZipFile(String zipFilePath, String unzipDestination, String attachmentPassword) {

    List<String> extractedFilesList=new ArrayList<String>();

    // Get 7zip file
    try (SevenZFile sevenZFile = new SevenZFile(new File(zipFilePath),attachmentPassword.toCharArray())) {

        SevenZArchiveEntry entry;
        while ((entry = sevenZFile.getNextEntry()) != null) {

            File file = new File(unzipDestination+ entry.getName());
            System.out.println("Un seven zipping - " + file);
            byte[] content = new byte[(int) entry.getSize()];
            sevenZFile.read(content);
            Files.write(file.toPath(), content);
            extractedFilesList.add(unzipDestination+ entry.getName());

        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return extractedFilesList;
}

ContentLicense: CC BY-SA 4.0


问:
Uncaught TypeError: navigate.push is not a function
i tried to build my webapp but i have a little problem the reason is because the verson the instructor is old verson but i updated to the latest verson i have this problem.

What I am trying to do is generate clicks into the post. But I can't click on it. When I open it, this error is what I'm getting.

```<code>Home.js:23 Uncaught TypeError: navigate.push is not a function
    at onClick (Home.js:23:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
    at invokeGuardedCallback (react-dom.development.js:4056:1)
    at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:4070:1)
    at executeDispatch (react-dom.development.js:8243:1)
    at processDispatchQueueItemsInOrder (react-dom.development.js:8275:1)
    at processDispatchQueue (react-dom.development.js:8288:1)
    at dispatchEventsForPlugins (react-dom.development.js:8299:1)
    at react-dom.development.js:8508:1
</code>```

this is the code

```<code>    import React from "react";
import axios from "axios";
import { useEffect, useState } from "react";
import { useNavigate } from 'react-router-dom';

function Home() {
  const [listOfPosts, setListOfPosts] = useState([]);
  const navigate = useNavigate();

  useEffect(() => {
    axios.get("https://my-project-ienpf.run-us-west2.goorm.io/posts").then((response) => {
      setListOfPosts(response.data);
    });
  }, []);

  return (
    <div>
      {listOfPosts.map((value, key) => {
        return (
          <div
            className="post"
            onClick={() => {
              navigate.push(`/post/${value.id}`);
            }}
          >
            <div className="title"> {value.title} </div>
            <div className="body">{value.postText}</div>
            <div className="footer">{value.username}</div>
          </div>
        );
      })}
    </div>
  );
}

export default Home;
</code>```

I hope you can help me

答:
You can change

```<code>navigate.push(`/post/${value.id}`);
</code>```

to

```<code>navigate(`/post/${value.id}`);
</code>```

Body:
i tried to build my webapp but i have a little problem the reason is because the verson the instructor is old verson but i updated to the latest verson i have this problem.

What I am trying to do is generate clicks into the post. But I can't click on it. When I open it, this error is what I'm getting.

Home.js:23 Uncaught TypeError: navigate.push is not a function
    at onClick (Home.js:23:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
    at invokeGuardedCallback (react-dom.development.js:4056:1)
    at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:4070:1)
    at executeDispatch (react-dom.development.js:8243:1)
    at processDispatchQueueItemsInOrder (react-dom.development.js:8275:1)
    at processDispatchQueue (react-dom.development.js:8288:1)
    at dispatchEventsForPlugins (react-dom.development.js:8299:1)
    at react-dom.development.js:8508:1

this is the code

    import React from "react";
import axios from "axios";
import { useEffect, useState } from "react";
import { useNavigate } from 'react-router-dom';

function Home() {
  const [listOfPosts, setListOfPosts] = useState([]);
  const navigate = useNavigate();

  useEffect(() => {
    axios.get("https://my-project-ienpf.run-us-west2.goorm.io/posts").then((response) => {
      setListOfPosts(response.data);
    });
  }, []);

  return (

      {listOfPosts.map((value, key) => {
        return (

 {
              navigate.push(`/post/${value.id}`);
            }}
          >

 {value.title}

{value.postText}

{value.username}

        );
      })}

  );
}

export default Home;

I hope you can help me

Body:
You can change

navigate.push(`/post/${value.id}`);

to

navigate(`/post/${value.id}`);


问:
Merge objects in mutable list on Scala
I have recently started looking at Scala code and I am trying to understand how to go about a problem.

I have a mutable list of objects, these objects have an id: String and values: List[Int]. The way I get the data, more than one object can have the same id. I am trying to merge the items in the list, so if for example, I have 3 objects with id 123 and whichever values, I end up with just one object with the id, and the values of the 3 combined.

I could do this the java way, iterating, and so on, but I was wondering if there is an easier Scala-specific way of going about this?

答:
The first thing to do is avoid using mutable data and think about transforming one immutable object into another. So rather than mutating the contents of one collection, think about creating a new collection from the old one.

Once you have done that it is actually very straightforward because this is the sort of thing that is directly supported by the Scala library.

```<code>case class Data(id: String, values: List[Int])

val list: List[Data] = ???

val result: Map[String, List[Int]] =
   list.groupMapReduce(_.id)(_.values)(_ ++ _)
</code>```

The groupMapReduce call breaks down into three parts:

The first part groups the data by the id field and makes that the key. This gives a Map[String, List[Data]]

The second part extracts the values field and makes that the data, so the result is now Map[String, List[List[Int]]]

The third part combines all the values fields into a single list, giving the final result Map[String, List[Int]]

Title: Merge objects in mutable list on Scala

Body:
The first thing to do is avoid using mutable data and think about transforming one immutable object into another. So rather than mutating the contents of one collection, think about creating a new collection from the old one.

Once you have done that it is actually very straightforward because this is the sort of thing that is directly supported by the Scala library.

case class Data(id: String, values: List[Int])

val list: List[Data] = ???

val result: Map[String, List[Int]] =
   list.groupMapReduce(_.id)(_.values)(_ ++ _)

The groupMapReduce call breaks down into three parts:

The first part groups the data by the id field and makes that the key. This gives a Map[String, List[Data]]

The second part extracts the values field and makes that the data, so the result is now Map[String, List[List[Int]]]

The third part combines all the values fields into a single list, giving the final result Map[String, List[Int]]


问:
Splitting large text file into smaller text files by line numbers using Python
I have a text file say really_big_file.txt that contains:

```<code>line 1
line 2
line 3
line 4
...
line 99999
line 100000
</code>```

I would like to write a Python script that divides really_big_file.txt into smaller files with 300 lines each. For example, small_file_300.txt to have lines 1-300, small_file_600 to have lines 301-600, and so on until there are enough small files made to contain all the lines from the big file.

I would appreciate any suggestions on the easiest way to accomplish this using Python

答:
```<code>with open('/really_big_file.txt') as infile:
    file_line_limit = 300
    counter = -1
    file_index = 0
    outfile = None
    for line in infile.readlines():
        counter += 1
        if counter % file_line_limit == 0:
            # close old file
            if outfile is not None:
                outfile.close()
            # create new file
            file_index += 1
            outfile = open('small_file_%03d.txt' % file_index, 'w')
        # write to file
        outfile.write(line)
</code>```

Body:
I have a text file say really_big_file.txt that contains:

line 1
line 2
line 3
line 4
...
line 99999
line 100000

I would like to write a Python script that divides really_big_file.txt into smaller files with 300 lines each. For example, small_file_300.txt to have lines 1-300, small_file_600 to have lines 301-600, and so on until there are enough small files made to contain all the lines from the big file.

I would appreciate any suggestions on the easiest way to accomplish this using Python


问:
How to ensure that the messages will be enqueued in chronological order on multithreaded Asio io_service?
Following Michael Caisse's cppcon talk I created a connection handler MyUserConnection which has a sendMessage method. sendMessage method adds a message to the queue similarly to the send() in the cppcon talk. My sendMessage method is called from multiple threads outside of the connection handler in high intervals. The messages must be enqueued chronologically.

When I run my code with only one Asio io_service::run call (aka one io_service thread) it async_write's and empties my queue as expected (FIFO), however, the problem occurs when there are, for example, 4 io_service::run calls, then the queue is not filled or the send calls are not called chronologically.

class MyUserConnection : public std::enable_shared_from_this<MyUserConnection> {
public:
  MyUserConnection(asio::io_service& io_service, SslSocket socket) :
      service_(io_service),
      socket_(std::move(socket)),
      strand_(io_service) {
  }

  void sendMessage(std::string msg) {
    auto self(shared_from_this());
    service_.post(strand_.wrap([self, msg]() {
      self->queueMessage(msg);
    }));
  }

private:
  void queueMessage(const std::string& msg) {
    bool writeInProgress = !sendPacketQueue_.empty();
    sendPacketQueue_.push_back(msg);
    if (!writeInProgress) {
      startPacketSend();
    }
  }

  void startPacketSend() {
    auto self(shared_from_this());
    asio::async_write(socket_,
                      asio::buffer(sendPacketQueue_.front().data(), sendPacketQueue_.front().length()),
                      strand_.wrap([self](const std::error_code& ec, std::size_t /*n*/) {
                        self->packetSendDone(ec);
                      }));
  }

  void packetSendDone(const std::error_code& ec) {
    if (!ec) {
      sendPacketQueue_.pop_front();
      if (!sendPacketQueue_.empty()) { startPacketSend(); }
    } else {
      // end(); // My end call
    }
  }

  asio::io_service& service_;
  SslSocket socket_;
  asio::io_service::strand strand_;
  std::deque<std::string> sendPacketQueue_;
};
```

I'm quite sure that I misinterpreted the strand and io_service::post when running the connection handler on multithreaded io_service. I'm also quite sure that the messages are not enqueued chronologically instead of messages not being async_write chronologically. How to ensure that the messages will be enqueued in chronological order in sendMessage call on multithreaded io_service?

答:
On a multi core or even on a single core preemptive OS, you cannot truly feed messages into a queue in strictly chronological order. Even if you use a mutex to synchronize write access to the queue, the strict order is no longer guaranteed once multiple writers wait on the mutex and the mutex becomes free. At best, the order, in which the waiting write threads acquire the mutex, is implementation dependent (OS code dependent), but it is best to assume it is just random.

With that being said, the strict chronological order is a matter of definition in the first place. To explain that, imagine your PC has some digital output bits (1 for each writer thread) and you connected a logic analyzer to those bits.... and imagine, you pick some spot in the code, where you toggle such a respective bit in your enqueue function. Even if that bit toggle takes place just one assembly instruction prior to acquiring the mutex, it is possible, that the order had been changed, while the writer code approached that point. You could also set it to other arbirtrary points prior (e.g. when you enter the enqueue function). But then, the same reasoning applies. Hence, the strict chronological order is in itself a matter of definition.

There is an analogy to a case, where a CPUs interrupt controller has multiple inputs and you tried to build a system which processes those interrupts in strictly chronological order. Even if all interrupt inputs were signaled exactly at the same moment (a switch, pulling them all to signaled state simultaneously), some order would occur (e.g. caused by hardware logic or just by noise at the input pins or by the systems interrupt dispatcher function (some CPUs (e.g. MIPS 4102)  have a single interrupt vector and assembly code checks the possible interrupt sources and dispatches to dedicated interrupt handlers).

This analogy helps see the pattern: It comes down to asynchronous inputs on a synchronous system. Which is a notoriously hard problem in itself.

So, the best you could possibly do, is to make a suitable definition of your applications "strict ordering" and live with it.

Then, to avoid violations of your definition, you could use a priority queue instead of a normal FIFO data type and use as priority some atomic counter:

At your chosen point in the code, atomically read and increment the counter.
This is your messages sequence number.

Assemble your message and enqueue it into the priority queue, using your sequence number as priority.

Another possible approach is to define a notion of "simultaneous", which is detectable on the other side of the queue (and thus, the reader cannot assume strict ordering for a set of "simultaneous" messages). This could be implemented by reading some high frequency tick count and all those messages, which have the same "time stamp" are to be considered simultaneous on reader side.

Body:
Following Michael Caisse's cppcon talk I created a connection handler MyUserConnection which has a sendMessage method. sendMessage method adds a message to the queue similarly to the send() in the cppcon talk. My sendMessage method is called from multiple threads outside of the connection handler in high intervals. The messages must be enqueued chronologically.

When I run my code with only one Asio io_service::run call (aka one io_service thread) it async_write's and empties my queue as expected (FIFO), however, the problem occurs when there are, for example, 4 io_service::run calls, then the queue is not filled or the send calls are not called chronologically.

class MyUserConnection : public std::enable_shared_from_this<MyUserConnection> {
public:
  MyUserConnection(asio::io_service& io_service, SslSocket socket) :
      service_(io_service),
      socket_(std::move(socket)),
      strand_(io_service) {
  }

  void sendMessage(std::string msg) {
    auto self(shared_from_this());
    service_.post(strand_.wrap([self, msg]() {
      self->queueMessage(msg);
    }));
  }

private:
  void queueMessage(const std::string& msg) {
    bool writeInProgress = !sendPacketQueue_.empty();
    sendPacketQueue_.push_back(msg);
    if (!writeInProgress) {
      startPacketSend();
    }
  }

  void startPacketSend() {
    auto self(shared_from_this());
    asio::async_write(socket_,
                      asio::buffer(sendPacketQueue_.front().data(), sendPacketQueue_.front().length()),
                      strand_.wrap([self](const std::error_code& ec, std::size_t /*n*/) {
                        self->packetSendDone(ec);
                      }));
  }

  void packetSendDone(const std::error_code& ec) {
    if (!ec) {
      sendPacketQueue_.pop_front();
      if (!sendPacketQueue_.empty()) { startPacketSend(); }
    } else {
      // end(); // My end call
    }
  }

  asio::io_service& service_;
  SslSocket socket_;
  asio::io_service::strand strand_;
  std::deque<std::string> sendPacketQueue_;
};

I'm quite sure that I misinterpreted the strand and io_service::post when running the connection handler on multithreaded io_service. I'm also quite sure that the messages are not enqueued chronologically instead of messages not being async_write chronologically. How to ensure that the messages will be enqueued in chronological order in sendMessage call on multithreaded io_service?


问:
how to set focus on jquery confirm dialog
i have a simple jquery confirm dialog and wants to set focus on dialog itself rather on any other element. code below is what i did to set focus on:

```<code>function showAlert() {

                $("#dialog-confirm").dialog({
                    title: 'Main Information',
                    resizable: false,
                    height:140,
                    modal: true,
                    closeOnEscape:true,
                    buttons: {
                        "Yes": function() {
                            document.getElementById('form1:newProfile' ).value="true";
                            if(disableSaveFlag) return false; else disableEnableSaveBtn('true');
                               $( this ).dialog( "close" );
                        },
                        "No": function() {
                            document.getElementById('form1:newProfile' ).value="false";
                            if(disableSaveFlag) return false; else disableEnableSaveBtn('true');
                            $( this ).dialog( "close" );
                        }
                    }
                });
                 $("#dialog-confirm").focus(); // this line sets focus on div element with given id
            }

<div id="dialog-confirm" style="display:none">
    <p><span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span>
        Do you want to create a new profile ?
    </p>
</div>
</code>```

problem is i cannot find "Id" of a dialog itself to being focus on to it.
As a result focus is set on Div element and my title is not focused.

below is what i get with above code:

答:
I guess we can focus anything on below event. I just tried and working fine for me..

```<code>onContentReady: function () {
    //select the element you want to focus here
    $(".btn-success").focus();
}
</code>```

So my full code looks like this. In this case I am focusing the Button on my dialog.

```<code>$.confirm({
    icon: "fas fa-check-square",
    title: " Completed!",
    content: "Action Plans Updated Successfully!",
    type: "green",
    typeAnimated: true
    buttons: {
    Complete: {
      text: "Complete",
      btnClass: "btn-success",
      action: function () {
        location.reload(true);
      },
    },
  },
  onContentReady: function () {
      $(".btn-success").focus();
  },
});
</code>```

Body:
i have a simple jquery confirm dialog and wants to set focus on dialog itself rather on any other element. code below is what i did to set focus on:

function showAlert() {

                $("#dialog-confirm").dialog({
                    title: 'Main Information',
                    resizable: false,
                    height:140,
                    modal: true,
                    closeOnEscape:true,
                    buttons: {
                        "Yes": function() {
                            document.getElementById('form1:newProfile' ).value="true";
                            if(disableSaveFlag) return false; else disableEnableSaveBtn('true');
                               $( this ).dialog( "close" );
                        },
                        "No": function() {
                            document.getElementById('form1:newProfile' ).value="false";
                            if(disableSaveFlag) return false; else disableEnableSaveBtn('true');
                            $( this ).dialog( "close" );
                        }
                    }
                });
                 $("#dialog-confirm").focus(); // this line sets focus on div element with given id
            }

        Do you want to create a new profile ?

problem is i cannot find "Id" of a dialog itself to being focus on to it.
As a result focus is set on Div element and my title is not focused.

below is what i get with above code:

Body:
I guess we can focus anything on below event. I just tried and working fine for me..

onContentReady: function () {
    //select the element you want to focus here
    $(".btn-success").focus();
}

So my full code looks like this. In this case I am focusing the Button on my dialog.

$.confirm({
    icon: "fas fa-check-square",
    title: "&nbsp;Completed!",
    content: "Action Plans Updated Successfully!",
    type: "green",
    typeAnimated: true
    buttons: {
    Complete: {
      text: "Complete",
      btnClass: "btn-success",
      action: function () {
        location.reload(true);
      },
    },
  },
  onContentReady: function () {
      $(".btn-success").focus();
  },
});


问:
How I add new 'Show answer' button to display the correct answer to the question?
How I add new 'Show answer' button to display the correct answer to the question? The answer isn't visible when the question is retrieved but is only displayed when the 'Show answer' button is pressed. I need to make only one fetch request / question and I can display the answer using conditional rendering, for example.</p>
```<code>const Trivia = () => {
    const [question, setQuestion] = React.useState();

    const fetchQuestion = () => {
        fetch("https://opentdb.com/api.php?amount=1")
        .then((response) => response.json())
        .then((data) => {
            setQuestion(data.results[0].question);
        });
    };

    React.useEffect(() => {
        fetchQuestion();
    }, []);

    return(
        <div>
            <p>{question}</p>
            <button onClick={fetchQuestion}>New Question</button>
        </div>
    );
};
</code>```

答:
You can store the answer along with the question and add a state to check if the answer is to be displayed.
The answer will be shown when the user clicks Show answer and will be hidden when a new question is loaded.

```<code>  const Trivia = () => {
  const [question, setQuestion] = React.useState(null);
  const [showAnswer, setShowAnswer] = React.useState(false);

  const fetchQuestion = () => {
    fetch("https://opentdb.com/api.php?amount=1")
      .then((response) => response.json())
      .then((data) => {
        console.log(data);
        setShowAnswer(false);
        setQuestion({
          question: data.results[0].question,
          answer: data.results[0].correct_answer
        });
      });
  };

  React.useEffect(() => {
    fetchQuestion();
  }, []);

  return (
    <div>
      {question && (
        <>
          <p> {question.question}</p>
          {showAnswer && <p>{question.answer}</p>}
          <button onClick={fetchQuestion}>New Question</button>
          <button onClick={() => setShowAnswer(true)}>Show Answer</button>
        </>
      )}
    </div>
  );
};
</code>```

View on codesandbox

Body:
How I add new 'Show answer' button to display the correct answer to the question? The answer isn't visible when the question is retrieved but is only displayed when the 'Show answer' button is pressed. I need to make only one fetch request / question and I can display the answer using conditional rendering, for example.

const Trivia = () => {
    const [question, setQuestion] = React.useState();

    const fetchQuestion = () => {
        fetch("https://opentdb.com/api.php?amount=1")
        .then((response) => response.json())
        .then((data) => {
            setQuestion(data.results[0].question);
        });
    };

    React.useEffect(() => {
        fetchQuestion();
    }, []);

    return(

{question}

            <button onClick={fetchQuestion}>New Question</button>

    );
};

Body:
You can store the answer along with the question and add a state to check if the answer is to be displayed.
The answer will be shown when the user clicks Show answer and will be hidden when a new question is loaded.

  const Trivia = () => {
  const [question, setQuestion] = React.useState(null);
  const [showAnswer, setShowAnswer] = React.useState(false);

  const fetchQuestion = () => {
    fetch("https://opentdb.com/api.php?amount=1")
      .then((response) => response.json())
      .then((data) => {
        console.log(data);
        setShowAnswer(false);
        setQuestion({
          question: data.results[0].question,
          answer: data.results[0].correct_answer
        });
      });
  };

  React.useEffect(() => {
    fetchQuestion();
  }, []);

  return (
    <div>
      {question && (
        <>
          <p> {question.question}</p>
          {showAnswer && <p>{question.answer}</p>}
          <button onClick={fetchQuestion}>New Question</button>
          <button onClick={() => setShowAnswer(true)}>Show Answer</button>
        </>
      )}
    </div>
  );
};

View on codesandbox


问:
Annotate one (or more) values in a typescript string literal union as deprecated
I know it's possible to annotate entire properties as deprecated, but is it possible to annotated one (or more) single values within a string union as deprecated?

For example, given this type declaration:

```<code>export type BoxProps = HTMLAttributes<HTMLDivElement> & {
  /**
   * @deprecated rounded has no effect and will be removed in a future version
   */
  rounded?: boolean;
  variant?:
    | 'neutral'
    | 'grey'
    | 'success'
    | 'warning';
  thickBorder?: boolean;
};
</code>```

...my IDE (VS Code) will warn me that the rounded param is deprecated and will show it as visually "crossed out".

But If I try to annotate one single value of the variant string literal union type, my IDE will suggest all possible options with no warnings or visual treatments indicating that any string is deprecated:

```<code>TypeScript
export type BoxProps = HTMLAttributes<HTMLDivElement> & {
  /**
   * @deprecated rounded has no effect and will be removed in a future version
   */
  rounded?: boolean;
  variant?:
    | 'neutral'
    /** @deprecated */
    | 'grey'
    | 'success'
    | 'warning';
  thickBorder?: boolean;

// or

TypeScript
export type BoxProps = HTMLAttributes<HTMLDivElement> & {
  /**
   * @deprecated rounded has no effect and will be removed in a future version
   */
  rounded?: boolean;
  variant?:
    | 'neutral'
    | 'grey' /** @deprecated */
    | 'success'
    | 'warning';
  thickBorder?: boolean;
};

// or

TypeScript
export type BoxProps = HTMLAttributes<HTMLDivElement> & {
  /**
   * @deprecated rounded has no effect and will be removed in a future version
   */
  rounded?: boolean;
  variant?:
    | 'neutral'
    | /** @deprecated */ 'grey'
    | 'success'
    | 'warning';
  thickBorder?: boolean;
};
</code>```

Is this just not possible? Or is there some other syntax that needs to be used to annotate single strings as deprecated? (Or am I missing a VS Code plugin?)

答:
I don't think this is possible with TSDoc in Visual Studio Code. I've tried it in my IDE (Visual Studio Code), with no success.

However, there is a GitHub Issue about the same issue with a function parameter instead. Even though it isn't with union types, it might help a little. Just click here!

Body:
I know it's possible to annotate entire properties as deprecated, but is it possible to annotated one (or more) single values within a string union as deprecated?

For example, given this type declaration:

export type BoxProps = HTMLAttributes<HTMLDivElement> & {
  /**
   * @deprecated rounded has no effect and will be removed in a future version
   */
  rounded?: boolean;
  variant?:
    | 'neutral'
    | 'grey'
    | 'success'
    | 'warning';
  thickBorder?: boolean;
};

...my IDE (VS Code) will warn me that the rounded param is deprecated and will show it as visually "crossed out".

But If I try to annotate one single value of the variant string literal union type, my IDE will suggest all possible options with no warnings or visual treatments indicating that any string is deprecated:

TypeScript
export type BoxProps = HTMLAttributes<HTMLDivElement> & {
  /**
   * @deprecated rounded has no effect and will be removed in a future version
   */
  rounded?: boolean;
  variant?:
    | 'neutral'
    /** @deprecated */
    | 'grey'
    | 'success'
    | 'warning';
  thickBorder?: boolean;

// or

TypeScript
export type BoxProps = HTMLAttributes<HTMLDivElement> & {
  /**
   * @deprecated rounded has no effect and will be removed in a future version
   */
  rounded?: boolean;
  variant?:
    | 'neutral'
    | 'grey' /** @deprecated */
    | 'success'
    | 'warning';
  thickBorder?: boolean;
};

// or

TypeScript
export type BoxProps = HTMLAttributes<HTMLDivElement> & {
  /**
   * @deprecated rounded has no effect and will be removed in a future version
   */
  rounded?: boolean;
  variant?:
    | 'neutral'
    | /** @deprecated */ 'grey'
    | 'success'
    | 'warning';
  thickBorder?: boolean;
};

Is this just not possible? Or is there some other syntax that needs to be used to annotate single strings as deprecated? (Or am I missing a VS Code plugin?)


问:
Handle NaN values in mean pandas
I calculated the average of the values contained in a column within my df as follows:

```<code>meanBpm = df['tempo'].mean()
</code>```

the average is calculated for different days of the week and for some days the value I expect is returned, while for other days it returns NaN. This is because it is possible that the bpm (the tempo column) for a certain day is not there because for example I have not listened to any songs. I would like to replace these NaNs in ouput with a default value which could be 0 or -1

EDIT: i solved it, thanks a lot everyone for the replies

答:
what your'e looking for is -</p>
```<code>df['tempo'].fillna(0).mean()
</code>```

Title: Handle NaN values in mean pandas

Body:
I calculated the average of the values contained in a column within my df as follows:

meanBpm = df['tempo'].mean()

the average is calculated for different days of the week and for some days the value I expect is returned, while for other days it returns NaN. This is because it is possible that the bpm (the tempo column) for a certain day is not there because for example I have not listened to any songs. I would like to replace these NaNs in ouput with a default value which could be 0 or -1

EDIT: i solved it, thanks a lot everyone for the replies

Body:
what your'e looking for is -

df['tempo'].fillna(0).mean()


问:
How to make my cpp code smaller and look more sustainable?
Hello guys currently I am kinda between entry and medium level on C++. I made 2 class which they include carModel,carBrand,carAge and carPrice. I defined both A and B classes. I also used void function to design a basic menu. I got the data option as using switch case. Here is my question how can I make them smaller I mean less code lines.

If anybody can't see my codes here the code lines:

```<code>#include <iostream>
#include <string>
#include <algorithm>
#include <stdlib.h>
#include <time.h>
#include <list>
#include <ctype.h>
using std::string;
using std::endl;
using std::cout;
using std::cin;

void carMenu() {

    cout << " ---    WELCOME TO CAR MENU --- " << endl;
    cout << "---   Choose car model A or Choose car model B  --- " << endl;

};

class A {
public:
    string carModelA;
    string carBrandA;
    double carPriceA;
    int carAgeA;

};

class B {
public:
    string carModelB;
    string carBrandB;
    double carPriceB;
    int carAgeB;

};

int main()
{
    carMenu();
    char option;
    cout << "Please Enter an option " << endl;
    cin >> option;
    A carA;
    B carB;
    carA.carModelA = "Sedan";
    carA.carBrandA = "Ford";
    carA.carPriceA = 25500;
    carA.carAgeA = 5;

    carB.carModelB = "Hatchback";
    carB.carBrandB = "Toyota";
    carB.carPriceB = 15500;
    carB.carAgeB = 2;

    switch (option) {
    case 'A':
        cout << "Car model A is " << carA.carModelA << endl;
        cout << "Car Brand A is " << carA.carBrandA << endl;
        cout << "Car model A is " << carA.carPriceA << endl;
        cout << "Car model A is " << carA.carAgeA << endl;
        break;
    case'B':
        cout << "Car model B is " << carB.carModelB << endl;
        cout << "Car Brand B is " << carB.carBrandB << endl;
        cout << "Car model B is " << carB.carPriceB << endl;
        cout << "Car model B is " << carB.carAgeB << endl;
        break;
    default:
        cout << "You did not choose a option :" << endl;
    }

    return 0;
};
</code>```

答:
For a start, A and B are structurally the same, so you may as well have just one of them, and have multiple instances of that single class. As you only have public data, you can use the keyword struct, which declares a class with public as the default access.

Similarly, rather than having two variables, carA and carB, you could have a collection of Car instances.

Similarly you can write a function that displays a Car, rather than repeating the cout << "Car attribute id is " << data << endl.

```<code>struct Car {
    std::string model;
    std::string brand;
    double price;
    int age;
};

void printMenu() {
    std::cout << " ---    WELCOME TO CAR MENU --- " << std::endl;
    std::cout << "---   Choose car model A or Choose car model B  --- " << std::endl;
}

void printCar(const Car & car, char id) {
    std::cout << "Car model " << id << " is " << car.model << std::endl;
    std::cout << "Car Brand " << id << " is " << car.brand << std::endl;
    // these probably want to say price and age, not model again
    std::cout << "Car model " << id << " is " << car.price << std::endl;
    std::cout << "Car model " << id << " is " << car.age << std::endl;
}

std::map<char, Car> cars = {
    { 'A', { "Sedan", "Ford", 25500, 5 } },
    { 'B', { "Hatchback", "Toyota", 15500, 2 } },
};

int main() {
    printMenu();
    char option;
    std::cout << "Please Enter an option " << std::endl;
    std::cin >> option;
    if (auto it = cars.find(option); it != cars.end()) {
        printCar(it->second, it->first);
    } else {
        std::cout << "You did not choose a option :" << std::endl;
    }
}
</code>```

https://godbolt.org/z/9oqKK384b

Body:
Hello guys currently I am kinda between entry and medium level on C++. I made 2 class which they include carModel,carBrand,carAge and carPrice. I defined both A and B classes. I also used void function to design a basic menu. I got the data option as using switch case. Here is my question how can I make them smaller I mean less code lines.

If anybody can't see my codes here the code lines:

#include <iostream>
#include <string>
#include <algorithm>
#include <stdlib.h>
#include <time.h>
#include <list>
#include <ctype.h>
using std::string;
using std::endl;
using std::cout;
using std::cin;

void carMenu() {

    cout << " ---    WELCOME TO CAR MENU --- " << endl;
    cout << "---   Choose car model A or Choose car model B  --- " << endl;

};

class A {
public:
    string carModelA;
    string carBrandA;
    double carPriceA;
    int carAgeA;

};

class B {
public:
    string carModelB;
    string carBrandB;
    double carPriceB;
    int carAgeB;

};

int main()
{
    carMenu();
    char option;
    cout << "Please Enter an option " << endl;
    cin >> option;
    A carA;
    B carB;
    carA.carModelA = "Sedan";
    carA.carBrandA = "Ford";
    carA.carPriceA = 25500;
    carA.carAgeA = 5;

    carB.carModelB = "Hatchback";
    carB.carBrandB = "Toyota";
    carB.carPriceB = 15500;
    carB.carAgeB = 2;

    switch (option) {
    case 'A':
        cout << "Car model A is " << carA.carModelA << endl;
        cout << "Car Brand A is " << carA.carBrandA << endl;
        cout << "Car model A is " << carA.carPriceA << endl;
        cout << "Car model A is " << carA.carAgeA << endl;
        break;
    case'B':
        cout << "Car model B is " << carB.carModelB << endl;
        cout << "Car Brand B is " << carB.carBrandB << endl;
        cout << "Car model B is " << carB.carPriceB << endl;
        cout << "Car model B is " << carB.carAgeB << endl;
        break;
    default:
        cout << "You did not choose a option :" << endl;
    }

    return 0;
};

Body:
For a start, A and B are structurally the same, so you may as well have just one of them, and have multiple instances of that single class. As you only have public data, you can use the keyword struct, which declares a class with public as the default access.

Similarly, rather than having two variables, carA and carB, you could have a collection of Car instances.

Similarly you can write a function that displays a Car, rather than repeating the cout << "Car attribute id is " << data << endl.

struct Car {
    std::string model;
    std::string brand;
    double price;
    int age;
};

void printMenu() {
    std::cout << " ---    WELCOME TO CAR MENU --- " << std::endl;
    std::cout << "---   Choose car model A or Choose car model B  --- " << std::endl;
}

void printCar(const Car & car, char id) {
    std::cout << "Car model " << id << " is " << car.model << std::endl;
    std::cout << "Car Brand " << id << " is " << car.brand << std::endl;
    // these probably want to say price and age, not model again
    std::cout << "Car model " << id << " is " << car.price << std::endl;
    std::cout << "Car model " << id << " is " << car.age << std::endl;
}

std::map<char, Car> cars = {
    { 'A', { "Sedan", "Ford", 25500, 5 } },
    { 'B', { "Hatchback", "Toyota", 15500, 2 } },
};

int main() {
    printMenu();
    char option;
    std::cout << "Please Enter an option " << std::endl;
    std::cin >> option;
    if (auto it = cars.find(option); it != cars.end()) {
        printCar(it->second, it->first);
    } else {
        std::cout << "You did not choose a option :" << std::endl;
    }
}

https://godbolt.org/z/9oqKK384b


问:
How to compare two dataframes and find the combination for which there is value in first dataframe but not in second
I have two pandas dataframes with same columns say name, jan, feb, march, april. I want to compare the two dataframes and find out the name, month combination for which I have value in my first dataframe but not in my second dataframe.

df1:

Name
jan
feb
March

ABC
125
225
NaN

DEF
NaN
30
214

df2:

Name
jan
feb
March

ABC
125
NaN
NaN

XYZ
254
130
NaN

Expected output:

Name
Month

ABC
feb

Def
feb

Def
March

I tried to merge the two dataframes, but it is not giving me the expected result. I'm not sure how to proceed with this.

答:
Here is a possible approach:

```<code># only if not already index
# df1 = df1.set_index('Name')
# df2 = df2.set_index('Name')

s = ((df1.notna()&df1.ne(df2.reindex_like(df1)))
     .rename_axis('Month', axis=1).stack())
s[s].reset_index().drop(0, axis=1)
</code>```

output:

```<code>   Name  Month
0  ABC     feb
1  DEF     feb
2  DEF   March
</code>```

Body:
Here is a possible approach:

# only if not already index
# df1 = df1.set_index('Name')
# df2 = df2.set_index('Name')

s = ((df1.notna()&df1.ne(df2.reindex_like(df1)))
     .rename_axis('Month', axis=1).stack())
s[s].reset_index().drop(0, axis=1)

output:

   Name  Month
0  ABC     feb
1  DEF     feb
2  DEF   March


问:
How to debug swift code on Android Studio for KMM?
I can't set up breakpoints in Android Studio on my Swift code. I thought the KMM plugin allowed for this. Is there any way to achieve this?

How can I debug my iOS UI + shared business logic in iOS?

答: You could use https://github.com/touchlab/xcode-kotlin to debug shared code in Xcode</p>


问:
Blazor ProtectedSessionStorage doesn't work
I try to implement ProtectedSessionStorage in some Blazor components (.NetCore 6, Blazor Server).

I followed too this thread: Blazor ProtectedSessionStorage object NULL, but when I try to set session data the code stop and immediately exit from his scope.

This is my code:

SessionService.cs

```<code>using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
...

    public class SessionService
    {
        private ProtectedSessionStorage _sessionStorage;

        public SessionService(ProtectedSessionStorage storage)
        {
            _sessionStorage = storage;
        }

        public async Task<User> GetUserProperty()
        {
            var value = await _sessionStorage.GetAsync<User>("user");
            return value.Value;
        }

        public async Task SetUserProperty(User value)
        {
            await _sessionStorage.SetAsync("user", value);
        }
    }
</code>```

Startup.cs

```<code>public void ConfigureServices(IServiceCollection services)
{
    ...
    //registering the service
    services.addScoped<SessionService>();
    ...
}
</code>```

MyComponent.razor

```<code>@code
{
   [Inject] public SessionService SessionService { get; set; } = default!;

   protected override async void OnInitialized()
   {
       InitUser();
       LoadInterface();
   }

   protected async Task InitUser()
   {
      ...
      try
      {
          User user = new User("id", "location");
          //after this row, code exit from this scope
          await SessionService.SetUserProperty(user);

          //this part of code aren't read
          if(..)
          {
             //some other check
          }
          ...
      }
      catch(Exception ex)
      {
          //No exceptions caught
      }

   }
{
</code>```

What I Wrong?

Update:

I forgot async on onInitialized method and now code don't stop and don't exit from his scope. But unfortunately I receive this error on browser console.

```<code>blazor.server.js:1

       [2022-02-09T17:11:25.128Z] Error: System.InvalidOperationException: Each parameter in the deserialization constructor on type 'MyProject.Models.Shared.User' must bind to an object property or field on deserialization. Each parameter name must match with a property or field on the object. The match can be case-insensitive.
   at System.Text.Json.ThrowHelper.ThrowInvalidOperationException_ConstructorParameterIncompleteBinding(Type parentType)
   at System.Text.Json.Serialization.Converters.ObjectWithParameterizedConstructorConverter`1.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
   at System.Text.Json.Serialization.JsonConverter`1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
   at System.Text.Json.Serialization.JsonConverter`1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
   at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan`1 utf8Json, JsonTypeInfo jsonTypeInfo, Nullable`1 actualByteCount)
   at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan`1 json, JsonTypeInfo jsonTypeInfo)
   at System.Text.Json.JsonSerializer.Deserialize[TValue](String json, JsonSerializerOptions options)
   at Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage.ProtectedBrowserStorage.Unprotect[TValue](String purpose, String protectedJson)
   at Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage.ProtectedBrowserStorage.GetAsync[TValue](String purpose, String key)
   at MyProject.Services.Dashboard.SessionService.GetUserProperty() in C:\Source\MyProject\Services\Dashboard\SessionService.cs:line 18
   at MyProject.Shared.DashHeaderMenu.OnInitialized() in C:\Source\MyProject\Shared\DashHeaderMenu.razor:line 128
   at System.Threading.Tasks.Task.<>c.<ThrowAsync>b__127_0(Object state)
   at Microsoft.AspNetCore.Components.Rendering.RendererSynchronizationContext.ExecuteSynchronously(TaskCompletionSource`1 completion, SendOrPostCallback d, Object state)
   at Microsoft.AspNetCore.Components.Rendering.RendererSynchronizationContext.<>c.<.cctor>b__23_0(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at Microsoft.AspNetCore.Components.Rendering.RendererSynchronizationContext.ExecuteBackground(WorkItem item)
</code>```

答:
Solved!

When you try to insert an object, like a custom class (in my case is User), you need add an empty constructor for serialize and put into the Protected Session Storage.

```<code>public class User
{
   public string name;
   public string surname;
   public int id;
   .....

   //required for serialization
   public User(){}

   //others constructor used
   public User(string name, string surname, ...)
   {
       ...
   }
}
</code>```

So, for solve all my problems I inserted async to OnInitialized() and add a empty constructor to User class

Body:
I try to implement ProtectedSessionStorage in some Blazor components (.NetCore 6, Blazor Server).

I followed too this thread: Blazor ProtectedSessionStorage object NULL, but when I try to set session data the code stop and immediately exit from his scope.

This is my code:

SessionService.cs

using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
...

    public class SessionService
    {
        private ProtectedSessionStorage _sessionStorage;

        public SessionService(ProtectedSessionStorage storage)
        {
            _sessionStorage = storage;
        }

        public async Task<User> GetUserProperty()
        {
            var value = await _sessionStorage.GetAsync<User>("user");
            return value.Value;
        }

        public async Task SetUserProperty(User value)
        {
            await _sessionStorage.SetAsync("user", value);
        }
    }

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    ...
    //registering the service
    services.addScoped<SessionService>();
    ...
}

MyComponent.razor

@code
{
   [Inject] public SessionService SessionService { get; set; } = default!;

   protected override async void OnInitialized()
   {
       InitUser();
       LoadInterface();
   }

   protected async Task InitUser()
   {
      ...
      try
      {
          User user = new User("id", "location");
          //after this row, code exit from this scope
          await SessionService.SetUserProperty(user);

          //this part of code aren't read
          if(..)
          {
             //some other check
          }
          ...
      }
      catch(Exception ex)
      {
          //No exceptions caught
      }

   }
{

What I Wrong?

Update:

I forgot async on onInitialized method and now code don't stop and don't exit from his scope. But unfortunately I receive this error on browser console.

blazor.server.js:1

       [2022-02-09T17:11:25.128Z] Error: System.InvalidOperationException: Each parameter in the deserialization constructor on type 'MyProject.Models.Shared.User' must bind to an object property or field on deserialization. Each parameter name must match with a property or field on the object. The match can be case-insensitive.
   at System.Text.Json.ThrowHelper.ThrowInvalidOperationException_ConstructorParameterIncompleteBinding(Type parentType)
   at System.Text.Json.Serialization.Converters.ObjectWithParameterizedConstructorConverter`1.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
   at System.Text.Json.Serialization.JsonConverter`1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
   at System.Text.Json.Serialization.JsonConverter`1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
   at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan`1 utf8Json, JsonTypeInfo jsonTypeInfo, Nullable`1 actualByteCount)
   at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan`1 json, JsonTypeInfo jsonTypeInfo)
   at System.Text.Json.JsonSerializer.Deserialize[TValue](String json, JsonSerializerOptions options)
   at Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage.ProtectedBrowserStorage.Unprotect[TValue](String purpose, String protectedJson)
   at Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage.ProtectedBrowserStorage.GetAsync[TValue](String purpose, String key)
   at MyProject.Services.Dashboard.SessionService.GetUserProperty() in C:\Source\MyProject\Services\Dashboard\SessionService.cs:line 18
   at MyProject.Shared.DashHeaderMenu.OnInitialized() in C:\Source\MyProject\Shared\DashHeaderMenu.razor:line 128
   at System.Threading.Tasks.Task.<>c.<ThrowAsync>b__127_0(Object state)
   at Microsoft.AspNetCore.Components.Rendering.RendererSynchronizationContext.ExecuteSynchronously(TaskCompletionSource`1 completion, SendOrPostCallback d, Object state)
   at Microsoft.AspNetCore.Components.Rendering.RendererSynchronizationContext.<>c.<.cctor>b__23_0(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at Microsoft.AspNetCore.Components.Rendering.RendererSynchronizationContext.ExecuteBackground(WorkItem item)

Body:
Solved!

When you try to insert an object, like a custom class (in my case is User), you need add an empty constructor for serialize and put into the Protected Session Storage.

public class User
{
   public string name;
   public string surname;
   public int id;
   .....

   //required for serialization
   public User(){}

   //others constructor used
   public User(string name, string surname, ...)
   {
       ...
   }
}

So, for solve all my problems I inserted async to OnInitialized() and add a empty constructor to User class


问:
Fast Data load from RDBMS to Ignite Cache
I have a user interface which internally connects to a RDBMS. From the UI, a user can select any number of tables or the user can write a select query to get a result set and load it into an Apache Ignite cache. Can you please suggest with sample examples or API which loads the data into cache in table format.</p>

答: You need to use the Data Streamer API. As for how long it will take: it depends on the size of your cluster, the performance of your network, the size of the records, etc. Ignite scales horizontally, so it'll be able to load it as fast as you can send it with a big enough cluster.</p>


问:
Visual Studio Code debug python file stopped working
Visual Studio Code debug Python file stopped working
I have been using visual studio code for years, and for no apparent reason debug stopped working.  It worked yesterday, but not today.  Here is what I do:

Double click a simple "Hello World" .py file.  It opens with visual studio code

Press arrow on the left side for run and debug

Select “Python File”.  Nothing happens

Similarly, if I select the pulldown menu on the right and “debug Python file” nothing happens

But if I select the pulldown menu on the right and “run Python file”, the program runs: a terminal opens, and hello world is printed.

How do I get debug to work (again)?

I tried reboot and reinstall.

Below is the version I am using
Version: 1.64.0 (user setup)
Commit: 5554b12acf27056905806867f251c859323ff7e9
Date: 2022-02-03T04:22:20.678Z
Electron: 13.5.2
Chromium: 91.0.4472.164
Node.js: 14.16.0
V8: 9.1.269.39-electron.0
OS: Windows_NT x64 10.0.19043

I am running on Window 10

答:
Start Anaconda Prompt and then type:

```<code>conda update --all
</code>```

Python debugging will work after update to conda version > 4.9

Another option is to install previous version of python extension for VSC 2021.12
Both solutions does not requires reinstallation of VSC.

You can read more about this issue on:https://github.com/microsoft/vscode-python/issues/18436

Body:
Start Anaconda Prompt and then type:

conda update --all

Python debugging will work after update to conda version > 4.9

Another option is to install previous version of python extension for VSC 2021.12
Both solutions does not requires reinstallation of VSC.

You can read more about this issue on:https://github.com/microsoft/vscode-python/issues/18436


问:
Subtraction of numbers double and long
In my JAVA program there is code like this:

```<code>int f_part = (int) ((f_num - num) * 100);
</code>```

f_num is double and num is long. I just want to take the fractional part out and assign it to f_part. But some times f_part value is one less than it's value. Which means if f_num = 123.55 and num = 123, But f_part equals to 54. And it happens only f_num and num is greater than 100. I don't know why this happening. Please can someone explain why this happens and way to correct it.

答:
From The Floating-Point Guide:

internally, computers use a format (binary floating-point) that cannot
  accurately represent a number like 0.1, 0.2 or 0.3 at all.

When the code is compiled or interpreted, your “0.1” is already
  rounded to the nearest number in that format, which results in a small
  rounding error even before the calculation happens.

It looks like you're calculating money values. double is a completely inappropriate format for this. Use BigDecimal instead.

Title: Subtraction of numbers double and long

Body:
In my JAVA program there is code like this:

int f_part = (int) ((f_num - num) * 100);

f_num is double and num is long. I just want to take the fractional part out and assign it to f_part. But some times f_part value is one less than it's value. Which means if f_num = 123.55 and num = 123, But f_part equals to 54. And it happens only f_num and num is greater than 100. I don't know why this happening. Please can someone explain why this happens and way to correct it.


问:
Express, run code on a seperate thread on server
My Issue

I have a form where when the user submits, I want the server to start a separate  thread and run a function in that thread, then redirect the user back to the main page, where the connection can be closed and the code will still run.

Essentially the goal is that the user clicks a button, the form submits and the server runs the code without the user having to stay on the page.

```<code>app.get('/lockout/', async (req, res) => {
var nnumber = req.query.nnumber;
var time = req.query.time;

for (var i = 0; i < time; i++) {
    console.log(nnumber + " is locked out");
    sleep(1000);
}

res.send("Locked out");
});
</code>```

Notes

Please excuse my inexperience with Node and express, I am new to this so please explain thoroughly, my main languages are C# and C++. I am running an Ubuntu VPS with nginx reverse proxy on DigitalOcean.

答:
What you want to do is called "Asynchronus task processing" and needs some more things to it.

I would use bull as a framework to work with your Queue based on Redis. This will let you store a form submit request in a queue and process it in a new process and the user can close the connection after submitting the form.

In NodeJs it could look like

npm install bull --save
```
<pre class="lang-js prettyprint-override"><code>const Queue = require('bull');
//....

export class FormQueue{
  constructor(){
    // initialize queue
    this.queue = new Queue('formSubmits');
    // add a worker
    this.queue.process('forms', job => {
      this.sendEmail(job)
    })
  }
  addFormToQueue(data){
    this.queue.add('forms', data)
  }
  async sendEmail(job){
    const { to, from, subject, text, html} = job.data;
    const msg = {
      to,
      from,
      subject,
      text,
      html
    };
    try {
      await sgMail.send(msg)
      // mark the task as complete.
      job.moveToCompleted('done', true)
    } catch (error) {
      if (error.response) {
        job.moveToFailed({message: 'job failed'})
      }
    }
  }
}
</code>```

Credits / More Information: https://blog.logrocket.com/asynchronous-task-processing-in-node-js-with-bull/

Body:
My Issue

I have a form where when the user submits, I want the server to start a separate  thread and run a function in that thread, then redirect the user back to the main page, where the connection can be closed and the code will still run.

Essentially the goal is that the user clicks a button, the form submits and the server runs the code without the user having to stay on the page.

app.get('/lockout/', async (req, res) => {
var nnumber = req.query.nnumber;
var time = req.query.time;

for (var i = 0; i < time; i++) {
    console.log(nnumber + " is locked out");
    sleep(1000);
}

res.send("Locked out");
});

Notes

Please excuse my inexperience with Node and express, I am new to this so please explain thoroughly, my main languages are C# and C++. I am running an Ubuntu VPS with nginx reverse proxy on DigitalOcean.

Body:
What you want to do is called "Asynchronus task processing" and needs some more things to it.

I would use bull as a framework to work with your Queue based on Redis. This will let you store a form submit request in a queue and process it in a new process and the user can close the connection after submitting the form.

In NodeJs it could look like

npm install bull --save

const Queue = require('bull');
//....

export class FormQueue{
  constructor(){
    // initialize queue
    this.queue = new Queue('formSubmits');
    // add a worker
    this.queue.process('forms', job => {
      this.sendEmail(job)
    })
  }
  addFormToQueue(data){
    this.queue.add('forms', data)
  }
  async sendEmail(job){
    const { to, from, subject, text, html} = job.data;
    const msg = {
      to,
      from,
      subject,
      text,
      html
    };
    try {
      await sgMail.send(msg)
      // mark the task as complete.
      job.moveToCompleted('done', true)
    } catch (error) {
      if (error.response) {
        job.moveToFailed({message: 'job failed'})
      }
    }
  }
}

Credits / More Information: https://blog.logrocket.com/asynchronous-task-processing-in-node-js-with-bull/


问:
Live() function not working with some elements
I'm trying to bind some change events to a select element which has been previously been transformed by jqTransform (http://www.dfc-e.com/metiers/multimedia/opensource/jqtransform/).

As change() function does not work after this transformation, I've followed this excellent advice from Code-Pal. Then I'm trying to apply a click function with the live() event (as future forms will be called with Ajax).

So far I've got this, which does not work:

```<code>$("div#caracteristicas-form-wrap div.jqTransformSelectWrapper ul li a").live('click', function(e) {
console.log("Testing");
});
</code>```

Strangely, this DOES work:

```<code>$("div#caracteristicas-form-wrap div.jqTransformSelectWrapper ul li a").bind('click', function(e) {
console.log("Testing");
});
</code>```

And even this:

```<code>$("div#caracteristicas-form-wrap div.jqTransformSelectWrapper").live('click', function(e) {
console.log("Testing");
});
</code>```

So it's not that jqTransform is still not loaded. For some reason, live() stops working as soon as I'm selecting elements from a list. Any idea of what could be happening?

This is the html code after the jqtransform:

```<code><div class="jqTransformSelectWrapper" style="z-index: 10; width: 194px;">
  <div>
    <span style="width: 179px;">Tarjeta estándar</span>
    <a class="jqTransformSelectOpen" href="#"></a>
  </div>
  <ul style="width: 192px; display: none; visibility: visible; height: 125px; overflow: hidden;">
    <li>
      <a class="selected" index="0" href="#">Tarjeta estándar</a>
    </li>
    <li>
      <a index="1" href="#">Tarjetas cantos redondos</a>
    </li>
    <li>
      <a index="2" href="#">Tarjetas doble</a>
    </li>
    <li>
      <a index="3" href="#">Tarjeta PVC</a>
    </li>
    <li>
      <a index="4" href="#">Tarjeta adhesiva</a>
    </li>
  </ul>

  <select id="id-subproducto" class="jqTransformHidden" name="subproducto" style="">
    <option value="1">Tarjeta estándar</option>
    <option value="2">Tarjetas cantos redondos</option>
    <option value="3">Tarjetas doble</option>
    <option value="4">Tarjeta PVC</option>
    <option value="5">Tarjeta adhesiva</option>
  </select>
</div>
</code>```

Thanks in advance!

答:
I dont have exactly the same selectors but it all seems to be working:

http://jsfiddle.net/HenryGarle/DeYH2/1/

```<code>$("div#caracteristicas-form-wrap div.jqTransformSelectWrapper ul li a").live('click', function(e) {
   alert("Testing");
});
</code>```

Edit: Updated to use the same selectors

Body:
I'm trying to bind some change events to a select element which has been previously been transformed by jqTransform (http://www.dfc-e.com/metiers/multimedia/opensource/jqtransform/).

As change() function does not work after this transformation, I've followed this excellent advice from Code-Pal. Then I'm trying to apply a click function with the live() event (as future forms will be called with Ajax).

So far I've got this, which does not work:

$("div#caracteristicas-form-wrap div.jqTransformSelectWrapper ul li a").live('click', function(e) {
console.log("Testing");
});

Strangely, this DOES work:

$("div#caracteristicas-form-wrap div.jqTransformSelectWrapper ul li a").bind('click', function(e) {
console.log("Testing");
});

And even this:

$("div#caracteristicas-form-wrap div.jqTransformSelectWrapper").live('click', function(e) {
console.log("Testing");
});

So it's not that jqTransform is still not loaded. For some reason, live() stops working as soon as I'm selecting elements from a list. Any idea of what could be happening?

This is the html code after the jqtransform:

    Tarjeta estándar

      Tarjeta estándar

      Tarjetas cantos redondos

      Tarjetas doble

      Tarjeta PVC

      Tarjeta adhesiva

  <select id="id-subproducto" class="jqTransformHidden" name="subproducto" style="">
    <option value="1">Tarjeta estándar</option>
    <option value="2">Tarjetas cantos redondos</option>
    <option value="3">Tarjetas doble</option>
    <option value="4">Tarjeta PVC</option>
    <option value="5">Tarjeta adhesiva</option>
  </select>

Thanks in advance!

Body:
I dont have exactly the same selectors but it all seems to be working:

http://jsfiddle.net/HenryGarle/DeYH2/1/

$("div#caracteristicas-form-wrap div.jqTransformSelectWrapper ul li a").live('click', function(e) {
   alert("Testing");
});

Edit: Updated to use the same selectors


问:
How can I integrate in html pages 2 different CSS styles for 2 diferent images?
Can anyone help me?

How can I integrate in html pages 2 different CSS styles for 2 diferent images, both being separated vertically by a space?

See the paintings below. They have different sizes, different styles.

答:
Something like this. You may change the dimensions anytime</p>
```<code>.img, .firstImage, .secondImage {
    border: 1px dotted blue;
    width: 200px;
}

.firstImage {
    float:left;
    border: 1px solid #ddd;
    border-radius: 4px;
    padding: 5px;
    width: 150px;
}

.secondImage {
    float:right;
    border: 2px solid #fff;
    border-radius: 2px;
    padding: 3px;
    width: 120px;
}
</code>```

Body:
Something like this. You may change the dimensions anytime

.img, .firstImage, .secondImage {
    border: 1px dotted blue;
    width: 200px;
}

.firstImage {
    float:left;
    border: 1px solid #ddd;
    border-radius: 4px;
    padding: 5px;
    width: 150px;
}

.secondImage {
    float:right;
    border: 2px solid #fff;
    border-radius: 2px;
    padding: 3px;
    width: 120px;
}


问:
TypeError in py36compat
I get this strange error on Python2.7. It works fine with Python3:

```<code>    Traceback (most recent call last):
      File "/home/guettli/descript/projects/descript_jugendhaus/.tox/py27-django14/lib/python2.7/site-packages/pip/_vendor/pep517/_in_process.py", line 280, in <module>
        main()
      File "/home/guettli/descript/projects/descript_jugendhaus/.tox/py27-django14/lib/python2.7/site-packages/pip/_vendor/pep517/_in_process.py", line 263, in main
        json_out['return_val'] = hook(**hook_input['kwargs'])
      File "/home/guettli/descript/projects/descript_jugendhaus/.tox/py27-django14/lib/python2.7/site-packages/pip/_vendor/pep517/_in_process.py", line 133, in prepare_metadata_for_build_wheel
        return hook(metadata_directory, config_settings)
      File "/tmp/pip-build-env-sy2MSY/overlay/lib/python2.7/site-packages/setuptools/build_meta.py", line 156, in prepare_metadata_for_build_wheel
        self.run_setup()
      File "/tmp/pip-build-env-sy2MSY/overlay/lib/python2.7/site-packages/setuptools/build_meta.py", line 243, in run_setup
        self).run_setup(setup_script=setup_script)
      File "/tmp/pip-build-env-sy2MSY/overlay/lib/python2.7/site-packages/setuptools/build_meta.py", line 142, in run_setup
        exec(compile(code, __file__, 'exec'), locals())
      File "setup.py", line 195, in <module>
        distclass=BinaryDistribution,
      File "/tmp/pip-build-env-sy2MSY/overlay/lib/python2.7/site-packages/setuptools/__init__.py", line 162, in setup
        return distutils.core.setup(**attrs)
      File "/usr/lib/python2.7/distutils/core.py", line 151, in setup
        dist.run_commands()
      File "/usr/lib/python2.7/distutils/dist.py", line 953, in run_commands
        self.run_command(cmd)
      File "/usr/lib/python2.7/distutils/dist.py", line 972, in run_command
        cmd_obj.run()
      File "/tmp/pip-build-env-sy2MSY/overlay/lib/python2.7/site-packages/setuptools/command/dist_info.py", line 31, in run
        egg_info.run()
      File "/tmp/pip-build-env-sy2MSY/overlay/lib/python2.7/site-packages/setuptools/command/egg_info.py", line 296, in run
        self.find_sources()
      File "/tmp/pip-build-env-sy2MSY/overlay/lib/python2.7/site-packages/setuptools/command/egg_info.py", line 303, in find_sources
        mm.run()
      File "/tmp/pip-build-env-sy2MSY/overlay/lib/python2.7/site-packages/setuptools/command/egg_info.py", line 534, in run
        self.add_defaults()
      File "/tmp/pip-build-env-sy2MSY/overlay/lib/python2.7/site-packages/setuptools/command/egg_info.py", line 570, in add_defaults
        sdist.add_defaults(self)
      File "/tmp/pip-build-env-sy2MSY/overlay/lib/python2.7/site-packages/setuptools/command/py36compat.py", line 36, in add_defaults
        self._add_defaults_ext()
      File "/tmp/pip-build-env-sy2MSY/overlay/lib/python2.7/site-packages/setuptools/command/py36compat.py", line 118, in _add_defaults_ext
        if self.distribution.has_ext_modules():
      File "setup.py", line 109, in has_ext_modules
        return super().has_ext_modules() or 'SETUPPY_ALLOW_PURE' not in os.environ
    TypeError: super() takes at least 1 argument (0 given)
</code>```

What could be the root-cause?

答:
I found a solution.

If I disable the python-hunter library it works.

I guess python-hunter is not compatible with Python2.7 any more.

That's fine for my use case. I this case I can remove the library (although it is a great tracing library).

Title: TypeError in py36compat

Body:
I get this strange error on Python2.7. It works fine with Python3:

    Traceback (most recent call last):
      File "/home/guettli/descript/projects/descript_jugendhaus/.tox/py27-django14/lib/python2.7/site-packages/pip/_vendor/pep517/_in_process.py", line 280, in <module>
        main()
      File "/home/guettli/descript/projects/descript_jugendhaus/.tox/py27-django14/lib/python2.7/site-packages/pip/_vendor/pep517/_in_process.py", line 263, in main
        json_out['return_val'] = hook(**hook_input['kwargs'])
      File "/home/guettli/descript/projects/descript_jugendhaus/.tox/py27-django14/lib/python2.7/site-packages/pip/_vendor/pep517/_in_process.py", line 133, in prepare_metadata_for_build_wheel
        return hook(metadata_directory, config_settings)
      File "/tmp/pip-build-env-sy2MSY/overlay/lib/python2.7/site-packages/setuptools/build_meta.py", line 156, in prepare_metadata_for_build_wheel
        self.run_setup()
      File "/tmp/pip-build-env-sy2MSY/overlay/lib/python2.7/site-packages/setuptools/build_meta.py", line 243, in run_setup
        self).run_setup(setup_script=setup_script)
      File "/tmp/pip-build-env-sy2MSY/overlay/lib/python2.7/site-packages/setuptools/build_meta.py", line 142, in run_setup
        exec(compile(code, __file__, 'exec'), locals())
      File "setup.py", line 195, in <module>
        distclass=BinaryDistribution,
      File "/tmp/pip-build-env-sy2MSY/overlay/lib/python2.7/site-packages/setuptools/__init__.py", line 162, in setup
        return distutils.core.setup(**attrs)
      File "/usr/lib/python2.7/distutils/core.py", line 151, in setup
        dist.run_commands()
      File "/usr/lib/python2.7/distutils/dist.py", line 953, in run_commands
        self.run_command(cmd)
      File "/usr/lib/python2.7/distutils/dist.py", line 972, in run_command
        cmd_obj.run()
      File "/tmp/pip-build-env-sy2MSY/overlay/lib/python2.7/site-packages/setuptools/command/dist_info.py", line 31, in run
        egg_info.run()
      File "/tmp/pip-build-env-sy2MSY/overlay/lib/python2.7/site-packages/setuptools/command/egg_info.py", line 296, in run
        self.find_sources()
      File "/tmp/pip-build-env-sy2MSY/overlay/lib/python2.7/site-packages/setuptools/command/egg_info.py", line 303, in find_sources
        mm.run()
      File "/tmp/pip-build-env-sy2MSY/overlay/lib/python2.7/site-packages/setuptools/command/egg_info.py", line 534, in run
        self.add_defaults()
      File "/tmp/pip-build-env-sy2MSY/overlay/lib/python2.7/site-packages/setuptools/command/egg_info.py", line 570, in add_defaults
        sdist.add_defaults(self)
      File "/tmp/pip-build-env-sy2MSY/overlay/lib/python2.7/site-packages/setuptools/command/py36compat.py", line 36, in add_defaults
        self._add_defaults_ext()
      File "/tmp/pip-build-env-sy2MSY/overlay/lib/python2.7/site-packages/setuptools/command/py36compat.py", line 118, in _add_defaults_ext
        if self.distribution.has_ext_modules():
      File "setup.py", line 109, in has_ext_modules
        return super().has_ext_modules() or 'SETUPPY_ALLOW_PURE' not in os.environ
    TypeError: super() takes at least 1 argument (0 given)

What could be the root-cause?


问:
How to sort by first few letters of string?
For example, if I have an array of strings {"Bob", "Bom", "Ash", "Ben"}, how do I sort it first by first letter (ASCII value), then by second letter, and so on without losing the previous sorted order? so after sorting it would become {"Ash", "Ben", "Bob", "Bom"}?

答:
Pretty straight-forward - use custom Comparator that takes only first N letters (s.substring(0, N)):

```<code>String[] source = {"Bob", "Ben", "Bom", "Ash"};
int N = 2; // sort by first 2 chars

String[] result = Arrays.stream(source)
        .sorted(Comparator.comparing(s -> s.substring(0, N)))
        .toArray(String[]::new);
</code>```

Body:
Pretty straight-forward - use custom Comparator that takes only first N letters (s.substring(0, N)):

String[] source = {"Bob", "Ben", "Bom", "Ash"};
int N = 2; // sort by first 2 chars

String[] result = Arrays.stream(source)
        .sorted(Comparator.comparing(s -> s.substring(0, N)))
        .toArray(String[]::new);


问:
how do i interact with a pc camera using c++
i intend to interact with a pc camera using c plus plus. Are there any libraries you can recommend or ways to go about ? The idea is to take shots with a Samsung wireless cam then get the images transferred unto a pc with cam and on the pc show images as per the face detection using the cam . any ideas where to start ?</p>

答: If you're on Linux I think libwebcam would be a good start. Take a look at the example viewer app to get further details in using it. That is for camera access and general functionality. For face detection I guess you could use OpenCV(I haven't use it myself for this particular purpose so I cannot comment on its face detection capabilities).</p>


问:
Didomi trying to add events with variables
I'm trying to add these values according to what the user does but I can't figure out how to do it:

```<code>enum DidomiStatusType: String, Codable {
case custom = "custom"
case disableAll = "all-denied"
case enabledAll = "all-accepted"
case none = "no-gdpr" }
</code>```

In this function I have a listener where I call the actions that the user does, the problem is that I don't know what function to put if the user has customized it and I don't know if the way I was putting it is right

```<code>//If the user agreed all
let didomiEventListener = EventListener()

            didomiEventListener.onNoticeClickAgree = { _ in
            if self.type == .fakeSplash {
                DispatchQueue.main.async {
                    self.statusType = .enabledAll
                    self.delegate?.continueNavigation()
                }
            }
        }
</code>```

And if the user performs another action without accepting:

```<code>didomiEventListener.onHideNotice = { _ in
            if self.type == .fakeSplash {
                DispatchQueue.main.async {
                    self.statusType = .none
                    self.statusType = .custom
                    self.statusType = .disableAll
                    self.delegate?.continueNavigation()
                }
            }
        }
</code>```

I was following this documentation

答:
I was doing so bad, so there's the solution:

I upgraded the Didomi version too.

First I changed my enum to only String with the params I need

```<code>enum DidomiUserType: String {
case custom = "custom"
case disableAll = "all-denied"
case enabledAll = "all-accepted"
case none = "no-gdpr" }
</code>```

Then I added a Struct like this:

```<code>struct DidomiUserData {
var vendorEnabled: Int
var vendorDisabled: Int
var purposeEnabled: Int
var purposeDisabled: Int
var isUserConsentStatusPartial: Bool
var type: DidomiUserType = .none }
</code>```

The next thing I did was declare a constant that is and a variable with the struct of DidomiUserData.

```<code>let didomiUserStatusData = Didomi.shared.getUserStatus()
var didomiUserData = DidomiUserData(and the struct)
</code>```

Finally only have to do an if-if-else.

Body:
I'm trying to add these values according to what the user does but I can't figure out how to do it:

enum DidomiStatusType: String, Codable {
case custom = "custom"
case disableAll = "all-denied"
case enabledAll = "all-accepted"
case none = "no-gdpr" }

In this function I have a listener where I call the actions that the user does, the problem is that I don't know what function to put if the user has customized it and I don't know if the way I was putting it is right

//If the user agreed all
let didomiEventListener = EventListener()

            didomiEventListener.onNoticeClickAgree = { _ in
            if self.type == .fakeSplash {
                DispatchQueue.main.async {
                    self.statusType = .enabledAll
                    self.delegate?.continueNavigation()
                }
            }
        }

And if the user performs another action without accepting:

didomiEventListener.onHideNotice = { _ in
            if self.type == .fakeSplash {
                DispatchQueue.main.async {
                    self.statusType = .none
                    self.statusType = .custom
                    self.statusType = .disableAll
                    self.delegate?.continueNavigation()
                }
            }
        }

I was following this documentation

Body:
I was doing so bad, so there's the solution:

I upgraded the Didomi version too.

First I changed my enum to only String with the params I need

enum DidomiUserType: String {
case custom = "custom"
case disableAll = "all-denied"
case enabledAll = "all-accepted"
case none = "no-gdpr" }

Then I added a Struct like this:

struct DidomiUserData {
var vendorEnabled: Int
var vendorDisabled: Int
var purposeEnabled: Int
var purposeDisabled: Int
var isUserConsentStatusPartial: Bool
var type: DidomiUserType = .none }

The next thing I did was declare a constant that is and a variable with the struct of DidomiUserData.

let didomiUserStatusData = Didomi.shared.getUserStatus()
var didomiUserData = DidomiUserData(and the struct)

Finally only have to do an if-if-else.


问:
retrofit request @Part and @Query in kotlin android
I want to send Image as form-data and userId as Params in retrofit android.enter image description hereI have tried many solution but did not got any success. here is my code and api.

@Multipart
@POST("upload/profile")
fun uploadProfilePhoto(@Part image: MultipartBody.Part, @Query("userId") userId: String): Call

```<code>    val photoContent = RequestBody.create(MediaType.parse("image/*"), file)
    val photo = MultipartBody.Part.createFormData("image", file.name, photoContent)
</code>```

答:
send your request like this

```<code>val userId: RequestBody = userId.toRequestBody("multipart/formdata".toMediaTypeOrNull())

val image = file.asRequestBody("multipart/form-data".toMediaTypeOrNull())
val photo = MultipartBody.Part.createFormData("images", file.name, image)
</code>```

Use this userID as requestBody and photo for image

```<code>
@Multipart
    @POST("upload/profile")
    fun uploadProfilePhoto(
        @Part image: MultipartBody.Part,
        @Part("userId") userId: RequestBody
    ): Call<LoginSignUpGeneralResponse>
</code>```

Body:
I want to send Image as form-data and userId as Params in retrofit android.enter image description hereI have tried many solution but did not got any success. here is my code and api.

@Multipart
@POST("upload/profile")
fun uploadProfilePhoto(@Part image: MultipartBody.Part, @Query("userId") userId: String): Call

    val photoContent = RequestBody.create(MediaType.parse("image/*"), file)
    val photo = MultipartBody.Part.createFormData("image", file.name, photoContent)

Body:
send your request like this

val userId: RequestBody = userId.toRequestBody("multipart/formdata".toMediaTypeOrNull())

val image = file.asRequestBody("multipart/form-data".toMediaTypeOrNull())
val photo = MultipartBody.Part.createFormData("images", file.name, image)

Use this userID as requestBody and photo for image

@Multipart
    @POST("upload/profile")
    fun uploadProfilePhoto(
        @Part image: MultipartBody.Part,
        @Part("userId") userId: RequestBody
    ): Call<LoginSignUpGeneralResponse>


问:
Does it matter which type of exception you use in Python?
I'm new to working with exceptions in Python. Wondering how much it matters that you get the type of exception -- i.e. ValueError, FileNotFoundError, TypeError, etc. -- correct. For example:

```<code>files = os.listdir(path)
if not files:
    msg = "directory is empty"
    raise ValueError(msg)
</code>```

Obviously this is not a ValueError. But an error will be raised and the message will be displayed. So, does it matter (functionally) which error type I use? Or is it primarily to inform the user what went wrong?

答:
In some applications, depending on the situation, your code will not fail, but it will not perform the operation you want, because there may be a user behavior or workflow situation that does not reconcile with the code you have written. In this case, you might want to create your own exception to manipulate the workflow or user behavior the way you want.

To do this, you can create your own exception using the raise keyword and the Exception() function.

For example, let's say you are coding a number guessing game and your application is trying to guess the number the user has in mind. If you don't set a limit on the user, it may take a very long time for your application to guess the number it keeps because there is an infinite option. Let's say we ask the user to keep a number between 0 and 100;

num=int(input("Please enter a number between 0 and 100: "))

if num not in range(0,101):

```<code>raise Exception("You must enter number between 0 and 100!")
</code>```

Body:
I'm new to working with exceptions in Python. Wondering how much it matters that you get the type of exception -- i.e. ValueError, FileNotFoundError, TypeError, etc. -- correct. For example:

files = os.listdir(path)
if not files:
    msg = "directory is empty"
    raise ValueError(msg)

Obviously this is not a ValueError. But an error will be raised and the message will be displayed. So, does it matter (functionally) which error type I use? Or is it primarily to inform the user what went wrong?

Body:
In some applications, depending on the situation, your code will not fail, but it will not perform the operation you want, because there may be a user behavior or workflow situation that does not reconcile with the code you have written. In this case, you might want to create your own exception to manipulate the workflow or user behavior the way you want.

To do this, you can create your own exception using the raise keyword and the Exception() function.

For example, let's say you are coding a number guessing game and your application is trying to guess the number the user has in mind. If you don't set a limit on the user, it may take a very long time for your application to guess the number it keeps because there is an infinite option. Let's say we ask the user to keep a number between 0 and 100;

num=int(input("Please enter a number between 0 and 100: "))

if num not in range(0,101):

raise Exception("You must enter number between 0 and 100!")


问:
Optimized dot product in Python
The dot product of two n-dimensional vectors u=[u1,u2,...un] and v=[v1,v2,...,vn] is is given by u1*v1 + u2*v2 + ... + un*vn.

A question posted yesterday encouraged me to find the fastest way to compute dot products in Python using only the standard library, no third-party modules or C/Fortran/C++ calls.

I timed four different approaches; so far the fastest seems to be sum(starmap(mul,izip(v1,v2))) (where starmap and izip come from the itertools module).

For the code presented below, these are the elapsed times (in seconds, for one million runs):

```<code>d0: 12.01215
d1: 11.76151
d2: 12.54092
d3: 09.58523
</code>```

Can you think of a faster way to do this?

```<code>import timeit # module with timing subroutines
import random # module to generate random numnbers
from itertools import imap,starmap,izip
from operator import mul

def v(N=50,min=-10,max=10):
    """Generates a random vector (in an array) of dimension N; the
    values are integers in the range [min,max]."""
    out = []
    for k in range(N):
        out.append(random.randint(min,max))
    return out

def check(v1,v2):
    if len(v1)!=len(v2):
        raise ValueError,"the lenght of both arrays must be the same"
    pass

def d0(v1,v2):
    """
    d0 is Nominal approach:
    multiply/add in a loop
    """
    check(v1,v2)
    out = 0
    for k in range(len(v1)):
        out += v1[k] * v2[k]
    return out

def d1(v1,v2):
    """
    d1 uses an imap (from itertools)
    """
    check(v1,v2)
    return sum(imap(mul,v1,v2))

def d2(v1,v2):
    """
    d2 uses a conventional map
    """
    check(v1,v2)
    return sum(map(mul,v1,v2))

def d3(v1,v2):
    """
    d3 uses a starmap (itertools) to apply the mul operator on an izipped (v1,v2)
    """
    check(v1,v2)
    return sum(starmap(mul,izip(v1,v2)))

# generate the test vectors
v1 = v()
v2 = v()

if __name__ == '__main__':

    # Generate two test vectors of dimension N

    t0 = timeit.Timer("d0(v1,v2)","from dot_product import d0,v1,v2")
    t1 = timeit.Timer("d1(v1,v2)","from dot_product import d1,v1,v2")
    t2 = timeit.Timer("d2(v1,v2)","from dot_product import d2,v1,v2")
    t3 = timeit.Timer("d3(v1,v2)","from dot_product import d3,v1,v2")

    print "d0 elapsed: ", t0.timeit()
    print "d1 elapsed: ", t1.timeit()
    print "d2 elapsed: ", t2.timeit()
    print "d3 elapsed: ", t3.timeit()
</code>```

Notice that the name of the file must be dot_product.py for the script to run; I used Python 2.5.1 on a Mac OS X Version 10.5.8.

EDIT:

I ran the script for N=1000 and these are the results (in seconds, for one million runs):

```<code>d0: 205.35457
d1: 208.13006
d2: 230.07463
d3: 155.29670
</code>```

I guess it is safe to assume that, indeed, option three is the fastest and option two the slowest (of the four presented).

答:
In Mathematica (10^12 additions and multiplications):

```<code>a = RandomReal[1,{10^4,10^4}];
b = RandomReal[1,{10^4,10^4}];
AbsoluteTiming[c=a.b;]//First
</code>```

9.65295 seconds

(Windows 10, Dell XPS17 9700, Mathematica 12.3)

ContentLicense: CC BY-SA 2.5

Title: Optimized dot product in Python

Body:
The dot product of two n-dimensional vectors u=[u1,u2,...un] and v=[v1,v2,...,vn] is is given by u1*v1 + u2*v2 + ... + un*vn.

A question posted yesterday encouraged me to find the fastest way to compute dot products in Python using only the standard library, no third-party modules or C/Fortran/C++ calls.

I timed four different approaches; so far the fastest seems to be sum(starmap(mul,izip(v1,v2))) (where starmap and izip come from the itertools module).

For the code presented below, these are the elapsed times (in seconds, for one million runs):

d0: 12.01215
d1: 11.76151
d2: 12.54092
d3: 09.58523

Can you think of a faster way to do this?

import timeit # module with timing subroutines
import random # module to generate random numnbers
from itertools import imap,starmap,izip
from operator import mul

def v(N=50,min=-10,max=10):
    """Generates a random vector (in an array) of dimension N; the
    values are integers in the range [min,max]."""
    out = []
    for k in range(N):
        out.append(random.randint(min,max))
    return out

def check(v1,v2):
    if len(v1)!=len(v2):
        raise ValueError,"the lenght of both arrays must be the same"
    pass

def d0(v1,v2):
    """
    d0 is Nominal approach:
    multiply/add in a loop
    """
    check(v1,v2)
    out = 0
    for k in range(len(v1)):
        out += v1[k] * v2[k]
    return out

def d1(v1,v2):
    """
    d1 uses an imap (from itertools)
    """
    check(v1,v2)
    return sum(imap(mul,v1,v2))

def d2(v1,v2):
    """
    d2 uses a conventional map
    """
    check(v1,v2)
    return sum(map(mul,v1,v2))

def d3(v1,v2):
    """
    d3 uses a starmap (itertools) to apply the mul operator on an izipped (v1,v2)
    """
    check(v1,v2)
    return sum(starmap(mul,izip(v1,v2)))

# generate the test vectors
v1 = v()
v2 = v()

if __name__ == '__main__':

    # Generate two test vectors of dimension N

    t0 = timeit.Timer("d0(v1,v2)","from dot_product import d0,v1,v2")
    t1 = timeit.Timer("d1(v1,v2)","from dot_product import d1,v1,v2")
    t2 = timeit.Timer("d2(v1,v2)","from dot_product import d2,v1,v2")
    t3 = timeit.Timer("d3(v1,v2)","from dot_product import d3,v1,v2")

    print "d0 elapsed: ", t0.timeit()
    print "d1 elapsed: ", t1.timeit()
    print "d2 elapsed: ", t2.timeit()
    print "d3 elapsed: ", t3.timeit()

Notice that the name of the file must be dot_product.py for the script to run; I used Python 2.5.1 on a Mac OS X Version 10.5.8.

EDIT:

I ran the script for N=1000 and these are the results (in seconds, for one million runs):

d0: 205.35457
d1: 208.13006
d2: 230.07463
d3: 155.29670

I guess it is safe to assume that, indeed, option three is the fastest and option two the slowest (of the four presented).

Body:
In Mathematica (10^12 additions and multiplications):

a = RandomReal[1,{10^4,10^4}];
b = RandomReal[1,{10^4,10^4}];
AbsoluteTiming[c=a.b;]//First

9.65295 seconds

(Windows 10, Dell XPS17 9700, Mathematica 12.3)