答:
Fix came from Heroku article https://devcenter.heroku.com/articles/troubleshooting-node-deploys

This part -

```<code>Don’t check in generated directories
The app’s node_modules directory is generated at build time from the dependencies listed in package.json and the lockfile. Therefore, node_modules (and other generated directories like bower_components) shouldn’t be included in source control. Check with the following:

git ls-files | grep node_modules
If there are results, then instruct git to stop tracking node_modules:

echo "node_modules" >> .gitignore
git rm -r --cached node_modules
git commit -am 'untracked node_modules'
</code>```

That did it.  I don't really get why that did it when node_modules is in my gitignore AND when I've had this project up for almost a year without having this issue , but it did.

Title: Node JS Heroku Build Error - 'MODULE_NOT_FOUND'

Body:
I hadn't made any changes to my build (all the same dependencies) and yet all of a sudden now it's crashing when I push to my staging environment.

At first I was getting this -

2022-02-10T03:42:49.245470+00:00 app[web.1]: > node server.js
2022-02-10T03:42:49.245471+00:00 app[web.1]:
2022-02-10T03:42:49.311176+00:00 app[web.1]: node:internal/modules/cjs/loader:936
2022-02-10T03:42:49.311177+00:00 app[web.1]: throw err;
2022-02-10T03:42:49.311177+00:00 app[web.1]: ^
2022-02-10T03:42:49.311178+00:00 app[web.1]:
2022-02-10T03:42:49.311181+00:00 app[web.1]: Error: Cannot find module './internal/streams/buffer_list'
2022-02-10T03:42:49.311181+00:00 app[web.1]: Require stack:
2022-02-10T03:42:49.311182+00:00 app[web.1]: - /app/node_modules/readable-stream/lib/_stream_readable.js
2022-02-10T03:42:49.311182+00:00 app[web.1]: - /app/node_modules/readable-stream/readable.js
2022-02-10T03:42:49.311182+00:00 app[web.1]: - /app/node_modules/newrelic/lib/util/logger.js
2022-02-10T03:42:49.311182+00:00 app[web.1]: - /app/node_modules/newrelic/lib/logger.js
2022-02-10T03:42:49.311183+00:00 app[web.1]: - /app/node_modules/newrelic/index.js
2022-02-10T03:42:49.311183+00:00 app[web.1]: - /app/server.js
2022-02-10T03:42:49.311186+00:00 app[web.1]: at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
2022-02-10T03:42:49.311190+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:778:27)
2022-02-10T03:42:49.311190+00:00 app[web.1]: at Module.require (node:internal/modules/cjs/loader:1005:19)
2022-02-10T03:42:49.311190+00:00 app[web.1]: at require (node:internal/modules/cjs/helpers:102:18)
2022-02-10T03:42:49.311190+00:00 app[web.1]: at Object.<anonymous> (/app/node_modules/readable-stream/lib/_stream_readable.js:72:18)
2022-02-10T03:42:49.311191+00:00 app[web.1]: at Module._compile (node:internal/modules/cjs/loader:1103:14)
2022-02-10T03:42:49.311191+00:00 app[web.1]: at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10)
2022-02-10T03:42:49.311191+00:00 app[web.1]: at Module.load (node:internal/modules/cjs/loader:981:32)
2022-02-10T03:42:49.311191+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:822:12)
2022-02-10T03:42:49.311192+00:00 app[web.1]: at Module.require (node:internal/modules/cjs/loader:1005:19) {
2022-02-10T03:42:49.311192+00:00 app[web.1]: code: 'MODULE_NOT_FOUND',
2022-02-10T03:42:49.311192+00:00 app[web.1]: requireStack: [
2022-02-10T03:42:49.311192+00:00 app[web.1]: '/app/node_modules/readable-stream/lib/_stream_readable.js',
2022-02-10T03:42:49.311193+00:00 app[web.1]: '/app/node_modules/readable-stream/readable.js',
2022-02-10T03:42:49.311193+00:00 app[web.1]: '/app/node_modules/newrelic/lib/util/logger.js',
2022-02-10T03:42:49.311193+00:00 app[web.1]: '/app/node_modules/newrelic/lib/logger.js',
2022-02-10T03:42:49.311194+00:00 app[web.1]: '/app/node_modules/newrelic/index.js',
2022-02-10T03:42:49.311194+00:00 app[web.1]: '/app/server.js'
2022-02-10T03:42:49.311194+00:00 app[web.1]: ]
2022-02-10T03:42:49.311194+00:00 app[web.1]: }

So I thought maybe Heroku was cracking down on newrelic or something so I uninstalled that and then now I'm getting -

2022-02-10T04:17:31.000789+00:00 app[web.1]: > node server.js
2022-02-10T04:17:31.000789+00:00 app[web.1]:
2022-02-10T04:17:31.222303+00:00 app[web.1]: node:internal/modules/cjs/loader:936
2022-02-10T04:17:31.222304+00:00 app[web.1]: throw err;
2022-02-10T04:17:31.222305+00:00 app[web.1]: ^
2022-02-10T04:17:31.222305+00:00 app[web.1]:
2022-02-10T04:17:31.222306+00:00 app[web.1]: Error: Cannot find module '../../helpers/getConstructorName'
2022-02-10T04:17:31.222309+00:00 app[web.1]: Require stack:
2022-02-10T04:17:31.222310+00:00 app[web.1]: - /app/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js
2022-02-10T04:17:31.222310+00:00 app[web.1]: - /app/node_modules/mongoose/lib/drivers/node-mongodb-native/index.js
2022-02-10T04:17:31.222310+00:00 app[web.1]: - /app/node_modules/mongoose/lib/index.js
2022-02-10T04:17:31.222310+00:00 app[web.1]: - /app/node_modules/mongoose/index.js
2022-02-10T04:17:31.222311+00:00 app[web.1]: - /app/server.js
2022-02-10T04:17:31.222311+00:00 app[web.1]: at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
2022-02-10T04:17:31.222312+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:778:27)
2022-02-10T04:17:31.222312+00:00 app[web.1]: at Module.require (node:internal/modules/cjs/loader:1005:19)
2022-02-10T04:17:31.222312+00:00 app[web.1]: at require (node:internal/modules/cjs/helpers:102:18)
2022-02-10T04:17:31.222326+00:00 app[web.1]: at Object.<anonymous> (/app/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:12:28)
2022-02-10T04:17:31.222326+00:00 app[web.1]: at Module._compile (node:internal/modules/cjs/loader:1103:14)
2022-02-10T04:17:31.222326+00:00 app[web.1]: at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10)
2022-02-10T04:17:31.222326+00:00 app[web.1]: at Module.load (node:internal/modules/cjs/loader:981:32)
2022-02-10T04:17:31.222327+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:822:12)
2022-02-10T04:17:31.222327+00:00 app[web.1]: at Module.require (node:internal/modules/cjs/loader:1005:19) {
2022-02-10T04:17:31.222327+00:00 app[web.1]: code: 'MODULE_NOT_FOUND',
2022-02-10T04:17:31.222328+00:00 app[web.1]: requireStack: [
2022-02-10T04:17:31.222328+00:00 app[web.1]: '/app/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js',
2022-02-10T04:17:31.222328+00:00 app[web.1]: '/app/node_modules/mongoose/lib/drivers/node-mongodb-native/index.js',
2022-02-10T04:17:31.222329+00:00 app[web.1]: '/app/node_modules/mongoose/lib/index.js',
2022-02-10T04:17:31.222329+00:00 app[web.1]: '/app/node_modules/mongoose/index.js',
2022-02-10T04:17:31.222329+00:00 app[web.1]: '/app/server.js'
2022-02-10T04:17:31.222330+00:00 app[web.1]: ]
2022-02-10T04:17:31.222330+00:00 app[web.1]: }

I tried cleaning npm cache, removing node_modules folder, and npm install with both errors but they persisted.  It also boots up no issue when I use npm start on my commandline, so something is up with Heroku?  Any recommendations for what else I should try?  Could it be the node version? I'm not 100% on this but I feel like before in the build I would notice Node 14.x and now it's 16.x.

Also, package.json -

{
  "name": "CSQ",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "devStart": "nodemon server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@sendgrid/mail": "^7.4.6",
    "@slack/events-api": "^3.0.1",
    "@slack/web-api": "^6.5.1",
    "base-64": "^1.0.0",
    "base64-stream": "^1.0.0",
    "concat-stream": "^2.0.0",
    "excel4node": "^1.7.2",
    "express": "^4.17.1",
    "form-data": "^4.0.0",
    "googleapis": "^89.0.0",
    "https": "^1.0.0",
    "intuit-oauth": "^4.0.0",
    "mailgun-js": "^0.22.0",
    "mongodb": "^3.6.2",
    "mongoose": "^6.0.12",
    "node-fetch": "^2.6.1",
    "node-geocoder": "^3.27.0",
    "node-quickbooks": "^2.0.39",
    "pdf-forms": "^0.1.1",
    "pdf-lib": "^1.17.0",
    "pdfform.js": "^1.0.14",
    "plotly": "^1.0.6",
    "popsicle": "^10.0.0",
    "uuid": "^8.3.2",
    "xmlhttprequest": "^1.8.0"
  },
  "devDependencies": {
    "dotenv": "^10.0.0",
    "nodemon": "^2.0.12"
  }
}

Body:
Fix came from Heroku article https://devcenter.heroku.com/articles/troubleshooting-node-deploys

This part -

Don’t check in generated directories
The app’s node_modules directory is generated at build time from the dependencies listed in package.json and the lockfile. Therefore, node_modules (and other generated directories like bower_components) shouldn’t be included in source control. Check with the following:

git ls-files | grep node_modules
If there are results, then instruct git to stop tracking node_modules:

echo "node_modules" >> .gitignore
git rm -r --cached node_modules
git commit -am 'untracked node_modules'

That did it.  I don't really get why that did it when node_modules is in my gitignore AND when I've had this project up for almost a year without having this issue , but it did.


来源: stackexchange

问:
kaggle_metadata = pd.read_csv(f'{file_dir}movies_metadata.csv', low_memory=False) ratings = pd.read_csv(f'{file_dir}ratings.csv')
when i Run the code I get this error, how can I fix it?

FileNotFoundError                         Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_12432/2876068499.py in
----> 1 kaggle_metadata = pd.read_csv(f'{file_dir}movies_metadata.csv', low_memory=False)
2 ratings = pd.read_csv(f'{file_dir}ratings.csv')

~\anaconda3\envs\PythonData\lib\site-packages\pandas\util_decorators.py in wrapper(*args, **kwargs)
309                     stacklevel=stacklevel,
310                 )
--> 311             return func(*args, **kwargs)
312
313         return wrapper

