问:
Getting script component from a clicked object
I'm trying to get the script component of an object once it has been clicked by a player, then run a specific function from the script when clicked. What I want to go is ether find the script based of the clicked objects name, or just a general way of getting scripts without the class name as it changes with each script. I've looked for way to do both but none work. I may just be implementing it bad so would love some help.</p>

答:
It really depends on what type of objects you want to catch the clicks. If it’s 2d images, make sure you have RaycastTarget bool checked and use IPointerDownHandler interface.

If you gonna do it with 3d objects, then you should add some collider component to them and than make a raycast from camera view every time player clicks.

Get the ray from camera view - https://docs.unity3d.com/ScriptReference/Camera.ScreenPointToRay.html

Check the raycast with existing ray, putting the result to array - https://docs.unity3d.com/ScriptReference/Physics.Raycast.html

Better use separate layer for your objects so you can filter them among others

Use TryGetComponent to check if collision object has your target component - https://docs.unity3d.com/ScriptReference/GameObject.TryGetComponent.html

This way is more complicated than “OnMouseDown” event, but it is more reliable and debuggable, and also it fits perfectly for good common game architectures, unlike OnMouseDown event


来源: stackexchange

问:
Is there a simpler version of renaming columns with alternating patterns? Or tidyverse methods?

My Data

So I have a data frame that I am working with below:

```<code>structure(list(V1 = c(3L, 3L, 3L, 2L, 4L, 1L), V2 = c(1L, 1L,
1L, 1L, 1L, 1L), V3 = c(2L, 2L, 2L, 1L, 3L, 2L), V4 = c(2L, 2L,
3L, 1L, 1L, 1L), V5 = c(3L, 3L, 4L, 1L, 3L, 3L), V6 = c(3L, 3L,
4L, 3L, 3L, 3L), V7 = c(2L, 2L, 1L, 1L, 3L, 3L), V8 = c(3L, 3L,
4L, 4L, 3L, 3L), V9 = c(3L, 3L, 3L, 2L, 3L, 3L), V10 = c(2L,
2L, 1L, 1L, 1L, 1L)), row.names = c(NA, 6L), class = "data.frame")
</code>```

It looks like this:

```<code> V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1  3  1  2  2  3  3  2  3  3   2
2  3  1  2  2  3  3  2  3  3   2
3  3  1  2  3  4  4  1  4  3   1
4  2  1  1  1  1  3  1  4  2   1
5  4  1  3  1  3  3  3  3  3   1
6  1  1  2  1  3  3  3  3  3   1
</code>```

Solution So Far

The best code I have come up with for renaming the variables quickly is this:

```<code>new_names <- outer("cope",
                   1:10,
                   paste,
                   sep="_")
names(data1) <- new_names
data1
</code>```

Which gives me this data frame:

```<code>  cope_1 cope_2 cope_3 cope_4 cope_5 cope_6 cope_7 cope_8 cope_9 cope_10
1      3      1      2      2      3      3      2      3      3       2
2      3      1      2      2      3      3      2      3      3       2
3      3      1      2      3      4      4      1      4      3       1
4      2      1      1      1      1      3      1      4      2       1
5      4      1      3      1      3      3      3      3      3       1
6      1      1      2      1      3      3      3      3      3       1
</code>```

Question

While this serves my purpose well enough, it has made me consider two questions for the future. First, is there a way to simplify the code down in order to make it one line? I was thinking something that worked within dplyr if possible because that is what I am most accustomed to working with.

Second, I foresee issues on the horizon if there are, say, 30 variables, with some having repeating patterns and some being unique. What is the most economical use of time when renaming variables like these? I know rep is one option, but I am only aware of how it can repeat but not separate values into multiple patterns. I'm thinking along the lines of something like this, which would be easier to write with some kind of pattern and stops:

```<code>names <- c("v1","v2","v3","c1","c2","c3","u","p","z1","z2")
</code>```

For example:

```<code>names <- c("v1","v2","v3","c1","c2","c3","u","p","z1","z2")
colnames(data1) <- names
data1

  v1 v2 v3 c1 c2 c3 u p z1 z2
1   3  1  2  2  3  3 2 3  3  2
2   3  1  2  2  3  3 2 3  3  2
3   3  1  2  3  4  4 1 4  3  1
4   2  1  1  1  1  3 1 4  2  1
5   4  1  3  1  3  3 3 3  3  1
6   1  1  2  1  3  3 3 3  3  1
7   3  1  3  1  3  2 2 2  3  2
8   3  2  1  2  3  2 3 3  2  1
9   3  2  4  1  2  4 2 3  4  1
10  4  2  4  2  3  4 3 3  4  1
</code>```

This is time-consuming if you spell it out manually:

```<code>names <- c("cope_1", "cope_2","cope_3","sad_1","sad_2","sad_3","u","p","zip_1","zip_2")
colnames(data1) <- names
data1
</code>```

Which does get you what you want, yet slowly:

```<code>  cope_1 cope_2 cope_3 sad_1 sad_2 sad_3 u p zip_1 zip_2
1      3      1      2     2     3     3 2 3     3     2
2      3      1      2     2     3     3 2 3     3     2
3      3      1      2     3     4     4 1 4     3     1
4      2      1      1     1     1     3 1 4     2     1
5      4      1      3     1     3     3 3 3     3     1
6      1      1      2     1     3     3 3 3     3     1
</code>```

And something like outer doesnt seem to fit here:

```<code>outer("cope",
      1:3,
      paste,
      sep="_",
      "sad",
      1:3,
      paste,
      sep="_",
      "u",
      "p")
</code>```

So if there is a better way of naming chunks of variables like this, that would be great to know.

ContentLicense: CC BY-SA 4.0

Body:
My Data

So I have a data frame that I am working with below:

structure(list(V1 = c(3L, 3L, 3L, 2L, 4L, 1L), V2 = c(1L, 1L,
1L, 1L, 1L, 1L), V3 = c(2L, 2L, 2L, 1L, 3L, 2L), V4 = c(2L, 2L,
3L, 1L, 1L, 1L), V5 = c(3L, 3L, 4L, 1L, 3L, 3L), V6 = c(3L, 3L,
4L, 3L, 3L, 3L), V7 = c(2L, 2L, 1L, 1L, 3L, 3L), V8 = c(3L, 3L,
4L, 4L, 3L, 3L), V9 = c(3L, 3L, 3L, 2L, 3L, 3L), V10 = c(2L,
2L, 1L, 1L, 1L, 1L)), row.names = c(NA, 6L), class = "data.frame")

It looks like this:

 V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1  3  1  2  2  3  3  2  3  3   2
2  3  1  2  2  3  3  2  3  3   2
3  3  1  2  3  4  4  1  4  3   1
4  2  1  1  1  1  3  1  4  2   1
5  4  1  3  1  3  3  3  3  3   1
6  1  1  2  1  3  3  3  3  3   1

Solution So Far

The best code I have come up with for renaming the variables quickly is this:

new_names <- outer("cope",
                   1:10,
                   paste,
                   sep="_")
names(data1) <- new_names
data1

Which gives me this data frame:

  cope_1 cope_2 cope_3 cope_4 cope_5 cope_6 cope_7 cope_8 cope_9 cope_10
1      3      1      2      2      3      3      2      3      3       2
2      3      1      2      2      3      3      2      3      3       2
3      3      1      2      3      4      4      1      4      3       1
4      2      1      1      1      1      3      1      4      2       1
5      4      1      3      1      3      3      3      3      3       1
6      1      1      2      1      3      3      3      3      3       1

Question

While this serves my purpose well enough, it has made me consider two questions for the future. First, is there a way to simplify the code down in order to make it one line? I was thinking something that worked within dplyr if possible because that is what I am most accustomed to working with.

Second, I foresee issues on the horizon if there are, say, 30 variables, with some having repeating patterns and some being unique. What is the most economical use of time when renaming variables like these? I know rep is one option, but I am only aware of how it can repeat but not separate values into multiple patterns. I'm thinking along the lines of something like this, which would be easier to write with some kind of pattern and stops:

names <- c("v1","v2","v3","c1","c2","c3","u","p","z1","z2")

For example:

names <- c("v1","v2","v3","c1","c2","c3","u","p","z1","z2")
colnames(data1) <- names
data1

  v1 v2 v3 c1 c2 c3 u p z1 z2
1   3  1  2  2  3  3 2 3  3  2
2   3  1  2  2  3  3 2 3  3  2
3   3  1  2  3  4  4 1 4  3  1
4   2  1  1  1  1  3 1 4  2  1
5   4  1  3  1  3  3 3 3  3  1
6   1  1  2  1  3  3 3 3  3  1
7   3  1  3  1  3  2 2 2  3  2
8   3  2  1  2  3  2 3 3  2  1
9   3  2  4  1  2  4 2 3  4  1
10  4  2  4  2  3  4 3 3  4  1

This is time-consuming if you spell it out manually:

names <- c("cope_1", "cope_2","cope_3","sad_1","sad_2","sad_3","u","p","zip_1","zip_2")
colnames(data1) <- names
data1

Which does get you what you want, yet slowly:

  cope_1 cope_2 cope_3 sad_1 sad_2 sad_3 u p zip_1 zip_2
1      3      1      2     2     3     3 2 3     3     2
2      3      1      2     2     3     3 2 3     3     2
3      3      1      2     3     4     4 1 4     3     1
4      2      1      1     1     1     3 1 4     2     1
5      4      1      3     1     3     3 3 3     3     1
6      1      1      2     1     3     3 3 3     3     1

And something like outer doesnt seem to fit here:

outer("cope",
      1:3,
      paste,
      sep="_",
      "sad",
      1:3,
      paste,
      sep="_",
      "u",
      "p")

So if there is a better way of naming chunks of variables like this, that would be great to know.

Body:
One solution could be this:

library(dplyr)

df %>%
  setNames(paste0("cope_", seq_len(ncol(df))))

  cope_1 cope_2 cope_3 cope_4 cope_5 cope_6 cope_7 cope_8 cope_9 cope_10
1      3      1      2      2      3      3      2      3      3       2
2      3      1      2      2      3      3      2      3      3       2
3      3      1      2      3      4      4      1      4      3       1
4      2      1      1      1      1      3      1      4      2       1
5      4      1      3      1      3      3      3      3      3       1
6      1      1      2      1      3      3      3      3      3       1


问:
Do I need to create a model for a table I'm inserting through sqlalchemy in django?
I have a Command class that runs an api call to a coin market cap api and writes it into the database that I have rigged up to my django project called cryptographicdatascience. The table that the data is written to is called apis_cmc and is not defined in my models.py.

My question is if I am writing straight to a table using sqlalchemy do I need to go in and create a model for the same table in my models.py file?

It seems to me that the answer is no but I'm sure there is something I'm overlooking.

Thanks,
Justin

答:
No, there is no need to create table in models.py as it is not a part of a Django ORM.

But have in mind, that Django ORM won't know about your table and won't store any data in migration files. It can cause some problems on deploy stage or when you move to other working machine.


问:
Is there a way to evaluate a formula that is stored in a cell?
In a Google Docs spreadsheet, I'm looking for something like =EVAL(A1) where A1 is set to "=1+2".

I found out that in MS Excel there is an EVALUATE() function (which seems a bit tricky to use properly). But I could not find anything similar in Google Docs.

I also searched through the function list, but could not find anything helpful...

