问:
Angular Material Icons Not Rendering Within Component
I've used Angular Material Icons on multiple projects and they work just fine. For some reason they don't currently work on my new project.

Here's my package.json file within node_modules/@angular/material/icons...

```<code>{
  "name": "@angular/material/icon",
  "fesm2020": "../fesm2020/icon.mjs",
  "fesm2015": "../fesm2015/icon.mjs",
  "esm2020": "../esm2020/icon/icon_public_index.mjs",
  "typings": "./icon_public_index.d.ts",
  "module": "../fesm2015/icon.mjs",
  "es2020": "../fesm2020/icon.mjs"
}
</code>```

Here is my app.module...

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { MaterialModule } from './material.module';

import { AppRoutingModule } from './app-routing.module';

import { SharedModule } from './shared/shared.module';

import { AppComponent } from './app.component';
import { NavComponent } from './nav/nav.component';

@NgModule({
  declarations: [
    AppComponent,
    NavComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    MaterialModule,
    AppRoutingModule,
    SharedModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

</code>```

Here's my module where I house my material imports...

```<code>import { NgModule } from "@angular/core";

import { MatCardModule } from '@angular/material/card';
import { MatButtonModule } from '@angular/material/button';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatIconModule } from '@angular/material/icon';

@NgModule({
    imports: [
        MatCardModule,
        MatButtonModule,
        MatToolbarModule,
        MatIconModule
    ],
    exports: [
        MatCardModule,
        MatButtonModule,
        MatToolbarModule,
        MatIconModule
    ]
})
export class MaterialModule {}
</code>```

My component where I'm trying to use icons...

```<code>// The below code simply results in the word "menu" rather than the icon

<mat-toolbar>
    <a routerLink="/home">
        <mat-icon>menu</mat-icon>
    </a>
</mat-toolbar>
</code>```

Here is my index.html...

```<code><!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Eventer</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="preconnect" href="https://fonts.gstatic.com">
  <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
  <app-root></app-root>
</body>
</html>

</code>```

UPDATE

This might have something to do with this weird, incomplete installation (since some Material items work, but not the icons). When I create a new project, I'll attempt to go through the Getting Started guide and use ng add @angular/material, but I get the following kick-back...

```<code>$ ng add @angular/material
- Determining package manager...
i Using package manager: npm
- Searching for compatible package version...
ΓêÜ Found compatible package version: @angular/material@13.2.1.
- Loading package information from registry...
ΓêÜ Package information loaded.
No terminal detected. '--skip-confirmation' can be used to bypass installation confirmation. Ensure package name is correct prior to '--skip-confirmation' option usage.
Command aborted.
</code>```

In these cases I have to go through and use npm commands to manually install items and this could be why my Material icons are not working. Anyone have any knowledge on why I'm getting the above message when attempting to use ng add?

Thank you.

答:
Most likely what happened is you used npm install rather than ng add to install angular material. ng add performs some extra steps for an angular project.

Your best bet is to run ng add @angular/material to reinstall.

Exactly what extra steps are performed are located here: https://material.angular.io/guide/getting-started

Like was mentioned in another answer, missing this stylesheet from index.html will break mat-icons

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
```

Just an update: the author's ng add command was failing due to a bug involving git bash https://github.com/angular/angular-cli/issues/21512. Switching to a different shell solved the issue.

Body:
I've used Angular Material Icons on multiple projects and they work just fine. For some reason they don't currently work on my new project.

Here's my package.json file within node_modules/@angular/material/icons...

{
  "name": "@angular/material/icon",
  "fesm2020": "../fesm2020/icon.mjs",
  "fesm2015": "../fesm2015/icon.mjs",
  "esm2020": "../esm2020/icon/icon_public_index.mjs",
  "typings": "./icon_public_index.d.ts",
  "module": "../fesm2015/icon.mjs",
  "es2020": "../fesm2020/icon.mjs"
}

Here is my app.module...

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { MaterialModule } from './material.module';

import { AppRoutingModule } from './app-routing.module';

import { SharedModule } from './shared/shared.module';

import { AppComponent } from './app.component';
import { NavComponent } from './nav/nav.component';

@NgModule({
  declarations: [
    AppComponent,
    NavComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    MaterialModule,
    AppRoutingModule,
    SharedModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Here's my module where I house my material imports...

import { NgModule } from "@angular/core";

import { MatCardModule } from '@angular/material/card';
import { MatButtonModule } from '@angular/material/button';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatIconModule } from '@angular/material/icon';

@NgModule({
    imports: [
        MatCardModule,
        MatButtonModule,
        MatToolbarModule,
        MatIconModule
    ],
    exports: [
        MatCardModule,
        MatButtonModule,
        MatToolbarModule,
        MatIconModule
    ]
})
export class MaterialModule {}

My component where I'm trying to use icons...

// The below code simply results in the word "menu" rather than the icon

<mat-toolbar>

        <mat-icon>menu</mat-icon>

</mat-toolbar>

Here is my index.html...

<!doctype html>

  <meta charset="utf-8">
  <title>Eventer</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="preconnect" href="https://fonts.gstatic.com">
  <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

  <app-root></app-root>

UPDATE

This might have something to do with this weird, incomplete installation (since some Material items work, but not the icons). When I create a new project, I'll attempt to go through the Getting Started guide and use ng add @angular/material, but I get the following kick-back...

$ ng add @angular/material
- Determining package manager...
i Using package manager: npm
- Searching for compatible package version...
ΓêÜ Found compatible package version: @angular/material@13.2.1.
- Loading package information from registry...
ΓêÜ Package information loaded.
No terminal detected. '--skip-confirmation' can be used to bypass installation confirmation. Ensure package name is correct prior to '--skip-confirmation' option usage.
Command aborted.

In these cases I have to go through and use npm commands to manually install items and this could be why my Material icons are not working. Anyone have any knowledge on why I'm getting the above message when attempting to use ng add?

Thank you.

Body:
Most likely what happened is you used npm install rather than ng add to install angular material. ng add performs some extra steps for an angular project.

Your best bet is to run ng add @angular/material to reinstall.

Exactly what extra steps are performed are located here: https://material.angular.io/guide/getting-started

Like was mentioned in another answer, missing this stylesheet from index.html will break mat-icons

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

Just an update: the author's ng add command was failing due to a bug involving git bash https://github.com/angular/angular-cli/issues/21512. Switching to a different shell solved the issue.


来源: stackexchange

问:
Network media player has disappeared from Win10's File Explorer's "Computer" category, but is still in the "Media Devices" category
I apologize if the following is not appropriate for the tag I have used and I would appreciate a redirect to the correct place.  If stackoverflow is simply the wrong place for this altogether, I'll be glad to delete it :-)

I have three Intel-based PCs, all of which are running the latest version of Windows 10 Pro 64-bit.  I also have a WDTV media player with a USB drive connected to it.  All three PCs as well as the WDTV are connected to a common LAN via Ethernet.  There are no settings in the WDTV that specify which network devices are allowed to use it but instead, any network device that has its password should be able to access it and transfer files to/from its USB drive.

When I select "Network" in the left frame of Windows File Explorer, the WDTV device is listed in both the "Computer" and "Media Devices" categories in the right frame on the PC with the newest Win10 installation, but only in the "Media Devices" category on the other two PCs.  On the PC where it is listed in both categories I can access the WDTV's USB drive and transfer files to/from it, but on the other two PCs the USB drive is not even visible.  When Win10 was originally installed on the other two PCs the WDTV device was visible in both categories on them too and I could transfer to/from its USB drive, but something has obviously changed through all the various application installations and whatnot that have occurred since then.

I am far from a Windows or a network expert and my question is specifically how to debug this to find out the cause and correct it.  I realize I can do a complete reinstallation of everything but that is something I'd prefer to avoid if possible and without knowing the actual cause, it's likely the problem will eventually return anyway.  Any suggestions would be appreciated.

答: The problem was that the WDTV device uses the 'SMB 1.0/CIFS' network protocol, which was only enabled on my newest PC installation.  After enabling it on my two other PCs the WDTV device once again became accessible by them too.  There is also an "automatic removal" setting for 'SMB 1.0/CIFS'.  My GUESS is that it was likely initially set on both of the other PCs and caused the protocol to be removed during a Windows update :-(</p>

ContentLicense: CC BY-SA 4.0


问:
autofill container using keyboard digits
I am continuously trying to fill container by pressing keyboard digits I  want to autofill that circular shape container to autofill container is not working. What should I do? Please tell me.

答:
u can specify two more parameter one for focusNode of current textfield & another one for focus u want to change . you can have textField with icon where you can show the ui as per your screenshot . e.g.

```<code>textField(
    text: '1stelement',
    focusNode: // your focus node,
    nextFocusNode: // your next field focus node
),
</code>```

now u can use :

```<code>FocusScope.of(context).requestFocus(nextFocus);
</code>```

Body:
u can specify two more parameter one for focusNode of current textfield & another one for focus u want to change . you can have textField with icon where you can show the ui as per your screenshot . e.g.

textField(
    text: '1stelement',
    focusNode: // your focus node,
    nextFocusNode: // your next field focus node
),

now u can use :

FocusScope.of(context).requestFocus(nextFocus);


问:
Null check operator used on a null value instagram clone
[VERBOSE-2:ui_dart_state.cc(209)] Unhandled Exception: type 'Null' is not a subtype of type 'Map<String, dynamic>' in type cast</p>

答:
This might have basically happened while parsing json data from server into dart object. The issue basically arises in general whenever the members of the dart class are not nullable in which case they can't be left null at the time of initialisation. Due to which while you use the fromJson factory or function the value assigned to this parameter doesn't have that key available in it as a consequence you receive this error.

This could also arise while using named pushing of routes via arguments.


问:
How important is optimization?
I got into a bit of a debate yesterday with my boss about the proper role of optimization when building software. Essentially, his position was that optimization needs to be a primary concern during the entire process of development.

My opinion is that you need to make the right algorithmic decisions during development, but you should never be counting cycles during development. In fact, I feel so strongly about this I had to walk away from the conversation. I've seen too many bad programming decisions in the name of "optimization", and too much bad code defended with the excuse "this way is faster".

What does the StackOverflow.com community think?

答:
"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%."

- Donald Knuth

OwnerDisplayName: dicroce

ContentLicense: CC BY-SA 2.5

Title: How important is optimization?

LastEditorDisplayName: jpalecek

OwnerDisplayName: Chad Birch


问:
My values are not successfully inserting into my table. When I test the connection it is successful. What's wrong with my code?
Here is my index.php:

```<code>    private static function connection() {

        $servername = "localhost";
        $username = "root";
        $password = "";
        $dbname="social";

        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $conn;
    }
    public static function query($query, $params =array()) {
        $statement=self::connect->prepare($query);
        $statement->execute($params);
    }
</code>```

And here is my login.php:

```<code>include('index.php');
if (isset($_POST['createaccount'])){
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
DB::query('INSERT INTO users (username, password, email) VALUES (:username, :password, :email)', array(':username'=>$username, ':password'=>$password, ':email'=>$email));
echo "Success!";
}
</code>```

And here is my html form which is in the login.php under the php tags:

```<code><h1>Register</h1>
    <form class="login.php" method="post" action="login.php">
        <input type="text" name="username" value="" placeholder="Username ..." required><br/>
        <input type="password" name="password" value="" placeholder="Password ..." required><br/>
        <input type="email" name="email" value="" placeholder="someone@gmail.com" required><br/>
        <input type="submit" name="createaccount" value="submit"> <br/>
    </form>
</code>```

I am following a tutorial made five years ago. I am using Sequel Pro and my table is called users. I have four fields: id, username, password, and email.

Thanks for help

答:
You are calling a non-existant method/property in your query function.
You are currently calling self::connect->prepare while a "connect" function/property is never declared in your code example.

I am assuming what you actually wanted to do is call the connection function and call the prepare function from the result connection object.

A potential fix might be to adjust the query function like so:

    public static function query($query, $params =array()) {
        $statement=self::connection()->prepare($query);
        $statement->execute($params);
    }
```

Body:
Here is my index.php:

    private static function connection() {

        $servername = "localhost";
        $username = "root";
        $password = "";
        $dbname="social";

        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $conn;
    }
    public static function query($query, $params =array()) {
        $statement=self::connect->prepare($query);
        $statement->execute($params);
    }

And here is my login.php:

include('index.php');
if (isset($_POST['createaccount'])){
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
DB::query('INSERT INTO users (username, password, email) VALUES (:username, :password, :email)', array(':username'=>$username, ':password'=>$password, ':email'=>$email));
echo "Success!";
}

And here is my html form which is in the login.php under the php tags:

Register

    <form class="login.php" method="post" action="login.php">
        <input type="text" name="username" value="" placeholder="Username ..." required>

        <input type="password" name="password" value="" placeholder="Password ..." required>

        <input type="email" name="email" value="" placeholder="someone@gmail.com" required>

        <input type="submit" name="createaccount" value="submit">

    </form>

I am following a tutorial made five years ago. I am using Sequel Pro and my table is called users. I have four fields: id, username, password, and email.

Thanks for help


问:
Saving a pyspark dataframe to mongodb gives an error
I try to save a pyspark dataframe to mongodb using a google cloud dataproc cluster, but it keeps showing me an error message.
I'm using spark 2.4.7 and python 3.7, and mongoDB spark connector 2.4.3
Here is my code:

```<code>spark = SparkSession.builder\
                    .master("yarn")\
                    .appName("demo")\
                    .config("spark.mongodb.input.uri",
                             "mongodb+srv://my_host:27017/people_db") \
                    .config("spark.mongodb.output.uri",
                            "mongodb+srv://my_host:27017/people_db") \
                    .config('spark.jars.packages',
                            'org.mongodb.spark:mongo-spark-connector_2.12-2.4.3')\
                    .getOrCreate()
df = spark.read\
          .format('csv')\
          .options(header=True)\
          .load(csv_path)

# ----------Some data processing -----------

df.write\    #This is the block of code that shows the error
  .format("com.mongodb.spark.sql.DefaultSource")\
  .mode("append")\
  .option("collection", "people")\
  .save()
</code>```

Here is the error message:

答:
The mongo driver jar is not included in the class path. The two mongo jars (connector and driver) are essential in spark/jars path.
I was able to run on local and also as dataproc job by referring to the below link.
Mongo connector : 2.12_3.0.1
Mongo java driver : 3.12
Spark : 3.0.2

Mongo dependencies required

Body:
I try to save a pyspark dataframe to mongodb using a google cloud dataproc cluster, but it keeps showing me an error message.
I'm using spark 2.4.7 and python 3.7, and mongoDB spark connector 2.4.3
Here is my code:

spark = SparkSession.builder\
                    .master("yarn")\
                    .appName("demo")\
                    .config("spark.mongodb.input.uri",
                             "mongodb+srv://my_host:27017/people_db") \
                    .config("spark.mongodb.output.uri",
                            "mongodb+srv://my_host:27017/people_db") \
                    .config('spark.jars.packages',
                            'org.mongodb.spark:mongo-spark-connector_2.12-2.4.3')\
                    .getOrCreate()
df = spark.read\
          .format('csv')\
          .options(header=True)\
          .load(csv_path)

# ----------Some data processing -----------

df.write\    #This is the block of code that shows the error
  .format("com.mongodb.spark.sql.DefaultSource")\
  .mode("append")\
  .option("collection", "people")\
  .save()

Here is the error message:


问:
How to add values from previous input to textarea
I am trying to add values from 2 of my inputs to the text area. I was able to find a solution to grab one of the inputs and hope someone can help me find a way to get another one. Also, is there a way to grab another element from the page for example php echo of student's first name?

Please see the picture
I would like this to say "Hey, student_first_name, my name is last_name from university_name, let's connect.

This is the code I have

```<code>    <script>
  // save the location of the name field
  var message_field = document.getElementById('university');
  var last_name_field = document.getElementById('last_name');

  //add an event listener to activate if the value of the field changes
  message_field.addEventListener('change', function() {
    // when the field changes run the following code

    // copy the text (value)
    var name = message_field.value;

    // concatenate it with the desired message
    var autoFill = 'Hi ' + name + ', thank you for visiting us!';

    // and paste it into the message field.
    document.getElementById('message').value = autoFill;
  })
</script>
</code>```

答:
it's a little bit confuse your HTML code, but i did an HTML code and adjusted your javascript code, I hope this helps you.

PS.: You can always group your inputs and textareas inside a FORM tag

https://www.w3schools.com/html/html_forms.asp

var form = document.getElementById("myForm");

    form.addEventListener("input", function () {
        var name = document.getElementById('name').value;
        var lastName = document.getElementById('last_name').value;
        var university = document.getElementById('university').value;

        document.getElementById('message').value = 'Hey, ' + name + ', my name is ' + lastName + ' from ' + university + ', let\'s connect'

    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="myForm">
    <div>
        <input type="text" placeholder="First Name" id="name">
    </div>
    <div>
        <input type="text" placeholder="Last Name" id="last_name">
    </div>
    <div>
        <input type="text" placeholder="University Name" id="university">
    </div>
    <div>
        <input type="text" placeholder="Phone Number" id="phone">
    </div>
    <div>
        <input type="email" placeholder="Email address" id="email">
    </div>
    <div>
        <textarea name="Message" id="message" cols="30" rows="10" placeholder="Message (optional)"></textarea>
    </div>
</form></code>```

Body:
it's a little bit confuse your HTML code, but i did an HTML code and adjusted your javascript code, I hope this helps you.

PS.: You can always group your inputs and textareas inside a FORM tag

https://www.w3schools.com/html/html_forms.asp

var form = document.getElementById("myForm");

    form.addEventListener("input", function () {
        var name = document.getElementById('name').value;
        var lastName = document.getElementById('last_name').value;
        var university = document.getElementById('university').value;

        document.getElementById('message').value = 'Hey, ' + name + ', my name is ' + lastName + ' from ' + university + ', let\'s connect'

    });

<form id="myForm">
    <div>
        <input type="text" placeholder="First Name" id="name">
    </div>
    <div>
        <input type="text" placeholder="Last Name" id="last_name">
    </div>
    <div>
        <input type="text" placeholder="University Name" id="university">
    </div>
    <div>
        <input type="text" placeholder="Phone Number" id="phone">
    </div>
    <div>
        <input type="email" placeholder="Email address" id="email">
    </div>
    <div>
        <textarea name="Message" id="message" cols="30" rows="10" placeholder="Message (optional)"></textarea>
    </div>
</form>


问:
Angular Websocket Closes Immediately after send() is called
Below contains my sendMessage() function where I am trying to JSON.stringify() an object to then be able to call this.ws.send(), with that JSON string. Whenever I try to send a stringified object, which is really just a string, my websocket closes immediately after the ws.send is called. On the other hand, if I just provide the ws.send() with the content of my message (just the text message sent), then it works fine.

    ngOnInit() {
      this.messageForm = new FormGroup({
        message: new FormControl('')
      })
      this.routeSub = this.route.params.subscribe(params => {
        this.chatroomId = params['id']
        console.log(this.chatroomId)
      });
      this.store
      .pipe(
          select(getCurrUser)
      ).subscribe(data =>  {
          this.user = data
          this.userId = this.user.user_id || ""
          this.userType = this.user.user_category
          console.log(this.userId)
      })
      this.chatroomService.getChatroomsByUserId(this.userId).subscribe(data => {
        this.chatrooms = data

      })
      if (this.chatroomId) {
        this.chatroomService.getChatroomById(this.chatroomId).subscribe(chatroom => {
          this.currChatroom = chatroom
          this.user1 = chatroom.user1
          this.user2 = chatroom.user2
          this.user1_id = chatroom.user1_id
          this.user2_id = chatroom.user2_id
          if (this.user1_id == this.userId) {
            this.otherUser = this.user2
            this.otherUserId = this.user2_id
          } else {
            this.otherUser = this.user1
            this.otherUserId = this.user1_id
          }
        })
      }
      if (this.chatroomId) {
        this.chatroomService.getMessagesByChatroomId(this.chatroomId).subscribe(messages => {
          console.log(messages)
          this.messages = messages.reverse()
        })
        this.url = "ws://" + "localhost:8080" + "/api/" + this.chatroomId + "/ws";
        console.log(this.url)
        this.ws = new WebSocket(this.url)
        console.log(this.ws)
        this.ws.onopen = () => console.log('websocket connected!');
        this.ws.onmessage = (msg) => {
          const socket = msg.target as WebSocket;
          if (socket.url !== this.url) return socket.close();
          const d = JSON.parse(msg.data);
          console.log(d)
          this.messages = [...this.messages, d];
        }
        this.ws.onclose = () => console.log("websocket closed");
        window.addEventListener('beforeunload', () => this.ws.close())
      }
  }

    sendMessage() {
      const sender = this.user
      const id = this.userId
      const msg = this.messageForm.get('message').value
      var msgStr: string  = JSON.stringify({
        message: msg,
        sender_id: id,
        chatroom_id: this.chatroomId,
        sender: sender,
        timestamp: "Just now"
      })
      this.ws.send(msgStr)
      this.chatroomService.sendMessage(this.messageForm.get('message').value, this.userId, this.currChatroom.chatroom_id).subscribe(message => {
        console.log(message)
        this.messageForm.reset()
      })
    }

}```
</div>
</div>
</p>
<p>As soon as this.ws.send() is called, the websocket seems to close; however, when I change my sendMessage function to just send the message text and not a JSON string, it works. Thus, this following code block does not cause errors; however, I need to pass additional data such as sender_id.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>sendMessage() {
      const sender = this.user
      const id = this.userId
      const msg = this.messageForm.get('message').value
      this.ws.send(msg)
      this.chatroomService.sendMessage(this.messageForm.get('message').value, this.userId,       this.currChatroom.chatroom_id).subscribe(message => {
        console.log(message)
        this.messageForm.reset()
      })
    }</code>```

答:
The issue was that when stringifying my JSON Object, the sender attribute was a defined User type that for whatever reason, was causing issues and perhaps not being correctly handled by my Go backend API.

The following code with sender: sender is the culprit, as the sender value is a User object.

var msgStr: string  = JSON.stringify({
        message: msg,
        sender_id: id,
        chatroom_id: this.chatroomId,
        sender: sender,
        timestamp: "Just now"
      })```
</div>
</div>
</p>
<p>I fixed this by simply doing the following:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>var msgStr: string  = JSON.stringify({
        message: msg,
        sender: {
          first_name: sender.first_name,
          last_name: sender.last_name,
          user_id: sender.user_id
        },
        chatroom_id: this.chatroomId,
        timestamp: "Just now"
      })</code>```

I only provided the object with the necessary data from my sender User object, which was really just the first name, last name, and user_id.

Body:
Below contains my sendMessage() function where I am trying to JSON.stringify() an object to then be able to call this.ws.send(), with that JSON string. Whenever I try to send a stringified object, which is really just a string, my websocket closes immediately after the ws.send is called. On the other hand, if I just provide the ws.send() with the content of my message (just the text message sent), then it works fine.

    ngOnInit() {
      this.messageForm = new FormGroup({
        message: new FormControl('')
      })
      this.routeSub = this.route.params.subscribe(params => {
        this.chatroomId = params['id']
        console.log(this.chatroomId)
      });
      this.store
      .pipe(
          select(getCurrUser)
      ).subscribe(data =>  {
          this.user = data
          this.userId = this.user.user_id || ""
          this.userType = this.user.user_category
          console.log(this.userId)
      })
      this.chatroomService.getChatroomsByUserId(this.userId).subscribe(data => {
        this.chatrooms = data

      })
      if (this.chatroomId) {
        this.chatroomService.getChatroomById(this.chatroomId).subscribe(chatroom => {
          this.currChatroom = chatroom
          this.user1 = chatroom.user1
          this.user2 = chatroom.user2
          this.user1_id = chatroom.user1_id
          this.user2_id = chatroom.user2_id
          if (this.user1_id == this.userId) {
            this.otherUser = this.user2
            this.otherUserId = this.user2_id
          } else {
            this.otherUser = this.user1
            this.otherUserId = this.user1_id
          }
        })
      }
      if (this.chatroomId) {
        this.chatroomService.getMessagesByChatroomId(this.chatroomId).subscribe(messages => {
          console.log(messages)
          this.messages = messages.reverse()
        })
        this.url = "ws://" + "localhost:8080" + "/api/" + this.chatroomId + "/ws";
        console.log(this.url)
        this.ws = new WebSocket(this.url)
        console.log(this.ws)
        this.ws.onopen = () => console.log('websocket connected!');
        this.ws.onmessage = (msg) => {
          const socket = msg.target as WebSocket;
          if (socket.url !== this.url) return socket.close();
          const d = JSON.parse(msg.data);
          console.log(d)
          this.messages = [...this.messages, d];
        }
        this.ws.onclose = () => console.log("websocket closed");
        window.addEventListener('beforeunload', () => this.ws.close())
      }
  }

    sendMessage() {
      const sender = this.user
      const id = this.userId
      const msg = this.messageForm.get('message').value
      var msgStr: string  = JSON.stringify({
        message: msg,
        sender_id: id,
        chatroom_id: this.chatroomId,
        sender: sender,
        timestamp: "Just now"
      })
      this.ws.send(msgStr)
      this.chatroomService.sendMessage(this.messageForm.get('message').value, this.userId, this.currChatroom.chatroom_id).subscribe(message => {
        console.log(message)
        this.messageForm.reset()
      })
    }

}

As soon as this.ws.send() is called, the websocket seems to close; however, when I change my sendMessage function to just send the message text and not a JSON string, it works. Thus, this following code block does not cause errors; however, I need to pass additional data such as sender_id.

sendMessage() {
      const sender = this.user
      const id = this.userId
      const msg = this.messageForm.get('message').value
      this.ws.send(msg)
      this.chatroomService.sendMessage(this.messageForm.get('message').value, this.userId,       this.currChatroom.chatroom_id).subscribe(message => {
        console.log(message)
        this.messageForm.reset()
      })
    }

Body:
The issue was that when stringifying my JSON Object, the sender attribute was a defined User type that for whatever reason, was causing issues and perhaps not being correctly handled by my Go backend API.

The following code with sender: sender is the culprit, as the sender value is a User object.

var msgStr: string  = JSON.stringify({
        message: msg,
        sender_id: id,
        chatroom_id: this.chatroomId,
        sender: sender,
        timestamp: "Just now"
      })

I fixed this by simply doing the following:

var msgStr: string  = JSON.stringify({
        message: msg,
        sender: {
          first_name: sender.first_name,
          last_name: sender.last_name,
          user_id: sender.user_id
        },
        chatroom_id: this.chatroomId,
        timestamp: "Just now"
      })

I only provided the object with the necessary data from my sender User object, which was really just the first name, last name, and user_id.


问:
Is it bad to add jQuery multiple times on a page?
I am in a situation where I have multiple ASCX files that are being added to an aspx page.  Some of these files include the jQuery library.  Depending on which ones are added the jQuery library may be included more than once.

I cannot add jQuery at the masterpage or some other level, it must be from the ASCX.  The reasons for this are beyond the scope of this question, but if someone really wants an explanation I can provide one.

Is it bad to have jQuery added multiple times in an ASPX page?  Is there a way to conditionally add a script to an ASCX page?

答:
You should not add jQuery more than once.

You can add it conditionally though:

```<code><script>window.jQuery || document.write('<script src="js/jquery-1.8.2.min.js">\x3C/script>')</script>
</code>```

This is how they to it in the html5boilerplate

ContentLicense: CC BY-SA 3.0

Body:
You should not add jQuery more than once.

You can add it conditionally though:

<script>window.jQuery || document.write('<script src="js/jquery-1.8.2.min.js">\x3C/script>')</script>

This is how they to it in the html5boilerplate


问:
Angular Button Click Registering on Both the Button and Div Underneath
Whenever I click on my #dropDown button, it functions as intended and opens the dropdown menu; however, the click also hits the  underneath which is also clickable. I don't want the button click event to also hit the div underneath, as that is not the intended function.

{{post.title}}

{{post.date_of_job}}

Description:

{{post.care_description}}

Start: {{post.start_time}} | End: {{post.end_time}}

                    <button #dropDown (click)="toggleDropdown()" class="dropdownbutton mt-2 relative z-10 block p-2 text-gray-700 bg-white border border-transparent rounded-md dark:text-white focus:border-blue-500 focus:ring-opacity-40 dark:focus:ring-opacity-40 focus:ring-blue-300 dark:focus:ring-blue-400 focus:ring dark:bg-gray-800 focus:outline-none">
                        <svg class="w-5 h-5 text-gray-800 dark:text-white" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                            <path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" />
                        </svg>
                    </button>

Your Application:
 {{post.applications[0].message}}

```

答:
try using stopPropagation in the click function.

check out this link for more details:
https://www.freecodecamp.org/news/a-simplified-explanation-of-event-propagation-in-javascript-f9de7961a06e/


问:
How to check if array of array contain atleast one element?
I am facing one problem in javascript filter.

Suppose this is an array1-

```<code>const array1 = [
    {
        title: 'Stock market news',
        symbols: ['SPY.US', 'GSPC.INDX', 'DJI.INDX', 'CL.COMM', 'IXIC.INDX', 'NQ.COMM', 'ES.COMM'],
    },
    {
        title: 'Neil Young urges Spotify',
        symbols: ['SPOT.US', '639.F', '639.XETRA']
    },
    {
        title: 'Neil Young urges Spotify',
        symbols: ['AAPl.US', '639.F', '639.XETRA']
    }
]
</code>```

And this is an array2

```<code>const array2 = [
    {Code: "AAPL"},
    {Code: 'SPOT'}
]
</code>```

I have to filer array1 and remove an object that not complete the condition. The condition is if the array1 symbols contain at least one element of array2 Code. I mean if the array2 Code is match arry1 symbols field at least one element.

In the above example, the result should be-

```<code>const array1 = [
    {
        title: 'Neil Young urges Spotify',
        symbols: ['SPOT.US', '639.F', '639.XETRA']
    },
    {
        title: 'Neil Young urges Spotify',
        symbols: ['AAPl.US', '639.F', '639.XETRA']
    }
]
</code>```

Because this two object contain AAPL and SPOT in symbols field. I think I can clear all the things.

I am trying in this way-

```<code>const filterData = array1.filter(function (array1El) {
    return !array2.find(function (array2El) {
        return array1El.symbols.includes(`${array2El.Code}.US`);
    })
});
</code>```

But it is not working. Please say me where I am wrong.

答:
There are two issues:

Your !array2.find condition is backwards - you want to filter to include items for which array2.find does have a match, not items for which it doesn't.

'AAPl.US' !== 'AAPL.US' - make them the same case before comparing.

It'd also be clearer to use .some instead of .find.

const array1 = [
    {
        title: 'Stock market news',
        symbols: ['SPY.US', 'GSPC.INDX', 'DJI.INDX', 'CL.COMM', 'IXIC.INDX', 'NQ.COMM', 'ES.COMM'],
    },
    {
        title: 'Neil Young urges Spotify',
        symbols: ['SPOT.US', '639.F', '639.XETRA']
    },
    {
        title: 'Neil Young urges Spotify',
        symbols: ['AAPl.US', '639.F', '639.XETRA']
    }
]

const array2 = [
    {Code: "AAPL"},
    {Code: 'SPOT'}
]
const filterData = array1.filter(function (array1El) {
    return array2.some(function (array2El) {
        return array1El.symbols
            .map(s => s.toLowerCase())
            .includes(`${array2El.Code.toLowerCase()}.us`);
    })
});
console.log(filterData);```
</div>
</div>
</p>
<p>Or create a Set of matching symbols first, which I'd prefer for lower complexity.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const array1 = [
    {
        title: 'Stock market news',
        symbols: ['SPY.US', 'GSPC.INDX', 'DJI.INDX', 'CL.COMM', 'IXIC.INDX', 'NQ.COMM', 'ES.COMM'],
    },
    {
        title: 'Neil Young urges Spotify',
        symbols: ['SPOT.US', '639.F', '639.XETRA']
    },
    {
        title: 'Neil Young urges Spotify',
        symbols: ['AAPl.US', '639.F', '639.XETRA']
    }
]

const array2 = [
    {Code: "AAPL"},
    {Code: 'SPOT'}
];

const codesToFind = new Set(array2.map(({ Code }) => Code.toLowerCase() + '.us'));
const filterData = array1.filter(
  ({ symbols }) => symbols.some(
    sym => codesToFind.has(sym.toLowerCase())
  )
);
console.log(filterData);</code>```

Body:
I am facing one problem in javascript filter.

Suppose this is an array1-

const array1 = [
    {
        title: 'Stock market news',
        symbols: ['SPY.US', 'GSPC.INDX', 'DJI.INDX', 'CL.COMM', 'IXIC.INDX', 'NQ.COMM', 'ES.COMM'],
    },
    {
        title: 'Neil Young urges Spotify',
        symbols: ['SPOT.US', '639.F', '639.XETRA']
    },
    {
        title: 'Neil Young urges Spotify',
        symbols: ['AAPl.US', '639.F', '639.XETRA']
    }
]

And this is an array2

const array2 = [
    {Code: "AAPL"},
    {Code: 'SPOT'}
]

I have to filer array1 and remove an object that not complete the condition. The condition is if the array1 symbols contain at least one element of array2 Code. I mean if the array2 Code is match arry1 symbols field at least one element.

In the above example, the result should be-

const array1 = [
    {
        title: 'Neil Young urges Spotify',
        symbols: ['SPOT.US', '639.F', '639.XETRA']
    },
    {
        title: 'Neil Young urges Spotify',
        symbols: ['AAPl.US', '639.F', '639.XETRA']
    }
]

Because this two object contain AAPL and SPOT in symbols field. I think I can clear all the things.

I am trying in this way-

const filterData = array1.filter(function (array1El) {
    return !array2.find(function (array2El) {
        return array1El.symbols.includes(`${array2El.Code}.US`);
    })
});

But it is not working. Please say me where I am wrong.

Body:
There are two issues:

Your !array2.find condition is backwards - you want to filter to include items for which array2.find does have a match, not items for which it doesn't.

'AAPl.US' !== 'AAPL.US' - make them the same case before comparing.

It'd also be clearer to use .some instead of .find.

const array1 = [
    {
        title: 'Stock market news',
        symbols: ['SPY.US', 'GSPC.INDX', 'DJI.INDX', 'CL.COMM', 'IXIC.INDX', 'NQ.COMM', 'ES.COMM'],
    },
    {
        title: 'Neil Young urges Spotify',
        symbols: ['SPOT.US', '639.F', '639.XETRA']
    },
    {
        title: 'Neil Young urges Spotify',
        symbols: ['AAPl.US', '639.F', '639.XETRA']
    }
]

const array2 = [
    {Code: "AAPL"},
    {Code: 'SPOT'}
]
const filterData = array1.filter(function (array1El) {
    return array2.some(function (array2El) {
        return array1El.symbols
            .map(s => s.toLowerCase())
            .includes(`${array2El.Code.toLowerCase()}.us`);
    })
});
console.log(filterData);

Or create a Set of matching symbols first, which I'd prefer for lower complexity.

const array1 = [
    {
        title: 'Stock market news',
        symbols: ['SPY.US', 'GSPC.INDX', 'DJI.INDX', 'CL.COMM', 'IXIC.INDX', 'NQ.COMM', 'ES.COMM'],
    },
    {
        title: 'Neil Young urges Spotify',
        symbols: ['SPOT.US', '639.F', '639.XETRA']
    },
    {
        title: 'Neil Young urges Spotify',
        symbols: ['AAPl.US', '639.F', '639.XETRA']
    }
]

const array2 = [
    {Code: "AAPL"},
    {Code: 'SPOT'}
];

const codesToFind = new Set(array2.map(({ Code }) => Code.toLowerCase() + '.us'));
const filterData = array1.filter(
  ({ symbols }) => symbols.some(
    sym => codesToFind.has(sym.toLowerCase())
  )
);
console.log(filterData);


问:
How to set time zone of values in a Pandas DataFrame?
I'd like to set the time zone of the values of a column in a Pandas DataFrame. I am reading the DataFrame with pandas.read_csv().</p>

答:
df['date'] = df['date'].dt.tz_localize('UTC')

This seems to work starting with my 'naive' timezone.


问:
how to merge two lists with duplacated factors into a dict in python?
I know there's a way to merge lists into a dict by zip function, but once the 'key-list' contains duplicated factors it doesn't works well since many values will be cut. I wonder if there is a good solution to merge lists with the same keys?

assume we have two lists below, one is to be key and another is to be value

```<code>    list_k = [1,1,2]
    list_v = [3,6,9]
</code>```

if I apply zip as usual, we will get following result

```<code>    dict = {k:v for k, v in zip(list_k, list_v)}
    #{1:3, 2:9}
</code>```

however, what I want is as below

```<code>    #dict = {1:[3,6],2:[9]}
</code>```

答:
You could use collections.defaultdict:

```<code>from collections import defaultdict

list_k = [1, 1, 2]
list_v = [3, 6, 9]
merged = defaultdict(list)
for k, v in zip(list_k, list_v):
    merged[k].append(v)
merged = dict(merged)
print(merged)
</code>```

Output:

```<code>{1: [3, 6], 2: [9]}
</code>```

Body:
I know there's a way to merge lists into a dict by zip function, but once the 'key-list' contains duplicated factors it doesn't works well since many values will be cut. I wonder if there is a good solution to merge lists with the same keys?

assume we have two lists below, one is to be key and another is to be value

    list_k = [1,1,2]
    list_v = [3,6,9]

if I apply zip as usual, we will get following result

    dict = {k:v for k, v in zip(list_k, list_v)}
    #{1:3, 2:9}

however, what I want is as below

    #dict = {1:[3,6],2:[9]}

Body:
You could use collections.defaultdict:

from collections import defaultdict

list_k = [1, 1, 2]
list_v = [3, 6, 9]
merged = defaultdict(list)
for k, v in zip(list_k, list_v):
    merged[k].append(v)
merged = dict(merged)
print(merged)

Output:

{1: [3, 6], 2: [9]}


问:
Manually Creating a Root Token in Vault (the hard way)
Ok so I have an application that I inherited that we do not know the root token and we do not have any recovery keys or unseal keys. The problem is, we cannot authenticate into Vault at all and we also cannot have the instance go down.

I do have access to the datastore it uses (DynamoDB) and the encrypting keys. My assumption is that it would be possible in theory to manually add an entry and set a password directly on the underlying datastore instance so that we can have a root account again.

I know this one is weird but we cannot re-initialize the database.

Any thoughts on how this could be done?

答:
You can try one of the below -

The initial root token generated at vault operator init time -- this token has no expiration

By using another root token; a root token with an expiration cannot create a root token that never expires

By using vault operator generate-root (example) with the permission of a quorum of unseal key holders

Root tokens are useful in development but should be extremely carefully guarded in production. In fact, the Vault team recommends that root tokens are only used for just enough initial setup (usually, setting up auth methods and policies necessary to allow administrators to acquire more limited tokens) or in emergencies, and are revoked immediately after they are no longer needed. If a new root token is needed, the operator generate-root command and associated API endpoint can be used to generate one on-the-fly.

You can read more here - https://www.vaultproject.io/docs/concepts/tokens


答:
We could use a regex alternation approach here:

const array1 = [
    {
        title: 'Stock market news',
        symbols: ['SPY.US', 'GSPC.INDX', 'DJI.INDX', 'CL.COMM', 'IXIC.INDX', 'NQ.COMM', 'ES.COMM'],
    },
    {
        title: 'Neil Young urges Spotify',
        symbols: ['SPOT.US', '639.F', '639.XETRA']
    },
    {
        title: 'Neil Young urges Spotify',
        symbols: ['AAPL.US', '639.F', '639.XETRA']
    }
];

const array2 = [{Code: "AAPL"}, {Code: "SPOT"}];
var regex = new RegExp("\\b(?:" + array2.reduce((x, y) => x.Code + "|" + y.Code) + ")\\.US");
console.log(regex);  // /\b(?:AAPL|SPOT)\.US/
var output = array1.filter(x => x.symbols.some(e => regex.test(e)));
console.log(output);```

The strategy here is to form a regex alternation of stock symbols, one of which is required.  We then filter the original array, using some() and the regex to ensure that any match has at least one required stock symbol.

Title: How to check if array of array contain atleast one element?

Body:
We could use a regex alternation approach here:

const array1 = [
    {
        title: 'Stock market news',
        symbols: ['SPY.US', 'GSPC.INDX', 'DJI.INDX', 'CL.COMM', 'IXIC.INDX', 'NQ.COMM', 'ES.COMM'],
    },
    {
        title: 'Neil Young urges Spotify',
        symbols: ['SPOT.US', '639.F', '639.XETRA']
    },
    {
        title: 'Neil Young urges Spotify',
        symbols: ['AAPL.US', '639.F', '639.XETRA']
    }
];

const array2 = [{Code: "AAPL"}, {Code: "SPOT"}];
var regex = new RegExp("\\b(?:" + array2.reduce((x, y) => x.Code + "|" + y.Code) + ")\\.US");
console.log(regex);  // /\b(?:AAPL|SPOT)\.US/
var output = array1.filter(x => x.symbols.some(e => regex.test(e)));
console.log(output);

The strategy here is to form a regex alternation of stock symbols, one of which is required.  We then filter the original array, using some() and the regex to ensure that any match has at least one required stock symbol.


问:
scp (secure copy) to ec2 instance without password
I have an EC2 instance running (FreeBSD 9 AMI ami-8cce3fe5), and I can ssh into it using my amazon-created key file without password prompt, no problem.

However, when I want to copy a file to the instance using scp I am asked to enter a password:

```<code>scp somefile.txt -i mykey.pem root@my.ec2.id.amazonaws.com:/

Password:
</code>```

Any ideas why this is happening/how it can be prevented?

答:
For ec2 server

#move your key to /tmp or right folder on server

Assign right permission

sudo chmod 600 /tmp/dev-sunrobotics-snippetbucketcom.pem

then connect to server or transfer

scp   -i /tmp/dev-snippetbucketcom.pem filestore.tar.gz  ubuntu@85.111.5.33.98:/tmp

Make sure in your ip security you have allow ip address to connect

Body:
I have an EC2 instance running (FreeBSD 9 AMI ami-8cce3fe5), and I can ssh into it using my amazon-created key file without password prompt, no problem.

However, when I want to copy a file to the instance using scp I am asked to enter a password:

scp somefile.txt -i mykey.pem root@my.ec2.id.amazonaws.com:/

Password:

Any ideas why this is happening/how it can be prevented?


问:
Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view in Django RestFramework
I'm trying to return a response after the execution of loop but I'm getting an error as

```<code>AssertionError at Data/CurrentRunningActivityForAudit/10
Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`
</code>```

when I added another return response outside the loop it shows the empty array i.e.,.[ ] it's returning empty response

`

views.py:

```<code>def CurrentRunningActivity(UserID):
        cursor = connection.cursor()
        cursor.execute('EXEC [dbo].[sp_GetCurrentRunningActivityAudit] @UserId=%s',(UserID,))
        result_set = cursor.fetchall()

        IsActive = 'true'

        for row in result_set:
         data = []
         data.append({
            'TaskId':row[0],
            'TaskName' : row[1],
            'Source' : row[2],
            'Requester' : row[3],
            'type' : row[4],
            'IsActive':IsActive,

         })

         return Response(data[0], status=status.HTTP_200_OK)
</code>```

when I move the return response outside the loop it shows as local variable 'data' referenced before assignment

答:
Try this:</p>
```<code>def CurrentRunningActivity(UserID):
    cursor = connection.cursor()
    cursor.execute('EXEC [dbo].[sp_GetCurrentRunningActivityAudit] @UserId=%s',(UserID,))
    result_set = cursor.fetchall()

    IsActive = 'true'
    data = []
    for row in result_set:
        data.append({
            'TaskId': row[0],
            'TaskName' : row[1],
            'Source' : row[2],
            'Requester' : row[3],
            'type' : row[4],
            'IsActive': IsActive,
         })

    return Response(
        data[0] if data else [],
        status=status.HTTP_200_OK
    )
</code>```

Body:
I'm trying to return a response after the execution of loop but I'm getting an error as

AssertionError at Data/CurrentRunningActivityForAudit/10
Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`

when I added another return response outside the loop it shows the empty array i.e.,.[ ] it's returning empty response

`

views.py:

def CurrentRunningActivity(UserID):
        cursor = connection.cursor()
        cursor.execute('EXEC [dbo].[sp_GetCurrentRunningActivityAudit] @UserId=%s',(UserID,))
        result_set = cursor.fetchall()

        IsActive = 'true'

        for row in result_set:
         data = []
         data.append({
            'TaskId':row[0],
            'TaskName' : row[1],
            'Source' : row[2],
            'Requester' : row[3],
            'type' : row[4],
            'IsActive':IsActive,

         })

         return Response(data[0], status=status.HTTP_200_OK)

when I move the return response outside the loop it shows as local variable 'data' referenced before assignment

Body:
Try this:

def CurrentRunningActivity(UserID):
    cursor = connection.cursor()
    cursor.execute('EXEC [dbo].[sp_GetCurrentRunningActivityAudit] @UserId=%s',(UserID,))
    result_set = cursor.fetchall()

    IsActive = 'true'
    data = []
    for row in result_set:
        data.append({
            'TaskId': row[0],
            'TaskName' : row[1],
            'Source' : row[2],
            'Requester' : row[3],
            'type' : row[4],
            'IsActive': IsActive,
         })

    return Response(
        data[0] if data else [],
        status=status.HTTP_200_OK
    )


问:
MS Access DSUM issue
I have a text box in a form that sums up an "encumbered" column with the where condition matches the ID number in that table and the ID shown in the form. I get a #Name error but all of the naming is correct.

=DSum("EncAmount",[tblEncumbrances],"[BID]='" & [frmProcurementEdit]![BudgetItemID] & "''")

tblEncumbrances is the table name, EncAmount is the column whose sum I need to add up. FrmProcurementEdit is the form that the textbox is on and BudgetItemID (Also on the form) needs to match BID(In tblEncumbrances)

Am I missing something here? Any help would be greatly appreciated!!

答:
The literal table name must be enclosed in quote marks. Also, there is an extra closing apostrophe delimiter.

According to your comment, linking fields are not same data type. This will definitely be an issue and really should correct data structure. However, it can be dealt with. Assuming BID is an integer number:

=DSum("EncAmount", "[tblEncumbrances]", "[BID]=" & CInt([BudgetItemID]))

or

=DSum("EncAmount", "[tblEncumbrances]", "[BID]=" & Val([BudgetItemID]))

Title: MS Access DSUM issue


问:
git fatal: Authentication failed
I tried to contribute to Bioconda. However, I got the following error:

```<code>$ git clone https://github.com/mictadlo/bioconda-recipes.git
Cloning into 'bioconda-recipes'...
remote: Enumerating objects: 312339, done.
remote: Total 312339 (delta 0), reused 0 (delta 0), pack-reused 312339
Receiving objects: 100% (312339/312339), 332.37 MiB | 9.93 MiB/s, done.
Resolving deltas: 100% (172897/172897), done.
Updating files: 100% (18842/18842), done.

$ cd bioconda-recipes/
$ git remote add upstream https://ghp_eWgtJStONjyA40srOLuSCnEQ0rrdza@github.com/bioconda/bioconda-recipes.git
$ git checkout master
Already on 'master'

$ git push origin master
Username for 'https://github.com': mictadlo
Password for 'https://mictadlo@github.com':
remote: Support for password authentication was removed on August 13, 2021. Please use a personal access token instead.
remote: Please see https://github.blog/2020-12-15-token-authentication-requirements-for-git-operations/ for more information.
fatal: Authentication failed for 'https://github.com/mictadlo/bioconda-recipes.git/'

</code>```

What did I miss?

Thank you in advance.

答:
For pushing code into the repo, you need to add an SSH key to your GitHub.

Follow this link for more information:
https://docs.github.com/en/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent

Title: git fatal: Authentication failed

Body:
I tried to contribute to Bioconda. However, I got the following error:

$ git clone https://github.com/mictadlo/bioconda-recipes.git
Cloning into 'bioconda-recipes'...
remote: Enumerating objects: 312339, done.
remote: Total 312339 (delta 0), reused 0 (delta 0), pack-reused 312339
Receiving objects: 100% (312339/312339), 332.37 MiB | 9.93 MiB/s, done.
Resolving deltas: 100% (172897/172897), done.
Updating files: 100% (18842/18842), done.

$ cd bioconda-recipes/
$ git remote add upstream https://ghp_eWgtJStONjyA40srOLuSCnEQ0rrdza@github.com/bioconda/bioconda-recipes.git
$ git checkout master
Already on 'master'

$ git push origin master
Username for 'https://github.com': mictadlo
Password for 'https://mictadlo@github.com':
remote: Support for password authentication was removed on August 13, 2021. Please use a personal access token instead.
remote: Please see https://github.blog/2020-12-15-token-authentication-requirements-for-git-operations/ for more information.
fatal: Authentication failed for 'https://github.com/mictadlo/bioconda-recipes.git/'

What did I miss?

Thank you in advance.


问:
Django - get data from form and return to user so they can edit/delete
New to Django and making a restuarant booking system. I have everything going to my database but now i'm trying to return the info back to the user, ideally in a similar form view to what i have, so they can edit or delete the booking.

My code so far is as follows:

models.py:

```<code>class Reservations(models.Model):

    reservation form categories and attributes
    name = models.CharField(max_length=50)
    phone_number = models.CharField(validators=[phoneNumberRegex], max_length=16,
unique=True)
    email = models.EmailField()
    date = models.DateField()
    time = models.CharField(choices=time_options, default="12pm", max_length=10)
    number_of_party = models.IntegerField(choices=party_size, default=1)
    reservation_id = models.UUIDField(primary_key=True, default=uuid.uuid4,
editable=False, max_length=15)

    class Meta:
        ordering = ['date']
        verbose_name = 'Reservation'
        verbose_name_plural = 'Reservations'

    def __str__(self):
        return self.name
</code>```

Then my form looks like this:

form.py:

```<code>class ReservationForm(forms.ModelForm):
    class Meta:
        model = Reservations
        fields = ['name', 'phone_number', 'email', 'date', 'time', 'number_of_party']
        widgets = {
            'date': DatePickerInput(format='%d-%m-%Y'),
        }
</code>```

Then where I think i'm really getting lost is with the views.

view.py:

```<code>class ReservationsFormView(CreateView):
    model = Reservations
    template_name = "reservations/reservations.html"
    form_class = ReservationForm
    success_url = "reservation_complete/"

    def form_valid(self, form):
        return super().form_valid(form)

class EditReservationView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    model = Reservations
    template_name = "reservations/edit_reservations.html"
    form_class = ReservationForm
    success_url = "reservation_complete/"

    def test_func(self):
        return self.request.user == self.get_object().user

class ReservationCompleteView(CreateView):
    template_name = "reservations/reservation_complete.html"
    success_url = "/reservation_complete/"
    form_class = ReservationForm
    model = Reservations

class ReservationAccountView(TemplateView):
    template_name = "reservations/reservations_account.html"

class DeleteReservationView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
    """ A view to delete an reservation """
    model = Reservations
    success_url = "/reservations/"

    def test_func(self):
        return self.request.user == self.get_object().user
</code>```

So basically if someone could help me extract the data and present back to the user in a html file I would greatly appreciate it.
A lot of the material online isn't using class based views but i start that way so sticking it out.
Sorry for the verbose code.
Thanks in advance

答:
While Django's Edit, Create, etc views are quick and helpful, I find them hard to manipulate, especially if I haven't used them in a while. I recommend getting used to writing your own views, that way you can set whatever action you want the view to perform.

Let's say your URL looks like this - edit/4281ee81-a12a-4a0f-8928-2d9639903bd7/

forms.py

```<code>class EditReservationForm(forms.Form):
    name = forms.CharField()
    email = forms.EmailField()
</code>```

views.py

```<code>class EditReservationView(LoginRequiredMixing, View):
    def get(self, request, *args **kwargs):
        reservation = Reservations.objects.get(uuid=kwargs['uuid'])
        form = EditReservationForm(initial={"name": reservation.name, "email": reservation.email})
        return render(request, "reservation/edit-reservation.html", {"form": form})
</code>```

You now have a bound form to data from a specific reservation. I hope this helps. And more info on initial data here - initial form values

Body:
New to Django and making a restuarant booking system. I have everything going to my database but now i'm trying to return the info back to the user, ideally in a similar form view to what i have, so they can edit or delete the booking.

My code so far is as follows:

models.py:

class Reservations(models.Model):

    reservation form categories and attributes
    name = models.CharField(max_length=50)
    phone_number = models.CharField(validators=[phoneNumberRegex], max_length=16,
unique=True)
    email = models.EmailField()
    date = models.DateField()
    time = models.CharField(choices=time_options, default="12pm", max_length=10)
    number_of_party = models.IntegerField(choices=party_size, default=1)
    reservation_id = models.UUIDField(primary_key=True, default=uuid.uuid4,
editable=False, max_length=15)

    class Meta:
        ordering = ['date']
        verbose_name = 'Reservation'
        verbose_name_plural = 'Reservations'

    def __str__(self):
        return self.name

Then my form looks like this:

form.py:

class ReservationForm(forms.ModelForm):
    class Meta:
        model = Reservations
        fields = ['name', 'phone_number', 'email', 'date', 'time', 'number_of_party']
        widgets = {
            'date': DatePickerInput(format='%d-%m-%Y'),
        }

Then where I think i'm really getting lost is with the views.

view.py:

class ReservationsFormView(CreateView):
    model = Reservations
    template_name = "reservations/reservations.html"
    form_class = ReservationForm
    success_url = "reservation_complete/"

    def form_valid(self, form):
        return super().form_valid(form)

class EditReservationView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    model = Reservations
    template_name = "reservations/edit_reservations.html"
    form_class = ReservationForm
    success_url = "reservation_complete/"

    def test_func(self):
        return self.request.user == self.get_object().user

class ReservationCompleteView(CreateView):
    template_name = "reservations/reservation_complete.html"
    success_url = "/reservation_complete/"
    form_class = ReservationForm
    model = Reservations

class ReservationAccountView(TemplateView):
    template_name = "reservations/reservations_account.html"

class DeleteReservationView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
    """ A view to delete an reservation """
    model = Reservations
    success_url = "/reservations/"

    def test_func(self):
        return self.request.user == self.get_object().user

So basically if someone could help me extract the data and present back to the user in a html file I would greatly appreciate it.
A lot of the material online isn't using class based views but i start that way so sticking it out.
Sorry for the verbose code.
Thanks in advance

Body:
While Django's Edit, Create, etc views are quick and helpful, I find them hard to manipulate, especially if I haven't used them in a while. I recommend getting used to writing your own views, that way you can set whatever action you want the view to perform.

Let's say your URL looks like this - edit/4281ee81-a12a-4a0f-8928-2d9639903bd7/

forms.py

class EditReservationForm(forms.Form):
    name = forms.CharField()
    email = forms.EmailField()

views.py

class EditReservationView(LoginRequiredMixing, View):
    def get(self, request, *args **kwargs):
        reservation = Reservations.objects.get(uuid=kwargs['uuid'])
        form = EditReservationForm(initial={"name": reservation.name, "email": reservation.email})
        return render(request, "reservation/edit-reservation.html", {"form": form})

You now have a bound form to data from a specific reservation. I hope this helps. And more info on initial data here - initial form values


问:
SQL - safely downcast BIGINT to INT
I have a CSV I'm importing into our database. One of the "columns" contains data that should be an INT but some rows have numbers that only fall in the BIGINT range (because they're test data from one of our partners). We store INT internally and have no desire to change.

I want to safely downcast from BIGINT to INT. By safely, I mean no errors should be raised if an arithmetic overflow happens. If the cast/conversion succeeds, I want my script to go on. If it fails, I want it to short-circuit. I can't seem to figure out the proper syntax. This is what I've got:

```<code>DECLARE @UserIDBigInt BIGINT = 9723021913; -- actually provided by query param
--Setting within the INT range successfully converts
--SET @UserIDBigInt = 5;
DECLARE @UserID INT = CONVERT(INT, @UserIDBigInt);
--DECLARE @UserID INT = CAST(@UserIDBigInt AS INT);
SELECT @UserIDBigInt
SELECT @UserID
IF @UserID IS NOT NULL BEGIN
    SELECT 'Handle it as reliable data'
END
</code>```

I've thought about comparing @UserIDBigInt to the valid range of an INT (-2^31 (-2,147,483,648) to 2^31-1 (2,147,483,647)), but I really don't like that approach. That's my fallback. I was hoping for some language constructs or built-in functions I could use. If I absolutely have to compare to the valid range, are there at least some built-in constants (like C#'s int.MinValue & int.MaxValue)?