~\anaconda3\envs\PythonData\lib\site-packages\pandas\io\parsers\readers.py in read_csv(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, skipfooter, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, cache_dates, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, doublequote, escapechar, comment, encoding, encoding_errors, dialect, error_bad_lines, warn_bad_lines, on_bad_lines, delim_whitespace, low_memory, memory_map, float_precision, storage_options)
584     kwds.update(kwds_defaults)
585
--> 586     return _read(filepath_or_buffer, kwds)
587
588

答:
One possible reason is in the contents of file_dir variable.

Try print(f"{file_dir}movies_metadata.csv"), add the output to your question and see what goes wrong. It might be one of these:

The path is relative, but the program is executed from another directory (file_dir starts with a folder name)

File path starts in a wrong place (disk root instead of home folder or the other way around)

file_dir has no slash at the end and this leads to the wrong file name

The path is completely wrong

ContentLicense: CC BY-SA 4.0


问:
Error: free() double free detected in tcache 2
These lines of code are giving me the error: free() double free detected in tcache 2 when I attempt to run the program. If i remove the final line, there is no error.  append_new is a method that searches the array within item_vec and adds "initialString" to the end of the array.  The method append_new has been tested in other programs. Could someone please explain the reason for this error and how to fix?</p>
```<code>class item_vec {
    // Create private set of variables
private:
    int strSize;
    int strCapacity;
    string* arr;

// Define functions in public
public:

    item_vec()
        : strSize(0), strCapacity(10)
    {
        arr = new string[strCapacity];
    }

    item_vec(int n, string s)
        : strSize(n), strCapacity(2 * n + 1)  // initializer list
    {
        // Check for out of bounds error
        if (n < 0) {
            cmpt::error("str_vec(int n, string s): n must be 0 or greater");
        }
        // make array and populate with string s
        arr = new string[strCapacity];
        for (int i = 0; i < strSize; i++) {
            arr[i] = s;
        }
    }

    int size() const {
        return strSize;
    }

    void append_new(string s) {
        // Variable to track if string is already present
        bool hasString = false;
        // Iterate through and update if string found
        for (int i = 0; i < strSize; i++) {
            if (arr[i] == s) {
                hasString = true;
            }
        }
        // If string isnt found append to end
        if (hasString == false) {

            // Make new copy array and replace old if no space
            if (strSize >= strCapacity) {
                strCapacity *= 2;
                string* new_arr = new string[strCapacity];

                for (int i = 0; i < strSize; i++) {
                    new_arr[i] = arr[i];
                }
                delete[] arr;
                arr = new_arr;
                delete[] new_arr;
            }
            // Update array
            arr[strSize] = s;
            strSize++;
        }
    }

    // Make destructor
    ~item_vec() {
        delete[] arr;
    }
};
</code>```

答:
In append_new after the old array has been copied into the new array we find

```<code>            delete[] arr; // free the old array. Good. No leak
            arr = new_arr; // point at the new array
            delete[] new_arr; // Whoooaaa! arr's pointing at that!
</code>```

The program will be broken as soon as the now-deleteed array at arr is used. The program may may stagger on, mortally wounded, for a while after that, and it looks like it makes it to the next delete[] arr; where the program notices the array's already been deleteed and crashes to make sure you also know about the mistake, but it's no longer going to function correctly and the error could manifest in any manner of strange and unexpected ways at any time.

Solution: Remove

```<code>            delete[] new_arr;
</code>```

Body:
These lines of code are giving me the error: free() double free detected in tcache 2 when I attempt to run the program. If i remove the final line, there is no error.  append_new is a method that searches the array within item_vec and adds "initialString" to the end of the array.  The method append_new has been tested in other programs. Could someone please explain the reason for this error and how to fix?

class item_vec {
    // Create private set of variables
private:
    int strSize;
    int strCapacity;
    string* arr;

// Define functions in public
public:

    item_vec()
        : strSize(0), strCapacity(10)
    {
        arr = new string[strCapacity];
    }

    item_vec(int n, string s)
        : strSize(n), strCapacity(2 * n + 1)  // initializer list
    {
        // Check for out of bounds error
        if (n < 0) {
            cmpt::error("str_vec(int n, string s): n must be 0 or greater");
        }
        // make array and populate with string s
        arr = new string[strCapacity];
        for (int i = 0; i < strSize; i++) {
            arr[i] = s;
        }
    }

    int size() const {
        return strSize;
    }

    void append_new(string s) {
        // Variable to track if string is already present
        bool hasString = false;
        // Iterate through and update if string found
        for (int i = 0; i < strSize; i++) {
            if (arr[i] == s) {
                hasString = true;
            }
        }
        // If string isnt found append to end
        if (hasString == false) {

            // Make new copy array and replace old if no space
            if (strSize >= strCapacity) {
                strCapacity *= 2;
                string* new_arr = new string[strCapacity];

                for (int i = 0; i < strSize; i++) {
                    new_arr[i] = arr[i];
                }
                delete[] arr;
                arr = new_arr;
                delete[] new_arr;
            }
            // Update array
            arr[strSize] = s;
            strSize++;
        }
    }

    // Make destructor
    ~item_vec() {
        delete[] arr;
    }
};

Body:
In append_new after the old array has been copied into the new array we find

            delete[] arr; // free the old array. Good. No leak
            arr = new_arr; // point at the new array
            delete[] new_arr; // Whoooaaa! arr's pointing at that!

The program will be broken as soon as the now-deleteed array at arr is used. The program may may stagger on, mortally wounded, for a while after that, and it looks like it makes it to the next delete[] arr; where the program notices the array's already been deleteed and crashes to make sure you also know about the mistake, but it's no longer going to function correctly and the error could manifest in any manner of strange and unexpected ways at any time.

Solution: Remove

            delete[] new_arr;


问:
How do I clone a repository on a local Gitlab server from another computer on the network?
As the title says, I'm trying to clone a repository (named devops) that exists on a local Gitlab server from another computer on my network.

My setup is as follows:

I have a Mac that is running an Ubuntu Server OS via VirtualBox (named gitlab-server).  This is where I have Gitlab configured and working properly, as I am able to access the repo on the Host-only Adapter from other VirtualBox operating systems via SSH.