答:
It's a bit of a hack, but this works

get the formula from the cell;

set the formula back again; then

get the value from the cell.

var cell = sheet.getRange("A1");
var formula = cell.getFormula();

cell.setFormula(formula);
var fileCell = cell.getValue();
```


问:
How to remove rows with same id in different data frames?
```<code>df1
   id value
1  1    10
2  2    20
3  3    30
4  4    40
5  5    50

df2
   id value
1  2    25
2  3    35

I would like to have the following df3:

df3
   id value
1  1    10
2  4    40
3  5    50
</code>```

In other words, I would like to remove only the same ID between df1 and df2. How could I do that?

答:
You can use

df1[!df1$id %in% df2$id, ]
#>   id value
#> 1  1    10
#> 4  4    40
#> 5  5    50
```
<hr />
<p><strong>reproducible data from question</strong></p>
<pre class="lang-r prettyprint-override"><code>df1 <- data.frame(id = 1:5, value = 10 * (1:5))
df2 <- data.frame(id = 2:3, value = c(25, 35))
</code>```

Body:
df1
   id value
1  1    10
2  2    20
3  3    30
4  4    40
5  5    50

df2
   id value
1  2    25
2  3    35

I would like to have the following df3:

df3
   id value
1  1    10
2  4    40
3  5    50

In other words, I would like to remove only the same ID between df1 and df2. How could I do that?

Body:
You can use

df1[!df1$id %in% df2$id, ]
#>   id value
#> 1  1    10
#> 4  4    40
#> 5  5    50

reproducible data from question

df1 <- data.frame(id = 1:5, value = 10 * (1:5))
df2 <- data.frame(id = 2:3, value = c(25, 35))


问:
Wordpress get new post permalink title
So I want to get the permalink title of a new published post.
example "http://myblog.com/healthy-life.php" I need healthy-life.php

here is code I have but it gets me http://myblog.com/healthy-life.php

```<code>function get_laterst_post_url() {
  global $wpdb;
  $query = "SELECT ID FROM {$wpdb->prefix}posts WHERE post_type='post' AND post_status='publish' ORDER BY post_date DESC LIMIT 1;";
  $result = $wpdb->get_results($query);
  if(is_object($result[0])) {
    return get_permalink($result[0]->ID);
  } else {
    return '';
  };
}
</code>```

答:
You could add:

```<code>$url = get_bloginfo('wpurl') . "/";
$permalink_title = str_replace($url, "", get_permalink($result[0]->ID));
return $permalink_title;
</code>```

But its always best to use wordpress functions to get links. Say:

```<code>function get_laterst_post_url() {

$args = array(
'numberposts' => 1,
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish',
'suppress_filters' => true );

$recent_posts = wp_get_recent_posts();

$url = get_bloginfo('wpurl') . "/";
$permalink_title = str_replace($url, "", get_permalink($recent_posts[0]["ID"]));
return $permalink_title;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Wordpress get new post permalink title

Body:
So I want to get the permalink title of a new published post.
example "http://myblog.com/healthy-life.php" I need healthy-life.php

here is code I have but it gets me http://myblog.com/healthy-life.php

function get_laterst_post_url() {
  global $wpdb;
  $query = "SELECT ID FROM {$wpdb->prefix}posts WHERE post_type='post' AND post_status='publish' ORDER BY post_date DESC LIMIT 1;";
  $result = $wpdb->get_results($query);
  if(is_object($result[0])) {
    return get_permalink($result[0]->ID);
  } else {
    return '';
  };
}

Body:
You could add:

$url = get_bloginfo('wpurl') . "/";
$permalink_title = str_replace($url, "", get_permalink($result[0]->ID));
return $permalink_title;

But its always best to use wordpress functions to get links. Say:

function get_laterst_post_url() {

$args = array(
'numberposts' => 1,
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish',
'suppress_filters' => true );

$recent_posts = wp_get_recent_posts();

$url = get_bloginfo('wpurl') . "/";
$permalink_title = str_replace($url, "", get_permalink($recent_posts[0]["ID"]));
return $permalink_title;
}


问:
How can I stop dark mode from messing up how my app looks?
I am a student trying to learn app development with android studio. For my first project, im just building a basic calculator app. I have stumbled across a problem that I couldnt solve and didnt find a helpfull post about. It occurs when I trun on dark mode on the virtual device. Here are 2 pictures showing what happens.

How it looks with dark mode

How it is supposed to look

My activity_main.xml consists of some buttons that all have the same style and a TextView.
I left all the other files untouched. Id love some advice on how to fix this. Thanks for reading!

答:
You are most likely using the following default DayNight theme in your themes.xml file (values/themes/themes.xml)

```<code><style name="Theme.MyApp" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
</code>```

If you don't want things to change in night mode, you can change that to use the Light theme instead

```<code><style name="Theme.MyApp" parent="Theme.MaterialComponents.Light.DarkActionBar">
</code>```

and delete the themes.xml (night) file if it exists. There is some extra info about these options here

Body:
You are most likely using the following default DayNight theme in your themes.xml file (values/themes/themes.xml)

<style name="Theme.MyApp" parent="Theme.MaterialComponents.DayNight.DarkActionBar">

If you don't want things to change in night mode, you can change that to use the Light theme instead

<style name="Theme.MyApp" parent="Theme.MaterialComponents.Light.DarkActionBar">

and delete the themes.xml (night) file if it exists. There is some extra info about these options here


问:
How does Firestore count reads as it relates to the Provider package in Flutter?
When I call:

```<code>final user = Provider.of<CustomUser?>(context);
</code>```

downstream of My Provider and then call for example user.email... Does that count as a 'Read'?

For further Context when I log in I call ('Read' 1?):

```<code>Future signIn(String email, String password) async {
    await _authService.signInWithEmailAndPassword(
        email: email, password: password);
    print('Sign In');
    User? user = _authService.currentUser;
</code>```

And then I call ('Read' 2?):

```<code>CustomUser loggedInUser = CustomUser();
    await FirebaseFirestore.instance
        .collection("users")
        .doc(user!.uid)
        .get()
        .then((value) {
      loggedInUser = CustomUser.fromMap(value.data());
    });
</code>```

where I map the user info from my firestore collection to my CustomUser object.  I then pass the CustomUser through a stream provider (which I think I'm going to change to Change Notifier Provider, but that should be irrelevant for this question...):

```<code>Widget build(BuildContext context) {
    return StreamProvider<CustomUser?>.value(
      value: AuthService().user,
      initialData: null,
      child: MaterialApp(
        home: Home()
</code>```

I then call inside of Home:

```<code>final user = Provider.of<CustomUser?>(context);
</code>```

and populate some text widgets with user.email, user.name, etc...  Does that count as a read as well?  In other words, does the above logic count as 2 or 3 reads to firebase?

答:
Every time you call get() the Firestore SDK will have to connect to the server to at the very least check if there's a newer version of the document. This is a charged document read.

I recommend looking into onSnapshot, which keeps an active listener on the document, so will only have to check with the server once when you create the listener, and then only gets an updated document (and thus a charged document read) when there is an update.

Body:
When I call:

final user = Provider.of<CustomUser?>(context);

downstream of My Provider and then call for example user.email... Does that count as a 'Read'?

For further Context when I log in I call ('Read' 1?):

Future signIn(String email, String password) async {
    await _authService.signInWithEmailAndPassword(
        email: email, password: password);
    print('Sign In');
    User? user = _authService.currentUser;

And then I call ('Read' 2?):

CustomUser loggedInUser = CustomUser();
    await FirebaseFirestore.instance
        .collection("users")
        .doc(user!.uid)
        .get()
        .then((value) {
      loggedInUser = CustomUser.fromMap(value.data());
    });

where I map the user info from my firestore collection to my CustomUser object.  I then pass the CustomUser through a stream provider (which I think I'm going to change to Change Notifier Provider, but that should be irrelevant for this question...):

Widget build(BuildContext context) {
    return StreamProvider<CustomUser?>.value(
      value: AuthService().user,
      initialData: null,
      child: MaterialApp(
        home: Home()

I then call inside of Home:

final user = Provider.of<CustomUser?>(context);

and populate some text widgets with user.email, user.name, etc...  Does that count as a read as well?  In other words, does the above logic count as 2 or 3 reads to firebase?


问:
'BOT' is not recognized as an internal command or external command, an executable program or a command file
I'm trying to run a discord bot that I found on GitHub. I use Windows, the program uses Docker, Node, and maybe some other things I'm not aware of.

When I run the program with "node start-bots.js", cmd gives me an error:

'BOT' is not recognized as an internal command or external command, an executable program or a command file.

I tried many things but nothing works...

Here is the code of the start-bot.js :

```<code>const exec = require('child_process').exec;
const bots = require('./bots.json');

const recreate = () => {

    console.log(` Checking existing volumes...`);

    exec(`docker volume ls -q`, (err, stdout, stderr) => {

        const volumes = stdout.split('\n');

        bots.forEach((bot) => {
            console.log(` Starting ${bot.name}...`);

            const start = () => {
                exec(`BOT=${bot.name} VINTED_BOT_ADMIN_IDS=${bot.adminIDs}
VINTED_BOT_TOKEN=${bot.token} docker-compose -f docker-compose.yaml -p
bot-${bot.name} up -d`, (err, stdout, stderr) => {
                    if (err) {
                        console.error(` ${bot.name} failed to start.`);
                        console.error(err);
                        return;
                    }
                    console.log(stderr);
                });
        }

        if (volumes.includes(`bot-${bot.name}`)) {
            console.log(` ${bot.name} database has been recovered!`);
            start();
        } else {
            exec(`docker volume create bot-${bot.name}`, (err, stdout, stderr) => {
                if (!err) {
                    console.log(` ${bot.name} database has been created!`);
                    start();
                } else console.error(err);
            });
        }

    });

});

};

const restart = process.argv.includes('-restart');

if (restart) {
    console.log(' Shutting down all bots...');
    bots.forEach((bot) => {
        exec(`docker-compose -p bot-${bot.name} stop`, (err, stdout, stderr) => {
            if (!err) {
                exec(`docker-compose -p bot-${bot.name} rm -f`, (err, stdout, stderr) => {
                    if (!err) {
                        console.log(` Bot ${bot.name} has been shut down and
removed.`);
                    } else {
                        console.log(` Failed to remove containers for bot
${bot.name}`);
                    }
                });
            }
        });
    });
} else {
    recreate();
}
</code>```

and and docker-compose.yaml :

```<code>version: '3.8'

services:

  vinted-discord-bot:
    image: vinted-discord-bot:3.17
    environment:
      VINTED_BOT_ADMIN_IDS: "${VINTED_BOT_ADMIN_IDS}"
      VINTED_BOT_TOKEN: "${VINTED_BOT_TOKEN}"
      POSTGRES_DB: vinted_bot
      POSTGRES_USER: root
      POSTGRES_PASSWORD: password
    restart: always
    depends_on:
      - postgres

  postgres:
    image: postgres:14.1
    healthcheck:
      test: [ "CMD", "pg_isready", "-q", "-d", "postgres", "-U", "root" ]
      timeout: 45s
      interval: 10s
      retries: 10
    restart: always
    environment:
      POSTGRES_USER: root
      POSTGRES_PASSWORD: password
    volumes:
      - pgdata:/var/lib/postgresql/data

volumes:
  pgdata:
    external:
     name: bot-${BOT}
</code>```

and finally the bots.json :

```<code>[
    {
    "name": "thenameofthebot",
    "token": "thetokenofthebot",
    "adminIDs": "theidoftheadminserver"
    }
]
</code>```

Here is a screen of the error (in French):

You can find it on: https://github.com/Androz2091/vinted-discord-bot.

答:
You need to make a binary for your program. In Node.js, you can create a binary in package.json.

Step 1: In your main file, you need to add a shebang (#!), and /usr/bin/env node after that. Important! This must be on the very first line of your main file.

#!/usr/bin/env node
```
<p><strong>Step 2:</strong> In your <code>package.json</code> file, add the following two keys, replacing <code>index.js</code> with your own main file.</p>
<pre class="lang-json prettyprint-override"><code>{
  "main": "index.js",
  "bin": {
    "BOT": "./index.js"
  },
}
</code>```

Step 3: Run the following command to apply it to your computer.

```<code>npm link
</code>```

EDIT: If the above command doesn't work, run the following command.

```<code>npm install -g .
</code>```

And that's it! It should work when you run the following command.

```<code>BOT
</code>```

Body:
I'm trying to run a discord bot that I found on GitHub. I use Windows, the program uses Docker, Node, and maybe some other things I'm not aware of.

When I run the program with "node start-bots.js", cmd gives me an error:

'BOT' is not recognized as an internal command or external command, an executable program or a command file.

I tried many things but nothing works...

Here is the code of the start-bot.js :

const exec = require('child_process').exec;
const bots = require('./bots.json');

const recreate = () => {

    console.log(` Checking existing volumes...`);

    exec(`docker volume ls -q`, (err, stdout, stderr) => {

        const volumes = stdout.split('\n');

        bots.forEach((bot) => {
            console.log(` Starting ${bot.name}...`);

            const start = () => {
                exec(`BOT=${bot.name} VINTED_BOT_ADMIN_IDS=${bot.adminIDs}
VINTED_BOT_TOKEN=${bot.token} docker-compose -f docker-compose.yaml -p
bot-${bot.name} up -d`, (err, stdout, stderr) => {
                    if (err) {
                        console.error(` ${bot.name} failed to start.`);
                        console.error(err);
                        return;
                    }
                    console.log(stderr);
                });
        }

        if (volumes.includes(`bot-${bot.name}`)) {
            console.log(` ${bot.name} database has been recovered!`);
            start();
        } else {
            exec(`docker volume create bot-${bot.name}`, (err, stdout, stderr) => {
                if (!err) {
                    console.log(` ${bot.name} database has been created!`);
                    start();
                } else console.error(err);
            });
        }

    });

});

};

const restart = process.argv.includes('-restart');

if (restart) {
    console.log(' Shutting down all bots...');
    bots.forEach((bot) => {
        exec(`docker-compose -p bot-${bot.name} stop`, (err, stdout, stderr) => {
            if (!err) {
                exec(`docker-compose -p bot-${bot.name} rm -f`, (err, stdout, stderr) => {
                    if (!err) {
                        console.log(` Bot ${bot.name} has been shut down and
removed.`);
                    } else {
                        console.log(` Failed to remove containers for bot
${bot.name}`);
                    }
                });
            }
        });
    });
} else {
    recreate();
}

and and docker-compose.yaml :

version: '3.8'

services:

  vinted-discord-bot:
    image: vinted-discord-bot:3.17
    environment:
      VINTED_BOT_ADMIN_IDS: "${VINTED_BOT_ADMIN_IDS}"
      VINTED_BOT_TOKEN: "${VINTED_BOT_TOKEN}"
      POSTGRES_DB: vinted_bot
      POSTGRES_USER: root
      POSTGRES_PASSWORD: password
    restart: always
    depends_on:
      - postgres

  postgres:
    image: postgres:14.1
    healthcheck:
      test: [ "CMD", "pg_isready", "-q", "-d", "postgres", "-U", "root" ]
      timeout: 45s
      interval: 10s
      retries: 10
    restart: always
    environment:
      POSTGRES_USER: root
      POSTGRES_PASSWORD: password
    volumes:
      - pgdata:/var/lib/postgresql/data

volumes:
  pgdata:
    external:
     name: bot-${BOT}

and finally the bots.json :

[
    {
    "name": "thenameofthebot",
    "token": "thetokenofthebot",
    "adminIDs": "theidoftheadminserver"
    }
]

Here is a screen of the error (in French):

You can find it on: https://github.com/Androz2091/vinted-discord-bot.

Body:
You need to make a binary for your program. In Node.js, you can create a binary in package.json.

Step 1: In your main file, you need to add a shebang (#!), and /usr/bin/env node after that. Important! This must be on the very first line of your main file.

#!/usr/bin/env node

Step 2: In your package.json file, add the following two keys, replacing index.js with your own main file.

{
  "main": "index.js",
  "bin": {
    "BOT": "./index.js"
  },
}

Step 3: Run the following command to apply it to your computer.

npm link

EDIT: If the above command doesn't work, run the following command.

npm install -g .

And that's it! It should work when you run the following command.

BOT


问:
Can not find fftw3.h even after adding them to PATH

Basis

I have installed FFTW in my system manually by using ./configure, make commands the procedure mentioned in the website using some flags.

I do thus have fftw3.h header file as can be seen below

locate fftw3.h
/home/anirbankopty/Softwares/FFTW/fftw-3.3.10/api/fftw3.h
/home/anirbankopty/Softwares/FFTW/fftw-install/include/fftw3.h
```
<h2>Problem</h2>
<p>But, still, when compiling my <code>C</code> code using the <code>-lfftw3</code> flag, it says</p>
<pre class="lang-sh prettyprint-override"><code>gcc FFT_denoise.c -lfftw3 -lm
FFT_denoise.c:5:10: fatal error: fftw3.h: No such file or directory
    5 | #include <fftw3.h>
      |          ^~~~~~~~~
compilation terminated.
</code>```

I tried doing in Fortran and also there I am getting

gfortran FFT_denoise.f03 -lfftw3 -lm
/usr/bin/ld: cannot find -lfftw3
collect2: error: ld returned 1 exit status
```

Tried

I Tried adding those fftw3.h path i.e.
/home/anirbankopty/Softwares/FFTW/fftw-install/include/ to the PATH variable, but still the problem persists.

I use zsh shell.

答:
The path to included files belongs in the -I argument to the compiler, not in PATH:

```<code>gcc -I/home/anirbankopty/Softwares/FFTW/fftw-install/include/ FFT_denoise.c -lfftw3 -lm
</code>```

Similarly the path to library files belongs in the -L argument. This will probably the next issue you will face.

Body:
Basis

I have installed FFTW in my system manually by using ./configure, make commands the procedure mentioned in the website using some flags.

I do thus have fftw3.h header file as can be seen below

locate fftw3.h
/home/anirbankopty/Softwares/FFTW/fftw-3.3.10/api/fftw3.h
/home/anirbankopty/Softwares/FFTW/fftw-install/include/fftw3.h

Problem

But, still, when compiling my C code using the -lfftw3 flag, it says

gcc FFT_denoise.c -lfftw3 -lm
FFT_denoise.c:5:10: fatal error: fftw3.h: No such file or directory
    5 | #include <fftw3.h>
      |          ^~~~~~~~~
compilation terminated.

I tried doing in Fortran and also there I am getting

gfortran FFT_denoise.f03 -lfftw3 -lm
/usr/bin/ld: cannot find -lfftw3
collect2: error: ld returned 1 exit status

Tried

I Tried adding those fftw3.h path i.e.
/home/anirbankopty/Softwares/FFTW/fftw-install/include/ to the PATH variable, but still the problem persists.

I use zsh shell.

Body:
The path to included files belongs in the -I argument to the compiler, not in PATH:

gcc -I/home/anirbankopty/Softwares/FFTW/fftw-install/include/ FFT_denoise.c -lfftw3 -lm

Similarly the path to library files belongs in the -L argument. This will probably the next issue you will face.


问:
Migrating U2F to WebAuthn gem in Ruby, where to get the parameters for AuthenticatorAttestationResponse
I have a couple of questions about the WebAuthn gem and the use of U2fMigrator.
I hope someone can point me in the right direction about it.
I am in the step just after converting my old U2F credentials using U2fMigrator.

```<code>migrated_credential = WebAuthn::U2fMigrator.new(
        app_id: my_domain,
        certificate: u2f_registration.certificate,
        key_handle: u2f_registration.key_handle,
        public_key: u2f_registration.binary_public_key,
        counter: u2f_registration.counter
)
</code>```

The documentation says: “U2fMigrator class quacks like WebAuthn::AuthenticatorAttestationResponse” but without verify implementation.

Does that mean I need to create an instance of this AuthenticatorAttestationResponse for authentication?

If so. Where I should get this data from?

```<code>assertion_response = WebAuthn::AuthenticatorAssertionResponse.new(
        credential_id: '',
        authenticator_data: '',
        client_data_json: '',
        signature: '',
 )
</code>```

I am guessing that will allow me to authenticate the new migrated credentials like this:

```<code>assertion_response.verify(
        WebAuthn::Credential.options_for_get(:extensions => { appid: my_domain }).challenge,
        allowed_creadentials: migrated_credential.credential,
        rp_id: my_domain
)
</code>```

And also, I am guessing I don't need to re-register these credentials yet.

I am following this documentation:

https://github.com/cedarcode/webauthn-ruby/blob/master/docs/u2f_migration.md

https://github.com/castle/ruby-u2f

https://github.com/cedarcode/webauthn-ruby/blob/master/README.md#authentication

UPDATE 1

I've found this cool explanation in this guide

I will dig into it and I'll post the solution if I can find it.

UPDATE 2

I've spent the whole week trying to get the authenticatorAssertionResponse

from

Unfortunately, I only get a message saying I don't have a key registered:

I'm passing through the extension and appid where the U2F credential was registered originally. I wonder if it stoped working now the deprecation is complete.

答:
U2fMigrator is instantiated with data that's already stored in your database. Instances of it respond to the same methods as AuthenticatorAttestationResponse, except it misses a verify method since the data was already verified in the past. In other words: the migrator behaves nearly the same as a freshly WebAuthn registered authenticator and it is meant to be used as such.

Does that mean I need to create an instance of this
AuthenticatorAttestationResponse for authentication?

Yes. The AuthenticatorAttestationResponse is instantiated with browser data from the WebAuthn navigator.credentials.get call. This in itself is unrelated to the U2F migration question, except for the part where the data comes from for its verify method. This comes either from a migrator instance (in the "real time conversion" approach) or is retrieved from the database.

Hope that makes sense, PRs welcome to improve the docs!

Body:
I have a couple of questions about the WebAuthn gem and the use of U2fMigrator.
I hope someone can point me in the right direction about it.
I am in the step just after converting my old U2F credentials using U2fMigrator.

migrated_credential = WebAuthn::U2fMigrator.new(
        app_id: my_domain,
        certificate: u2f_registration.certificate,
        key_handle: u2f_registration.key_handle,
        public_key: u2f_registration.binary_public_key,
        counter: u2f_registration.counter
)

The documentation says: “U2fMigrator class quacks like WebAuthn::AuthenticatorAttestationResponse” but without verify implementation.

Does that mean I need to create an instance of this AuthenticatorAttestationResponse for authentication?

If so. Where I should get this data from?

assertion_response = WebAuthn::AuthenticatorAssertionResponse.new(
        credential_id: '',
        authenticator_data: '',
        client_data_json: '',
        signature: '',
 )

I am guessing that will allow me to authenticate the new migrated credentials like this:

assertion_response.verify(
        WebAuthn::Credential.options_for_get(:extensions => { appid: my_domain }).challenge,
        allowed_creadentials: migrated_credential.credential,
        rp_id: my_domain
)

And also, I am guessing I don't need to re-register these credentials yet.

I am following this documentation:

https://github.com/cedarcode/webauthn-ruby/blob/master/docs/u2f_migration.md

https://github.com/castle/ruby-u2f

https://github.com/cedarcode/webauthn-ruby/blob/master/README.md#authentication

UPDATE 1

I've found this cool explanation in this guide

I will dig into it and I'll post the solution if I can find it.

UPDATE 2

I've spent the whole week trying to get the authenticatorAssertionResponse

from

Unfortunately, I only get a message saying I don't have a key registered:

I'm passing through the extension and appid where the U2F credential was registered originally. I wonder if it stoped working now the deprecation is complete.


问:
Can role="rowheader" be used with role="table" or only role="grid"?
I'm a bit confused about the role="rowheader". The specification says this:

"Rowheader can be used as a row header in a table or grid"

but it also says this:

"Authors MUST ensure elements with role rowheader are contained in, or
owned by, an element with the role grid."

My table-like component is of role="table" because it's not interactive, just purely presentational.

https://www.w3.org/TR/wai-aria-1.1/#rowheader

答:
Looks like a typo in the documentation.  While https://www.w3.org/TR/wai-aria-1.1/#rowheader does indeed say:

Authors MUST ensure elements with role rowheader are contained in, or owned by, an element with the role grid.

it really should say the rowheader but be contained in a row, not a grid.  In fact, if your rowheader where a direct child of a grid, it would fail html parsing.

The latest draft version of the doc has this corrected.

https://w3c.github.io/aria/#rowheader

Authors MUST ensure elements with role rowheader are contained in, or owned by, an element with the role row.

Notice in the paragraph prior to the typo, it says:

Rowheader can be used as a row header in a table or grid

It is perfectly valid to use rowheader in both tables and grids.


问:
Shell scripting: intersperse comments between multiline logical operators
I have a multiline conditional like this:

```<code>command1 \
    && command2 \
    && command3
</code>```

This is fine, but I would like to put comments after each command, like this:

```<code>command1 \ # Comment for command 1.
    && command2 \ # Comment for command 2.
    && command3 # Comment for command 3.
</code>```

but the script breaks (in Bash and Zsh) because of a parsing error.

Is there a way to add comments between multiline conditionals?

NOTE: I realize that I could just create a function for each command, and then just add comments to each command in its function definition; but I would like to avoid that if possible.

答:
I use snippets like this in my dotfiles to embed comments in multiline calls:

function e() {
  setsid -f                 $(: "fork into separate session")        \
    emacsclient                                                      \
      --create-frame        $(: "force new gui window")              \
      --alternate-editor='' $(: "launch emacs if daemon is missing") \
      "$@"
}
```

: is the standard shorthand for true, which succeeds while ignoring arguments. This is why $(: "foo") is evaluated to nothing.

Body:
I have a multiline conditional like this:

command1 \
    && command2 \
    && command3

This is fine, but I would like to put comments after each command, like this:

command1 \ # Comment for command 1.
    && command2 \ # Comment for command 2.
    && command3 # Comment for command 3.

but the script breaks (in Bash and Zsh) because of a parsing error.

Is there a way to add comments between multiline conditionals?

NOTE: I realize that I could just create a function for each command, and then just add comments to each command in its function definition; but I would like to avoid that if possible.

Body:
I use snippets like this in my dotfiles to embed comments in multiline calls:

function e() {
  setsid -f                 $(: "fork into separate session")        \
    emacsclient                                                      \
      --create-frame        $(: "force new gui window")              \
      --alternate-editor='' $(: "launch emacs if daemon is missing") \
      "$@"
}

: is the standard shorthand for true, which succeeds while ignoring arguments. This is why $(: "foo") is evaluated to nothing.


问:
Python NotifyChangeEventLog (6, 'NotifyChangeEventLog', 'The handle is invalid.')
This is my code:

```
    import win32evtlog
    import win32event

    SERVER = '192.168.1.221'  # IP of remote PC
    SOURCE_TYPE = 'System'

    def syslogHandler(host, source_type):
        h_log = win32evtlog.OpenEventLog(host, source_type)
        h_evt0 = win32event.CreateEvent(None, True, False, 'evt0')
        win32evtlog.NotifyChangeEventLog(h_log, h_evt0)

    syslogHandler(SERVER, SOURCE_TYPE)
```

It works perfectly fine with localhost, but whenever I try to run this script with other pc IP (e.g '192.168.1.221') it returns

```
    Traceback (most recent call last):
        File "D:\Programming\PyCharm_projects\Test\main.py", line 14, in
            syslogHandler(SERVER, SOURCE_TYPE)
        File "D:\Programming\PyCharm_projects\Test\main.py", line 11, in syslogHandler
            win32evtlog.NotifyChangeEventLog(h_log, h_evt0)
    pywintypes.error: (6, 'NotifyChangeEventLog', 'The handle is invalid.')
```

Without line win32evtlog.NotifyChangeEventLog(h_log, h_evt0) script works perfectly fine.

I can add events = win32evtlog.ReadEventLog(h_log, win32evtlog.EVENTLOG_SEQUENTIAL_READ | win32evtlog.EVENTLOG_FORWARDS_READ, 0) and it returns all events from remote PC.

Both computers are members of domain. Remote PC in this example is Windows Server 2016. Script is run by user with admin privilages(on both local and domain PCs).

答:
It's not possible for remote systems, which makes sense (as if it was, a machine's event log could be easily spammed (by a privileged user from another machine)).

According to [MS.Docs]: NotifyChangeEventLog function (winbase.h) - Remarks (emphasis is mine):

The NotifyChangeEventLog function does not work with remote handles. If the hEventLog parameter is the handle to an event log on a remote computer, NotifyChangeEventLog returns zero, and GetLastError returns ERROR_INVALID_HANDLE.

Body:
This is my code:

    import win32evtlog
    import win32event

    SERVER = '192.168.1.221'  # IP of remote PC
    SOURCE_TYPE = 'System'

    def syslogHandler(host, source_type):
        h_log = win32evtlog.OpenEventLog(host, source_type)
        h_evt0 = win32event.CreateEvent(None, True, False, 'evt0')
        win32evtlog.NotifyChangeEventLog(h_log, h_evt0)

    syslogHandler(SERVER, SOURCE_TYPE)

It works perfectly fine with localhost, but whenever I try to run this script with other pc IP (e.g '192.168.1.221') it returns

    Traceback (most recent call last):
        File "D:\Programming\PyCharm_projects\Test\main.py", line 14, in
            syslogHandler(SERVER, SOURCE_TYPE)
        File "D:\Programming\PyCharm_projects\Test\main.py", line 11, in syslogHandler
            win32evtlog.NotifyChangeEventLog(h_log, h_evt0)
    pywintypes.error: (6, 'NotifyChangeEventLog', 'The handle is invalid.')

Without line win32evtlog.NotifyChangeEventLog(h_log, h_evt0) script works perfectly fine.

I can add events = win32evtlog.ReadEventLog(h_log, win32evtlog.EVENTLOG_SEQUENTIAL_READ | win32evtlog.EVENTLOG_FORWARDS_READ, 0) and it returns all events from remote PC.

Both computers are members of domain. Remote PC in this example is Windows Server 2016. Script is run by user with admin privilages(on both local and domain PCs).


问:
Javascript Timer Counter start again for every page reload
I build a timer to count Daily working time of employee. It is completely working fine until i refresh the page. I have three button clock in, stop, clock out. It should counting the time until I press the clock out button. What should I do in this case? I am not good with javascript so if anyone would love to help me, it would be great.

```<code>                       <form method="post" id="work-hour" action="">
                                {% csrf_token %}
                                <div class="card" id="holidays">
                                    <div class="card-header">
                                        <h5>Work Timer and Weekly Work History</h5>
                                        <div id="timeDiv"></div>
                                        <br>
                                        <button id="startBtn" class="btn btn-outline-success Btn">Clock In</button>
                                        <!-- <button id="" class="Btn btn btn-outline-primary">Take a break</button> -->
                                        <button id="stopBtn" class="btn btn-outline-warning Btn">Stop</button>
                                        <input type="text" hidden id="total_time_hour"  />
                                        <input type="text" hidden id="total_time_minute" />
                                        <input value="Clock Out" type="submit" id="submit" />                                    </div>

                                     </div>

                       </form>
</code>```

javascript

```<code></script>
const csrftoken = getCookie('csrftoken');

        // include "are you sure" before reset

            var timeNow = {
            h: 0,
            m: 0,
            s: 0
            };

            function startTimer() {
            // start the timer

            counting = true;
            $('#stopBtn').prop("disabled", "");
            $('#startBtn').prop("disabled", "true");
            $('#resetBtn').prop("disabled", "true");
            $('#submit').prop("disabled", "true");

            countInterval = setInterval(count, 1000);
            }

            function stopTimer() {
            // stop the timer, but ask to confirm first
            if (!(areYouSure())) { return; }
            clearInterval(countInterval);
            var total_time = timeNow;
            console.log(total_time);
            $('#total_time_hour').val(timeNow.h)
            $('#total_time_minute').val(timeNow.m)

            //timeNow.h = 0;
            //timeNow.m = 0;
            //timeNow.s = 0;

            showTime();
            $('#startBtn').prop("disabled", "");
            $('#stopBtn').prop("disabled", "true");
            $('#resetBtn').prop("disabled", "");
            $('#submit').prop("disabled", "");

            }

            function areYouSure() {
            // let user confirm before stopping timer
            var sure = confirm("Are you sure you want to take a break?");
            return sure;
            }

            function showTime() {
            // put h/m/s together for display
            var hr, min, sec;
            if (timeNow.h < 1) {
            hr = "";
            }
            else {
            hr = "" + timeNow.h + ":";
            }
            if (timeNow.m < 1) {
            min = "00:";
            }
            else {
            if (timeNow.m < 10) {
            min = "" + "0" + timeNow.m + ":";
            }
            else {
            min = timeNow.m + ":";
            }
            }
            if (timeNow.s < 10) {
            sec = "" + "0" + timeNow.s;
            }
            else {
            sec = timeNow.s;
            }
            $('#timeDiv').html(hr + min + sec);
            }

            function count(){
            // increment the timer by 1s
            timeNow.s++;
            if (timeNow.s > 59) {
            timeNow.m++;
            timeNow.s = 0;
            }
            if (timeNow.m > 59) {
            timeNow.h++;
            timeNow.m = 0;
            }
            showTime();

            }

            function resetTimer() {
            // reset timer back to 0 after confirming
            if (!(areYouSure())) { return; }
            var total_time = timeNow;
            $('#total_time_hour').val(timeNow.h)
            $('#total_time_minute').val(timeNow.m)

            timeNow.h = 0;
            timeNow.m = 0;
            timeNow.s = 0;
            $('#resetBtn').prop("disabled", "true");
            $('#submit').prop("disabled", "true");
            showTime();
        }

        function submitTimer() {
            // reset timer back to 0 after confirming
            timeNow.h = 0;
            timeNow.m = 0;
            timeNow.s = 0;
            showTime();

        }

            $(document).ready(function() {
            showTime();
            $('#startBtn').click(function() { startTimer(); });
            $('#stopBtn').click(function() { stopTimer(); });
            $('#resetBtn').click(function() { resetTimer(); });
            $('#submit').click(function() { submitTimer(); });
            $('#stopBtn').prop("disabled", "true");
            $('#submit').prop("disabled", "true");
            $('#resetBtn').prop("disabled", "true");
            });

// add days?

        $(document).on('submit', '#work-hour', function(e){
            e.preventDefault();
            $.ajax({
                type:'POST',
                headers: {"X-CSRFToken": csrftoken},
                url: '/account/work/created/',
                data:{
                    total_time_hour: $('#total_time_hour').val(),
                    total_time_minute: $('#total_time_minute').val(),
                },
                success:function(){
                }
            });
        })

    </script>
</code>```

答:
Maybe you can storage last starter Date in localstorage.

Using localStorage allows save the data even you lost the browser session or reload the page.

```<code>function starterTime(){
  let lastTimeInit = localStorage.getItem('lastTimeInit');

  if(!lastTimeInit){
     lastTimeInit = new Date();
     localStorage.setItem('lastTimeInit', lastTimeInit)
  }else{
    lastTimeInit = new Date(lastTimeInit);
  }

  // calculates diff between lastTimeInit and now. Then calls count([resultHere])
</code>```

}

You can do the same effect with cookies, but they have expiration.

But I think you can get better performance and "more clean coding" using moment.js

Body:
I build a timer to count Daily working time of employee. It is completely working fine until i refresh the page. I have three button clock in, stop, clock out. It should counting the time until I press the clock out button. What should I do in this case? I am not good with javascript so if anyone would love to help me, it would be great.

                       <form method="post" id="work-hour" action="">
                                {% csrf_token %}

Work Timer and Weekly Work History

                                        <button id="startBtn" class="btn btn-outline-success Btn">Clock In</button>

                                        <button id="stopBtn" class="btn btn-outline-warning Btn">Stop</button>
                                        <input type="text" hidden id="total_time_hour"  />
                                        <input type="text" hidden id="total_time_minute" />
                                        <input value="Clock Out" type="submit" id="submit" />

                       </form>

javascript

</script>
const csrftoken = getCookie('csrftoken');

        // include "are you sure" before reset

            var timeNow = {
            h: 0,
            m: 0,
            s: 0
            };

            function startTimer() {
            // start the timer

            counting = true;
            $('#stopBtn').prop("disabled", "");
            $('#startBtn').prop("disabled", "true");
            $('#resetBtn').prop("disabled", "true");
            $('#submit').prop("disabled", "true");

            countInterval = setInterval(count, 1000);
            }

            function stopTimer() {
            // stop the timer, but ask to confirm first
            if (!(areYouSure())) { return; }
            clearInterval(countInterval);
            var total_time = timeNow;
            console.log(total_time);
            $('#total_time_hour').val(timeNow.h)
            $('#total_time_minute').val(timeNow.m)

            //timeNow.h = 0;
            //timeNow.m = 0;
            //timeNow.s = 0;

            showTime();
            $('#startBtn').prop("disabled", "");
            $('#stopBtn').prop("disabled", "true");
            $('#resetBtn').prop("disabled", "");
            $('#submit').prop("disabled", "");

            }

            function areYouSure() {
            // let user confirm before stopping timer
            var sure = confirm("Are you sure you want to take a break?");
            return sure;
            }

            function showTime() {
            // put h/m/s together for display
            var hr, min, sec;
            if (timeNow.h < 1) {
            hr = "";
            }
            else {
            hr = "" + timeNow.h + ":";
            }
            if (timeNow.m < 1) {
            min = "00:";
            }
            else {
            if (timeNow.m < 10) {
            min = "" + "0" + timeNow.m + ":";
            }
            else {
            min = timeNow.m + ":";
            }
            }
            if (timeNow.s < 10) {
            sec = "" + "0" + timeNow.s;
            }
            else {
            sec = timeNow.s;
            }
            $('#timeDiv').html(hr + min + sec);
            }

            function count(){
            // increment the timer by 1s
            timeNow.s++;
            if (timeNow.s > 59) {
            timeNow.m++;
            timeNow.s = 0;
            }
            if (timeNow.m > 59) {
            timeNow.h++;
            timeNow.m = 0;
            }
            showTime();

            }

            function resetTimer() {
            // reset timer back to 0 after confirming
            if (!(areYouSure())) { return; }
            var total_time = timeNow;
            $('#total_time_hour').val(timeNow.h)
            $('#total_time_minute').val(timeNow.m)

            timeNow.h = 0;
            timeNow.m = 0;
            timeNow.s = 0;
            $('#resetBtn').prop("disabled", "true");
            $('#submit').prop("disabled", "true");
            showTime();
        }

        function submitTimer() {
            // reset timer back to 0 after confirming
            timeNow.h = 0;
            timeNow.m = 0;
            timeNow.s = 0;
            showTime();

        }

            $(document).ready(function() {
            showTime();
            $('#startBtn').click(function() { startTimer(); });
            $('#stopBtn').click(function() { stopTimer(); });
            $('#resetBtn').click(function() { resetTimer(); });
            $('#submit').click(function() { submitTimer(); });
            $('#stopBtn').prop("disabled", "true");
            $('#submit').prop("disabled", "true");
            $('#resetBtn').prop("disabled", "true");
            });

// add days?

        $(document).on('submit', '#work-hour', function(e){
            e.preventDefault();
            $.ajax({
                type:'POST',
                headers: {"X-CSRFToken": csrftoken},
                url: '/account/work/created/',
                data:{
                    total_time_hour: $('#total_time_hour').val(),
                    total_time_minute: $('#total_time_minute').val(),
                },
                success:function(){
                }
            });
        })

    </script>

Body:
Maybe you can storage last starter Date in localstorage.

Using localStorage allows save the data even you lost the browser session or reload the page.

function starterTime(){
  let lastTimeInit = localStorage.getItem('lastTimeInit');

  if(!lastTimeInit){
     lastTimeInit = new Date();
     localStorage.setItem('lastTimeInit', lastTimeInit)
  }else{
    lastTimeInit = new Date(lastTimeInit);
  }

  // calculates diff between lastTimeInit and now. Then calls count([resultHere])

}

You can do the same effect with cookies, but they have expiration.

But I think you can get better performance and "more clean coding" using moment.js


问:
Flutter gives error "Error running pod install"
I get the below error/log when i implement the google_sign_in package to my flutter application.
I'm using m1 chip. all the packages, flutter framework and xcode at their last versions.

Flutter project dependencies:

http: ^0.13.4

firebase_auth: ^3.3.6

google_sign_in: ^5.2.3

At the first i got this:

```
<code>

    Error output from CocoaPods:
    ↳
        [!] Automatically assigning platform `iOS` with version `9.0` on target `Runner` because no platform was specified. Please specify a platform for this target in your Podfile. See `https://guides.cocoapods.org/syntax/podfile.html#platform`.

</code>
```

Then I've uncomment this platform :ios, '9.0' at ios/Podfile

But different error shows up like this:

```
<code>

    Launching lib/main.dart on iPhone 13 in debug mode...
    lib/main.dart:1
    CocoaPods' output:
    ↳
          Preparing
        Analyzing dependencies
        Inspecting targets to integrate
          Using `ARCHS` setting to build architectures of target `Pods-Runner`: (``)
        Fetching external sources
        -> Fetching podspec for `Flutter` from `Flutter`
        -> Fetching podspec for `firebase_auth` from `.symlinks/plugins/firebase_auth/ios`
        firebase_auth: Using Firebase SDK version '8.11.0' defined in 'firebase_core'
        -> Fetching podspec for `firebase_core` from `.symlinks/plugins/firebase_core/ios`
        firebase_core: Using Firebase SDK version '8.11.0' defined in 'firebase_core'
        -> Fetching podspec for `google_sign_in` from `.symlinks/plugins/google_sign_in/ios`
        Resolving dependencies of `Podfile`
    Error output from CocoaPods:
    ↳
        /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require': dlopen(/Library/Ruby/Gems/2.6.0/gems/ffi-1.15.4/lib/ffi_c.bundle, 0x0009): tried: '/Library/Ruby/Gems/2.6.0/gems/ffi-1.15.4/lib/ffi_c.bundle' **(mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64'))**, '/usr/lib/ffi_c.bundle' (no such file) - /Library/Ruby/Gems/2.6.0/gems/ffi-1.15.4/lib/ffi_c.bundle (LoadError)
            from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
            from /Library/Ruby/Gems/2.6.0/gems/ffi-1.15.4/lib/ffi.rb:5:in `rescue in '
            from /Library/Ruby/Gems/2.6.0/gems/ffi-1.15.4/lib/ffi.rb:2:in `'
    2
            from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
            from /Library/Ruby/Gems/2.6.0/gems/ethon-0.15.0/lib/ethon.rb:3:in `'
    2
            from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
            from /Library/Ruby/Gems/2.6.0/gems/typhoeus-1.4.0/lib/typhoeus.rb:2:in `'
    2
            from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    ...

</code>
```

I think because of the m1 chip that i using, according to this error message (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64'))
Does anyone have an idea about this issue?

Also, the below subjects' answers didn't work for me.

Flutter Error running pod install After Upgrading Flutter version

Flutter pod install issue and ios app not running

https://github.com/CocoaPods/CocoaPods/issues/10127#issuecomment-705741320

答:
Use these commands in your project files to manually install pod files:

cd ios

arch -x86_64 pod install

cd ..

flutter run

Body:
I get the below error/log when i implement the google_sign_in package to my flutter application.
I'm using m1 chip. all the packages, flutter framework and xcode at their last versions.

Flutter project dependencies:

http: ^0.13.4

firebase_auth: ^3.3.6

google_sign_in: ^5.2.3

At the first i got this:

    Error output from CocoaPods:
    ↳
        [!] Automatically assigning platform `iOS` with version `9.0` on target `Runner` because no platform was specified. Please specify a platform for this target in your Podfile. See `https://guides.cocoapods.org/syntax/podfile.html#platform`.

Then I've uncomment this platform :ios, '9.0' at ios/Podfile

But different error shows up like this:

    Launching lib/main.dart on iPhone 13 in debug mode...
    lib/main.dart:1
    CocoaPods' output:
    ↳
          Preparing
        Analyzing dependencies
        Inspecting targets to integrate
          Using `ARCHS` setting to build architectures of target `Pods-Runner`: (``)
        Fetching external sources
        -> Fetching podspec for `Flutter` from `Flutter`
        -> Fetching podspec for `firebase_auth` from `.symlinks/plugins/firebase_auth/ios`
        firebase_auth: Using Firebase SDK version '8.11.0' defined in 'firebase_core'
        -> Fetching podspec for `firebase_core` from `.symlinks/plugins/firebase_core/ios`
        firebase_core: Using Firebase SDK version '8.11.0' defined in 'firebase_core'
        -> Fetching podspec for `google_sign_in` from `.symlinks/plugins/google_sign_in/ios`
        Resolving dependencies of `Podfile`
    Error output from CocoaPods:
    ↳
        /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require': dlopen(/Library/Ruby/Gems/2.6.0/gems/ffi-1.15.4/lib/ffi_c.bundle, 0x0009): tried: '/Library/Ruby/Gems/2.6.0/gems/ffi-1.15.4/lib/ffi_c.bundle' **(mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64'))**, '/usr/lib/ffi_c.bundle' (no such file) - /Library/Ruby/Gems/2.6.0/gems/ffi-1.15.4/lib/ffi_c.bundle (LoadError)
            from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
            from /Library/Ruby/Gems/2.6.0/gems/ffi-1.15.4/lib/ffi.rb:5:in `rescue in '
            from /Library/Ruby/Gems/2.6.0/gems/ffi-1.15.4/lib/ffi.rb:2:in `'
    2
            from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
            from /Library/Ruby/Gems/2.6.0/gems/ethon-0.15.0/lib/ethon.rb:3:in `'
    2
            from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
            from /Library/Ruby/Gems/2.6.0/gems/typhoeus-1.4.0/lib/typhoeus.rb:2:in `'
    2
            from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    ...

I think because of the m1 chip that i using, according to this error message (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64'))
Does anyone have an idea about this issue?

Also, the below subjects' answers didn't work for me.

Flutter Error running pod install After Upgrading Flutter version

Flutter pod install issue and ios app not running

https://github.com/CocoaPods/CocoaPods/issues/10127#issuecomment-705741320


问:
Entity Framework deadlock problem
I'm having a strange problem with new Entity Framework for .NET 4

I have a SQL Server 2005 (EXPRESS) database and my service writes data to two tables using entity framework. Let's say tables are TableA and TableB. TableB has foreign key to TableA. In my program there are several threads that writes data in parallel. Each thread has its own ObjectContext. The program creats TableA object and puts it in the object context. Then objects for TableB are created and put to object context. This repeats for several TableA items.

Finally when ObjectContext.Save method is called I see a deadlock error in the log:

System.Data.SqlClient.SqlException: Transaction (Process ID 56) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

It seems that it somehow depends on database options as it is reproduces on particular database only. One new database the issue is not reproduced. What database\table settings can influence on deadlock while Entity Framework performs batch insert? Or may be the problem somewhere else?

答:
Per your comment:

TableB didn't have primaryKey set in the database where issue was
  reproduced

ContentLicense: CC BY-SA 2.5

Title: Entity Framework deadlock problem


问:
How to filter out null values
The results of my SQL query include null values. How do I filter out null values?</p>

答:
My example works on every database I know, so it should work for you =)

```<code>SELECT *
FROM TABLE_NAME
WHERE COLUMN_NAME IS NOT NULL
</code>```

Here you can find a simple explanation and some examples: https://www.w3schools.com/sql/sql_null_values.asp

But some times you want to replace null values for a default value, like 'X', in this case, we should know the database for correct syntax, here some examples:

Oracle:

```<code>SELECT nvl(column_name,'X')
FROM TABLE_NAME
</code>```

Sqlite:

```<code>SELECT ifnull(column_name,'X')
FROM TABLE_NAME
</code>```

SqlServer:

```<code>SELECT coalesce(column_name,'X')
FROM TABLE_NAME
</code>```

Title: How to filter out null values

Body:
My example works on every database I know, so it should work for you =)

SELECT *
FROM TABLE_NAME
WHERE COLUMN_NAME IS NOT NULL

Here you can find a simple explanation and some examples: https://www.w3schools.com/sql/sql_null_values.asp

But some times you want to replace null values for a default value, like 'X', in this case, we should know the database for correct syntax, here some examples:

Oracle:

SELECT nvl(column_name,'X')
FROM TABLE_NAME

Sqlite:

SELECT ifnull(column_name,'X')
FROM TABLE_NAME

SqlServer:

SELECT coalesce(column_name,'X')
FROM TABLE_NAME


问:
Mongoose add/remove items from nested array
I have a document that has a nested array that I need to add/remove items from. Normally you query a nested object by id but in this case a dynamic object _id wont work and I need to update by the nested profile id.

Document

```<code>{
    title: 'Title',
    members: [
      {
          profile: { id: '123', name: 'Foo' },
          items: ['id1', 'id2', 'id3']
      }
    ]
}
</code>```

Query

My thinking is I need some sort of $elemMatch & $pushAll combo but cant seem to get it working. For removing items from the array I would swap push for pull

```<code>await this.repo.findByIdAndUpdate(id, {
    members: {
        $elemMatch: { 'profile.id': '123' },
        $pushAll: {
            items: ['xxx', 'yyy'],
        },
    },
})
</code>```

答:
You need to use arrayFilters & $push with $each since $pushAll has been deprecated

```<code>db.collection.update({},
{
 $push: {
   "members.$[x].items": {
     $each: [
       "xxx",
       "yyy"
     ]
   }
 }
},
 {
  arrayFilters: [
    {
     "x.profile.id": "123"
    }
  ]
})
</code>```

playground

Body:
I have a document that has a nested array that I need to add/remove items from. Normally you query a nested object by id but in this case a dynamic object _id wont work and I need to update by the nested profile id.

Document

{
    title: 'Title',
    members: [
      {
          profile: { id: '123', name: 'Foo' },
          items: ['id1', 'id2', 'id3']
      }
    ]
}

Query

My thinking is I need some sort of $elemMatch & $pushAll combo but cant seem to get it working. For removing items from the array I would swap push for pull

await this.repo.findByIdAndUpdate(id, {
    members: {
        $elemMatch: { 'profile.id': '123' },
        $pushAll: {
            items: ['xxx', 'yyy'],
        },
    },
})

Body:
You need to use arrayFilters & $push with $each since $pushAll has been deprecated

db.collection.update({},
{
 $push: {
   "members.$[x].items": {
     $each: [
       "xxx",
       "yyy"
     ]
   }
 }
},
 {
  arrayFilters: [
    {
     "x.profile.id": "123"
    }
  ]
})

playground


问:
Discord.py on_message() repeating execution
Long time user, first time poster. :-)

I'm using discord.py==1.7.2. I have a probably complicated bot that I have been hacking out through trial and error (super sketchy documentation as far as I can tell and maybe I don't really understand the Discord concept), but I am seeing some super strange behavior in the on_message() event. After having everything working like I wanted, I noticed an issue and simply wanted to check a value when the on_message() event was executed. I printed it to the chat. I then noticed it was printed repeatedly, non-stop to the chat until I killed the bot. Am I missing something here? My expectation is that the event on_message() runs when a user enters something and presses enter and then stops. Is this wrong? Code:

```<code>@bot.event
async def on_message(message):

    if len(message.content) < 5:
        return

    await message.channel.send('wtf')
</code>```

If I type anything below 5 chars, nothing happens. If I type "12345", the chaos begins.. it spits out 5 lines of "wtf" and then 4 "wtf"s every few seconds until I kill the bot. Is this happening for everyone? Or did I break it somewhere else? Super confused.

Thanks for any help!!!

Cheers

答:
This is because your event is on_message, and you are sending a message inside this event, which then triggers the event again, and then sends a message again and so on, in a loop.

you should check the sender of the message, if its the bot, then return.
like so,

#... other code
@bot.event
async def on_message(message: Message):
    if message.author.bot: #if message's author is a bot, then ignore it.
        return
    #... rest of your on_message()
```

Body:
Long time user, first time poster. :-)

I'm using discord.py==1.7.2. I have a probably complicated bot that I have been hacking out through trial and error (super sketchy documentation as far as I can tell and maybe I don't really understand the Discord concept), but I am seeing some super strange behavior in the on_message() event. After having everything working like I wanted, I noticed an issue and simply wanted to check a value when the on_message() event was executed. I printed it to the chat. I then noticed it was printed repeatedly, non-stop to the chat until I killed the bot. Am I missing something here? My expectation is that the event on_message() runs when a user enters something and presses enter and then stops. Is this wrong? Code:

@bot.event
async def on_message(message):

    if len(message.content) < 5:
        return

    await message.channel.send('wtf')

If I type anything below 5 chars, nothing happens. If I type "12345", the chaos begins.. it spits out 5 lines of "wtf" and then 4 "wtf"s every few seconds until I kill the bot. Is this happening for everyone? Or did I break it somewhere else? Super confused.

Thanks for any help!!!

Cheers


问:
How do I click link hidden by element in selenium?
I am trying to access a link that is only available when I select a filter button element.
Filter Button
Desired Link

I have tried to access the element using CSS Selector, since the link text contains "include-out-of-stock".

driver.get("https://www.target.com/c/young-adult/-/N-qh1tf?Nao=0")

#Selects the filter button
link = driver.find_element(By.ID, "filterButton")
link.click()

#The code that is given me issues. It doesn't find the desired link even though it's in the html inspector
element = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "a[href*='include-out-of-stock']")))
element.click()
```