EDIT: Corrected typo.

答:
Cast your bigint to varbinary, then store the lower half to @UserID and check the upper half:

if the upper half is all 0's and the lower half represents a non-negative value, @UserID then contains the correct int value;

if the upper half is all 1's and @UserID is negative, it's all right too;

otherwise there's an arithmetic overflow.

Here's an implementation:

```<code>DECLARE @UserIDBigInt BIGINT = 9723021913;
DECLARE @UserID INT, @HighInt INT;

WITH v AS (SELECT CAST(@UserIDBigInt AS varbinary) AS bin)
SELECT
  @HighInt = SUBSTRING(bin, 1, 4),
  @UserID  = SUBSTRING(bin, 5, 4)
FROM v;

IF (@HighInt = 0 AND @UserID >= 0 OR @HighInt = -1 AND @UserID < 0) BEGIN
    SELECT 'Handle it as reliable data'
END
</code>```

Title: SQL - safely downcast BIGINT to INT

Body:
I have a CSV I'm importing into our database. One of the "columns" contains data that should be an INT but some rows have numbers that only fall in the BIGINT range (because they're test data from one of our partners). We store INT internally and have no desire to change.

I want to safely downcast from BIGINT to INT. By safely, I mean no errors should be raised if an arithmetic overflow happens. If the cast/conversion succeeds, I want my script to go on. If it fails, I want it to short-circuit. I can't seem to figure out the proper syntax. This is what I've got:

DECLARE @UserIDBigInt BIGINT = 9723021913; -- actually provided by query param
--Setting within the INT range successfully converts
--SET @UserIDBigInt = 5;
DECLARE @UserID INT = CONVERT(INT, @UserIDBigInt);
--DECLARE @UserID INT = CAST(@UserIDBigInt AS INT);
SELECT @UserIDBigInt
SELECT @UserID
IF @UserID IS NOT NULL BEGIN
    SELECT 'Handle it as reliable data'
END

I've thought about comparing @UserIDBigInt to the valid range of an INT (-2^31 (-2,147,483,648) to 2^31-1 (2,147,483,647)), but I really don't like that approach. That's my fallback. I was hoping for some language constructs or built-in functions I could use. If I absolutely have to compare to the valid range, are there at least some built-in constants (like C#'s int.MinValue & int.MaxValue)?

EDIT: Corrected typo.

Body:
Cast your bigint to varbinary, then store the lower half to @UserID and check the upper half:

if the upper half is all 0's and the lower half represents a non-negative value, @UserID then contains the correct int value;

if the upper half is all 1's and @UserID is negative, it's all right too;

otherwise there's an arithmetic overflow.

Here's an implementation:

DECLARE @UserIDBigInt BIGINT = 9723021913;
DECLARE @UserID INT, @HighInt INT;