On the same network I have another computer using Ubuntu that I am trying to configure to be my deployment server (let's call this deployment-server).

On the deployment-server, I have added the following line to the /etc/hosts file:

192.168.1.20 gitlab.test

That is the IP address to the gitlab-server

Currently, I am able to SSH into the gitlab-server from the deployment-server via the NAT network configured by VirtualBox.  I set up port forwarding from external port 2222 to internal port 22.

I run ssh -p2222 jaded@gitlab.test to access gitlab-server

An SSH key from deployment-server has been added to the Maintainer's profile (jadedInsomnia89) for the project in GitLab.

However, when I run git clone git@gitlab.test:jadedInsomnia89/devops.git on the deployment-server, I get the following error:

Cloning into 'devops'...

ssh: connect to host gitlab.test port 22: Connection refused.

fatal: Could not read from remote repository.

Please make sure you have the correct access rights

and the repository exists.

How do I properly access the GitLab server on the gitlab-server OS?  Please let me know any other details you may need.

Note:  I am setting up another computer for the deployment-server because the Mac doesn't have enough RAM to simultaneously run a deployment server, Jenkins server, and a GitLab server on 3 separate virtual operating systems like the course I am currently attending does.

答:
You will need to add your port number.

Try this:

```<code>git clone ssh://git@gitlab.test:2222/jadedInsomnia89/devops.git
</code>```

Body:
You will need to add your port number.

Try this:

git clone ssh://git@gitlab.test:2222/jadedInsomnia89/devops.git


问:
Use vim syntax definition with sublime-text2
Does anyone know if you can use (or convert) vim Syntax Highlight Definition Files with Sublime Text?

I am searching for a highlighter for promela and only found one for vim, but am using sublime-text as my default editor

The Definition i've found https://github.com/vim-scripts/promela.vim/blob/master/syntax/promela.vim

答:
In case somebody else comes looking for one (it's now 2022 and we're on ST3 and ST4): There's vimscript-sublime which says it's deprecated and has a pointer to VimL, which is available by Package Control.

For some reason, none of these came up for me when I searched in Package Control for things like "vim script" or "vimscript" or "vim syntax".  Now you know.

ContentLicense: CC BY-SA 3.0


问:
pyreverse not showing composition relationships in the UMLs when using absolute imports
I am having trouble generating UMLs with pyreverse, in particular with composition relationships when classes are not part of the same module, and when using absolute imports.

To illustrate the problem, I have the following two modules a.py and b.py in the same package:

a.py:

```<code>from b import B

class A:
    def __init__(self, b):
        self.b: B = b
</code>```

b.py:

```<code>class B:
    pass
</code>```

When I run a pyreverse command in a terminal from the package, I get the following UML. It does not show the composition relationship between the two classes A and B:

However, when I do a relative import from .b import B in a.py, I get the expected result:

It seems like pyreverse does not recognize in the first case that classes B are the same. To resolve the problem, I have tried to add the absolute path of the package to the environment variable PYTHONPATH. However, this did not resolve the problem.

Does anybody know how I can make pyreverse generate the right relationships in the UMLs when classes are defined in different modules, and when using absolute imports?

I am using python 3.8.8 and pylint version 2.12.2.

答:
Edited answer following additional experimentation

I'm not a python expert, but after a couple more experiments I think I get the information that you need

First experiments : no package

In my first experiment, I used several modules that were not in a package.  It appeared when using different ways to do the imports that pyreverse shows only the classes of the modules that are mentioned on the command line.

While I initially assumed that the issue was related to a stricter import syntax, it turned out that in reality it just worked as designed and documented in the man page:  pyreverse shows in the diagram only the classes of the modules listed in the pyreverse command line.

So with a little project with, using almost your definitions in files      main.py,a.py and b.py the easy workaround to get all the classes in the diagram  was to use pyresverse main.py a.py b.py on a single command line. It generates the diagram:

It appears however that the result also depends on the PYTHONPATH, the current directory from where you call pyreverse and the path used to specify the module, as these elements can influence the finding of the right import.

Additional experiments : packages

I renamed then main.py into __init__.py to make a package. I can then use pyreverse providing only the directory name of the package (or . if it's the current working directory).  Then all the files of the packages are processed for making the class diagram, withoout a need to enumerate them.

Using pyreverse on the package from within the package directory works with your import syntax and produced a similar diagram as above.  However,  running pyreverse from its parent directory produces 2 classes side by side without relationship.  This means that we are dealing with two different classes B one of which was not found. Using the relative import solved the issue.

I found it by the way useful to add option -m y to disambiguate the class names by adding the module name:

I could verify experimentally:  whenever I get unlinked classes,  launching the module in python from the same current working directory as pyreverse caused an import error.

Body:
I am having trouble generating UMLs with pyreverse, in particular with composition relationships when classes are not part of the same module, and when using absolute imports.

To illustrate the problem, I have the following two modules a.py and b.py in the same package:

a.py:

from b import B

class A:
    def __init__(self, b):
        self.b: B = b

b.py:

class B:
    pass

When I run a pyreverse command in a terminal from the package, I get the following UML. It does not show the composition relationship between the two classes A and B:

However, when I do a relative import from .b import B in a.py, I get the expected result:

It seems like pyreverse does not recognize in the first case that classes B are the same. To resolve the problem, I have tried to add the absolute path of the package to the environment variable PYTHONPATH. However, this did not resolve the problem.

Does anybody know how I can make pyreverse generate the right relationships in the UMLs when classes are defined in different modules, and when using absolute imports?

I am using python 3.8.8 and pylint version 2.12.2.


问:
Python3: for-loop does not start
i have the code below and my problem is the third for-loop doesn't start.  This part should compare ids in history file with ids from json_result list and then download or not. What do i do wrong and how to fix it?</p>
```<code>today = datetime.datetime.today().strftime('%d.%m')
for day in var.red_letter_days.keys():
    if today == day:
        api = AppPixivAPI()
        api.auth(refresh_token=var.refresh_token)
        json_result = api.search_illust(f'{var.red_letter_days[today]}', search_target='partial_match_for_tags')
        with open(var.history_file, 'a+', encoding='utf-8') as f:
            for idx, illust in enumerate(json_result.illusts):
                for i in f.readlines():
                    if i == illust.id:
                        print(illust.id)
                        break
                    else:
                        f.write(str(i) + '\n')
                        download(api, idx, illust)
</code>```

答: You've opened the file in append mode, with the 'a' option (the '+' part opens for reading and writing, but it's still opened in append mode). This means the file is opened at the end of the file, so data can be appended. Reading from the end of a file will result in nothing, so f.readlines() will be empty, and for i in f.readlines() will be an empty loop.

Title: Python3: for-loop does not start

Body:
i have the code below and my problem is the third for-loop doesn't start.  This part should compare ids in history file with ids from json_result list and then download or not. What do i do wrong and how to fix it?

today = datetime.datetime.today().strftime('%d.%m')
for day in var.red_letter_days.keys():
    if today == day:
        api = AppPixivAPI()
        api.auth(refresh_token=var.refresh_token)
        json_result = api.search_illust(f'{var.red_letter_days[today]}', search_target='partial_match_for_tags')
        with open(var.history_file, 'a+', encoding='utf-8') as f:
            for idx, illust in enumerate(json_result.illusts):
                for i in f.readlines():
                    if i == illust.id:
                        print(illust.id)
                        break
                    else:
                        f.write(str(i) + '\n')
                        download(api, idx, illust)


问:
npm ERR! argv "/usr/bin/node" "/usr/bin/npm" "install" "-y" "--no-install-recommends" "--global" "mathjax-node-cli"
Good morning,
I was trying to install the following repository: https://github.com/AntoineMeler/Paraglidable
I simply ran the following command:

```<code>docker build -t paraglidable Paraglidable/docker/.
</code>```

I got the following error:

```<code>npm ERR! Linux 5.4.0-97-generic
npm ERR! argv "/usr/bin/node" "/usr/bin/npm" "install" "-y" "--no-install-recommends" "--global" "mathjax-node-cli"
npm ERR! node v8.10.0
npm ERR! npm  v3.5.2
npm ERR! code EMISSINGARG

npm ERR! typeerror Error: Missing required argument #1
npm ERR! typeerror     at andLogAndFinish (/usr/share/npm/lib/fetch-package-metadata.js:31:3)
npm ERR! typeerror     at fetchPackageMetadata (/usr/share/npm/lib/fetch-package-metadata.js:51:22)
npm ERR! typeerror     at resolveWithNewModule (/usr/share/npm/lib/install/deps.js:456:12)
npm ERR! typeerror     at /usr/share/npm/lib/install/deps.js:457:7
npm ERR! typeerror     at /usr/share/npm/node_modules/iferr/index.js:13:50
npm ERR! typeerror     at /usr/share/npm/lib/fetch-package-metadata.js:37:12
npm ERR! typeerror     at addRequestedAndFinish (/usr/share/npm/lib/fetch-package-metadata.js:82:5)
npm ERR! typeerror     at returnAndAddMetadata (/usr/share/npm/lib/fetch-package-metadata.js:117:7)
npm ERR! typeerror     at pickVersionFromRegistryDocument (/usr/share/npm/lib/fetch-package-metadata.js:134:20)
npm ERR! typeerror     at /usr/share/npm/node_modules/iferr/index.js:13:50
npm ERR! typeerror This is an error with npm itself. Please report this error at:
npm ERR! typeerror     <http://github.com/npm/npm/issues>
npm WARN deprecated mathjax-node-sre@3.0.3: This package has been archived. MathJax v3 provides equivalent functionality.

npm ERR! Please include the following file with any support request:
npm ERR!     /npm-debug.log
</code>```

I searched online for the following problem, I believe it is caused by a deprecated version of the mathjax module but I don't understand how I can correct the problem.

Docker is running on ubuntu server 20.04.

Could you be so kind as to help me? Thank you very much!

答:
The error seems to be related to the npm version used while installing the package mathjax-node-cli.

Installing a newer version of node.js will solve the issue, since it will also upgrade the npm version.

I've edited the Dockerfile as follows, and now it seems to be working.

```<code>FROM tensorflow/tensorflow:latest-py3

ARG USERNAME=paraglidable
RUN useradd -m $USERNAME
ENV HOME /home/$USERNAME

ENV DEBIAN_FRONTEND=noninteractive

## Added the line below for installing node.js version 12 instead of 8.
RUN curl -fsSL https://deb.nodesource.com/setup_12.x | bash -

## Also removed `npm` from here since it is already included in `nodejs` package
RUN apt-get -y update && apt-get install -y --no-install-recommends net-tools libopenjp2-7-dev libpng-dev libpng16-16 vim sass wget qt5-default pdf2svg apache2 php libapache2-mod-php nodejs ibgeos-3.6.2 libgeos-dev unzip

# grib
RUN apt-get -y update && apt-get install -y --no-install-recommends libgrib-api-dev libgrib-api0
RUN apt-get -y update && apt-get install -y --no-install-recommends libeccodes-dev libeccodes0

# tex2svg
RUN npm install -y --no-install-recommends --global mathjax-node-cli

# Add sudo support
RUN apt-get install -y sudo \
    && echo $USERNAME ALL=\(root\) NOPASSWD:ALL > /etc/sudoers.d/$USERNAME && \
    chmod 0440 /etc/sudoers.d/$USERNAME

USER $USERNAME

RUN sudo pip install glob3 tqdm colorama requests pandas matplotlib pillow numba pyproj jupyter
RUN sudo pip install pygrib
RUN sudo pip install https://github.com/matplotlib/basemap/archive/master.zip
</code>```

Body:
Good morning,
I was trying to install the following repository: https://github.com/AntoineMeler/Paraglidable
I simply ran the following command:

docker build -t paraglidable Paraglidable/docker/.

I got the following error:

npm ERR! Linux 5.4.0-97-generic
npm ERR! argv "/usr/bin/node" "/usr/bin/npm" "install" "-y" "--no-install-recommends" "--global" "mathjax-node-cli"
npm ERR! node v8.10.0
npm ERR! npm  v3.5.2
npm ERR! code EMISSINGARG

npm ERR! typeerror Error: Missing required argument #1
npm ERR! typeerror     at andLogAndFinish (/usr/share/npm/lib/fetch-package-metadata.js:31:3)
npm ERR! typeerror     at fetchPackageMetadata (/usr/share/npm/lib/fetch-package-metadata.js:51:22)
npm ERR! typeerror     at resolveWithNewModule (/usr/share/npm/lib/install/deps.js:456:12)
npm ERR! typeerror     at /usr/share/npm/lib/install/deps.js:457:7
npm ERR! typeerror     at /usr/share/npm/node_modules/iferr/index.js:13:50
npm ERR! typeerror     at /usr/share/npm/lib/fetch-package-metadata.js:37:12
npm ERR! typeerror     at addRequestedAndFinish (/usr/share/npm/lib/fetch-package-metadata.js:82:5)
npm ERR! typeerror     at returnAndAddMetadata (/usr/share/npm/lib/fetch-package-metadata.js:117:7)
npm ERR! typeerror     at pickVersionFromRegistryDocument (/usr/share/npm/lib/fetch-package-metadata.js:134:20)
npm ERR! typeerror     at /usr/share/npm/node_modules/iferr/index.js:13:50
npm ERR! typeerror This is an error with npm itself. Please report this error at:
npm ERR! typeerror     <http://github.com/npm/npm/issues>
npm WARN deprecated mathjax-node-sre@3.0.3: This package has been archived. MathJax v3 provides equivalent functionality.

npm ERR! Please include the following file with any support request:
npm ERR!     /npm-debug.log

I searched online for the following problem, I believe it is caused by a deprecated version of the mathjax module but I don't understand how I can correct the problem.

Docker is running on ubuntu server 20.04.

Could you be so kind as to help me? Thank you very much!

Body:
The error seems to be related to the npm version used while installing the package mathjax-node-cli.

Installing a newer version of node.js will solve the issue, since it will also upgrade the npm version.

I've edited the Dockerfile as follows, and now it seems to be working.

FROM tensorflow/tensorflow:latest-py3

ARG USERNAME=paraglidable
RUN useradd -m $USERNAME
ENV HOME /home/$USERNAME

ENV DEBIAN_FRONTEND=noninteractive

## Added the line below for installing node.js version 12 instead of 8.
RUN curl -fsSL https://deb.nodesource.com/setup_12.x | bash -

## Also removed `npm` from here since it is already included in `nodejs` package
RUN apt-get -y update && apt-get install -y --no-install-recommends net-tools libopenjp2-7-dev libpng-dev libpng16-16 vim sass wget qt5-default pdf2svg apache2 php libapache2-mod-php nodejs ibgeos-3.6.2 libgeos-dev unzip

# grib
RUN apt-get -y update && apt-get install -y --no-install-recommends libgrib-api-dev libgrib-api0
RUN apt-get -y update && apt-get install -y --no-install-recommends libeccodes-dev libeccodes0

# tex2svg
RUN npm install -y --no-install-recommends --global mathjax-node-cli

# Add sudo support
RUN apt-get install -y sudo \
    && echo $USERNAME ALL=\(root\) NOPASSWD:ALL > /etc/sudoers.d/$USERNAME && \
    chmod 0440 /etc/sudoers.d/$USERNAME

USER $USERNAME

RUN sudo pip install glob3 tqdm colorama requests pandas matplotlib pillow numba pyproj jupyter
RUN sudo pip install pygrib
RUN sudo pip install https://github.com/matplotlib/basemap/archive/master.zip


问:
How do I replace the list of nan with list of zeroes in a pandas dataframe cell
I have this dataframe. How do I replace the list of nan with list of zeroes?</p>
```<code>a   b
1   [nan, nan]
5   [nan, nan, nan]
0   [0, 0]
</code>```

答:
One option is explode + fillna + groupby:

```<code>df['b'] = df['b'].explode().fillna(0).groupby(level=0).agg(list)
</code>```

Another option is list comprehension:

```<code>df['b'] = [[0 if isinstance(x, float) and np.isnan(x) else x for x in lst] for lst in df['b']]
</code>```

Output:

```<code>   a          b
0  1     [0, 0]
1  5  [0, 0, 0]
2  0     [0, 0]
</code>```

Body:
I have this dataframe. How do I replace the list of nan with list of zeroes?

a   b
1   [nan, nan]
5   [nan, nan, nan]
0   [0, 0]

Body:
One option is explode + fillna + groupby:

df['b'] = df['b'].explode().fillna(0).groupby(level=0).agg(list)

Another option is list comprehension:

df['b'] = [[0 if isinstance(x, float) and np.isnan(x) else x for x in lst] for lst in df['b']]

Output:

   a          b
0  1     [0, 0]
1  5  [0, 0, 0]
2  0     [0, 0]


问:
Using regular expression in SQL to read the values for an attribute
I am working on Snowflake to look for values for a string in a particular field. For example, I have a column called col1 with two values as follows

```<code>1. |LFD: |**Wed 07 Jul 2021**|
2. LFD & additional info
</code>```

Here in the first record we have value for string LFD, given as July 7,2021. But in second row we don't have value for LFD.

I tried to create a boolean flag as follows;

```<code>case when col1 ilike '%LFD%' then 0 else 1 end as LFD_missing_flag
</code>```

Interestingly it is giving 0 for both rows, but it shd be giving 1 for second row and 0 for first row.
Expected Output

```<code>    col1                              LFD_missing_flag
  |LFD: |**Wed 07 Jul 2021**|   |      0

   LFD & additional info.       |      1
</code>```

Since in second row we don't have value for LFD, it shd be 1, otherwise 0, as seen for first record.

Modifications
Along the same lines I have following piece of text;

```<code>|FIRMS Code: |**Unknown**|
|FIRMS Code: |**WAM7**|
|FIRMS Code: |WAM7|
</code>```

For this case the output shd be;

```<code>col1                           FIRMS_flag
|FIRMS Code: |**Unknown**|        1
|FIRMS Code: |**WAM7**|.          0
|FIRMS Code: |WAM7|.              0
</code>```

Can I get help to modify my logic so that I can get the correct output? thanks

答:
So given both input strings appear to have the sub-string LFD in them search for just that is not enough, the row to want result does have a : also so we can add that:

```<code>SELECT
    column1
    ,column1 ilike '%lfd%' as _like
    ,column1 ilike '%lfd:%' as not_like
    ,(column1 not ilike '%lfd:%')::int as results_a
    ,iff(column1 ilike '%lfd:%', 0, 1) as results_b
    ,case when column1 ilike '%LFD:%' then 0 else 1 end as results_c
FROM VALUES
    ('|LFD: |**Wed 07 Jul 2021**|'),
    ('LFD & additional info')
</code>```

which gives:

COLUMN1
_LIKE
NOT_LIKE
RESULTS_A
RESULTS_B
RESULTS_C

|LFD: |**Wed 07 Jul 2021**|
TRUE
TRUE
0
0
0

LFD & additional info
TRUE
FALSE
1
1
1

Body:
I am working on Snowflake to look for values for a string in a particular field. For example, I have a column called col1 with two values as follows

1. |LFD: |**Wed 07 Jul 2021**|
2. LFD & additional info

Here in the first record we have value for string LFD, given as July 7,2021. But in second row we don't have value for LFD.

I tried to create a boolean flag as follows;

case when col1 ilike '%LFD%' then 0 else 1 end as LFD_missing_flag

Interestingly it is giving 0 for both rows, but it shd be giving 1 for second row and 0 for first row.
Expected Output

    col1                              LFD_missing_flag
  |LFD: |**Wed 07 Jul 2021**|   |      0

   LFD & additional info.       |      1

Since in second row we don't have value for LFD, it shd be 1, otherwise 0, as seen for first record.

Modifications
Along the same lines I have following piece of text;

|FIRMS Code: |**Unknown**|
|FIRMS Code: |**WAM7**|
|FIRMS Code: |WAM7|

For this case the output shd be;

col1                           FIRMS_flag
|FIRMS Code: |**Unknown**|        1
|FIRMS Code: |**WAM7**|.          0
|FIRMS Code: |WAM7|.              0

Can I get help to modify my logic so that I can get the correct output? thanks

Body:
So given both input strings appear to have the sub-string LFD in them search for just that is not enough, the row to want result does have a : also so we can add that:

SELECT
    column1
    ,column1 ilike '%lfd%' as _like
    ,column1 ilike '%lfd:%' as not_like
    ,(column1 not ilike '%lfd:%')::int as results_a
    ,iff(column1 ilike '%lfd:%', 0, 1) as results_b
    ,case when column1 ilike '%LFD:%' then 0 else 1 end as results_c
FROM VALUES
    ('|LFD: |**Wed 07 Jul 2021**|'),
    ('LFD & additional info')

which gives:

COLUMN1
_LIKE
NOT_LIKE
RESULTS_A
RESULTS_B
RESULTS_C

|LFD: |**Wed 07 Jul 2021**|
TRUE
TRUE
0
0
0

LFD & additional info
TRUE
FALSE
1
1
1


问:
Sort array inside a nested object while maintaining the original json object
The goal is to sort the bill rates array by the percentage while maintaining the original json object.

```<code>[{
    "id": 2,
    "employee_observations": [{
        "id": 1,
        "bill_rates": [{
                "bill_classification": "Lawn Mowing",
                "percentage": 0.672399672399672
            },
            {
                "bill_classification": "Trimming",
                "percentage": 0.00163800163800164
            },
            {
                "bill_classification": "Snow Removal",
                "percentage": 0.630630630630631
            },
            {
                "bill_classification": "Rock Removal",
                "percentage": 0.00163800163800164
            }
        ]
    }]
}]
</code>```

Output expected

```<code>[{
    "id": 2,
    "employee_observations": [{
        "id": 1,
        "bill_rates": [
            {
                "bill_classification": "Lawn Mowing",
                "percentage": 0.672399672399672
            },
            {
                "bill_classification": "Snow Removal",
                "percentage": 0.630630630630631
            },
            {
                "bill_classification": "Rock Removal",
                "percentage": 0.00163800163800164
            },
            {
                "bill_classification": "Trimming",
                "percentage": 0.00163800163800164
            }
        ]
    }]
}]
</code>```

If I break it out by itself I can get to the expected result but haven't found the right combo to keep the format intact in the nested version above.

```<code>[
  {
    "activity_classification": "Lawn Mowing",
    "percentage": 0.672399672399672
  },
  {
    "activity_classification": "Trimming",
    "percentage": 0.00163800163800164
  },
  {
    "activity_classification": "Snow Removal",
    "percentage": 0.630630630630631
  },
  {
    "activity_classification": "Rock Removal",
    "percentage": 0.00163800163800164
  }
]
</code>```

jq 'sort_by(.activity_percentage) | reverse' - Results

```<code>[
  {
    "activity_classification": "Lawn Mowing",
    "percentage": 0.672399672399672
  },
  {
    "activity_classification": "Snow Removal",
    "percentage": 0.630630630630631
  },
  {
    "activity_classification": "Rock Removal",
    "percentage": 0.00163800163800164
  },
  {
    "activity_classification": "Trimming",
    "percentage": 0.00163800163800164
  }
]
</code>```

答:
Use the update operator |= to preserve the overall structure, and a negative comparison value -.percentage to sort in descending order:

jq '.[].employee_observations[].bill_rates |= sort_by(-.percentage)'
```
<pre class="lang-json prettyprint-override"><code>[
  {
    "id": 2,
    "employee_observations": [
      {
        "id": 1,
        "bill_rates": [
          {
            "bill_classification": "Lawn Mowing",
            "percentage": 0.672399672399672
          },
          {
            "detection_classification": "Snow Removal",
            "percentage": 0.630630630630631
          },
          {
            "detection_classification": "Trimming",
            "percentage": 0.00163800163800164
          },
          {
            "detection_classification": "Rock Removal",
            "percentage": 0.00163800163800164
          }
        ]
      }
    ]
  }
]
</code>```

Demo

Body:
The goal is to sort the bill rates array by the percentage while maintaining the original json object.

[{
    "id": 2,
    "employee_observations": [{
        "id": 1,
        "bill_rates": [{
                "bill_classification": "Lawn Mowing",
                "percentage": 0.672399672399672
            },
            {
                "bill_classification": "Trimming",
                "percentage": 0.00163800163800164
            },
            {
                "bill_classification": "Snow Removal",
                "percentage": 0.630630630630631
            },
            {
                "bill_classification": "Rock Removal",
                "percentage": 0.00163800163800164
            }
        ]
    }]
}]

Output expected

[{
    "id": 2,
    "employee_observations": [{
        "id": 1,
        "bill_rates": [
            {
                "bill_classification": "Lawn Mowing",
                "percentage": 0.672399672399672
            },
            {
                "bill_classification": "Snow Removal",
                "percentage": 0.630630630630631
            },
            {
                "bill_classification": "Rock Removal",
                "percentage": 0.00163800163800164
            },
            {
                "bill_classification": "Trimming",
                "percentage": 0.00163800163800164
            }
        ]
    }]
}]

If I break it out by itself I can get to the expected result but haven't found the right combo to keep the format intact in the nested version above.

[
  {
    "activity_classification": "Lawn Mowing",
    "percentage": 0.672399672399672
  },
  {
    "activity_classification": "Trimming",
    "percentage": 0.00163800163800164
  },
  {
    "activity_classification": "Snow Removal",
    "percentage": 0.630630630630631
  },
  {
    "activity_classification": "Rock Removal",
    "percentage": 0.00163800163800164
  }
]

jq 'sort_by(.activity_percentage) | reverse' - Results

[
  {
    "activity_classification": "Lawn Mowing",
    "percentage": 0.672399672399672
  },
  {
    "activity_classification": "Snow Removal",
    "percentage": 0.630630630630631
  },
  {
    "activity_classification": "Rock Removal",
    "percentage": 0.00163800163800164
  },
  {
    "activity_classification": "Trimming",
    "percentage": 0.00163800163800164
  }
]

Body:
Use the update operator |= to preserve the overall structure, and a negative comparison value -.percentage to sort in descending order:

jq '.[].employee_observations[].bill_rates |= sort_by(-.percentage)'

[
  {
    "id": 2,
    "employee_observations": [
      {
        "id": 1,
        "bill_rates": [
          {
            "bill_classification": "Lawn Mowing",
            "percentage": 0.672399672399672
          },
          {
            "detection_classification": "Snow Removal",
            "percentage": 0.630630630630631
          },
          {
            "detection_classification": "Trimming",
            "percentage": 0.00163800163800164
          },
          {
            "detection_classification": "Rock Removal",
            "percentage": 0.00163800163800164
          }
        ]
      }
    ]
  }
]

Demo


问:
What is the easiest way to generate a String of n repeated characters?
Given a character c and a number n, how can I create a String that consists of n repetitions of c? Doing it manually is too cumbersome:

```<code>StringBuilder sb = new StringBuilder(n);
for (int i = 0; i < n; ++i)
{
    sb.append(c);
}
String result = sb.toString();
</code>```

Surely there is some static library function that already does this for me?

答:
Google Guava Time!

```<code>Strings.repeat("a", 3)
</code>```

http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Strings.html

Body:
Given a character c and a number n, how can I create a String that consists of n repetitions of c? Doing it manually is too cumbersome:

StringBuilder sb = new StringBuilder(n);
for (int i = 0; i < n; ++i)
{
    sb.append(c);
}
String result = sb.toString();

Surely there is some static library function that already does this for me?

Body:
Google Guava Time!

Strings.repeat("a", 3)

http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Strings.html


问:
extract elements of tuple from a pandas series
I have a pandas series with data of type tuple as list elements. The length of the tuple is exactly 2 and there are a bunch of NaNs. I am trying to split each list in the tuple into its own column.

```<code>import pandas as pd
import numpy as np

df = pd.DataFrame({'val': [([1,2,3],[4,5,6]),
                           ([7,8,9],[10,11,12]),
                           np.nan]
                 })
</code>```

Expected Output:

答:
If you know the lenght of tuples are exactly 2, you can do:

df["x"] = df.val.str[0]
df["y"] = df.val.str[1]
print(df[["x", "y"]])
```
<p>Prints:</p>
<pre class="lang-none prettyprint-override"><code>           x             y
0  [1, 2, 3]     [4, 5, 6]
1  [7, 8, 9]  [10, 11, 12]
2        NaN           NaN
</code>```

Body:
I have a pandas series with data of type tuple as list elements. The length of the tuple is exactly 2 and there are a bunch of NaNs. I am trying to split each list in the tuple into its own column.

import pandas as pd
import numpy as np

df = pd.DataFrame({'val': [([1,2,3],[4,5,6]),
                           ([7,8,9],[10,11,12]),
                           np.nan]
                 })

Expected Output:

Body:
If you know the lenght of tuples are exactly 2, you can do:

df["x"] = df.val.str[0]
df["y"] = df.val.str[1]
print(df[["x", "y"]])

Prints:

           x             y
0  [1, 2, 3]     [4, 5, 6]
1  [7, 8, 9]  [10, 11, 12]
2        NaN           NaN


问:
Multiple of the same component spawning the same modal on the same page?
I'm using Vue, and I have a component that outputs a button.  That button opens a modal, also part of that component.  This works.

If I have multiple of those buttons on the page then the modal is spawned twice.  I understand why, but that's not what I want to happen.

Below is the code:

```<code><template>
    <div>
        <button @click="$bvModal.show('edit-profile-modal')" class="btn btn-sm btn-secondary mt-3">Edit</button>

        <b-modal id="edit-profile-modal" ref="editProfileModal" :ok-only="true">
            <template #modal-title>
                Edit your profile
            </template>
            <div class="d-block text-center">

            </div>
        </b-modal>
    </div>
</template>

<script>
    export default {
        props: {
        },

        data() {
            return {};
        },

        mounted() {
        },

        computed: {
        },

        methods: {
        }
    }
</script>
</code>```

Is there a way to make this modal totally unique, so it isn't duplicated?  It will always have the same content no matter what button is pressed.

The other questions on StackOverflow around this problem are focussed on the pattern of tabled data with 'Edit' buttons next to a row that spawns a modal with a form in it to edit that data - that's not what I'm trying to achieve.  The modal is always the same and will always have the same data in it.  I want to achieve a single component that I can drop in anywhere to allow a user to open this modal, so the solution isn't to put the modal outside of this component.

Thanks

答:
I know this is a bit old, but I stumbled upon the question while fiddling around with Bootstrap Vue's Modals and thought I'd add in an alternate solution.

BvModal identifies templates by id, and when the show function is called, it will display ALL matching templates tagged with that ID. So knowing that, all we have to do is make the IDs unique!

A sneaky way of doing this is to utilise the uid that Vue assigns to it's components:

```<code><template>
<div>
    <button @click="$bvModal.show(`edit-profile-modal-${_uid}`)" class="btn btn-sm btn-secondary mt-3">Edit</button>

    <b-modal :id="`edit-profile-modal-${_uid}`" ref="editProfileModal" :ok-only="true">
        <template #modal-title>
            Edit your profile
        </template>
        <div class="d-block text-center">

        </div>
    </b-modal>
</div>
</code>```

Note that we're using template literals for both the $bvModal.show function and the id prop of the b-modal. You could just as easily use "'edit-profile-modal-' + _uid" if that looks nicer to you.

This will let you have any number of the same component on the page, without BvModal getting confused as to which modal belongs to which component and without having to create a custom component.

Body:
I'm using Vue, and I have a component that outputs a button.  That button opens a modal, also part of that component.  This works.

If I have multiple of those buttons on the page then the modal is spawned twice.  I understand why, but that's not what I want to happen.

Below is the code:

<template>

        <button @click="$bvModal.show('edit-profile-modal')" class="btn btn-sm btn-secondary mt-3">Edit</button>

            <template #modal-title>
                Edit your profile
            </template>

</template>

Is there a way to make this modal totally unique, so it isn't duplicated?  It will always have the same content no matter what button is pressed.

The other questions on StackOverflow around this problem are focussed on the pattern of tabled data with 'Edit' buttons next to a row that spawns a modal with a form in it to edit that data - that's not what I'm trying to achieve.  The modal is always the same and will always have the same data in it.  I want to achieve a single component that I can drop in anywhere to allow a user to open this modal, so the solution isn't to put the modal outside of this component.

Thanks

Body:
I know this is a bit old, but I stumbled upon the question while fiddling around with Bootstrap Vue's Modals and thought I'd add in an alternate solution.

BvModal identifies templates by id, and when the show function is called, it will display ALL matching templates tagged with that ID. So knowing that, all we have to do is make the IDs unique!

A sneaky way of doing this is to utilise the uid that Vue assigns to it's components:

<template>
<div>
    <button @click="$bvModal.show(`edit-profile-modal-${_uid}`)" class="btn btn-sm btn-secondary mt-3">Edit</button>

    <b-modal :id="`edit-profile-modal-${_uid}`" ref="editProfileModal" :ok-only="true">
        <template #modal-title>
            Edit your profile
        </template>
        <div class="d-block text-center">

        </div>
    </b-modal>
</div>

Note that we're using template literals for both the $bvModal.show function and the id prop of the b-modal. You could just as easily use "'edit-profile-modal-' + _uid" if that looks nicer to you.

This will let you have any number of the same component on the page, without BvModal getting confused as to which modal belongs to which component and without having to create a custom component.


问:
JsonElement GetRawText method throws "Operation is not valid" exception on empty array

Situation

I am running into an issue with my implementation of .NET Core's System.Text.Json.JsonSerializer.
The API which my application utilizes for getting data returns JSON in the following format:

{
    "context": "SomeUnusedContextValue",
    "value": [
        {...}
    ]
}
```
<p>I only care for the actual response, so I only need the value item.</p>
<p>I have written below method to get the specific property and deserialize the items into objects.</p>
<pre class="lang-cs prettyprint-override"><code> public static async Task<T?> DeserializeResponse<T>(Stream str, string? property, CancellationToken ct)
 {
        JsonDocument jsonDocument = await JsonDocument.ParseAsync(str, default, ct).ConfigureAwait(false);

        if (property is null) // some calls to the API do return data at root-level
        {
            return JsonSerializer.Deserialize<T>(jsonDocument.RootElement.GetRawText());
        }

        if (!jsonDocument.RootElement.TryGetProperty(property, out JsonElement parsed))
            throw new InvalidDataException($"The specified lookup property \"{property}\" could not be found.");

        return JsonSerializer.Deserialize<T>(!typeof(IEnumerable).IsAssignableFrom(typeof(T))
            ? parsed.EnumerateArray().FirstOrDefault().GetRawText()
            : parsed.GetRawText(), new JsonSerializerOptions
            { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault });
}
</code>```

Problem

Now for my problem. Sometimes I only need a single object, however even if there is only one result, the API will still return an array. Not a problem since, as can be seen in the bottom return statement, I will just enumerate the array and get the first item (or the default null). This seems to crash when the returned array is empty, throwing below exception:

```<code>System.InvalidOperationException: Operation is not valid due to the current state of the object.
   at System.Text.Json.JsonElement.GetRawText()
   at BAS.Utilities.Deserializing.ResponseDeserializer.DeserializeResponse[T](Stream str, String property, CancellationToken ct) in C:\dev\bas.api\Modules\BAS.Utilities\Deserializing\ResponseDeserializer.cs:line 40
</code>```

The object I'm trying to serialize into is as below:

public class JobFunctionCombination
{
        ///
        /// Gets or sets the combined identifier of the main function group, the function group and the sub function group.
        ///
        /// <example>01_0101_010101</example>
        [JsonPropertyName("job_function_combination_id")]
        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
        public string Id { get; set; } = string.Empty;

        ///
        /// Gets or sets the combined names of the function groups.
        ///
        /// <example>Management | Human Resources | Finance controller</example>
        [JsonPropertyName("description")]
        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
        public string Description { get; set; } = string.Empty;

        ///
        /// Gets or sets the identifier of the main function group.
        ///
        [JsonPropertyName("job_main_function_group_id")]
        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
        public string MainFunctionGroupId { get; set; } = string.Empty;

        ///
        /// Gets or sets the identifier of the function group.
        ///
        [JsonPropertyName("job_function_group_id")]
        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
        public string FunctionGroupId { get; set; } = string.Empty;

        ///
        /// Gets or sets the identifier of the sub function group.
        ///
        [JsonPropertyName("job_sub_function_group_id")]
        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
        public string SubFunctionGroupId { get; set; } = string.Empty;
}
```

The types and JsonPropertyName attributes all match to the returned JSON.

Attempted fixes

To try and fix this issue, I have tried some fixes (two of which you can still see in the given code samples).

Adding the JsonIgnore attribute to the properties in the class.

I have tried to set the condition to WhenWritingDefault as well as WhenWritingNull. Neither seem to fix the problem.

Setting the DefaultIgnoreCondition in a JsonSerializerOptions object passed to JsonSerializer.Deserialze.

Here I have also tried both WhenWritingDefault and WhenWritingNull, also to no avail.

Checking if the array in JsonElement, when enumerated, is null or empty using .isNullOrEmpty().

This does prevent the exception from occuring, however it does not seem like an actual fix to me. More like a FlexTape solution just cancelling out the exception.

I am not sure what the exact issue is, other than the clear fact that JsonSerializer clearly has an issue with null objects. What could I do to fix this?

答:
Your problem is with your call to FirstOrDefault():

```<code>parsed.EnumerateArray().FirstOrDefault()
</code>```

JsonElement is a struct, so when the array has no items, FirstOrDefault() will return a default struct -- one initialized with zeros but without any property values set.  Such an element does not correspond to any JSON token; ValueKind will have the default value of JsonValueKind.None and GetRawText() will have no raw text to return.  In such a situation Microsoft chose to make GetRawText() throw an exception rather than return a null string.

To avoid the problem, enumerate the array, use a Select() statement to deserialize each item, then afterwards do FirstOrDefault() to return default(T) when the array is empty, like so:

```<code>public static partial class JsonExtensions
{
    public static async Task<T?> DeserializeResponse<T>(Stream str, string? property, CancellationToken ct = default)
    {
        if (property is null) // some calls to the API do return data at root-level
        {
            return await JsonSerializer.DeserializeAsync<T>(str, cancellationToken: ct).ConfigureAwait(false);
        }

        using var jsonDocument = await JsonDocument.ParseAsync(str, default, ct).ConfigureAwait(false);

        if (!jsonDocument.RootElement.TryGetProperty(property, out JsonElement parsed))
            throw new InvalidDataException($"The specified lookup property \"{property}\" could not be found.");

        return typeof(T).IsSerializedAsArray()
            ? parsed.Deserialize<T>()
            : parsed.EnumerateArray().Select(i => i.Deserialize<T>()).FirstOrDefault();
    }

    static bool IsSerializedAsArray(this Type type) =>
        type != typeof(string)
        && typeof(IEnumerable).IsAssignableFrom(type)
        && type != typeof(byte []) // byte arrays are serialized as Base64 strings.
        && !type.IsDictionary();

    static bool IsDictionary(this Type type) =>
        typeof(IDictionary).IsAssignableFrom(type)
        || type.GetInterfacesAndSelf().Any(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IDictionary<,>));

    static IEnumerable<Type> GetInterfacesAndSelf(this Type type) =>
        (type ?? throw new ArgumentNullException()).IsInterface
        ? new[] { type }.Concat(type.GetInterfaces())
        : type.GetInterfaces();
}
</code>```

Notes:

Since Enumerable.Select() uses deferred execution, only the first element (if present) will be deserialized.

In .NET 6 you may use JsonSerialzier.Deserialize(JsonElement, Type, JsonSerializerOptions = default) to deserialize directly from a JsonElement.  In .NET 5 and earlier, use one of the ToObject<T>() workaround extension methods from System.Text.Json.JsonElement ToObject workaround.

I corrected the logic that tests whether the type T is to be serialized as an array.

JsonDocument is disposable, and must be disposed of to return pooled memory to the memory pool.

Demo fiddle here.

Body:
Situation

I am running into an issue with my implementation of .NET Core's System.Text.Json.JsonSerializer.
The API which my application utilizes for getting data returns JSON in the following format:

{
    "context": "SomeUnusedContextValue",
    "value": [
        {...}
    ]
}

I only care for the actual response, so I only need the value item.

I have written below method to get the specific property and deserialize the items into objects.

 public static async Task<T?> DeserializeResponse<T>(Stream str, string? property, CancellationToken ct)
 {
        JsonDocument jsonDocument = await JsonDocument.ParseAsync(str, default, ct).ConfigureAwait(false);

        if (property is null) // some calls to the API do return data at root-level
        {
            return JsonSerializer.Deserialize<T>(jsonDocument.RootElement.GetRawText());
        }

        if (!jsonDocument.RootElement.TryGetProperty(property, out JsonElement parsed))
            throw new InvalidDataException($"The specified lookup property \"{property}\" could not be found.");

        return JsonSerializer.Deserialize<T>(!typeof(IEnumerable).IsAssignableFrom(typeof(T))
            ? parsed.EnumerateArray().FirstOrDefault().GetRawText()
            : parsed.GetRawText(), new JsonSerializerOptions
            { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault });
}

Problem

Now for my problem. Sometimes I only need a single object, however even if there is only one result, the API will still return an array. Not a problem since, as can be seen in the bottom return statement, I will just enumerate the array and get the first item (or the default null). This seems to crash when the returned array is empty, throwing below exception:

System.InvalidOperationException: Operation is not valid due to the current state of the object.
   at System.Text.Json.JsonElement.GetRawText()
   at BAS.Utilities.Deserializing.ResponseDeserializer.DeserializeResponse[T](Stream str, String property, CancellationToken ct) in C:\dev\bas.api\Modules\BAS.Utilities\Deserializing\ResponseDeserializer.cs:line 40

The object I'm trying to serialize into is as below:

public class JobFunctionCombination
{
        ///
        /// Gets or sets the combined identifier of the main function group, the function group and the sub function group.
        ///
        /// <example>01_0101_010101</example>
        [JsonPropertyName("job_function_combination_id")]
        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
        public string Id { get; set; } = string.Empty;

        ///
        /// Gets or sets the combined names of the function groups.
        ///
        /// <example>Management | Human Resources | Finance controller</example>
        [JsonPropertyName("description")]
        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
        public string Description { get; set; } = string.Empty;

        ///
        /// Gets or sets the identifier of the main function group.
        ///
        [JsonPropertyName("job_main_function_group_id")]
        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
        public string MainFunctionGroupId { get; set; } = string.Empty;

        ///
        /// Gets or sets the identifier of the function group.
        ///
        [JsonPropertyName("job_function_group_id")]
        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
        public string FunctionGroupId { get; set; } = string.Empty;

        ///
        /// Gets or sets the identifier of the sub function group.
        ///
        [JsonPropertyName("job_sub_function_group_id")]
        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
        public string SubFunctionGroupId { get; set; } = string.Empty;
}

The types and JsonPropertyName attributes all match to the returned JSON.

Attempted fixes

To try and fix this issue, I have tried some fixes (two of which you can still see in the given code samples).

Adding the JsonIgnore attribute to the properties in the class.

I have tried to set the condition to WhenWritingDefault as well as WhenWritingNull. Neither seem to fix the problem.

Setting the DefaultIgnoreCondition in a JsonSerializerOptions object passed to JsonSerializer.Deserialze.

Here I have also tried both WhenWritingDefault and WhenWritingNull, also to no avail.

Checking if the array in JsonElement, when enumerated, is null or empty using .isNullOrEmpty().

This does prevent the exception from occuring, however it does not seem like an actual fix to me. More like a FlexTape solution just cancelling out the exception.

I am not sure what the exact issue is, other than the clear fact that JsonSerializer clearly has an issue with null objects. What could I do to fix this?

Body:
Your problem is with your call to FirstOrDefault():

parsed.EnumerateArray().FirstOrDefault()

JsonElement is a struct, so when the array has no items, FirstOrDefault() will return a default struct -- one initialized with zeros but without any property values set.  Such an element does not correspond to any JSON token; ValueKind will have the default value of JsonValueKind.None and GetRawText() will have no raw text to return.  In such a situation Microsoft chose to make GetRawText() throw an exception rather than return a null string.

To avoid the problem, enumerate the array, use a Select() statement to deserialize each item, then afterwards do FirstOrDefault() to return default(T) when the array is empty, like so:

public static partial class JsonExtensions
{
    public static async Task<T?> DeserializeResponse<T>(Stream str, string? property, CancellationToken ct = default)
    {
        if (property is null) // some calls to the API do return data at root-level
        {
            return await JsonSerializer.DeserializeAsync<T>(str, cancellationToken: ct).ConfigureAwait(false);
        }

        using var jsonDocument = await JsonDocument.ParseAsync(str, default, ct).ConfigureAwait(false);

        if (!jsonDocument.RootElement.TryGetProperty(property, out JsonElement parsed))
            throw new InvalidDataException($"The specified lookup property \"{property}\" could not be found.");

        return typeof(T).IsSerializedAsArray()
            ? parsed.Deserialize<T>()
            : parsed.EnumerateArray().Select(i => i.Deserialize<T>()).FirstOrDefault();
    }

    static bool IsSerializedAsArray(this Type type) =>
        type != typeof(string)
        && typeof(IEnumerable).IsAssignableFrom(type)
        && type != typeof(byte []) // byte arrays are serialized as Base64 strings.
        && !type.IsDictionary();

    static bool IsDictionary(this Type type) =>
        typeof(IDictionary).IsAssignableFrom(type)
        || type.GetInterfacesAndSelf().Any(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IDictionary<,>));

    static IEnumerable<Type> GetInterfacesAndSelf(this Type type) =>
        (type ?? throw new ArgumentNullException()).IsInterface
        ? new[] { type }.Concat(type.GetInterfaces())
        : type.GetInterfaces();
}

Notes:

Since Enumerable.Select() uses deferred execution, only the first element (if present) will be deserialized.

In .NET 6 you may use JsonSerialzier.Deserialize(JsonElement, Type, JsonSerializerOptions = default) to deserialize directly from a JsonElement.  In .NET 5 and earlier, use one of the ToObject<T>() workaround extension methods from System.Text.Json.JsonElement ToObject workaround.

I corrected the logic that tests whether the type T is to be serialized as an array.

JsonDocument is disposable, and must be disposed of to return pooled memory to the memory pool.

Demo fiddle here.


问:
Insert existing element an just created one
If I have: Some Code Here, can I create a new div element and move the span element inside just created div?

The new element must be in same place where span element was before

I'd like to use pure javascript code

答:
here you go:

http://jsbin.com/uyiluf/3

source:

http://jsbin.com/uyiluf/3/edit#source


问:
Why does extracting a specific git tag to a /tmp directory mess up the working tree?
Because I wanted to look at the files in the last release, tagged v2.1, to run it in isolation from my working directory, I created a tmp directory

```<code>mkdir /tmp/lastRelease
</code>```

and extracted the last release in that directory

```<code>git --work-tree=/tmp/lastRelease checkout tags/v2.1 -- .
</code>```

The files are indeed extracted just fine to /tmp/lastRelease.

But now when I run git status in the working directory I find that very many files (all the files modified since tag v2.1?) appear as staged for commit, and another long list of files (that are in HEAD) appears as not staged for commit.

Was this last command the right way to extract a specific tag? How do I reset to HEAD? (The obvious git checkout HEAD doesn't modify what git status says, even though the files are there.)

答:
It doesn't (do anything to your current working tree).  What it does effectively damage / mess-up is the (singular) index.  (It also will affect HEAD.)

Each non-bare Git repository has one working tree, one index, and one HEAD.  That one index is used by git checkout or git switch; that one HEAD is set by it.  When you run:

```<code>git --work-tree=<path> checkout ...
</code>```

your Git extracts the specified commit—the ... part—and writes it through the index into the working tree.

Normally, the working tree to which your git checkout or git switch would write is the (singular) working tree.  But with --work-tree you temporarily override that one working tree with one different working tree—so that is the working tree to which this Git operation writes.  But you have not changed the (singular) index, nor the (singular) HEAD, and git checkout or git switch will write to those as well.

The HEAD keeps track of the current commit by containing:

a raw hash ID, or

the name of the current branch (with the branch name itself then containing the commit hash ID).

The index holds your proposed next commit, which starts out matching the current commit—so that when you switch commits, Git first removes the existing checked-out commit's files (as recorded in the index and stored in the existing in the working tree), and then plugs in the target commit's files (to the index and working tree).  Using --work-tree to re-point the working tree, without first cleaning out and removing the current working tree and index, leaves them out of sync.

If you don't mind the effect on HEAD, and are otherwise using this git checkout or git switch for a special purpose, consider setting GIT_INDEX_FILE to the name of a temporary file that does not exist now, and that you will delete once the git checkout or git switch finishes.

If you do mind the effect on HEAD, or intend to do this for more general purposes, consider not using git --work-tree checkout like this at all: instead, make sure your Git is at least 2.15, and begin using git worktree.  See the git worktree documentation for more about git worktree.  Edit: Or, as jthill notes, use git archive to build an archive you can extract without disturbing the working tree (note that this is a bit different, especially if there are .gitattributes rules for archive-building in the tag you'll be extracting).

Body:
Because I wanted to look at the files in the last release, tagged v2.1, to run it in isolation from my working directory, I created a tmp directory

mkdir /tmp/lastRelease

and extracted the last release in that directory

git --work-tree=/tmp/lastRelease checkout tags/v2.1 -- .

The files are indeed extracted just fine to /tmp/lastRelease.

But now when I run git status in the working directory I find that very many files (all the files modified since tag v2.1?) appear as staged for commit, and another long list of files (that are in HEAD) appears as not staged for commit.

Was this last command the right way to extract a specific tag? How do I reset to HEAD? (The obvious git checkout HEAD doesn't modify what git status says, even though the files are there.)

Body:
It doesn't (do anything to your current working tree).  What it does effectively damage / mess-up is the (singular) index.  (It also will affect HEAD.)

Each non-bare Git repository has one working tree, one index, and one HEAD.  That one index is used by git checkout or git switch; that one HEAD is set by it.  When you run:

git --work-tree=<path> checkout ...

your Git extracts the specified commit—the ... part—and writes it through the index into the working tree.

Normally, the working tree to which your git checkout or git switch would write is the (singular) working tree.  But with --work-tree you temporarily override that one working tree with one different working tree—so that is the working tree to which this Git operation writes.  But you have not changed the (singular) index, nor the (singular) HEAD, and git checkout or git switch will write to those as well.

The HEAD keeps track of the current commit by containing:

a raw hash ID, or

the name of the current branch (with the branch name itself then containing the commit hash ID).

The index holds your proposed next commit, which starts out matching the current commit—so that when you switch commits, Git first removes the existing checked-out commit's files (as recorded in the index and stored in the existing in the working tree), and then plugs in the target commit's files (to the index and working tree).  Using --work-tree to re-point the working tree, without first cleaning out and removing the current working tree and index, leaves them out of sync.

If you don't mind the effect on HEAD, and are otherwise using this git checkout or git switch for a special purpose, consider setting GIT_INDEX_FILE to the name of a temporary file that does not exist now, and that you will delete once the git checkout or git switch finishes.

If you do mind the effect on HEAD, or intend to do this for more general purposes, consider not using git --work-tree checkout like this at all: instead, make sure your Git is at least 2.15, and begin using git worktree.  See the git worktree documentation for more about git worktree.  Edit: Or, as jthill notes, use git archive to build an archive you can extract without disturbing the working tree (note that this is a bit different, especially if there are .gitattributes rules for archive-building in the tag you'll be extracting).


问:
why adding a size or button code in tkinter gives this error?
i was having some problem in tkinter GUI in python. i write the code to open a blank window :

```<code>from tkinter import *
window = Tk()
window.mainloop()
</code>```

in this moment , there is no error and opens a blank window. but when i want to add label or button or window size , like this code :

```<code>from tkinter import *
window =  Tk()
window.mainloop()