However, the element is seemingly unfound as I encounter a TimeoutException. I did play around to see if xpath would work, but I still meet the same issues. Is the element not interactable since it's not directly on the webpage? Could I just not be accessing the element right?

答:
You have incorrect identifier as it has no attribute id with filtersButton.
A simple xpath for that button would be</p>
```<code>//button[@data-test='filtersButton']
</code>```

Body:
I am trying to access a link that is only available when I select a filter button element.
Filter Button
Desired Link

I have tried to access the element using CSS Selector, since the link text contains "include-out-of-stock".

driver.get("https://www.target.com/c/young-adult/-/N-qh1tf?Nao=0")

#Selects the filter button
link = driver.find_element(By.ID, "filterButton")
link.click()

#The code that is given me issues. It doesn't find the desired link even though it's in the html inspector
element = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "a[href*='include-out-of-stock']")))
element.click()

However, the element is seemingly unfound as I encounter a TimeoutException. I did play around to see if xpath would work, but I still meet the same issues. Is the element not interactable since it's not directly on the webpage? Could I just not be accessing the element right?

Body:
You have incorrect identifier as it has no attribute id with filtersButton.
A simple xpath for that button would be

//button[@data-test='filtersButton']


问:
CoreData error: +entityForName: could not locate an NSManagedObjectModel for entity name
I've been struggling with CoreData for a few days, but I keep getting this error:

'NSInternalInconsistencyException', reason: '+entityForName: could not locate an NSManagedObjectModel for entity name.

I have checked the entity name and what I wrote on my code and they're the same. I also recreated the object data-model and even delete the app from the simulator but nothing seems to fix it.
Here's what I have:

method to save into CoreData:

```<code>-(IBAction)save:(id)sender {
    NSManagedObject * newNews = [NSEntityDescription insertNewObjectForEntityForName:@"NewsStand"
    inManagedObjectContext:coredata.managedObjectContext];
    [newNews setValue:news_title forKey:@"story_title"];
    [newNews setValue:news_desc forKey:@"story_desc"];
    [newNews setValue:news_image  forKey:@"story_image"];
    [newNews setValue:test  forKey:@"story_url"];
    [coredata commit];
    NSLog(@"data saved!!!!");
}
</code>```

I have implemented all methods of core data in a separated class:

```<code>applicationDocumentsDirectory,
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator,
- (NSManagedObjectModel *)managedObjectModel,
- (NSManagedObjectContext *)managedObjectContext
</code>```

答: Ensure that coredata.managedObjectContext is not nil.

Body:
I've been struggling with CoreData for a few days, but I keep getting this error:

'NSInternalInconsistencyException', reason: '+entityForName: could not locate an NSManagedObjectModel for entity name.