WITH v AS (SELECT CAST(@UserIDBigInt AS varbinary) AS bin)
SELECT
  @HighInt = SUBSTRING(bin, 1, 4),
  @UserID  = SUBSTRING(bin, 5, 4)
FROM v;

IF (@HighInt = 0 AND @UserID >= 0 OR @HighInt = -1 AND @UserID < 0) BEGIN
    SELECT 'Handle it as reliable data'
END


问:
Random sampling in python3
Suppose I have two lists A = [1,2,3,4] and B=[a,b,c,d]. I have to do random sampling such that my new list could look like this C= [1 or a , 2 or b , 3 or c , 4 or d], there is also a constrain that that the list C should have 50 % data from both  A and B.

Input:

```<code>A = [1,2,3,4]
B = ['a','b','c','d']
</code>```

答:
You could randomly sample the indices to ensure having half and half:

```<code>A = [1,2,3,4]
B = ['a','b','c','d']

import random
idx = set(random.sample(range(len(A)), len(A)//2))

C = [a if i in idx else b for i,(a,b) in enumerate(zip(A, B))]
</code>```

Example output: ['a', 2, 3, 'd']

Title: Random sampling in python3

Body:
Suppose I have two lists A = [1,2,3,4] and B=[a,b,c,d]. I have to do random sampling such that my new list could look like this C= [1 or a , 2 or b , 3 or c , 4 or d], there is also a constrain that that the list C should have 50 % data from both  A and B.