window.minsize(400,300)
window.maxsize(640,450)

window.geometry('350x200')
</code>```

now in this code , i wrote a size change code . but it gives an error now and the size code doesnt work. it gives the following error :

```<code>    Traceback (most recent call last):
  File "C:\Users\Green\Desktop\coding\main.py", line 5, in <module>
    window.minsize(400,300)
  File "C:\Users\Green\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 2196, in wm_minsize
    return self._getints(self.tk.call(
_tkinter.TclError: can't invoke "wm" command: application has been destroyed
</code>```

can you help me in this code ? thanks.

答:
Widgets need to go in between window = Tk() and window.mainloop. So, try:

```<code>    from tkinter import *
    window =  Tk()

    window.minsize(400,300)
    window.maxsize(640,450)

    window.geometry('350x200')

    # Code to add widgets will go here...
    # For example:
    button = Button(window, text="example button")
    button.pack()

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

Body:
i was having some problem in tkinter GUI in python. i write the code to open a blank window :

from tkinter import *
window = Tk()
window.mainloop()

in this moment , there is no error and opens a blank window. but when i want to add label or button or window size , like this code :

from tkinter import *
window =  Tk()
window.mainloop()

window.minsize(400,300)
window.maxsize(640,450)

window.geometry('350x200')

now in this code , i wrote a size change code . but it gives an error now and the size code doesnt work. it gives the following error :

    Traceback (most recent call last):
  File "C:\Users\Green\Desktop\coding\main.py", line 5, in <module>
    window.minsize(400,300)
  File "C:\Users\Green\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 2196, in wm_minsize
    return self._getints(self.tk.call(
_tkinter.TclError: can't invoke "wm" command: application has been destroyed

can you help me in this code ? thanks.

Body:
Widgets need to go in between window = Tk() and window.mainloop. So, try:

    from tkinter import *
    window =  Tk()

    window.minsize(400,300)
    window.maxsize(640,450)

    window.geometry('350x200')

    # Code to add widgets will go here...
    # For example:
    button = Button(window, text="example button")
    button.pack()

    window.mainloop()


问:
Protobuf Comparison field name vs generic fieldname, value
I have protobuf where there are multiple fields like

temperature, CPU, memory etc.

Is it better to define it in generic way eg: B or specific  eg:A

```<code>messsage Sensor {
    uint32 temperature = 1;
    uint32 cpu = 2;
    uint32 mem = 3;
}
</code>```

eg: B

```<code>message Sensor {
    repeated FieldValues = 1; // might be map also
}

message FieldValues {
    string name = 1;
    uint64 = 2;  // To accomodate all the ranges(int/long/double)
}
</code>```

For performance    A

For extensibility(Adding additional fields) B

Is there any other pros/cons ?

答:
Protobufs has you covered with extensibility of A because you can evolve the message by adding (!) fields.

I think you should (generally!) prefer to use the abstraction that is most intuitive|understandable and (generally!) prefer to leave optimization to the machines.

That said, there are differences between A and B.

A always includes temperature, cpu and mem which, if modeling e.g. a computer, each of these will always have a value. But, if you don't measure e.g. the temperature, you will need to have logic that e.g. defines a 0 temperature as representing "not recorded".

A enables you to (slightly more easily) represent different value types (you could have float, enum values too).

B enables you to record a variable set of values. And (unlike A), the absence of a value is a useful fact that no value was recorded.

Depending upon your encoding choice repeated or map, you will receive (depending on your language(s) of choice) an (ordered) list|array|slice or a map. If you choose repeated, finding individual values requires enumerating (half of the) slice to find the value.

Body:
I have protobuf where there are multiple fields like

temperature, CPU, memory etc.

Is it better to define it in generic way eg: B or specific  eg:A

messsage Sensor {
    uint32 temperature = 1;
    uint32 cpu = 2;
    uint32 mem = 3;
}

eg: B

message Sensor {
    repeated FieldValues = 1; // might be map also
}

message FieldValues {
    string name = 1;
    uint64 = 2;  // To accomodate all the ranges(int/long/double)
}

For performance    A

For extensibility(Adding additional fields) B

Is there any other pros/cons ?


问:
Is there a good way to remove a element from a map?
I made an map called mymap where I would like to remove every element in it that is the biggest in order to find the second biggest. Is there a good way to remove the elements in the map. This is what I have done so far:

```<code>n = int(input())
mymap = map(int, input().split())
biggestnum  = max(mymap)
mymap.(biggestnum)
secondbiggestnum = max(mymap)
print(secondbiggestnum)
</code>```

What would be an efficient and easy way to remove all instances of biggestnum?

答:
You've made this more complicated than it needs to be.  Just sort the list, and the biggest will be at the end.

```<code>mymap = list(sorted(set(map(int, input().split()))))
print('biggest',mymap[-1])
print('second',mymap[-2])
</code>```

If you still need the original list, you'd want to separate this into two statement: one to do the map, and one to do the extraction.

Body:
I made an map called mymap where I would like to remove every element in it that is the biggest in order to find the second biggest. Is there a good way to remove the elements in the map. This is what I have done so far:

n = int(input())
mymap = map(int, input().split())
biggestnum  = max(mymap)
mymap.(biggestnum)
secondbiggestnum = max(mymap)
print(secondbiggestnum)

What would be an efficient and easy way to remove all instances of biggestnum?

Body:
You've made this more complicated than it needs to be.  Just sort the list, and the biggest will be at the end.

mymap = list(sorted(set(map(int, input().split()))))
print('biggest',mymap[-1])
print('second',mymap[-2])

If you still need the original list, you'd want to separate this into two statement: one to do the map, and one to do the extraction.


问:
How can I configure Ansible playbook to ignore certain error codes?
I have a task to configure the following Ansible playbook to ignore error code 422 (which should happen when it looks for a volume that is detached from the server).

Furthermore, I currently see that this situation can also display error code 400, so, I may also have to exclude this.

    # ---
#   # This script will print the received parameters only
 - hosts: localhost
   connection: local

#   # Required parameters
#   # for testing locally
   vars:
     server_id: xxx
     backup_properties:
       name: xxx
       retention_period: x
       volume_ids:
       - xxx

   gather_facts: no

   tasks:

    # Get moss_url variable
    - include_tasks: ../vault_get_moss_environment.yml

    # Request the backup from the endpoint
    - name: Call MOS Windows Service Endpoint
      uri:
        url: "{{ moss_url }}/v1/service-instances/{{ server_id }}/backups"
        method: POST
        return_content: yes
        status_code: 202
        headers:
            Content-Type: "application/json"
            Authorization: "Bearer {{ getToken.json.access_token }}"
        body_format: json
        body: {
              "name": "{{ backup_properties.name | default('Backup Before Update') }}",
              "volumeIds": "{{ backup_properties.volume_ids | default(omit) }}",
              "retentionPeriod": "{{ backup_properties.retention_period | default(14) }}"
        }
      register: trigger_backup_response
      no_log: false
      ignore_errors: yes

    - fail:
       msg: "Error code: {% if trigger_backup_response.msg %}{{ trigger_backup_response.msg }}{% else %}{{ trigger_backup_response }}{% endif %}"
      when: trigger_backup_response.failed | default(false) and trigger_backup_response.json.status != "NOT_FOUND" # .failed is defined only when it fails

    - name: Delete server's backup schedules if server is not found in Openstack
      include_tasks: ../MOSS/call_moss_delete_backup_schedules.yml
      vars:
        id: "{{ server_id }}"
      when: trigger_backup_response.status == 404 and trigger_backup_response.json.status == "NOT_FOUND"

    - name: Get the id from the content
      debug:
        msg: "Started backup job with id: {{ trigger_backup_response.json.id }} for server with id: {{ server_id }}"
      when: trigger_backup_response.status == 202

    - name: Set backup_job_id as a fact
      set_fact:
        backup_job_id="{{ trigger_backup_response.json.id }}"
      when: trigger_backup_response.status == 202

    ###### Please do not delete this debug as it is used by MOSS #####
    - debug:
        msg: "backup_job_id={{ backup_job_id }}"
      when: trigger_backup_response.status == 202
```

I am aware that I probably have to use ignore_erros in some context, but, am not able to locate any way to exclude errors specifically by their code.

So, overall the question is how can I make this playbook ignore specifically errors 422 and 400 without sending any alerts or performing any actions?

答:
You can use a better mechanism than ignore_errors in this case, it is failed_when.

With it, you can fine grain the failure of a task to exactly what you want.

In your case it would be something like:

- name: Call MOS Windows Service Endpoint
  uri:
    url: https://example.org/api
  ## reduced the uri for brevity
  register: trigger_backup_response
  failed_when: trigger_backup_response.status not in [202, 400, 422]
```
<p>This will cause the codes <code>202</code>, <code>400</code> and <code>422</code> to have a successful task, all other status code would, then, fail.</p>
<p>Next to this, in order to handle the tasks based on the return of that API call, you can either use a <code>block</code>:</p>
<pre class="lang-yaml prettyprint-override"><code>- block:
    - debug:
        msg: First task upon receiving a return form the API

    - debug:
        msg: Second task upon receiving a return form the API

    - debug:
        msg: Third task upon receiving a return form the API

  when: trigger_backup_response.status == 202
</code>```

Or, stop the execution totally, with the help of the meta module.

The task here under will stop the play, on an host basis, if the the return code of the API is either 400 or 422.

- meta: end_host
  when: trigger_backup_response.status in [400, 422]
```
<p>So, having a scenario like:</p>
<pre class="lang-yaml prettyprint-override"><code>- name: Call API
  uri:
    url: https://example.org/api
  register: trigger_backup_response
  failed_when: trigger_backup_response.status not in [202, 400, 422]

- name: End play for hosts with detached volumes
  meta: end_host
  when: trigger_backup_response.status in [400, 422]

## From now on, it is safe to assume
## we are only dealing with API answer status being 202
- name: Display volume IDs
  debug:
    var: backup_properties.volume_ids
</code>```

Body:
I have a task to configure the following Ansible playbook to ignore error code 422 (which should happen when it looks for a volume that is detached from the server).

Furthermore, I currently see that this situation can also display error code 400, so, I may also have to exclude this.

    # ---
#   # This script will print the received parameters only
 - hosts: localhost
   connection: local

#   # Required parameters
#   # for testing locally
   vars:
     server_id: xxx
     backup_properties:
       name: xxx
       retention_period: x
       volume_ids:
       - xxx

   gather_facts: no

   tasks:

    # Get moss_url variable
    - include_tasks: ../vault_get_moss_environment.yml

    # Request the backup from the endpoint
    - name: Call MOS Windows Service Endpoint
      uri:
        url: "{{ moss_url }}/v1/service-instances/{{ server_id }}/backups"
        method: POST
        return_content: yes
        status_code: 202
        headers:
            Content-Type: "application/json"
            Authorization: "Bearer {{ getToken.json.access_token }}"
        body_format: json
        body: {
              "name": "{{ backup_properties.name | default('Backup Before Update') }}",
              "volumeIds": "{{ backup_properties.volume_ids | default(omit) }}",
              "retentionPeriod": "{{ backup_properties.retention_period | default(14) }}"
        }
      register: trigger_backup_response
      no_log: false
      ignore_errors: yes

    - fail:
       msg: "Error code: {% if trigger_backup_response.msg %}{{ trigger_backup_response.msg }}{% else %}{{ trigger_backup_response }}{% endif %}"
      when: trigger_backup_response.failed | default(false) and trigger_backup_response.json.status != "NOT_FOUND" # .failed is defined only when it fails

    - name: Delete server's backup schedules if server is not found in Openstack
      include_tasks: ../MOSS/call_moss_delete_backup_schedules.yml
      vars:
        id: "{{ server_id }}"
      when: trigger_backup_response.status == 404 and trigger_backup_response.json.status == "NOT_FOUND"

    - name: Get the id from the content
      debug:
        msg: "Started backup job with id: {{ trigger_backup_response.json.id }} for server with id: {{ server_id }}"
      when: trigger_backup_response.status == 202

    - name: Set backup_job_id as a fact
      set_fact:
        backup_job_id="{{ trigger_backup_response.json.id }}"
      when: trigger_backup_response.status == 202

    ###### Please do not delete this debug as it is used by MOSS #####
    - debug:
        msg: "backup_job_id={{ backup_job_id }}"
      when: trigger_backup_response.status == 202

I am aware that I probably have to use ignore_erros in some context, but, am not able to locate any way to exclude errors specifically by their code.

So, overall the question is how can I make this playbook ignore specifically errors 422 and 400 without sending any alerts or performing any actions?

Body:
You can use a better mechanism than ignore_errors in this case, it is failed_when.

With it, you can fine grain the failure of a task to exactly what you want.

In your case it would be something like:

- name: Call MOS Windows Service Endpoint
  uri:
    url: https://example.org/api
  ## reduced the uri for brevity
  register: trigger_backup_response
  failed_when: trigger_backup_response.status not in [202, 400, 422]

This will cause the codes 202, 400 and 422 to have a successful task, all other status code would, then, fail.

Next to this, in order to handle the tasks based on the return of that API call, you can either use a block:

- block:
    - debug:
        msg: First task upon receiving a return form the API

    - debug:
        msg: Second task upon receiving a return form the API

    - debug:
        msg: Third task upon receiving a return form the API

  when: trigger_backup_response.status == 202

Or, stop the execution totally, with the help of the meta module.

The task here under will stop the play, on an host basis, if the the return code of the API is either 400 or 422.

- meta: end_host
  when: trigger_backup_response.status in [400, 422]

So, having a scenario like:

- name: Call API
  uri:
    url: https://example.org/api
  register: trigger_backup_response
  failed_when: trigger_backup_response.status not in [202, 400, 422]

- name: End play for hosts with detached volumes
  meta: end_host
  when: trigger_backup_response.status in [400, 422]

## From now on, it is safe to assume
## we are only dealing with API answer status being 202
- name: Display volume IDs
  debug:
    var: backup_properties.volume_ids


问:
Create Full AWS RDS Snapshot
Can I create a full database snapshot or backup (manual/automated) for Amazon RDS Postgres Databases and not incremental ones. I want to create a job that provides full database parquet files everyday and share it with the Data warehousing team.

The document here says the following:

The first snapshot of a DB instance contains the data for the full DB instance. Subsequent snapshots of the same DB instance are incremental, which means that only the data that has changed after your most recent snapshot is saved.

答:
The RDS snapshots do not create Parquet files, as they are based on EBS snapshots.

To get Parquet files the best way would be to setup a Glue job which can run automatically on your schedule.

Title: Create Full AWS RDS Snapshot


问:
Connect SendGrid Event Webhooks to Azure Application Insights
In setting up SendGrid, I was advised to use SendGrid Event Webhooks.  Since I'm working in Azure, Application Insights seemed like the most sensible end-point for event logging.  It gives me integrated logs across my app and provides extensibility if I need to do more (like alerting) in the future.

I've found no instances online that this can be done directly.  I assume I could consume the events in a custom app and feed it into Application Insights that way, but it feels like that step shouldn't be required for a basic level of functionality.

I'm very new to this environment (Azure/cloud), so I expect I'm missing either a technical or rational reason why this wouldn't or shouldn't work.

Can you connect Twilo SendGrid Event Webhooks to Azure Application Insights directly?  If so, how?  If not, why not (either technically or for more philosophical reasons)?

答:
Twilio SendGrid developer evangelist here.

I'm not aware of a way to connect SendGrid directly to Azure Application Insights.

I have not used Application Insights myself. I've had a quick look around the docs and it seems that when sending metrics or other things you want to track to Application Insights there are libraries you use to make those requests in the format that Application Insights requires as well as with a key that presumably identifies and authorizes your account to do so.

SendGrid event webhooks do not follow the same format that Application Insights would expect (and why would they? They are different services from different companies), nor do they allow for you to include the key in the request. SendGrid event webhooks were built for anyone to be able to consume them, not for a particular third party service to do so, so I can't see why there would necessarily be a direct integration to Application Insights. As far as I can tell, SendGrid event webhooks also pre-date Application Insights by a few years.

I think your idea to consume the events in a custom app and translate the data into a format that Application Insights can ingest is the right idea.