I have checked the entity name and what I wrote on my code and they're the same. I also recreated the object data-model and even delete the app from the simulator but nothing seems to fix it.
Here's what I have:

method to save into CoreData:

-(IBAction)save:(id)sender {
    NSManagedObject * newNews = [NSEntityDescription insertNewObjectForEntityForName:@"NewsStand"
    inManagedObjectContext:coredata.managedObjectContext];
    [newNews setValue:news_title forKey:@"story_title"];
    [newNews setValue:news_desc forKey:@"story_desc"];
    [newNews setValue:news_image  forKey:@"story_image"];
    [newNews setValue:test  forKey:@"story_url"];
    [coredata commit];
    NSLog(@"data saved!!!!");
}

I have implemented all methods of core data in a separated class:

applicationDocumentsDirectory,
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator,
- (NSManagedObjectModel *)managedObjectModel,
- (NSManagedObjectContext *)managedObjectContext


问:
Python pyscard control the buzzer of an NFC reader
I have two NFC reading devices: ACR12U and ACR1252U

I have a short script in python using pyscard to read the UIDs of NFC tags:

```<code>from smartcard.CardMonitoring import CardMonitor, CardObserver
from smartcard.util import toHexString
from smartcard.Exceptions import CardConnectionException

getuid = [0xFF, 0xCA, 0x00, 0x00, 0x00]

class transmitobserver(CardObserver):
    def update(self, observable, actions):
        (addedcards, removedcards) = actions
        for card in addedcards:
            card.connection = card.createConnection()
            try:
                card.connection.connect()
            except CardConnectionException:
                # print("Card was removed too fast!")
                return
            response, sw1, sw2 = card.connection.transmit(
                getuid)
            nfc_id = "{}".format(toHexString(response)).replace(" ", "").lower()
            return nfc_id

if __name__ == '__main__':
    cardmonitor = CardMonitor()
    cardobserver = transmitobserver()
    cardmonitor.addObserver(cardobserver)
    try:
        while True:
            pass
    except KeyboardInterrupt:
        pass
</code>```