Input:

A = [1,2,3,4]
B = ['a','b','c','d']

Body:
You could randomly sample the indices to ensure having half and half:

A = [1,2,3,4]
B = ['a','b','c','d']

import random
idx = set(random.sample(range(len(A)), len(A)//2))

C = [a if i in idx else b for i,(a,b) in enumerate(zip(A, B))]

Example output: ['a', 2, 3, 'd']


答:
If you're doing this search multiple times, it would be best to build a symbol index and query that.

For example...

const array1 = [{"title":"Stock market news","symbols":["SPY.US","GSPC.INDX","DJI.INDX","CL.COMM","IXIC.INDX","NQ.COMM","ES.COMM"]},{"title":"Neil Young urges Spotify","symbols":["SPOT.US","639.F","639.XETRA"]},{"title":"Neil Young urges Spotify","symbols":["AAPl.US","639.F","639.XETRA"]}]

const array2 = [{Code: "AAPL"},{Code: 'SPOT'}]

// utility function to write into the index
const writeIndex = (map, key, entry) => {
  const normalisedKey = String.prototype.toUpperCase.call(key)
  if (!map.has(normalisedKey)) map.set(normalisedKey, new Set())
  map.get(normalisedKey).add(entry)
}

const symbolIndex = array1.reduce((map, entry) => {
  // convert all symbols to tokens
  // eg AAPL.US becomes ["AAPL.US", "AAPL", "US"]
  const keys = entry.symbols.flatMap(symbol =>
    [symbol, ...symbol.split(".")])

  // add the entry for each symbol token
  keys.forEach(key => writeIndex(map, key, entry))
  return map
}, new Map())

// pull unique items out of the index for the given codes
const queryIndex = codes => Array.from(new Set(codes.flatMap(code =>
  [...symbolIndex.get(code) ?? []]
)))

console.log(queryIndex(array2.map(({ Code }) => Code)))```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; }</code>```

Alternatively, you can use a nested some clause with a string includes check to see if the symbol contains your code.

const array1 = [{"title":"Stock market news","symbols":["SPY.US","GSPC.INDX","DJI.INDX","CL.COMM","IXIC.INDX","NQ.COMM","ES.COMM"]},{"title":"Neil Young urges Spotify","symbols":["SPOT.US","639.F","639.XETRA"]},{"title":"Neil Young urges Spotify","symbols":["AAPl.US","639.F","639.XETRA"]}]

const array2 = [
    {Code: "AAPL"},
    {Code: 'SPOT'}
]

const normalise = str => str.toUpperCase()

const normalisedCodes = array2.map(({ Code }) => normalise(Code))

const filtered = array1.filter(({ symbols }) =>
  normalisedCodes.some(code =>
    symbols.some(symbol => normalise(symbol).includes(code))
  )
)

console.log(filtered)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; }</code>```

Body:
If you're doing this search multiple times, it would be best to build a symbol index and query that.

For example...

const array1 = [{"title":"Stock market news","symbols":["SPY.US","GSPC.INDX","DJI.INDX","CL.COMM","IXIC.INDX","NQ.COMM","ES.COMM"]},{"title":"Neil Young urges Spotify","symbols":["SPOT.US","639.F","639.XETRA"]},{"title":"Neil Young urges Spotify","symbols":["AAPl.US","639.F","639.XETRA"]}]

const array2 = [{Code: "AAPL"},{Code: 'SPOT'}]

// utility function to write into the index
const writeIndex = (map, key, entry) => {
  const normalisedKey = String.prototype.toUpperCase.call(key)
  if (!map.has(normalisedKey)) map.set(normalisedKey, new Set())
  map.get(normalisedKey).add(entry)
}

const symbolIndex = array1.reduce((map, entry) => {
  // convert all symbols to tokens
  // eg AAPL.US becomes ["AAPL.US", "AAPL", "US"]
  const keys = entry.symbols.flatMap(symbol =>
    [symbol, ...symbol.split(".")])

  // add the entry for each symbol token
  keys.forEach(key => writeIndex(map, key, entry))
  return map
}, new Map())

// pull unique items out of the index for the given codes
const queryIndex = codes => Array.from(new Set(codes.flatMap(code =>
  [...symbolIndex.get(code) ?? []]
)))

console.log(queryIndex(array2.map(({ Code }) => Code)))

.as-console-wrapper { max-height: 100% !important; }

Alternatively, you can use a nested some clause with a string includes check to see if the symbol contains your code.

const array1 = [{"title":"Stock market news","symbols":["SPY.US","GSPC.INDX","DJI.INDX","CL.COMM","IXIC.INDX","NQ.COMM","ES.COMM"]},{"title":"Neil Young urges Spotify","symbols":["SPOT.US","639.F","639.XETRA"]},{"title":"Neil Young urges Spotify","symbols":["AAPl.US","639.F","639.XETRA"]}]

const array2 = [
    {Code: "AAPL"},
    {Code: 'SPOT'}
]

const normalise = str => str.toUpperCase()

const normalisedCodes = array2.map(({ Code }) => normalise(Code))

const filtered = array1.filter(({ symbols }) =>
  normalisedCodes.some(code =>
    symbols.some(symbol => normalise(symbol).includes(code))
  )
)

console.log(filtered)

.as-console-wrapper { max-height: 100% !important; }


问:
net::ERR_FILE_NOT_FOUND file:///android_asset/www/index.html was not found
I have a cordova app (that i'm building for Android) that I have signed using the keytools on the command line and installed this onto my Android device.

Whenever I open the app on my phone I get the following error:

```<code>Application Error
net::ERR_FILE_NOT_FOUND (file:///android_asset/www/index.html)
</code>```

My phone has an internet connection so there is an active mobile internet connection - can anyone help in debugging the problem?

I have come across a number of fixes that relate to moving remote assets however I cannot see in my app where I have any links to a remote URL.

Is there a way I can do a 'stack-trace' to allow me to pin-point the exact point this Application Error is being thrown within my app?

Any tips at all would be appreciated

-- update --
Here is the adb log that is generated when in the emulator

For anyone else that this may help I used the following to output the emulator log to a file:- (the double >> is needed to append data to the file)

```<code>adb -e logcat >> emulator.log
</code>```

https://gist.github.com/anonymous/e53abb7eb089950ac4e5

-- update --
My AndroidManifest.xml file looks like the following:

```<code><?xml version='1.0' encoding='utf-8'?>
<manifest android:hardwareAccelerated="true" android:versionCode="1" android:versionName="0.0.1" package="com.myapp" xmlns:android="http://schemas.android.com/apk/res/android">
<supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" />
<uses-permission android:name="android.permission.INTERNET" />
<application android:hardwareAccelerated="true" android:icon="@drawable/icon" android:label="@string/app_name" android:supportsRtl="true">
    <activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/activity_name" android:launchMode="singleTop" android:name="MainActivity" android:theme="@android:style/Theme.Black.NoTitleBar" android:windowSoftInputMode="adjustResize">
        <intent-filter android:label="@string/launcher_name">
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
<uses-sdk android:minSdkVersion="10" android:targetSdkVersion="21" />
</manifest>
</code>```

-- update --
Within my platforms 'android' folder is a 'assets' folder - this has the following structure:

```<code>www/
_where-is-www.txt
  www/css
  www/img
  www/js
  www/res
  www/app.html
  www/cordova.js
  www/cordova_plugins.js
  www/index.php
</code>```

There doesn't appear to be an index.html - even though the cordova setup states an index.html file... I cannot understand why it would be doing this.

NOTE :
I am creating a cordova app, adding a Android platform, then copying my existing www folder from another directory of the existing app (that has been developed and released to the Play store so works ok) - then finally doing the build. Not sure why index.html should be showing... any ideas??

答:
I had to run the ionic commands to fix this error:

```<code>ionic cordova platform add android
ionic cordova run android
</code>```

https://forum.ionicframework.com/t/ionic-err-file-not-found-file-android-asset-www-index-html/91629/2

Body:
I have a cordova app (that i'm building for Android) that I have signed using the keytools on the command line and installed this onto my Android device.

Whenever I open the app on my phone I get the following error:

Application Error
net::ERR_FILE_NOT_FOUND (file:///android_asset/www/index.html)

My phone has an internet connection so there is an active mobile internet connection - can anyone help in debugging the problem?

I have come across a number of fixes that relate to moving remote assets however I cannot see in my app where I have any links to a remote URL.

Is there a way I can do a 'stack-trace' to allow me to pin-point the exact point this Application Error is being thrown within my app?

Any tips at all would be appreciated

-- update --
Here is the adb log that is generated when in the emulator

For anyone else that this may help I used the following to output the emulator log to a file:- (the double >> is needed to append data to the file)

adb -e logcat >> emulator.log

https://gist.github.com/anonymous/e53abb7eb089950ac4e5

-- update --
My AndroidManifest.xml file looks like the following:

<?xml version='1.0' encoding='utf-8'?>
<manifest android:hardwareAccelerated="true" android:versionCode="1" android:versionName="0.0.1" package="com.myapp" xmlns:android="http://schemas.android.com/apk/res/android">
<supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" />
<uses-permission android:name="android.permission.INTERNET" />
<application android:hardwareAccelerated="true" android:icon="@drawable/icon" android:label="@string/app_name" android:supportsRtl="true">
    <activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/activity_name" android:launchMode="singleTop" android:name="MainActivity" android:theme="@android:style/Theme.Black.NoTitleBar" android:windowSoftInputMode="adjustResize">
        <intent-filter android:label="@string/launcher_name">
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
<uses-sdk android:minSdkVersion="10" android:targetSdkVersion="21" />
</manifest>

-- update --
Within my platforms 'android' folder is a 'assets' folder - this has the following structure:

www/
_where-is-www.txt
  www/css
  www/img
  www/js
  www/res
  www/app.html
  www/cordova.js
  www/cordova_plugins.js
  www/index.php

There doesn't appear to be an index.html - even though the cordova setup states an index.html file... I cannot understand why it would be doing this.

NOTE :
I am creating a cordova app, adding a Android platform, then copying my existing www folder from another directory of the existing app (that has been developed and released to the Play store so works ok) - then finally doing the build. Not sure why index.html should be showing... any ideas??

Body:
I had to run the ionic commands to fix this error:

ionic cordova platform add android
ionic cordova run android

https://forum.ionicframework.com/t/ionic-err-file-not-found-file-android-asset-www-index-html/91629/2


问:
Will a new instance of Singleton scoped object in a WebApplicationContext be created if the application is closed and started again in Spring MVC
In a Spring MVC app, will a new instance of Singleton Class in WebApplicationContext ,be created if the application is closed and then started again?

Say there is a singleton scoped DAO class with some member variables(states) that were modified in the application and then the application was closed.
Now when we run that app again, would the previous changes(made before the application was closed) be still there for that DAO or it will be a fresh singleton instance when the app restarts ?

答:
If it was a web application, then application will be down when the server stops or undeploys the given war if war was the artifact, or in case of jar(embedded server like in spring boot) application closes by terminating the program by quitting.
In this case when application is quitted, jvm process will also quit and the spring container inside your application will also quit with it, and when spring container is no longer up, the objects contained in it will also be not available.

Hence, you will get a fresh instance on app restart.


问:
With dvcs/git, is a single commit preferred over multiple, small, thematic commits?
This may not be a git specific question, but it comes up in the context of git. The idea may apply more broadly to other vcs's.

I am working on a small project in which I am currently the only developer. I'm getting used to using git, so I am wondering about best practices. As I implement new features/functions, I find that I work on multiple files, their examples, and documentation at once, such that my git status may report 15 files that have changed. But those files might relate to 3 different parts of the project.

Is it better to commit them in 3 separate parts, keeping the related files together, so that I could later go back and more easily find those commits. Or it is just as easy to commit them all at once with an appropriate message?

答:
One criteria that can help you make the right "amount" of commit is git bisect or git blame: would a large commit be a nuisance when trying to git bisect in order to detect a bug?

That is what describes the "Understanding the Git Workflow" blog post, when it describes "checkpoint commits" (too little commits capturing the code in a unstable state), or "no-ff commits" (which represents too many modification bundled together in one large commit).


问:
Category Page is broken after import or update the product and category in magento 2
Category Page is broken after import or update the product or category. But after run the reindex, cache flush command and refresh the browser cache, it works well.

Cron job is run correctly. Please let me know why this is happening.

Thanks.

答: It is very vague information you gave. You need to be specific and give proper detail. After every catalog import your catalog data is changed.  You need to reindex and flush the cache after every catalog import.</p>


问:
why C++ member function address is the same under release mode
```<code>class Test2
{
  public:

    void Test111(INT32 i)
    {
        i++;
    }
    void Test112(INT32 i)
    {
        i++;
    }
};

typedef void (Test2::* TestF)(int);

/*main*/
int main()
{
  TestF val1 = &Test2::Test111;
  TestF val2 = &Test2::Test112;

  if(val1==val2)
  {
    /*in VS2019 release mode with Same Address*/
    printf("Same Address in VS2019 release mode");
  }
  else
  {
    /*in VS2019 debug mode with Different Address*/
    printf("Different Address in VS2019 debug mode");
  }
  return 0;
};
</code>```

答:
The behaviour of the example program is undefined. You may only use int (or similar) when using the format specifier %d. There is no format specifier for pointers to member functions.

Furthermore, a pointer to member function doesn't store "an address". Its structure is more complex than that. It  may involve one or more addresses and/or offsets, or whatever it is that the language implementation needs to implement it.


问:
Display lines number in Stack Trace for .NET assembly in Release mode
Is there a way to display the lines in the stack trace for the .NET assembly build/deployed in Release mode?

UPDATE:

My application is divided into three class library projects and one ASP.NET "website" project.  The error I am trying to track down is in one of the three class library projects.  I only deployed the pdb file for the class library project that is generating the "Object reference not set to an instance of an object" error.

The line numbers are still not showing up in the stack trace.  Do I need to deploy the pdb files for all projects to get the line numbers in the stack trace?

Working solution

Deploying the pdb file for each application fixed the line number issue.

答:
In .NET Core you need to turn off 'Optimize code' option for release mode to show the correct line number.

C# Compiler Options that control code generation

OwnerDisplayName: Michael Kniskern

LastEditorDisplayName: Michael Kniskern


问:
Add thousand separator with javascript when add input dynamically
I have problem when adding input dynamically with thousand separator,
when I click add and the input form appears.
it should be when I type the number it will be arranged in thousand separator.
Please help me

$(document).ready(function(){
 $(document).on('click', '.add', function(){
  var html = '';
  html += '
';
  html += '<input type="text" name="item_name[]" class="form-control inputnumber" onkeypress="return event.keyCode > 47 && event.keyCode < 58 || event.keyCode == 46" />	';
  html += '
';
  $('#item_table').append(html);
 });

$('input.inputnumber').keyup(function(event) {
  if (event.which >= 37 && event.which <= 40) return;
  $(this).val(function(index, value) {
    return value
      // Keep only digits and decimal points:
      .replace(/[^\d.]/g, "")
      // Remove duplicated decimal point, if one exists:
      .replace(/^(\d*\.)(.*)\.(.*)$/, '$1$2$3')
      // Keep only two digits past the decimal point:
      .replace(/\.(\d{2})\d+/, '.$1')
      // Add thousands separators:
      .replace(/\B(?=(\d{3})+(?!\d))/g, ",")
  });
});
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <div class="table-repsonsive">
     <table class="table table-bordered" id="item_table">
      <tr>
       <th><button type="button" name="add" class="btn btn-success btn-sm add">ADD</button></th>
      </tr>
     </table>
    </div></code>```

答:
I would use the Intl.NumberFormat() constructor. You can find the docs and all the different options here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat

In the snippet below, you will see the formatting change as you type. If you add in text, it will just delete out the text. If you add in a second decimal, it won't do anything at first
I've forgotten most of the jQuery I once knew, so I wrote the snippet in Vanilla JS. I included comments on each line to explain the step.

const table = document.querySelector(`#item_table`);

// Add an event listener to the button in the form
table.querySelector(`button`).addEventListener(`click`, function() {

  // Create a
 element
  const tr = document.createElement(`tr`);

  // Create a  element
  const td = document.createElement(`td`);

  // Create an <input> element
  const inpt = document.createElement(`input`);

  // Add the input attributes
  inpt.type = `text`;
  inpt.classList.add(`form-control`);
  inpt.classList.add(`inputnumber`);

  // Add an event listener to the input element
  inpt.addEventListener(`keyup`, function(event) {
    // Current string value of the input
    const value = this.value;

    // Split the value string into an array on each decimal and
    // count the number of elements in the array
    const decimalCount = value.split(`.`).length - 1;

    // Don't do anything if a first decimal is entered
    if (event.key === `.` && decimalCount === 1) return

    // Remove any commas from the string and convert to a float
    // This will remove any non digit characters and second decimals
    const numericVal = parseFloat(value.replace(/,/g, ''));

    //NumberFormat options
    const options = {
      style: `decimal`,
      maximumFractionDigits: 20,
    };

    // Assign the formatted number to the input box
    this.value = new Intl.NumberFormat(`en-US`, options).format(numericVal);
  })
  // Append the input to the td
  td.append(inpt);

  // Append the td to the tr
  tr.append(td);

  // Append the tr to the table
  table.append(tr);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="table-repsonsive">
  <table class="table table-bordered" id="item_table">
    <tr>
      <th><button type="button" name="add" class="btn btn-success btn-sm add">ADD</button></th>
    </tr>
  </table>
</div></code>```

Body:
I have problem when adding input dynamically with thousand separator,
when I click add and the input form appears.
it should be when I type the number it will be arranged in thousand separator.
Please help me

$(document).ready(function(){
 $(document).on('click', '.add', function(){
  var html = '';
  html += '
';
  html += '<input type="text" name="item_name[]" class="form-control inputnumber" onkeypress="return event.keyCode > 47 && event.keyCode < 58 || event.keyCode == 46" />	';
  html += '
';
  $('#item_table').append(html);
 });

$('input.inputnumber').keyup(function(event) {
  if (event.which >= 37 && event.which <= 40) return;
  $(this).val(function(index, value) {
    return value
      // Keep only digits and decimal points:
      .replace(/[^\d.]/g, "")
      // Remove duplicated decimal point, if one exists:
      .replace(/^(\d*\.)(.*)\.(.*)$/, '$1$2$3')
      // Keep only two digits past the decimal point:
      .replace(/\.(\d{2})\d+/, '.$1')
      // Add thousands separators:
      .replace(/\B(?=(\d{3})+(?!\d))/g, ",")
  });
});
});

       <button type="button" name="add" class="btn btn-success btn-sm add">ADD</button>

Body:
I would use the Intl.NumberFormat() constructor. You can find the docs and all the different options here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat

In the snippet below, you will see the formatting change as you type. If you add in text, it will just delete out the text. If you add in a second decimal, it won't do anything at first
I've forgotten most of the jQuery I once knew, so I wrote the snippet in Vanilla JS. I included comments on each line to explain the step.

const table = document.querySelector(`#item_table`);

// Add an event listener to the button in the form
table.querySelector(`button`).addEventListener(`click`, function() {

  // Create a <tr> element
  const tr = document.createElement(`tr`);

  // Create a <td> element
  const td = document.createElement(`td`);

  // Create an <input> element
  const inpt = document.createElement(`input`);

  // Add the input attributes
  inpt.type = `text`;
  inpt.classList.add(`form-control`);
  inpt.classList.add(`inputnumber`);

  // Add an event listener to the input element
  inpt.addEventListener(`keyup`, function(event) {
    // Current string value of the input
    const value = this.value;

    // Split the value string into an array on each decimal and
    // count the number of elements in the array
    const decimalCount = value.split(`.`).length - 1;

    // Don't do anything if a first decimal is entered
    if (event.key === `.` && decimalCount === 1) return

    // Remove any commas from the string and convert to a float
    // This will remove any non digit characters and second decimals
    const numericVal = parseFloat(value.replace(/,/g, ''));

    //NumberFormat options
    const options = {
      style: `decimal`,
      maximumFractionDigits: 20,
    };

    // Assign the formatted number to the input box
    this.value = new Intl.NumberFormat(`en-US`, options).format(numericVal);
  })
  // Append the input to the td
  td.append(inpt);

  // Append the td to the tr
  tr.append(td);

  // Append the tr to the table
  table.append(tr);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="table-repsonsive">
  <table class="table table-bordered" id="item_table">
    <tr>
      <th><button type="button" name="add" class="btn btn-success btn-sm add">ADD</button></th>
    </tr>
  </table>
</div>