The ACR122U buzzes as soon as I an NFC card is in proximity.
The ACR1252U buzzes when an NFC is in proximity and buzzes again when I remove it.

I would like to change this behaviour so they only buzz when I remove the card and the card has been read. I tested it out and the program fails if I remove a card too fast, but the reader still buzzes like it was a success.

This is the first time I am working with things like this so I tried some trial and error methods.

So I figured getuid = [0xFF, 0xCA, 0x00, 0x00, 0x00] is sending the reader a command to read the UID, which I was able to find in both of their manuals:

Now I thought I could use this to control the buzzer. In the manual for the ACR1252U I found this:

So I tried the following:

```<code>buzzer = [0xE0, 0x00, 0x00, 0x28, 0x01, 0xFF]
response = card.connection.transmit(buzzer)
</code>```

But nothing is happening. There is a different instruction for the ACR122U, but same thing happens. Can anyone aid me what am I doing wrong?

EDIT:

I was able to come a little closer to the solution, however I still dont understand what is going on 100%.

I only have a ACR122U when I am writing this, so all testing is done with that one. from the manual I was able to get a bunch of APDUs and I found a code that emulates a card read without an actual card being touched to the device, so I can test it.

```<code>from smartcard.System import readers
from smartcard.CardConnection import CardConnection
from smartcard.scard import SCARD_SHARE_DIRECT

reader = readers()[0]
connection = reader.createConnection()
connection.connect(protocol=CardConnection.RAW_protocol, mode=SCARD_SHARE_DIRECT)
turn_off_red = [0xFF, 0x00, 0x40, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00]
r, sw1, sw2 = connection.transmit(turn_off_red)
</code>```

Now I have this APDU: turn_off_red = [0xFF, 0x00, 0x40, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00]

Which turns of the red led according to the manual, and it works as well, but just for a few seconds. Even if I put a sleep(50) at the end of the code, the red LED only blinks for a second, than turns back.

I think the same thing is happening when I try to use configBuzzer = [0xFF, 0x00, 0x52, 0x00, 0x00]. It turn the buzzer off for a couple of seconds, but turns it back on afterwards.

答:
Two pointers

1)All commands sent using Command APDU's have a standard Response APDU format of Result (If available - most do have a Result), SW1 and SW2

So you should use the code
response, sw1, sw2 = card.connection.transmit(buzzer)

You should always check that SW1 = 90h and SW2 = 00h to confirm the command was successful (Other values will indicate an error, see the datasheet for more details of what the codes mean)

2)You say you want it to buzz when it successful read the card, but you don't check the SW1 and SW2 values for success when you read the UID.

3)The command buzzer = [0xE0, 0x00, 0x00, 0x28, 0x01, 0xFF] is to manually turn the buzzer on, great for when you manually want to indicate success after checking in the SW1 and SW2 values of the read but this command does not change the default buzzing behaviour of the reader.

On the ACR1252U configBuzzer = [0xE0, 0x00, 0x00, 0x21, 0x01, 0x67] should be the right bits to turn off buzzing on Card Insertion Events and Card Removal Events, which is what you described you wanted, so you can manually trigger the buzzer on success (Again check SW1 and SW2 for success)

Update for the ACR122U

configBuzzer = [0xFF, 0x00, 0x52, 0x00, 0x00]

then

response, sw1, sw2 = card.connection.transmit(configBuzzer)

This will not cause buzzer to not turn on during Tag detection (the ACR122U has less configuration options than the ACR1252U)

Body:
I have two NFC reading devices: ACR12U and ACR1252U

I have a short script in python using pyscard to read the UIDs of NFC tags:

from smartcard.CardMonitoring import CardMonitor, CardObserver
from smartcard.util import toHexString
from smartcard.Exceptions import CardConnectionException

getuid = [0xFF, 0xCA, 0x00, 0x00, 0x00]

class transmitobserver(CardObserver):
    def update(self, observable, actions):
        (addedcards, removedcards) = actions
        for card in addedcards:
            card.connection = card.createConnection()
            try:
                card.connection.connect()
            except CardConnectionException:
                # print("Card was removed too fast!")
                return
            response, sw1, sw2 = card.connection.transmit(
                getuid)
            nfc_id = "{}".format(toHexString(response)).replace(" ", "").lower()
            return nfc_id

if __name__ == '__main__':
    cardmonitor = CardMonitor()
    cardobserver = transmitobserver()
    cardmonitor.addObserver(cardobserver)
    try:
        while True:
            pass
    except KeyboardInterrupt:
        pass

The ACR122U buzzes as soon as I an NFC card is in proximity.
The ACR1252U buzzes when an NFC is in proximity and buzzes again when I remove it.

I would like to change this behaviour so they only buzz when I remove the card and the card has been read. I tested it out and the program fails if I remove a card too fast, but the reader still buzzes like it was a success.

This is the first time I am working with things like this so I tried some trial and error methods.

So I figured getuid = [0xFF, 0xCA, 0x00, 0x00, 0x00] is sending the reader a command to read the UID, which I was able to find in both of their manuals:

Now I thought I could use this to control the buzzer. In the manual for the ACR1252U I found this:

So I tried the following:

buzzer = [0xE0, 0x00, 0x00, 0x28, 0x01, 0xFF]
response = card.connection.transmit(buzzer)

But nothing is happening. There is a different instruction for the ACR122U, but same thing happens. Can anyone aid me what am I doing wrong?

EDIT:

I was able to come a little closer to the solution, however I still dont understand what is going on 100%.

I only have a ACR122U when I am writing this, so all testing is done with that one. from the manual I was able to get a bunch of APDUs and I found a code that emulates a card read without an actual card being touched to the device, so I can test it.

from smartcard.System import readers
from smartcard.CardConnection import CardConnection
from smartcard.scard import SCARD_SHARE_DIRECT

reader = readers()[0]
connection = reader.createConnection()
connection.connect(protocol=CardConnection.RAW_protocol, mode=SCARD_SHARE_DIRECT)
turn_off_red = [0xFF, 0x00, 0x40, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00]
r, sw1, sw2 = connection.transmit(turn_off_red)

Now I have this APDU: turn_off_red = [0xFF, 0x00, 0x40, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00]

Which turns of the red led according to the manual, and it works as well, but just for a few seconds. Even if I put a sleep(50) at the end of the code, the red LED only blinks for a second, than turns back.

I think the same thing is happening when I try to use configBuzzer = [0xFF, 0x00, 0x52, 0x00, 0x00]. It turn the buzzer off for a couple of seconds, but turns it back on afterwards.


问:
Rollup/Svelte is not producing chunkfiles for dynamic imports. How to make Components to lazy loadable chunks?
I want to lazy load some components in svelte.
No Svelte-kit, just in pure svelte.

I want to dynamically import a Svelte-Component and use it when required:

const About = () => import("../Pages/About.svelte");
```
<p>The import works. The component displays.
But there is no lazy loading or chunk files generated on build nor will there be any lazy fetched requests for the component.</p>
<p>Everything gets bundled in the main.js instead of beeing splitted accordingly.</p>
<p>here is my Rollup config:</p>
<pre class="lang-js prettyprint-override"><code>export default {
    input: 'src/main.ts',
    output: {
        sourcemap: true,
        format: 'esm', // added this to allow modules
        name: 'app',
        dir: 'public/build/',
        inlineDynamicImports: true, //Added this to allow dynamic imports
        chunkFileNames: '[name].[hash].js' // though this would help
    },
    plugins: [
        svelte({
            preprocess: sveltePreprocess({ sourceMap: !production }),
            compilerOptions: {
                // have routing and need hydration maybe this is a issue with chunking?
                hydratable: true,
                dev: !production
            }
        }),
        // we'll extract any component CSS out into
        // a separate file - better for performance
        css({ output: 'bundle.css' }),
        scss({
            failOnError: true,
            include: ['src/**/*.css', 'src/**/*.scss', 'src/**/*.sass'],
        }),
        resolve({
            browser: true,
            dedupe: ['svelte']
        }),
        commonjs({

        }),
        // I use typescript mabye this could be an issue?
        typescript({
            sourceMap: !production,
            inlineSources: !production,
            include: ['src/**/*.ts', 'src/**/*.js'],
        }),
        copy({
            targets: [
                { src: 'public/index.html', dest: 'public', rename: '200.html' }
            ]
        }),

        // In dev mode, call `npm run start` once
        // the bundle has been generated
        !production && serve(),

        // Watch the `public` directory and refresh the
        // browser on changes when not in production
        !production && livereload('public'),

        // If we're building for production (npm run build
        // instead of npm run dev), minify
        production && terser()
    ],
    watch: {
        clearScreen: false
    }
};

</code>```

Did I miss something in my config?
Or how should I set up Svelte component code splitting/lazy loaded components ?

EDIT: This is how my build directory looks like after running build

As you can see, there is no chunks. Only one main.js.

答:
By setting the inlineDynamicImports option to true, you are telling Rollup to inline the dynamic import into the single output file instead of creating separate chunks. Removing that option should cause Rollup to create separate chunks for dynamic imports instead (the default behavior).

Rollup should support dynamic imports by default, so you didn't need to set that option to allow them.

Body:
I want to lazy load some components in svelte.
No Svelte-kit, just in pure svelte.

I want to dynamically import a Svelte-Component and use it when required:

const About = () => import("../Pages/About.svelte");

The import works. The component displays.
But there is no lazy loading or chunk files generated on build nor will there be any lazy fetched requests for the component.

Everything gets bundled in the main.js instead of beeing splitted accordingly.

here is my Rollup config:

export default {
    input: 'src/main.ts',
    output: {
        sourcemap: true,
        format: 'esm', // added this to allow modules
        name: 'app',
        dir: 'public/build/',
        inlineDynamicImports: true, //Added this to allow dynamic imports
        chunkFileNames: '[name].[hash].js' // though this would help
    },
    plugins: [
        svelte({
            preprocess: sveltePreprocess({ sourceMap: !production }),
            compilerOptions: {
                // have routing and need hydration maybe this is a issue with chunking?
                hydratable: true,
                dev: !production
            }
        }),
        // we'll extract any component CSS out into
        // a separate file - better for performance
        css({ output: 'bundle.css' }),
        scss({
            failOnError: true,
            include: ['src/**/*.css', 'src/**/*.scss', 'src/**/*.sass'],
        }),
        resolve({
            browser: true,
            dedupe: ['svelte']
        }),
        commonjs({

        }),
        // I use typescript mabye this could be an issue?
        typescript({
            sourceMap: !production,
            inlineSources: !production,
            include: ['src/**/*.ts', 'src/**/*.js'],
        }),
        copy({
            targets: [
                { src: 'public/index.html', dest: 'public', rename: '200.html' }
            ]
        }),

        // In dev mode, call `npm run start` once
        // the bundle has been generated
        !production && serve(),

        // Watch the `public` directory and refresh the
        // browser on changes when not in production
        !production && livereload('public'),

        // If we're building for production (npm run build
        // instead of npm run dev), minify
        production && terser()
    ],
    watch: {
        clearScreen: false
    }
};

Did I miss something in my config?
Or how should I set up Svelte component code splitting/lazy loaded components ?

EDIT: This is how my build directory looks like after running build

As you can see, there is no chunks. Only one main.js.


问:
Wordpress Database Optimisation for large Sites
I have a large Wordpress site with 170.000 users and a lot of daily page views.
I just tuned all MySQL indexes based on several comments but actually in my slow logs the SELECT distinct wp_usermeta.meta_key FROM wp_usermeta; takes around 3 seconds.
Server Hardware is: Dedicated Server with AMD Epyc 64 Cores, 128Gb DDR4, 2x480 NVMe SSD.

DB Server is MariaDB newest Version and config is (only innoDB tables):

```<code>innodb_buffer_pool_size = 64G
innodb_log_file_size = 16G
innodb_buffer_pool_instances = 16
innodb_io_capacity = 5000
max_binlog_size = 200M
max_connections = 250
wait_timeout = 28700
interactive_timeout = 28700
join_buffer_size = 128M
expire_logs_days = 3
skip-host-cache
skip-name-resolve
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 1
sql-mode = "STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION"

tmp_table_size = 256M
max_heap_table_size = 256M
table_definition_cache = 500
sort_buffer_size = 24M
key_buffer_size = 32M
performance_schema = on
</code>```

Maybe someone has some suggestions

答:
Of the 49 'values' that are associated with each user, how many are used in a WHERE or ORDER BY?  I suspect only a few.

Here's a way to work around WP's abuse of the "Entity-Attribute-Value" design pattern.

Let's say, a,b,c are useful for filtering and/or ordering.  And the other 46 values are simply saved for displaying later.  Have 4 rows, not 49 rows in usermeta for each user.  3 rows would be for a,b,c; the rest for a JSON string of the rest of the stuff.

Then have the application aware of the JSON and code accordingly.

This change would necessitate rebuilding wp_usermeta.  46 rows per user would be gathered together and rearranged into a single meta row with a moderately large JSON string (in meta_value).  That might not shrink the table much, but it would make it faster to use.

Body:
I have a large Wordpress site with 170.000 users and a lot of daily page views.
I just tuned all MySQL indexes based on several comments but actually in my slow logs the SELECT distinct wp_usermeta.meta_key FROM wp_usermeta; takes around 3 seconds.
Server Hardware is: Dedicated Server with AMD Epyc 64 Cores, 128Gb DDR4, 2x480 NVMe SSD.

DB Server is MariaDB newest Version and config is (only innoDB tables):

innodb_buffer_pool_size = 64G
innodb_log_file_size = 16G
innodb_buffer_pool_instances = 16
innodb_io_capacity = 5000
max_binlog_size = 200M
max_connections = 250
wait_timeout = 28700
interactive_timeout = 28700
join_buffer_size = 128M
expire_logs_days = 3
skip-host-cache
skip-name-resolve
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 1
sql-mode = "STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION"

tmp_table_size = 256M
max_heap_table_size = 256M
table_definition_cache = 500
sort_buffer_size = 24M
key_buffer_size = 32M
performance_schema = on

Maybe someone has some suggestions


问:
SQL IN command but not for any of the values that match, but must match all values
The SQL IN command allows you to find values that match any of the specified values in a WHERE clause. For example:

```<code>WHERE Keywords IN ('Blue', 'Green', 'Red');
</code>```

would give you results that contain any of those keywords. What if I want to return only those rows that have ALL of those keywords? So if only 'Blue' was in keywords but not 'Red' it would not be included.

答:
How about this:</p>
```<code>where lower(keyword) like '%red%'
and lower(keyword) like '%blue%'
and lower(keyword) like '%green%'
</code>```

Body:
The SQL IN command allows you to find values that match any of the specified values in a WHERE clause. For example:

WHERE Keywords IN ('Blue', 'Green', 'Red');

would give you results that contain any of those keywords. What if I want to return only those rows that have ALL of those keywords? So if only 'Blue' was in keywords but not 'Red' it would not be included.

Body:
How about this:

where lower(keyword) like '%red%'
and lower(keyword) like '%blue%'
and lower(keyword) like '%green%'


问:
How do I left or right justify, text within specific columns of a table in HTML,CSS
In the following code, I need to left justify the text in the first two columns and right justify the text in the last 4 columns with the exception of the table headers. Can't seem to figure it out and when I look for answers online I can't find anything on how to justify text within the cell of a table or specifically texts of just two columns. Would appreciate any help. Thanks

<!DOCTYPE html>

Top 10 Stocks

    Symbol
    Company
    Market Cap
    Price
    Dividend
    5-Year Growth

    MSFT
    Microsoft Corporation
    2.31T
    308.79
    .80%
    404.02%

    AAPL
    Apple Inc.
    2.78T
    173.04
    .52%
    493.54%

    AMZN
    Amazon.com Inc.
    1.46T
    2960.99
    N/A
    244.54%

```

答:
Use the nth-child if you wanna specify exactly td which you wanna set style. Take a look below. (Paste this code at the very bottom)

```<code>tr td:nth-child(3), tr td:nth-child(4), tr td:nth-child(5), tr td:nth-child(6) {
  text-align: right;
}
th {
  text-align: center;
}
</code>```

Body:
Use the nth-child if you wanna specify exactly td which you wanna set style. Take a look below. (Paste this code at the very bottom)

tr td:nth-child(3), tr td:nth-child(4), tr td:nth-child(5), tr td:nth-child(6) {
  text-align: right;
}
th {
  text-align: center;
}


问:
creating views count of a perticular articule with request.remote_ip
I have a rails app which has an story model and a views_count model. when a user enters a stories show page it increments the stories view count by 1. From what i have do the story fails to increment from my code below

Stories controller

```<code>  def show
    @story = Story.find(params[:id])
    @story.viewed!(request.remote_ip)

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @story }
    end
  end
</code>```

story model

```<code>  def viewed!(ip)
    view_count_id = "#{self.id}-#{ip}"
    if ViewsCount.where({:id => view_count_id}).first.nil?
      ViewsCount.create(:id => view_count_id)
      self.views_count += 1
    end
  end
</code>```

i cant increment the stories views_count.

The approch i took prevents the user from holding down the reload button to keep incrementing the counter. pls any better approach to this or what am i getting wrong

答: I was able to accomplish this with the impressionist gem </p>

Body:
I have a rails app which has an story model and a views_count model. when a user enters a stories show page it increments the stories view count by 1. From what i have do the story fails to increment from my code below

Stories controller

  def show
    @story = Story.find(params[:id])
    @story.viewed!(request.remote_ip)

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @story }
    end
  end

story model

  def viewed!(ip)
    view_count_id = "#{self.id}-#{ip}"
    if ViewsCount.where({:id => view_count_id}).first.nil?
      ViewsCount.create(:id => view_count_id)
      self.views_count += 1
    end
  end

i cant increment the stories views_count.

The approch i took prevents the user from holding down the reload button to keep incrementing the counter. pls any better approach to this or what am i getting wrong


问:
Loki json logs filter by detected fields from grafana
I am sending json logs to loki and visualizing in grafana. Initially, my logs looked like as following.

```<code>  {
     "log": "{\"additionalDetails\":{\"body\":{},\"ip\":\"::ffff:1.1.1.1\",\"params\":{},\"query\":{},\"responseTime\":0,\"userAgent\":\"ELB-HealthChecker/2.0\"},\"context\":\"http\",\"endpoint\":\"/healthz\",\"level\":\"info\",\"message\":\"[::ffff:1.1.1.1] HTTP/1.1 GET 200 /healthz 0ms\",\"requestId\":\"9fde4910-86cd-11ec-a1c5-cd8277a61e4a\",\"statusCode\":200}\n",
     "stream": "stdout",
     "time": "2022-02-05T21:49:58.178290044Z"
  }
</code>```

To make it more usabe, I am using following query.

```<code>{app="awesome-loki-logs-with-grafana"} | json | line_format "{{.log}}"
</code>```

And the results are really good. It automaticaly detects fileds as following.

How can I filter by statusCode, which is already being detected by grafana?

答:
You can create a "status" custom variable with values like 200, 401, 403, 404, etc, and use the variable in the LogQL, like in the following example:</p>
```<code>{app="awesome-loki-logs-with-grafana"} | json | statusCode=$status
</code>```

Body:
I am sending json logs to loki and visualizing in grafana. Initially, my logs looked like as following.

  {
     "log": "{\"additionalDetails\":{\"body\":{},\"ip\":\"::ffff:1.1.1.1\",\"params\":{},\"query\":{},\"responseTime\":0,\"userAgent\":\"ELB-HealthChecker/2.0\"},\"context\":\"http\",\"endpoint\":\"/healthz\",\"level\":\"info\",\"message\":\"[::ffff:1.1.1.1] HTTP/1.1 GET 200 /healthz 0ms\",\"requestId\":\"9fde4910-86cd-11ec-a1c5-cd8277a61e4a\",\"statusCode\":200}\n",
     "stream": "stdout",
     "time": "2022-02-05T21:49:58.178290044Z"
  }

To make it more usabe, I am using following query.

{app="awesome-loki-logs-with-grafana"} | json | line_format "{{.log}}"

And the results are really good. It automaticaly detects fileds as following.

How can I filter by statusCode, which is already being detected by grafana?

Body:
You can create a "status" custom variable with values like 200, 401, 403, 404, etc, and use the variable in the LogQL, like in the following example:

{app="awesome-loki-logs-with-grafana"} | json | statusCode=$status