问:
Beautiful soup returns none even when there is an element
Trying to filter the products name list using the header tags, but it always returns none.

source : https://www.tendercuts.in/chicken

code :

```<code>import requests
from bs4 import BeautifulSoup
def ExtractData(url):
response = requests.get(url=url).content
soup = BeautifulSoup(response, 'lxml')
header = soup.find("mat-card-header", {"class": "mat-card-header ng-tns- c9-188"})
print(header)
ExtractData(url="https://www.tendercuts.in/chicken")
</code>```

答:
What happens?

You try to find your tags by class that do not exist in your soup, cause it is generated dynamically and/or is caused by typo.

How to fix?

Select your elements more specific by tag or id and avoid classes cause these are more often created dynamically:

```<code>[t.text for t in soup.find_all('mat-card-title')]
</code>```

To avoid the duplicates just use set() on result:

```<code>set([t.text for t in soup.find_all('mat-card-title')])
</code>```

Example

```<code>import requests
from bs4 import BeautifulSoup

URL = 'https://www.tendercuts.in/chicken'
r = requests.get(URL)
soup = BeautifulSoup(r.text)

print(set([t.text for t in soup.find_all('mat-card-title')]))
</code>```

Output

```<code>{'Chicken Biryani Cut - Skin On','Chicken Biryani Cut - Skinless','Chicken Boneless (Cubes)','Chicken Breast Boneless','Chicken Curry Cut (Skin Off)','Chicken Curry Cut (Skin On)','Chicken Drumsticks',     'Chicken Liver','Chicken Lollipop','Chicken Thigh & Leg (Boneless)','Chicken Whole Leg','Chicken Wings','Country Chicken','Minced Chicken','Premium Chicken-Strips (Boneless)','Premium Chicken-Supreme (Boneless)','Smoky Country Chicken (Turmeric)'}
</code>```

EDIT

To get title, prices, ... I would recommend to iterate the mat-cards in following way.

```<code>import requests,re
from bs4 import BeautifulSoup

URL = 'https://www.tendercuts.in/chicken'
r = requests.get(URL)
soup = BeautifulSoup(r.text)

data = []
for item in soup.select('mat-card:has(mat-card-title)')[::2]:
    data.append({
        'title':item.find('mat-card-title').text,
        'price':re.search(r'₹\d*',soup.find('p', class_='current-price').text).group(),
        'weight':w if (w:=item.select_one('.weight span span:last-of-type').next_sibling) else None
    })

print(data)
</code>```

Output

```<code>[{'title': 'Chicken Curry Cut (Skin Off)', 'price': '₹99', 'weight': 'Customizable'}, {'title': 'Chicken Curry Cut (Skin On)', 'price': '₹99', 'weight': 'Customizable'}, {'title': 'Country Chicken', 'price': '₹99', 'weight': 'Customizable'}, {'title': 'Premium Chicken-Supreme (Boneless)', 'price': '₹99', 'weight': ' 330 - 350 Gms'}, {'title': 'Chicken Boneless (Cubes)', 'price': '₹99', 'weight': ' 480 - 500 Gms'}, {'title': 'Chicken Drumsticks', 'price': '₹99', 'weight': ' 280 - 360 Gms'}, {'title': 'Chicken Biryani Cut - Skin On', 'price': '₹99', 'weight': ' 480 - 500 Gms'}, {'title': 'Chicken Thigh & Leg (Boneless)', 'price': '₹99', 'weight': ' 480 - 500 Gms'}, {'title': 'Chicken Biryani Cut - Skinless', 'price': '₹99', 'weight': ' 480 - 500 Gms'}, {'title': 'Minced Chicken', 'price': '₹99', 'weight': ' 480 - 500 Gms'}, {'title': 'Smoky Country Chicken (Turmeric)', 'price': '₹99', 'weight': ' 650 - 800 Gms'}, {'title': 'Chicken Lollipop', 'price': '₹99', 'weight': ' 280 - 300 Gms'}, {'title': 'Chicken Whole Leg', 'price': '₹99', 'weight': ' 370 - 390 Gms'}, {'title': 'Chicken Breast Boneless', 'price': '₹99', 'weight': ' 240 - 280 Gms'}, {'title': 'Premium Chicken-Strips (Boneless)', 'price': '₹99', 'weight': ' 330 - 350 Gms'}, {'title': 'Chicken Liver', 'price': '₹99', 'weight': ' 190 - 210 Gms'}, {'title': 'Chicken Wings', 'price': '₹99', 'weight': ' 480 - 500 Gms'}]
</code>```

Body:
Trying to filter the products name list using the header tags, but it always returns none.

source : https://www.tendercuts.in/chicken

code :

import requests
from bs4 import BeautifulSoup
def ExtractData(url):
response = requests.get(url=url).content
soup = BeautifulSoup(response, 'lxml')
header = soup.find("mat-card-header", {"class": "mat-card-header ng-tns- c9-188"})
print(header)
ExtractData(url="https://www.tendercuts.in/chicken")

Body:
What happens?

You try to find your tags by class that do not exist in your soup, cause it is generated dynamically and/or is caused by typo.

How to fix?

Select your elements more specific by tag or id and avoid classes cause these are more often created dynamically:

[t.text for t in soup.find_all('mat-card-title')]

To avoid the duplicates just use set() on result:

set([t.text for t in soup.find_all('mat-card-title')])

Example

import requests
from bs4 import BeautifulSoup

URL = 'https://www.tendercuts.in/chicken'
r = requests.get(URL)
soup = BeautifulSoup(r.text)

print(set([t.text for t in soup.find_all('mat-card-title')]))

Output

{'Chicken Biryani Cut - Skin On','Chicken Biryani Cut - Skinless','Chicken Boneless (Cubes)','Chicken Breast Boneless','Chicken Curry Cut (Skin Off)','Chicken Curry Cut (Skin On)','Chicken Drumsticks',     'Chicken Liver','Chicken Lollipop','Chicken Thigh & Leg (Boneless)','Chicken Whole Leg','Chicken Wings','Country Chicken','Minced Chicken','Premium Chicken-Strips (Boneless)','Premium Chicken-Supreme (Boneless)','Smoky Country Chicken (Turmeric)'}

EDIT

To get title, prices, ... I would recommend to iterate the mat-cards in following way.

import requests,re
from bs4 import BeautifulSoup

URL = 'https://www.tendercuts.in/chicken'
r = requests.get(URL)
soup = BeautifulSoup(r.text)

data = []
for item in soup.select('mat-card:has(mat-card-title)')[::2]:
    data.append({
        'title':item.find('mat-card-title').text,
        'price':re.search(r'₹\d*',soup.find('p', class_='current-price').text).group(),
        'weight':w if (w:=item.select_one('.weight span span:last-of-type').next_sibling) else None
    })

print(data)

Output

[{'title': 'Chicken Curry Cut (Skin Off)', 'price': '₹99', 'weight': 'Customizable'}, {'title': 'Chicken Curry Cut (Skin On)', 'price': '₹99', 'weight': 'Customizable'}, {'title': 'Country Chicken', 'price': '₹99', 'weight': 'Customizable'}, {'title': 'Premium Chicken-Supreme (Boneless)', 'price': '₹99', 'weight': ' 330 - 350 Gms'}, {'title': 'Chicken Boneless (Cubes)', 'price': '₹99', 'weight': ' 480 - 500 Gms'}, {'title': 'Chicken Drumsticks', 'price': '₹99', 'weight': ' 280 - 360 Gms'}, {'title': 'Chicken Biryani Cut - Skin On', 'price': '₹99', 'weight': ' 480 - 500 Gms'}, {'title': 'Chicken Thigh & Leg (Boneless)', 'price': '₹99', 'weight': ' 480 - 500 Gms'}, {'title': 'Chicken Biryani Cut - Skinless', 'price': '₹99', 'weight': ' 480 - 500 Gms'}, {'title': 'Minced Chicken', 'price': '₹99', 'weight': ' 480 - 500 Gms'}, {'title': 'Smoky Country Chicken (Turmeric)', 'price': '₹99', 'weight': ' 650 - 800 Gms'}, {'title': 'Chicken Lollipop', 'price': '₹99', 'weight': ' 280 - 300 Gms'}, {'title': 'Chicken Whole Leg', 'price': '₹99', 'weight': ' 370 - 390 Gms'}, {'title': 'Chicken Breast Boneless', 'price': '₹99', 'weight': ' 240 - 280 Gms'}, {'title': 'Premium Chicken-Strips (Boneless)', 'price': '₹99', 'weight': ' 330 - 350 Gms'}, {'title': 'Chicken Liver', 'price': '₹99', 'weight': ' 190 - 210 Gms'}, {'title': 'Chicken Wings', 'price': '₹99', 'weight': ' 480 - 500 Gms'}]


来源: stackexchange

问:
Webpack regenerator compile issue for React app, help me pls
enter image description here    enter image description here

```<code>       WARNING in ./src/pages/Home.jsx 41:24-43

    export 'default' (imported as 'React') was not found in 'react' (possible exports: __esModule)
     @ ./src/App.js 7:0-32 158:46-50
     @ ./src/index.js 6:0-24 7:97-100

      [1]: https://i.stack.imgur.com/0mRcJ.png

----------
</code>```

I am using a lot of ES6 syntax and I realize on apple systems sometimes certain feature dont work. So I figure this will be killing two birds with one stone. Minimizing and optimizing. This issue is I am unsure what the issue is here.

My webpack.config.js

```<code>const path = require('path');
    const MiniCssExtractPlugin = require("mini-css-extract-plugin");

    module.exports = {
      target: ['web', 'es5'],
      entry: path.resolve(__dirname, 'src/index.js'),
      output: {
        path: path.resolve(__dirname, 'public'),
        filename: 'bundle.js',

      },

      mode: "development",
      plugins: [new MiniCssExtractPlugin()],
      module: {
           rules: [
               {
                   test:/\.js$|jsx/,
                   use: ["babel-loader"],

               },

               {
                test: /\.s[ac]ss$/i,
                use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader" ]
               },

               {
                test: /\.(png|svg|jpg|jpeg|gif|mp4)$/i,
                type: 'asset/resource',
              },

              {
                test: /\.tsx?$/,
                use: 'ts-loader',
                exclude: /node_modules/,
              }

           ]

        },

        devServer: {
               static: {
                 directory: path.resolve(__dirname,'public') ,

               },

                open: true,
                liveReload: true,
                port:8080,
                historyApiFallback:true,

             },

             resolve: {
               extensions: ['.js', '.jsx'],
               alias: {
                 components: path.resolve(__dirname, 'src/components'),
                 images: path.resolve(__dirname, 'src/images'),
                 pages: path.resolve(__dirname, 'src/pages'),

               }
             }

    }

    ----------

</code>```

My  babel-config.js

```<code>    module.exports = {
        presets: ['@babel/preset-env', '@babel/preset-react'],

        plugins: [
          [
              "@babel/plugin-proposal-class-properties",
              {
                  "loose": true
              }
          ],
          [
              "@babel/plugin-transform-runtime",
              {
                  "asyncGenerators": true,
                  "generators": true,
                  "async": true
              }
          ],
          ["@babel/plugin-proposal-export-default-from"]
      ]

      };

    ----------

</code>```

index.js

```<code>    import React from 'react';
    import ReactDOM from 'react-dom';
    import "regenerator-runtime/runtime.js";
    import { BrowserRouter as Router } from 'react-router-dom';

    import './index.scss';

    import App  from './App'

    ReactDOM.render(
      <Router>
          <App />
      </Router>,
      document.getElementById('root')
    );

    ----------

</code>```

components Home.jsx

```<code>    import  React from 'react';
    import Card from "../components/Card"

    const Home = ({
        items,
        searchValue,
        setSearchValue,
        onChangeSearchInput,
        onAddToFavorite,
        onAddToCart
              } ) =>{
        return (

                 <div className="content">

                    <div className="contentSearch">
                        <h1 className="titleContent">{searchValue ? `Поиск запроса: "${searchValue}"` : "Все кроссовки"}</h1>
                        <div className="searchBlock">
                            <img src="search.svg" alt="Search" width={14} height={14}></img>
                            {searchValue && <img src="clear.svg"
                                alt="Clear"
                                className="clear"
                                onClick={() => setSearchValue('')}
                            />}
                            <input onChange={onChangeSearchInput} value={searchValue} placeholder="Поиск..."></input>
                        </div>
                    </div>

                    <div className="sneakers" >
                        {items
                            .filter((item) => item.title.toLowerCase().includes(searchValue.toLowerCase()))
                            .map((item, index) => (
                                <Card
                                    key={index}
                                    onFavorite={onAddToFavorite}
                                    onPlus={onAddToCart}
                                    {...item}
                                />
                            ))}

                    </div>

                </div>

        )

    }
    export default Home;
</code>```

答:
```<code>npm i regenerator-runtime
</code>```

and in webpack.config.js add this setting to entry:

```<code> entry: ["regenerator-runtime/runtime", "./src/index.js"],
</code>```

ContentLicense: CC BY-SA 4.0

Body:
enter image description here    enter image description here

       WARNING in ./src/pages/Home.jsx 41:24-43

    export 'default' (imported as 'React') was not found in 'react' (possible exports: __esModule)
     @ ./src/App.js 7:0-32 158:46-50
     @ ./src/index.js 6:0-24 7:97-100

      [1]: https://i.stack.imgur.com/0mRcJ.png

----------

I am using a lot of ES6 syntax and I realize on apple systems sometimes certain feature dont work. So I figure this will be killing two birds with one stone. Minimizing and optimizing. This issue is I am unsure what the issue is here.

My webpack.config.js

const path = require('path');
    const MiniCssExtractPlugin = require("mini-css-extract-plugin");

    module.exports = {
      target: ['web', 'es5'],
      entry: path.resolve(__dirname, 'src/index.js'),
      output: {
        path: path.resolve(__dirname, 'public'),
        filename: 'bundle.js',

      },

      mode: "development",
      plugins: [new MiniCssExtractPlugin()],
      module: {
           rules: [
               {
                   test:/\.js$|jsx/,
                   use: ["babel-loader"],

               },

               {
                test: /\.s[ac]ss$/i,
                use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader" ]
               },

               {
                test: /\.(png|svg|jpg|jpeg|gif|mp4)$/i,
                type: 'asset/resource',
              },

              {
                test: /\.tsx?$/,
                use: 'ts-loader',
                exclude: /node_modules/,
              }

           ]

        },

        devServer: {
               static: {
                 directory: path.resolve(__dirname,'public') ,

               },

                open: true,
                liveReload: true,
                port:8080,
                historyApiFallback:true,

             },

             resolve: {
               extensions: ['.js', '.jsx'],
               alias: {
                 components: path.resolve(__dirname, 'src/components'),
                 images: path.resolve(__dirname, 'src/images'),
                 pages: path.resolve(__dirname, 'src/pages'),

               }
             }

    }

    ----------

My  babel-config.js

    module.exports = {
        presets: ['@babel/preset-env', '@babel/preset-react'],

        plugins: [
          [
              "@babel/plugin-proposal-class-properties",
              {
                  "loose": true
              }
          ],
          [
              "@babel/plugin-transform-runtime",
              {
                  "asyncGenerators": true,
                  "generators": true,
                  "async": true
              }
          ],
          ["@babel/plugin-proposal-export-default-from"]
      ]

      };

    ----------

index.js

    import React from 'react';
    import ReactDOM from 'react-dom';
    import "regenerator-runtime/runtime.js";
    import { BrowserRouter as Router } from 'react-router-dom';

    import './index.scss';

    import App  from './App'

    ReactDOM.render(
      <Router>
          <App />
      </Router>,
      document.getElementById('root')
    );

    ----------

components Home.jsx

    import  React from 'react';
    import Card from "../components/Card"

    const Home = ({
        items,
        searchValue,
        setSearchValue,
        onChangeSearchInput,
        onAddToFavorite,
        onAddToCart
              } ) =>{
        return (

{searchValue ? `Поиск запроса: "${searchValue}"` : "Все кроссовки"}

                            {searchValue &&  setSearchValue('')}
                            />}
                            <input onChange={onChangeSearchInput} value={searchValue} placeholder="Поиск..."></input>

                        {items
                            .filter((item) => item.title.toLowerCase().includes(searchValue.toLowerCase()))
                            .map((item, index) => (
                                <Card
                                    key={index}
                                    onFavorite={onAddToFavorite}
                                    onPlus={onAddToCart}
                                    {...item}
                                />
                            ))}

        )

    }
    export default Home;

Body:
npm i regenerator-runtime

and in webpack.config.js add this setting to entry:

 entry: ["regenerator-runtime/runtime", "./src/index.js"],


问:
Can you use a POST to GET data?
A company is asking me to do an Angular assignment. They provide the following instructions, but the API URL doesn't work:

```<code>Create a single page angular application and use the following API to retrieve sports results and sort into a table of results that are displayed. Each sport result contains several data and always includes the publication time.
Method: POST
Content-Type: application/json
Url: https://ancient-wood-1161.getsandbox.com:443/results
Tasks:
-Display the sports results in reverse chronological order on the page.
-Add a filter to the page to display only certain types or events (e.g. f1Results)
-How can you confirm the code works?
-Bonus: Implement the rest call asynchronously
</code>```

You can click the URL https://ancient-wood-1161.getsandbox.com:443/results right now and see that it doesn't work - it returns {"errors":[{"message":"Error processing request"}]} and in Angular it gives me a standard CORS error.

I asked the company to please send a working URL and/or update the API to accept requests from everywhere. Their response was:
*guy's name* confirmed it worked. It is a post and the content type is json.

Can you use a POST request to GET data?

答:
Absolutely. Take for example your avg Login Request that returns an access token for instance. It is going to be a POST as POST also has a bit more security than GET given that the payload is in the body rather than the URL string.

As for their excuse of it not working, try it in postman and see if the same issue still occurs. If it still does then ask them where did they test their API as if it is on prem then no duh the CORS would work. It is most likely not a company you would want to work for.

Title: Can you use a POST to GET data?

Body:
A company is asking me to do an Angular assignment. They provide the following instructions, but the API URL doesn't work:

Create a single page angular application and use the following API to retrieve sports results and sort into a table of results that are displayed. Each sport result contains several data and always includes the publication time.
Method: POST
Content-Type: application/json
Url: https://ancient-wood-1161.getsandbox.com:443/results
Tasks:
-Display the sports results in reverse chronological order on the page.
-Add a filter to the page to display only certain types or events (e.g. f1Results)
-How can you confirm the code works?
-Bonus: Implement the rest call asynchronously

You can click the URL https://ancient-wood-1161.getsandbox.com:443/results right now and see that it doesn't work - it returns {"errors":[{"message":"Error processing request"}]} and in Angular it gives me a standard CORS error.

I asked the company to please send a working URL and/or update the API to accept requests from everywhere. Their response was:
*guy's name* confirmed it worked. It is a post and the content type is json.

Can you use a POST request to GET data?


问:
Setting parameter based on output of text file?
I am working on code to read the output of a text file and will set a parameter (or variable?) of the number value of line 2. For testing purposes, it should read from the :NEW, but it doesn't.

This is the output of the text file:

```<code>var1=RANK|SCORE|NAME
var2=1|52456|NLM
var3=2|24610|ABS
var4=3|23385|ABT
var5=4|22158|ABU
var6=5|21821|ABV
var7=6|20272|ABW
var8=7|19476|ABX
var9=8|18864|ABY
</code>```

This is what I have so far, but it obviously isn't right:

```<code>@echo off
setlocal ENABLEDELAYEDEXPANSION
color 0a
set vidx=0
for /F "tokens=*" %%A in (hiscores.txt) do (
    SET /A vidx=!vidx! + 1
    set var!vidx!=%%A
)
set var

pause

set /p %var2=%

if %var2=% LSS 1|52456|NLM GOTO INVALID
if %var2=% EQU 1|52456|NLM GOTO NEW
if %var2=% GTR 1|52456|NLM GOTO SCORE

:INVALID
echo Sorry, you did not win any tickets this time!
PING -n 3 127.0.0.1 > NUL

:SCORE
echo Congratulations on a new high score!
PING -n 3 127.0.0.1 > NUL

:NEW
echo Congratulations on a new high score!
PING -n 3 127.0.0.1 > NUL
pause
</code>```

答:
Comments: You cannot set an environment variable name which contains =.

| is a special character which needs special processing.

```<code>@ECHO OFF
SETLOCAL
rem The following settings for the source directory and filenames are names
rem that I use for testing and deliberately include names which include spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.

SET "sourcedir=u:\your files"
SET "filename1=%sourcedir%\q71082577.txt"

FOR /f "usebackq delims=" %%b IN ("%filename1%") DO (SET "%%b")
SET var

SET /p "score=New score [number,name] ? "

SET "newscore="
FOR %%b IN (%score%) DO IF DEFINED newscore (SET "newname=%%b") else (SET "newscore=%%b")

SET "pos="
FOR /f "tokens=1-4delims==|" %%g IN ('set var') DO IF %newscore% gtr %%i IF NOT DEFINED pos SET /a pos=%%h+1

IF NOT DEFINED pos GOTO notontable

SET pos

:: shuffle lower scores down 1 place

IF %pos% lss 10 FOR /L %%p IN (9,-1,%pos%) DO (
 SET /a from=%%p - 1
 CALL CALL SET "var%%p=%%%%var%%from%%%%%%"
)

SET var

:: put new score into table

SET "var%pos%=new|%newscore%|%newname%"

SET var

:: Now correct column1 of data

FOR /L %%b IN (2,1,9) DO SET /a c1=%%b-1&FOR /f "tokens=1-4delims==|" %%g IN ('set var%%b') DO CALL SET "var%%b=%%c1%%|%%i|%%j"

SET var
SET /a pos-=1
ECHO new position ON table : %pos%

GOTO :EOF

:notontable
ECHO NOT ON high-score table
SET var
GOTO :eof
</code>```

Since each line of the file is of the form var=string, you can simply execute SET "linecontents" to set the var? values.

You are evidently maintaining a high-score table...

Get the candidate score and initials from the prompt in the format score,initials. I have deliberately left this unverified for format and assume the input will always be correct as it is likely to appear from elsewhere in your code.

Given that the string "input" is of the correct format, the variable newscore is set to nothing and %%b is used in a simple for which will assign each of the two comma-separated tokens in turn. The first token finds newscore is undefined, so assigns the first token to newscore. The second token - newscore is now defined, so the token is assigned to newname.

Next, a for/f is applied to each of the var? variables in turn. Since the set command will deliver the data in the form var3=2|24610|ABS and = and | are defined as delimiters, then token1..4 are "var3","2","24610" and "ABS" respectively, and these values are assigned to %%g..%%j. If the newscore input is greater than %%i (which contains the recorded score) then pos is assigned a value (table position + 1).

If pos is not defined, then the newly-input score is not greater than any existing scores, so its fate is to not be on the table.

Next bit is tricky.We need to copy each variable varn-1 to varn to shuffle the values down and duplicate the value of var%pos%. First, the operation only makes sense if pos is less than 10 (which means "matches lowest high-score") so for other values of pos, we need to calculate which variable to move, and assign that variable's value to var%pos%.

First step is obvious - set from as the value 1 less than %%p. Then there's the complicated bit. I'm attempting to avoid delayedexpansion as that introduces problems of "crossing the bridge" if not invoked ab initio.

So - decoding the statement

```<code>CALL CALL SET "var%%p=%%%%var%%from%%%%%%"
</code>```

First step is the inner call. Assuming %%p is 5 (and therefore from contains 4) then the set command is interpreted as

```<code>set "var5=%%var%from%%%"
</code>```

because %%p is 5 and %% is processed as %. The inner call inherits its values from the caller process, where from is defined as 4.

That set command is then re-interpreted in yet another subshell, which then substitutes for from, giving

```<code>set "var5=%var4%"
</code>```

So the value is then set from the previous value which means the values shuffle down as is displayed by the set var

Then assign the new values to the appropriate entry in pos.

Last step is to correct the values of the first data column. This only needs to be done for 2..9 as 1 is constant. The methodology should be obvious from the techniques used and described in this epistle.

Body:
I am working on code to read the output of a text file and will set a parameter (or variable?) of the number value of line 2. For testing purposes, it should read from the :NEW, but it doesn't.

This is the output of the text file:

var1=RANK|SCORE|NAME
var2=1|52456|NLM
var3=2|24610|ABS
var4=3|23385|ABT
var5=4|22158|ABU
var6=5|21821|ABV
var7=6|20272|ABW
var8=7|19476|ABX
var9=8|18864|ABY

This is what I have so far, but it obviously isn't right:

@echo off
setlocal ENABLEDELAYEDEXPANSION
color 0a
set vidx=0
for /F "tokens=*" %%A in (hiscores.txt) do (
    SET /A vidx=!vidx! + 1
    set var!vidx!=%%A
)
set var

pause

set /p %var2=%

if %var2=% LSS 1|52456|NLM GOTO INVALID
if %var2=% EQU 1|52456|NLM GOTO NEW
if %var2=% GTR 1|52456|NLM GOTO SCORE

:INVALID
echo Sorry, you did not win any tickets this time!
PING -n 3 127.0.0.1 > NUL

:SCORE
echo Congratulations on a new high score!
PING -n 3 127.0.0.1 > NUL

:NEW
echo Congratulations on a new high score!
PING -n 3 127.0.0.1 > NUL
pause

Body:
Comments: You cannot set an environment variable name which contains =.

| is a special character which needs special processing.

@ECHO OFF
SETLOCAL
rem The following settings for the source directory and filenames are names
rem that I use for testing and deliberately include names which include spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.

SET "sourcedir=u:\your files"
SET "filename1=%sourcedir%\q71082577.txt"

FOR /f "usebackq delims=" %%b IN ("%filename1%") DO (SET "%%b")
SET var

SET /p "score=New score [number,name] ? "

SET "newscore="
FOR %%b IN (%score%) DO IF DEFINED newscore (SET "newname=%%b") else (SET "newscore=%%b")

SET "pos="
FOR /f "tokens=1-4delims==|" %%g IN ('set var') DO IF %newscore% gtr %%i IF NOT DEFINED pos SET /a pos=%%h+1

IF NOT DEFINED pos GOTO notontable

SET pos

:: shuffle lower scores down 1 place

IF %pos% lss 10 FOR /L %%p IN (9,-1,%pos%) DO (
 SET /a from=%%p - 1
 CALL CALL SET "var%%p=%%%%var%%from%%%%%%"
)

SET var

:: put new score into table

SET "var%pos%=new|%newscore%|%newname%"

SET var

:: Now correct column1 of data

FOR /L %%b IN (2,1,9) DO SET /a c1=%%b-1&FOR /f "tokens=1-4delims==|" %%g IN ('set var%%b') DO CALL SET "var%%b=%%c1%%|%%i|%%j"

SET var
SET /a pos-=1
ECHO new position ON table : %pos%

GOTO :EOF

:notontable
ECHO NOT ON high-score table
SET var
GOTO :eof

Since each line of the file is of the form var=string, you can simply execute SET "linecontents" to set the var? values.

You are evidently maintaining a high-score table...

Get the candidate score and initials from the prompt in the format score,initials. I have deliberately left this unverified for format and assume the input will always be correct as it is likely to appear from elsewhere in your code.

Given that the string "input" is of the correct format, the variable newscore is set to nothing and %%b is used in a simple for which will assign each of the two comma-separated tokens in turn. The first token finds newscore is undefined, so assigns the first token to newscore. The second token - newscore is now defined, so the token is assigned to newname.

Next, a for/f is applied to each of the var? variables in turn. Since the set command will deliver the data in the form var3=2|24610|ABS and = and | are defined as delimiters, then token1..4 are "var3","2","24610" and "ABS" respectively, and these values are assigned to %%g..%%j. If the newscore input is greater than %%i (which contains the recorded score) then pos is assigned a value (table position + 1).

If pos is not defined, then the newly-input score is not greater than any existing scores, so its fate is to not be on the table.

Next bit is tricky.We need to copy each variable varn-1 to varn to shuffle the values down and duplicate the value of var%pos%. First, the operation only makes sense if pos is less than 10 (which means "matches lowest high-score") so for other values of pos, we need to calculate which variable to move, and assign that variable's value to var%pos%.

First step is obvious - set from as the value 1 less than %%p. Then there's the complicated bit. I'm attempting to avoid delayedexpansion as that introduces problems of "crossing the bridge" if not invoked ab initio.

So - decoding the statement

CALL CALL SET "var%%p=%%%%var%%from%%%%%%"

First step is the inner call. Assuming %%p is 5 (and therefore from contains 4) then the set command is interpreted as

set "var5=%%var%from%%%"

because %%p is 5 and %% is processed as %. The inner call inherits its values from the caller process, where from is defined as 4.

That set command is then re-interpreted in yet another subshell, which then substitutes for from, giving

set "var5=%var4%"

So the value is then set from the previous value which means the values shuffle down as is displayed by the set var

Then assign the new values to the appropriate entry in pos.

Last step is to correct the values of the first data column. This only needs to be done for 2..9 as 1 is constant. The methodology should be obvious from the techniques used and described in this epistle.


问:
Elasticsearch - Migrate data from one large index to many time-based indicies
We have one large index on 5 shards on a 5.5 cluster.  Each shard has several hundred GB of time-series data.  It's not log data for debugging, we're serving production requests doing aggregations on the documents.  So we need solid read performance on these aggregations, and enough indexing performance to keep up with the flow of new records.

Most of the aggregation queries probably need to only go over a subset of the data (e.g. the last 30 days of it), so we'd like to migrate the data to an index configuration where we have one index per day, or something similar so that we can increase the number of indexes / shards and scale more horizontally.

How do you migrate your data from one large index to 500 daily indexes?  I don't see an API in ES that lets you do this.  Can ILM do this during a re-index?

答:
if it's time based data, logs or something else, then treat it the same and use time based indices

ILM is the best longer term approach here, but a reindex into an ILM index/policy won't really work as it works of index ages, not the age of data in those indices

you could do a historic reindex into time based indices, and then point new data into an ILM policy, that'd be the best approach


问:
Update a table using JPA in Play Framework
I'm trying to update a table using JPA

```<code>EntityManager em=JPA.em();
EntityTransaction entr = em.getTransaction();
try{
if(!entr.isActive())
  entr.begin();
  Tblrecordtypefields updateTblrecordtypes = em.find(Tblrecordtypefields.class,9);
  updateTblrecordtypes.setFieldlabel("JPATest");
  em.getTransaction().commit();
}finally
{
if(entr.isActive())
entr.rollback();
}
</code>```

i'm getting the error
NullPointerException occured : null at
updateTblrecordtypes.setFieldlabel("JPATest");
What should i do.

答:
I see some possible issues in there:

First, Play manages the transactions on it's own. A transaction is created at the beginning of the request and committed (rollback if exception) at the end. You are trying to force your way into it, that's not recommended. To manage the entity, just do an entity.save() to mark it as "to be saved" and don't do tht to ignore any changes.

Second, if you are using the Model class in Play (as you should) you can use the "find" and "findById" methods provided by this class. This is recommened, instead of using the EntityManager directly.

See the documentation for more information.

Basically, redo your code to follow the Play way, to avoid problems :)

EDIT: as a clarification, I'm not really answering your question on why you get the NPE, but I think that as you are forcing your way into the settings of the framework you might (maybe not!) be seeing unexpected artifacts that will dissapear once you fix your code to follow convention.

If after that you still have the error let us know :)

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to update a table using JPA

EntityManager em=JPA.em();
EntityTransaction entr = em.getTransaction();
try{
if(!entr.isActive())
  entr.begin();
  Tblrecordtypefields updateTblrecordtypes = em.find(Tblrecordtypefields.class,9);
  updateTblrecordtypes.setFieldlabel("JPATest");
  em.getTransaction().commit();
}finally
{
if(entr.isActive())
entr.rollback();
}

i'm getting the error
NullPointerException occured : null at
updateTblrecordtypes.setFieldlabel("JPATest");
What should i do.


问:
Continue in range based for loop after exception
I have the following program that iterates through a directory and can catch exceptions:

```<code>#include <iostream>
#include <filesystem>
#include <exception>

int main() {

    const std::filesystem::path md("/");

    try {

        for(auto const& dir : std::filesystem::recursive_directory_iterator(md)) {
            std::cout << dir.path() << std::endl;
        }

    }
    catch(const std::exception& e) {
        std::cout << "Error: " << e.what() << std::endl;
    }

    return 0;
}
</code>```

The problem is, whenever an exception is thrown it exits the for loop and end the program. Is there any way to go back to the position where the for loop left off after handling the exception?

EDIT: The error is caused by the for loop recursive_directory_iterator not from inside the loop. It is guaranteed to throw the same error at the same position in the loop every time so I need continue to the loop at the position after the error is thrown.

答:
What you want is not fully possible with std::filesystem::recursive_directory_iterator, even if you write the loop manually.

There are two places where the iterator can throw exceptions1, the de-referencing operator (*it) and the increment operator (++it).

If any of these reports an error (i.e., throws an exception in your case), the iterator cannot be used anymore.2

For the de-referencing iterator, you can backup the iterator and skip invalid entries

auto it = std::filesystem::recursive_directory_iterator{md};
while (it != std::filesystem::recursive_directory_iterator{}) {
    const auto tmp_it = it;
    try {
        const auto& path = *tmp_it;
        // use path...
    }
    catch (std::filesystem::filesystem_error const&) {

    }

    // you can still increment it here
    ++it;
}
```
<p>Unfortunately, if the increment operator reports an error (throws or reports an <code>std::error_code</code>), there is not much you can do to simply "skip" that element — you can handle some cases, but not everything, e.g.</p>
<pre class="lang-cpp prettyprint-override"><code>std::error_code ec;
const auto backup = it;

// try increment
it.increment(ec);

// failed
if (ec) {
    it = backup;

    // the iterator tried to enter a directory and failed, disable the
    // recursion for the next entry
    if (it.recursion_pending()) {
        it.disable_recursion_pending();

        // try again
        it.increment(ec);
    }
}

// still failed, or was not recursion_pending()
if (ec) {
    it = backup;

    // try to skip the remaining entry at the given depth go back to
    // the parent
    it.pop(ec);
}

// nothing much you can do here unfortunately
if (ec) {

}
</code>```

1 The constructor can also report error but in this case you do not even have a valid iterator to begin with so that is not relevant for your question.

2 Standard quotes:

[filesystems#fs.class.directory.iterator.general-3]

If an iterator of type directory_iterator reports an error or is advanced past the last directory element, that iterator shall become equal to the end iterator value. [..]

[filesystems#fs.class.rec.dir.itr.general-3]

The behavior of a recursive_directory_iterator is the same as a directory_iterator unless otherwise specified.

Body:
I have the following program that iterates through a directory and can catch exceptions:

#include <iostream>
#include <filesystem>
#include <exception>

int main() {

    const std::filesystem::path md("/");

    try {

        for(auto const& dir : std::filesystem::recursive_directory_iterator(md)) {
            std::cout << dir.path() << std::endl;
        }

    }
    catch(const std::exception& e) {
        std::cout << "Error: " << e.what() << std::endl;
    }

    return 0;
}

The problem is, whenever an exception is thrown it exits the for loop and end the program. Is there any way to go back to the position where the for loop left off after handling the exception?

EDIT: The error is caused by the for loop recursive_directory_iterator not from inside the loop. It is guaranteed to throw the same error at the same position in the loop every time so I need continue to the loop at the position after the error is thrown.

Body:
What you want is not fully possible with std::filesystem::recursive_directory_iterator, even if you write the loop manually.

There are two places where the iterator can throw exceptions1, the de-referencing operator (*it) and the increment operator (++it).

If any of these reports an error (i.e., throws an exception in your case), the iterator cannot be used anymore.2

For the de-referencing iterator, you can backup the iterator and skip invalid entries

auto it = std::filesystem::recursive_directory_iterator{md};
while (it != std::filesystem::recursive_directory_iterator{}) {
    const auto tmp_it = it;
    try {
        const auto& path = *tmp_it;
        // use path...
    }
    catch (std::filesystem::filesystem_error const&) {

    }

    // you can still increment it here
    ++it;
}

Unfortunately, if the increment operator reports an error (throws or reports an std::error_code), there is not much you can do to simply "skip" that element — you can handle some cases, but not everything, e.g.

std::error_code ec;
const auto backup = it;

// try increment
it.increment(ec);

// failed
if (ec) {
    it = backup;

    // the iterator tried to enter a directory and failed, disable the
    // recursion for the next entry
    if (it.recursion_pending()) {
        it.disable_recursion_pending();

        // try again
        it.increment(ec);
    }
}

// still failed, or was not recursion_pending()
if (ec) {
    it = backup;

    // try to skip the remaining entry at the given depth go back to
    // the parent
    it.pop(ec);
}

// nothing much you can do here unfortunately
if (ec) {

}

1 The constructor can also report error but in this case you do not even have a valid iterator to begin with so that is not relevant for your question.

2 Standard quotes:

[filesystems#fs.class.directory.iterator.general-3]

If an iterator of type directory_iterator reports an error or is advanced past the last directory element, that iterator shall become equal to the end iterator value. [..]

[filesystems#fs.class.rec.dir.itr.general-3]

The behavior of a recursive_directory_iterator is the same as a directory_iterator unless otherwise specified.


问:
Elm - decoding a recursive multiway tree
I'm working on a recursive tree of this type

```<code>type Node anyType
  = Leaf Id (Maybe anyType) Name
  | Tree Id (List (Node anyType)) Name
</code>```

where

```<code>type Id
  = Id Int
  | Root
</code>```

and I'm trying to decode a json of this kind into it

```<code>{
  "id": "root",
  "entries": [
    {
      "id": 1,
      "value": 0,
      "name": "New Entry"
    },
    {
      "id": 2,
      "entries": [
        {
          "id": 4,
          "value": 0,
          "name": "New Entry"
        }
      ],
      "name": "New Entry"
    }
  ],
  "name": "Budget"
}
</code>```

To decode the Id type I'm using these decoders

```<code>rootDecoder =
(Decode.field "id" Decode.string)
    |> Decode.andThen
        (\str ->
            if str == "root" then
                (Decode.succeed Root)

            else
                Decode.fail <| "[exactMatch] tgt: " ++ "root" ++ " /= " ++ str
        )

intIdDecoder =
    Decode.map Id (Decode.field "id" Decode.int)

idDecoder =
    Decode.oneOf
        [ rootDecoder
        , intIdDecoder
        ]
</code>```

To decode the tree structure i tried the following, using Json.Decode.Pipeline:

```<code>leafDecoder valueDecoder =
    Decode.succeed Leaf
        |> required "id" idDecoder
        |> required "value" valueDecoder
        |> required "name" Decode.string

treeDecoder valueDecoder =
    Decode.succeed Tree
        |> required "id" idDecoder
        |> required "entries"
            (Decode.list
                (Decode.lazy
                    (\_ ->
                        Decode.oneOf
                            [ leafDecoder valueDecoder
                            , treeDecoder valueDecoder
                            ]
                    )
                )
            )
        |> required "name" Decode.string
</code>```

But when I try to decode the structure I get the following error:

```<code>The Json.Decode.oneOf at json.budget.entries[0] failed in the following 2 ways: (1) The Json.Decode.oneOf at json.id failed in the following 2 ways: (1) Problem with the given value: 1 Expecting an OBJECT with a field named `id` (2) Problem with the given value: 1 Expecting an OBJECT with a field named `id` (2) Problem with the given value: { "id": 1, "value": 0, "name": "New Entry" } Expecting an OBJECT with a field named `entries`
</code>```

But I don't understand why since both the field id and entries are there, and yet it complains.

What am I doing wrong?

Thanks in advance for the help

答:
The problem is that both rootDecoder and intIdDecoder are defined as looking for a field named "id" in an object via Decode.field "id" .... Inside treeDecoder, you are first fetching the "id" field, so your decoder is valid for some JSON like this

// Not what you're looking for
{
  "id": {
    "id": ...
  },
  ...
}
```
<p>You can fix this by removing the <code>Decode.field "id"</code> portion in those decoders:</p>
```rootDecoder = Decode.string
    |> Decode.andThen
        (\str ->
            if str == "root" then
                (Decode.succeed Root)

            else
                Decode.fail <| "[exactMatch] tgt: " ++ "root" ++ " /= " ++ str
        )

intIdDecoder =
    Decode.map Id Decode.int
```

Body:
I'm working on a recursive tree of this type

type Node anyType
  = Leaf Id (Maybe anyType) Name
  | Tree Id (List (Node anyType)) Name

where

type Id
  = Id Int
  | Root

and I'm trying to decode a json of this kind into it

{
  "id": "root",
  "entries": [
    {
      "id": 1,
      "value": 0,
      "name": "New Entry"
    },
    {
      "id": 2,
      "entries": [
        {
          "id": 4,
          "value": 0,
          "name": "New Entry"
        }
      ],
      "name": "New Entry"
    }
  ],
  "name": "Budget"
}

To decode the Id type I'm using these decoders

rootDecoder =
(Decode.field "id" Decode.string)
    |> Decode.andThen
        (\str ->
            if str == "root" then
                (Decode.succeed Root)

            else
                Decode.fail <| "[exactMatch] tgt: " ++ "root" ++ " /= " ++ str
        )

intIdDecoder =
    Decode.map Id (Decode.field "id" Decode.int)

idDecoder =
    Decode.oneOf
        [ rootDecoder
        , intIdDecoder
        ]

To decode the tree structure i tried the following, using Json.Decode.Pipeline:

leafDecoder valueDecoder =
    Decode.succeed Leaf
        |> required "id" idDecoder
        |> required "value" valueDecoder
        |> required "name" Decode.string

treeDecoder valueDecoder =
    Decode.succeed Tree
        |> required "id" idDecoder
        |> required "entries"
            (Decode.list
                (Decode.lazy
                    (\_ ->
                        Decode.oneOf
                            [ leafDecoder valueDecoder
                            , treeDecoder valueDecoder
                            ]
                    )
                )
            )
        |> required "name" Decode.string

But when I try to decode the structure I get the following error:

The Json.Decode.oneOf at json.budget.entries[0] failed in the following 2 ways: (1) The Json.Decode.oneOf at json.id failed in the following 2 ways: (1) Problem with the given value: 1 Expecting an OBJECT with a field named `id` (2) Problem with the given value: 1 Expecting an OBJECT with a field named `id` (2) Problem with the given value: { "id": 1, "value": 0, "name": "New Entry" } Expecting an OBJECT with a field named `entries`

But I don't understand why since both the field id and entries are there, and yet it complains.

What am I doing wrong?

Thanks in advance for the help

Body:
The problem is that both rootDecoder and intIdDecoder are defined as looking for a field named "id" in an object via Decode.field "id" .... Inside treeDecoder, you are first fetching the "id" field, so your decoder is valid for some JSON like this

// Not what you're looking for
{
  "id": {
    "id": ...
  },
  ...
}

You can fix this by removing the Decode.field "id" portion in those decoders:

rootDecoder = Decode.string
    |> Decode.andThen
        (\str ->
            if str == "root" then
                (Decode.succeed Root)

            else
                Decode.fail <| "[exactMatch] tgt: " ++ "root" ++ " /= " ++ str
        )

intIdDecoder =
    Decode.map Id Decode.int


问:
UIButton event 'Touch Up Inside' not working. 'Touch Down' works fine
I've got a UIButton in a UIView, which is in a UIViewController that I've allocated and inited from a .xib file.

When hooking an IBAction up to the 'Touch Down' event of a UIButton it triggers correctly. But if I hook it up to the 'Touch Up Inside' event it doesn't respond.

Other events don't work either. 'Touch Drag Enter', 'Touch Drag Exit', 'Touch Up Outside' etc. Only Touch Down.

Does anyone have any idea why this might be?

The button is a simple rounded rectangle button in a view controller.
I have loaded the view controller as such:

```<code>-(void) pushNewViewController
{
    MyViewController* newViewController = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil];
    [self.view addSubview:newViewController.view];
    [newViewController release];
}
</code>```

I've added this button to rounded rect button to MyViewController, in IB.
I created the following IBActions:

```<code>-(IBAction) buttonTouchDown:(id)sender
{
    NSLog(@"Button Touch Down Event Fired.");
}

-(IBAction) buttonTouchUpInside:(id)sender
{
    NSLog(@"Button Touch Up Inside Event Fired.");
}
</code>```

In the IB I menu clicked on the button and dragged the Touch Down outlet to MyViewController and selected buttonTouchDown:.  Saved the IB xib.

When I run and test the button and get the "Button Touch Down Event Fired" log message.

But when I go back to IB and change the Action to Touch Up Inside and hook it upto the buttonTouchUpInside: IBAction and save.  I test again, I get no response.

Regards,
Rich

答: Lol well this was dumb solution, but in the xib I had it linked to buttonTouchUp outside, and that was causing the problem.  Maybe this will help :)</p>

ContentLicense: CC BY-SA 2.5

Body:
I've got a UIButton in a UIView, which is in a UIViewController that I've allocated and inited from a .xib file.

When hooking an IBAction up to the 'Touch Down' event of a UIButton it triggers correctly. But if I hook it up to the 'Touch Up Inside' event it doesn't respond.

Other events don't work either. 'Touch Drag Enter', 'Touch Drag Exit', 'Touch Up Outside' etc. Only Touch Down.

Does anyone have any idea why this might be?

The button is a simple rounded rectangle button in a view controller.
I have loaded the view controller as such:

-(void) pushNewViewController
{
    MyViewController* newViewController = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil];
    [self.view addSubview:newViewController.view];
    [newViewController release];
}

I've added this button to rounded rect button to MyViewController, in IB.
I created the following IBActions:

-(IBAction) buttonTouchDown:(id)sender
{
    NSLog(@"Button Touch Down Event Fired.");
}

-(IBAction) buttonTouchUpInside:(id)sender
{
    NSLog(@"Button Touch Up Inside Event Fired.");
}

In the IB I menu clicked on the button and dragged the Touch Down outlet to MyViewController and selected buttonTouchDown:.  Saved the IB xib.

When I run and test the button and get the "Button Touch Down Event Fired" log message.

But when I go back to IB and change the Action to Touch Up Inside and hook it upto the buttonTouchUpInside: IBAction and save.  I test again, I get no response.

Regards,
Rich


答:
In your leafDecoder and treeDecoder you have the following lines:

```<code>leafDecoder valueDecoder =
    Decode.succeed Leaf
        |> required "id" idDecoder
        -- rest of function omitted...

treeDecoder valueDecoder =
    Decode.succeed Tree
        |> required "id" idDecoder
        -- rest of function omitted...
</code>```

These will both pull out the value of the field id within the current object and pass this value on to idDecoder, which calls Decode.oneOf with rootDecoder and intIdDecoder.

However, in your rootDecoder and intIdDecoder you have the following:

```<code>rootDecoder =
    (Decode.field "id" Decode.string)
        |> Decode.andThen
            -- rest of function omitted...

intIdDecoder =
    Decode.map Id (Decode.field "id" Decode.int)
</code>```

These decoders attempt to pull the value of a field named id from the current object. But you pass these functions the value of the id property, not an object containing this property.

These decoders would work if your ids were nested in objects that only contained id properties, for example:

{
  "id": {"id": "root"},
  "entries": [
    {
      "id": {"id": 1},
      "value": 0,
      "name": "New Entry"
    },
    ...
```
<p>The fix is to remove the calls to <code>Decode.field</code> in <code>rootDecoder</code> and <code>intIdDecoder</code>, as these decoders already get passed the value of the <code>id</code> field:</p>
```rootDecoder =
    Decode.string
        |> Decode.andThen
            -- rest of function as before, and omitted for brevity...

intIdDecoder =
    Decode.map Id Decode.int
```

Title: Elm - decoding a recursive multiway tree

Body:
In your leafDecoder and treeDecoder you have the following lines:

leafDecoder valueDecoder =
    Decode.succeed Leaf
        |> required "id" idDecoder
        -- rest of function omitted...

treeDecoder valueDecoder =
    Decode.succeed Tree
        |> required "id" idDecoder
        -- rest of function omitted...

These will both pull out the value of the field id within the current object and pass this value on to idDecoder, which calls Decode.oneOf with rootDecoder and intIdDecoder.

However, in your rootDecoder and intIdDecoder you have the following:

rootDecoder =
    (Decode.field "id" Decode.string)
        |> Decode.andThen
            -- rest of function omitted...

intIdDecoder =
    Decode.map Id (Decode.field "id" Decode.int)

These decoders attempt to pull the value of a field named id from the current object. But you pass these functions the value of the id property, not an object containing this property.

These decoders would work if your ids were nested in objects that only contained id properties, for example:

{
  "id": {"id": "root"},
  "entries": [
    {
      "id": {"id": 1},
      "value": 0,
      "name": "New Entry"
    },
    ...

The fix is to remove the calls to Decode.field in rootDecoder and intIdDecoder, as these decoders already get passed the value of the id field:

rootDecoder =
    Decode.string
        |> Decode.andThen
            -- rest of function as before, and omitted for brevity...

intIdDecoder =
    Decode.map Id Decode.int


问:
Object destructuring: Assign null values in one line
Assuming I have an object like this

```<code>foo = {
    a: 1,
    b: 2,
    c: 3
};
</code>```

I would destructure it this way

```<code>const {a, b, c} = foo;
</code>```

However, what, if the keys a, b and c do not exist?

```<code>foo = null;
</code>```

This won't work then

```<code>const {a, b, c} = foo;
</code>```

I would have to do something like

```<code>let a, b, c;

if(foo) {
    a = foo.a;
    b = foo.b;
    c = foo.c;
};
</code>```

Is there a way to do this in one line? Something like

```<code> const {a, b, c} = foo ? foo : null; // this is not working
</code>```

null is not an object. (evaluating '_ref2.a')

答:
When foo is not an object, you are going to have to give it an object so the destructuring can happen. So set it to an empty object using an 'or'. Now if foo is defined it will use foo, if it is not defined it will use the default object.

const foo = undefined;
const { a, b, c } = foo || {};
console.log(a, b, c);```
</div>
</div>
</p>
<p>If you want default values, set them in the object.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const foo = undefined;
const { a, b, c } = foo || {a : 'a', b: 'b', c: 'c' };
console.log(a, b, c);</code>```

If you want default values if the object does not provide them all, you can set values in the destructuring.

const foo = { a: 1};
const { a = "a", b = "b", c = "c" } = foo || {};
console.log(a, b, c);```

Body:
Assuming I have an object like this

foo = {
    a: 1,
    b: 2,
    c: 3
};

I would destructure it this way

const {a, b, c} = foo;

However, what, if the keys a, b and c do not exist?

foo = null;

This won't work then

const {a, b, c} = foo;

I would have to do something like

let a, b, c;

if(foo) {
    a = foo.a;
    b = foo.b;
    c = foo.c;
};

Is there a way to do this in one line? Something like

 const {a, b, c} = foo ? foo : null; // this is not working

null is not an object. (evaluating '_ref2.a')

Body:
When foo is not an object, you are going to have to give it an object so the destructuring can happen. So set it to an empty object using an 'or'. Now if foo is defined it will use foo, if it is not defined it will use the default object.

const foo = undefined;
const { a, b, c } = foo || {};
console.log(a, b, c);

If you want default values, set them in the object.

const foo = undefined;
const { a, b, c } = foo || {a : 'a', b: 'b', c: 'c' };
console.log(a, b, c);

If you want default values if the object does not provide them all, you can set values in the destructuring.

const foo = { a: 1};
const { a = "a", b = "b", c = "c" } = foo || {};
console.log(a, b, c);


问:
How to add values from an array as textContent with JavaScript
I'm having trouble figuring out how to add the values from an array as .textContent of a div.

What I want to happen is if I receive an array (topics) I want the contents of the array to be set as the .textContent of the elements with class="tab".

I feel like this code is correct, but doesn't seem to be working. Any ideas?

const Tabs = (topics) => {
  const tabsTopics = document.createElement("div");
  const tabsOne = document.createElement("div");
  const tabsTwo = document.createElement("div");
  const tabsThree = document.createElement("div");

  tabsTopics.classList.add("topics");
  tabsOne.classList.add("tab");
  tabsTwo.classList.add("tab");
  tabsThree.classList.add("tab");

  tabsTopics.appendChild(tabsOne);
  tabsTopics.appendChild(tabsTwo);
  tabsTopics.appendChild(tabsThree);

  document.querySelectorAll(".tab").forEach((el, i) => {
      el.textContent = topics[i];
    });

  return tabsTopics;
}

const topics = ['1', '2', '3'];

document.getElementById('container').appendChild(Tabs(topics));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container"></div></code>```

答:
You cannot querySelector/All while your elements are still in-memory, only after they are appended to the DOM.

Here's a suggestion/remake:

// DOM utility functions:

const EL = (sel, par) => (par || document).querySelector(sel);
const ELNew = (tag, prop) => Object.assign(document.createElement(tag), prop);

// Task:

const createTabs = (topics) => {

  // Create wrapper
  const EL_topics = ELNew("div", {className: "topics"});

  // Iterate topics and create tabs
  topics.forEach(topic => {
    EL_topics.append(ELNew("div", {className: "tab", textContent:topic}));
  });

  // Append wrapper to container
  EL("#container").append(EL_topics);
};

createTabs(["1", "2", "3"]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container"></div></code>```

Body:
You cannot querySelector/All while your elements are still in-memory, only after they are appended to the DOM.

Here's a suggestion/remake:

// DOM utility functions:

const EL = (sel, par) => (par || document).querySelector(sel);
const ELNew = (tag, prop) => Object.assign(document.createElement(tag), prop);

// Task:

const createTabs = (topics) => {

  // Create wrapper
  const EL_topics = ELNew("div", {className: "topics"});

  // Iterate topics and create tabs
  topics.forEach(topic => {
    EL_topics.append(ELNew("div", {className: "tab", textContent:topic}));
  });

  // Append wrapper to container
  EL("#container").append(EL_topics);
};

createTabs(["1", "2", "3"]);

<div id="container"></div>


问:
Javascript - Giving alert for string input but number
Hi recently I was writing a code which basically askes users to input a cost for any item.
The item name or price are not important so far.
How the system works is that a prompt pops up and asks what is the cost of the item, and when you enter a cost, it asks you again (while loop). When total cost reaches $36, while loop ends and an alert screen pops up saying your shipping is free since it is over $35.

My problem is when I enter string value as a user input it takes the value into cost array and since it goes as Nan value, my cost calculation never end even though it passes $36.

How can I eliminate any string input and do not push it into the array?

Here is my code:

```<code>while (complete === false) {
var costValue = prompt('Enter the cost of the item?');

//If user click cancel
if (costValue === null) {
alert('Process canceled');
complete = true;}

//AT THIS LINE HOW CAN I ELIMINATE STRING VALUES
//convert input to a number
userInput = parseInt(costValue);
/push the value into the array
myCost.push(userInput);
</code>```

答:
After you parse your user input into an integer (i.e. using parseInt method), then have an if statement that checks whether the parsed values is not NaN. If so, then only push the parsed value into your array.

```<code>// TRY parse user input into an integer
userInput = parseInt(costValue);

// only push into your array when it is not `NaN`
if (userInput !== 'NaN') {
// push the value into the array
myCost.push(userInput);
}
</code>```

Body:
Hi recently I was writing a code which basically askes users to input a cost for any item.
The item name or price are not important so far.
How the system works is that a prompt pops up and asks what is the cost of the item, and when you enter a cost, it asks you again (while loop). When total cost reaches $36, while loop ends and an alert screen pops up saying your shipping is free since it is over $35.

My problem is when I enter string value as a user input it takes the value into cost array and since it goes as Nan value, my cost calculation never end even though it passes $36.

How can I eliminate any string input and do not push it into the array?

Here is my code:

while (complete === false) {
var costValue = prompt('Enter the cost of the item?');

//If user click cancel
if (costValue === null) {
alert('Process canceled');
complete = true;}

//AT THIS LINE HOW CAN I ELIMINATE STRING VALUES
//convert input to a number
userInput = parseInt(costValue);
/push the value into the array
myCost.push(userInput);

Body:
After you parse your user input into an integer (i.e. using parseInt method), then have an if statement that checks whether the parsed values is not NaN. If so, then only push the parsed value into your array.

// TRY parse user input into an integer
userInput = parseInt(costValue);

// only push into your array when it is not `NaN`
if (userInput !== 'NaN') {
// push the value into the array
myCost.push(userInput);
}


问:
How can I avoid "Data too large" in ELK / elasticsearch bulk inserts?
I'm sending data daily to my elk-stack via https://metacpan.org/pod/Search::Elasticsearch::Client::7_0::Bulk
Sometimes it happens, more often recently, that I receive a "Data too large" error. The first part of my data was received, but after this error my sending script stops and I end up with incomplete data.

As far as I understood, correct me if I'm wrong, this happens when my stack is experiencing memory issues while processing the data it already received. I assume that, after some time, I could send the rest of the data, because the next day, the same issue occurs: The first bunch of my data is processed, the rest rejected with "Data too large".

I saw that I can add an "on-error" callback, but I have no clue what I can do in it. My idea would be to implement a delay and retry after some time.

Can anyone give me have a hint how to achieve it?
Are there any ideas how to avoid the issue in the first place? I already increased heap space some time ago, but after 2 month the issue reoccured.

答:
you'd need to check your Elasticsearch logs and the full response that Elasticsearch sends back (eg was it a 429?). however heap pressure can cause this, and you'd probably need to dig into why you are experiencing that

the other option is to reduce the size of your requests that you are sending


问:
calculating counts and percentages of a variable
I am trying to create a count of the number of observations and extract percentages from those counts.

I have data that looks like this:

```<code>UserID              substance_use
43124                       0
43124                       1
43124                       0
43124                       0
43124                       1
215                         1
215                         1

</code>```

I want a count of the total observations of substance use like this:

```<code>UserID             substance_use                                 count
43124                       0                                        5
43124                       1                                        5
43124                       0                                        5
43124                       0                                        5
43124                       1                                        5
215                         1                                        2
215                         1                                        2

</code>```

And then, I want the % of visits that participants said yes and no, like this:

```<code>UserID      substance_use      count      percent_yes       percent_no
43124        0                  5            40%               60%
43124        1                  5            40%               60%
43124        0                  5            40%               60%
43124        0                  5            40%               60%
43124        1                  5            40%              0%
215          1                  2            100%              0
215          1                  2            100%              0%
</code>```

I tried using the count function for the first part, but it's not taking into account the 0's. Any help would be greatly appreciated.

答:
We may use add_count to create the 'count' column and then get the mean of the binary column by group to return the percent_yes and subtract 100 from the percent_yes to return percent_no

```<code>library(dplyr)
df1 %>%
  add_count(UserID, name = 'count') %>%
  group_by(UserID) %>%
  mutate(percent_yes = 100 * mean(substance_use),
       percent_no = 100 - percent_yes) %>%
  ungroup
</code>```

-output

```<code># A tibble: 7 × 5
  UserID substance_use count percent_yes percent_no
   <int>         <int> <int>       <dbl>      <dbl>
1  43124             0     5          40         60
2  43124             1     5          40         60
3  43124             0     5          40         60
4  43124             0     5          40         60
5  43124             1     5          40         60
6    215             1     2         100          0
7    215             1     2         100          0
</code>```

NOTE: Here, we assumed no missing values in 'substance_use' column

data

```<code>df1 <- structure(list(UserID = c(43124L, 43124L, 43124L, 43124L, 43124L,
215L, 215L), substance_use = c(0L, 1L, 0L, 0L, 1L, 1L, 1L)),
class = "data.frame", row.names = c(NA,
-7L))
</code>```

Body:
I am trying to create a count of the number of observations and extract percentages from those counts.

I have data that looks like this:

UserID              substance_use
43124                       0
43124                       1
43124                       0
43124                       0
43124                       1
215                         1
215                         1

I want a count of the total observations of substance use like this:

UserID             substance_use                                 count
43124                       0                                        5
43124                       1                                        5
43124                       0                                        5
43124                       0                                        5
43124                       1                                        5
215                         1                                        2
215                         1                                        2

And then, I want the % of visits that participants said yes and no, like this:

UserID      substance_use      count      percent_yes       percent_no
43124        0                  5            40%               60%
43124        1                  5            40%               60%
43124        0                  5            40%               60%
43124        0                  5            40%               60%
43124        1                  5            40%              0%
215          1                  2            100%              0
215          1                  2            100%              0%

I tried using the count function for the first part, but it's not taking into account the 0's. Any help would be greatly appreciated.

Body:
We may use add_count to create the 'count' column and then get the mean of the binary column by group to return the percent_yes and subtract 100 from the percent_yes to return percent_no

library(dplyr)
df1 %>%
  add_count(UserID, name = 'count') %>%
  group_by(UserID) %>%
  mutate(percent_yes = 100 * mean(substance_use),
       percent_no = 100 - percent_yes) %>%
  ungroup

-output

# A tibble: 7 × 5
  UserID substance_use count percent_yes percent_no
   <int>         <int> <int>       <dbl>      <dbl>
1  43124             0     5          40         60
2  43124             1     5          40         60
3  43124             0     5          40         60
4  43124             0     5          40         60
5  43124             1     5          40         60
6    215             1     2         100          0
7    215             1     2         100          0

NOTE: Here, we assumed no missing values in 'substance_use' column

data

df1 <- structure(list(UserID = c(43124L, 43124L, 43124L, 43124L, 43124L,
215L, 215L), substance_use = c(0L, 1L, 0L, 0L, 1L, 1L, 1L)),
class = "data.frame", row.names = c(NA,
-7L))


问:
Behat, PhantomJS - wait for page load after clicking link?
I'm using Behat 3 and PhantomJS 2. Currently I have a scenario defined as such:

```<code>@javascript
Scenario: I visit the blog through the Blog & Events menu.
  Given I am an anonymous user
  And I am on the homepage
  And I follow "Link Text"
  Then I should be on "/path-to-page"
</code>```

When I run this with Goutte it's fine. When I run this with vanilla Selenium, it's fine (it launches a browser I can see). However, when I configure Selenium to point the webdriver host to PhantomJS, it explodes on Then I should be on "/path-to-page" claiming it's still on /.

If I add the following wait step:

```<code>@javascript
Scenario: I visit the blog through the Blog & Events menu.
  Given I am an anonymous user
  And I am on the homepage
  And I follow "Link Text"
  And I wait 4 seconds
  Then I should be on "/path-to-page"
</code>```

Then my scenario passes in the green, all good.

Is there a way to get PhantomJS to wait for the page to load before checking the current path? I don't want to depend on arbitrary timeouts. I need a headless solution and PhantomJS seems to be pretty well supported, but if I can't do something as simple as clicking a link and verifying the page that was loaded without adding random waiting steps everywhere, I might need to re-evaluate my decision.

答:
You can always make use of a closure function to encapsule your steps, just as mentioned in the docs. Through it, you can get your steps to run when they're ready. Let's implement a spinner function:

```<code>public function spinner($closure, $secs) {
    for ($i = 0; $i <= $secs; $i++) {
        try {
            $closure();
            return;
        }
        catch (Exception $e) {
            if ($i == $secs) {
                throw $e;
            }
        }
        sleep(1);
    }
}
</code>```

What we're doing here is wait for a number of seconds for the closure function to run successfully. When the time's run out, throw an exception, for we want to know when something's not behaving correctly.

Now let's wrap your function to assert you're in the right page within the spinner:

```<code>public function iShouldBeOnPage($wantedUrl) {
    $this->spinner(function() use($wantedUrl) {
        $currentUrl = $this->getSession()->getCurrentUrl();
        if ($currentUrl == $wantedUrl) {
            return;
        }
        else {
            throw new Exception("url is $currentUrl, not $wantedUrl");
        }
    }, 30);
</code>```

What we're doing here is wait up to 30 seconds to be on the url we want to be after clicking the button. It will not wait for 30 secs, but for as many secs we need until current url is the url we need to be at. Applying it in your function within the *Context.php will result in it being applied in every step you call it within your Gherkin files.

Body:
I'm using Behat 3 and PhantomJS 2. Currently I have a scenario defined as such:

@javascript
Scenario: I visit the blog through the Blog & Events menu.
  Given I am an anonymous user
  And I am on the homepage
  And I follow "Link Text"
  Then I should be on "/path-to-page"

When I run this with Goutte it's fine. When I run this with vanilla Selenium, it's fine (it launches a browser I can see). However, when I configure Selenium to point the webdriver host to PhantomJS, it explodes on Then I should be on "/path-to-page" claiming it's still on /.

If I add the following wait step:

@javascript
Scenario: I visit the blog through the Blog & Events menu.
  Given I am an anonymous user
  And I am on the homepage
  And I follow "Link Text"
  And I wait 4 seconds
  Then I should be on "/path-to-page"

Then my scenario passes in the green, all good.

Is there a way to get PhantomJS to wait for the page to load before checking the current path? I don't want to depend on arbitrary timeouts. I need a headless solution and PhantomJS seems to be pretty well supported, but if I can't do something as simple as clicking a link and verifying the page that was loaded without adding random waiting steps everywhere, I might need to re-evaluate my decision.

Body:
You can always make use of a closure function to encapsule your steps, just as mentioned in the docs. Through it, you can get your steps to run when they're ready. Let's implement a spinner function:

public function spinner($closure, $secs) {
    for ($i = 0; $i <= $secs; $i++) {
        try {
            $closure();
            return;
        }
        catch (Exception $e) {
            if ($i == $secs) {
                throw $e;
            }
        }
        sleep(1);
    }
}

What we're doing here is wait for a number of seconds for the closure function to run successfully. When the time's run out, throw an exception, for we want to know when something's not behaving correctly.

Now let's wrap your function to assert you're in the right page within the spinner:

public function iShouldBeOnPage($wantedUrl) {
    $this->spinner(function() use($wantedUrl) {
        $currentUrl = $this->getSession()->getCurrentUrl();
        if ($currentUrl == $wantedUrl) {
            return;
        }
        else {
            throw new Exception("url is $currentUrl, not $wantedUrl");
        }
    }, 30);

What we're doing here is wait up to 30 seconds to be on the url we want to be after clicking the button. It will not wait for 30 secs, but for as many secs we need until current url is the url we need to be at. Applying it in your function within the *Context.php will result in it being applied in every step you call it within your Gherkin files.


问:
Can i use more than once $(document).ready() of jquery in a single html page?
i have one html page named "text.html"

```<code><html>
    <body>
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript" src="js/Photos.js"></script>
        <script type="text/javascript" src="js/Animations.js"></script>
    </body>
</html>
</code>```

Both Photos.js and Animations.js start with "$(document).ready()" like this

```<code>//Javascript File Photos.js
$(document).ready(function() {
    //My code here ....
});

//Javascript File Animations.js
$(document).ready(function() {
    //My code here ....
});
</code>```

Does it matter if i use multiple $(document).ready(function() { in a single html page??

Thanks, in advance

答:
You can use as many as you would like, but its best to keep it to one for readability.

Also consider using short hand $(function() { ... });

Body:
i have one html page named "text.html"

Both Photos.js and Animations.js start with "$(document).ready()" like this

//Javascript File Photos.js
$(document).ready(function() {
    //My code here ....
});

//Javascript File Animations.js
$(document).ready(function() {
    //My code here ....
});

Does it matter if i use multiple $(document).ready(function() { in a single html page??

Thanks, in advance


问:
Convert time json to minutes and seconds
I have this json:

"result": {
  "status": "passed",
  "duration": 255561500
}
```

I would like to convert the number (255561500) in attribute duration to minutes and seconds.
And what format is this number?

答:
You can use Time.at to convert a value in date type.
This is a basic example as I do it.</p>
```<code>strJson = '{"result": { "status": "passed", "duration": 255561500 }}'
yourJson = JSON.parse(strJson)
duration = yourJson['result']['duration']
valueInDateFormat =Time.at(duration).utc.strftime("%H:%M:%S")
</code>```

Body:
I have this json:

"result": {
  "status": "passed",
  "duration": 255561500
}

I would like to convert the number (255561500) in attribute duration to minutes and seconds.
And what format is this number?

Body:
You can use Time.at to convert a value in date type.
This is a basic example as I do it.

strJson = '{"result": { "status": "passed", "duration": 255561500 }}'
yourJson = JSON.parse(strJson)
duration = yourJson['result']['duration']
valueInDateFormat =Time.at(duration).utc.strftime("%H:%M:%S")


问:
Flask Dynamic URL routing - bad request 400
I'm using Flask to build a web app and having issues with dynamic routing with variables.
I'm getting a bad request when I run the program.

The whole goal is to create a dynamic URL. The hope is to get dynamic URLs based on user selection. Running the program shows the correct URL (webapp.com/result/ko) but will not show the contents of the page.

Python:

```<code>from flask import Flask, redirect, render_template, request, url_for

app = Flask(__name__)
# This saves the users requested ticker choice in a varible to be used later
def users_request():
    global ticker_choice
    ticker_choice = request.form["variable"]
    return("Your choosen ticker: " + ticker_choice.upper())

class companySearch:

    # Stock price function
    def stock_price_func(self):
        try:
            with urlopen(base_url + quote + ticker_choice.upper() + api_key) as response:
                source = response.read()
                data = json.loads(source)

            price = "$" + str((data[0]["price"]))
            return(price)
        except:
            return("-")

# Routing to the homepage
@app.route("/", methods = ["GET", "POST"])
def market_hours_today():
    if request.method == "POST":
        result = request.form["variable"]
        return redirect(url_for("ticker_result", variable=result))

    return render_template(
        "index.html")

# Routing to the result page
@app.route("/result/<variable>", methods = ["GET", "POST"])
def ticker_result(variable):
    users_ticker_choice = users_request()
    stock_price = companySearch().stock_price_func()
    if request.method == "POST":
        result = request.form["variable"]
        return render_template(
            "result.html",
            result=result,
            users_ticker_choice=users_ticker_choice,
            stock_price=stock_price)

if __name__ == '__main__':
    app.run(debug=True)
</code>```

HTML:

```<code><!DOCTYPE html>
<html lang="en">
</head>
<body>
    <div class="container">
        <div class="cell" id="cell-1-2">
            <span class="data" style="text-align: center;">
                <form action="{{ url_for('market_hours_today') }}" method="POST">
                <input type="text" name="variable" placeholder="search ticker or company" maxlength="4" font-size="24px" onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" style="text-transform:uppercase">
                <input class="button" type="submit" value="Search" onclick="tickerSymbol();">
                </form>
            </span>
        </div>
    </div>
</body>
</html>
</code>```

答: That's because you have return for only POST requests. You don't return anything for get requests</p>

Body:
I'm using Flask to build a web app and having issues with dynamic routing with variables.
I'm getting a bad request when I run the program.

The whole goal is to create a dynamic URL. The hope is to get dynamic URLs based on user selection. Running the program shows the correct URL (webapp.com/result/ko) but will not show the contents of the page.

Python:

from flask import Flask, redirect, render_template, request, url_for

app = Flask(__name__)
# This saves the users requested ticker choice in a varible to be used later
def users_request():
    global ticker_choice
    ticker_choice = request.form["variable"]
    return("Your choosen ticker: " + ticker_choice.upper())

class companySearch:

    # Stock price function
    def stock_price_func(self):
        try:
            with urlopen(base_url + quote + ticker_choice.upper() + api_key) as response:
                source = response.read()
                data = json.loads(source)

            price = "$" + str((data[0]["price"]))
            return(price)
        except:
            return("-")

# Routing to the homepage
@app.route("/", methods = ["GET", "POST"])
def market_hours_today():
    if request.method == "POST":
        result = request.form["variable"]
        return redirect(url_for("ticker_result", variable=result))

    return render_template(
        "index.html")

# Routing to the result page
@app.route("/result/<variable>", methods = ["GET", "POST"])
def ticker_result(variable):
    users_ticker_choice = users_request()
    stock_price = companySearch().stock_price_func()
    if request.method == "POST":
        result = request.form["variable"]
        return render_template(
            "result.html",
            result=result,
            users_ticker_choice=users_ticker_choice,
            stock_price=stock_price)

if __name__ == '__main__':
    app.run(debug=True)

HTML:

<!DOCTYPE html>

                <form action="{{ url_for('market_hours_today') }}" method="POST">
                <input type="text" name="variable" placeholder="search ticker or company" maxlength="4" font-size="24px" onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" style="text-transform:uppercase">
                <input class="button" type="submit" value="Search" onclick="tickerSymbol();">
                </form>


问:
How to cache the RUN npm install instruction when docker build a Dockerfile
I am currently developing a Node backend for my application.
When dockerizing it (docker build .) the longest phase is the RUN npm install. The RUN npm install instruction runs on every small server code change, which impedes productivity through increased build time.

I found that running npm install where the application code lives and adding the node_modules to the container with the ADD instruction solves this issue, but it is far from best practice. It kind of breaks the whole idea of dockerizing it and it cause the container to weight much more.

Any other solutions?

答:
I wanted to use volumes, not copy, and keep using docker compose, and I could do it chaining the commands at the end</p>
```<code>FROM debian:latest
RUN apt -y update \
    && apt -y install curl \
    && curl -sL https://deb.nodesource.com/setup_12.x | bash - \
    && apt -y install nodejs
RUN apt -y update \
    &&  apt -y install wget \
        build-essential \
        net-tools
RUN npm install pm2 -g

RUN mkdir -p /home/services_monitor/ && touch /home/services_monitor/
RUN chown -R root:root /home/services_monitor/

WORKDIR /home/services_monitor/

CMD npm install \
    && pm2-runtime /home/services_monitor/start.json
</code>```

Body:
I wanted to use volumes, not copy, and keep using docker compose, and I could do it chaining the commands at the end

FROM debian:latest
RUN apt -y update \
    && apt -y install curl \
    && curl -sL https://deb.nodesource.com/setup_12.x | bash - \
    && apt -y install nodejs
RUN apt -y update \
    &&  apt -y install wget \
        build-essential \
        net-tools
RUN npm install pm2 -g

RUN mkdir -p /home/services_monitor/ && touch /home/services_monitor/
RUN chown -R root:root /home/services_monitor/

WORKDIR /home/services_monitor/

CMD npm install \
    && pm2-runtime /home/services_monitor/start.json


问:
Azure AD B2C Forgot Password with Text instead of Email?
We currently have a user flow that when someone resets their password an email is sent and they copy the validation code and they can move on.

I would like to add the option that it can be from an email OR from a text message.

However I cannot seem to find any documentation on this.

Is it possible to do with User Flow in Azure AD B2C?

答:
There are some samples here that show you how to do this.

e.g. "Demonstrate how to use a displayControl to conditionally process on the user's decision to verify their account via Email OTP or SMS".

I don't believe you can do it in user flow.


答:
You are always refering to an element one behind where you think you are.

This is the corrected code:

def my_saving_plan(P0, i, goal):
    P = [P0]
    years = 0
    for n in range(0, 10000):
        if P[n] < goal:
            P.append((1 + i) * P[n])
            years += 1
        else:
            print(P)
            return years
print(my_saving_plan(1000, 0.07, 2000))
```

Your code had: P.append((1+i)*P[n-1]).

The expression: P[n-1] on the first iteration has n == 0, so n-1 is -1 which refers to the last element, which is the same as the first element since there is only one element P0.

Each subsequent iteration (where n is 1...) then refers to the previous element, so you end up calculating each value twice.

Title: Why is my program calculating the compound interest twice

Body:
I want to calculate the time it takes for the compound interest to reach a certain goal by using Pn=(1+i)Pn−1.
What I have done is:

def my_saving_plan(P0,i,goal):
    P = [P0]
    years = 0
    for n in range(0,10000):
        if P[n] < goal:
            P.append((1+i)*P[n-1])
            years += 1
            print(P)
        elif P[n] >= goal:
            return years
print(my_saving_plan(1000, 0.07, 2000))

But What I get from that is the number of compound interest twice. So for this example what I get is:

    [1000, 1070.0, 1070.0, 1144.9, 1144.9, 1225.0430000000001,
1225.0430000000001, 1310.7960100000003, 1310.7960100000003,
1402.5517307000005, 1402.5517307000005, 1500.7303518490005,
1500.7303518490005, 1605.7814764784307, 1605.7814764784307,
 1718.186179831921, 1718.186179831921, 1838.4592124201556,
1838.4592124201556, 1967.1513572895667, 1967.1513572895667,
2104.8519522998363]
    21

Also I was wondering if there is a way to use a while loop instead of putting a ridiculous number in the for loop.

Body:
You are always refering to an element one behind where you think you are.

This is the corrected code:

def my_saving_plan(P0, i, goal):
    P = [P0]
    years = 0
    for n in range(0, 10000):
        if P[n] < goal:
            P.append((1 + i) * P[n])
            years += 1
        else:
            print(P)
            return years
print(my_saving_plan(1000, 0.07, 2000))

Your code had: P.append((1+i)*P[n-1]).

The expression: P[n-1] on the first iteration has n == 0, so n-1 is -1 which refers to the last element, which is the same as the first element since there is only one element P0.

Each subsequent iteration (where n is 1...) then refers to the previous element, so you end up calculating each value twice.


问:
Rails Concern class_macro with params from inherited class
This is probably a really easy question but I'd like to have a concern which adds a validation whose parameters depend on methods in the derived class.  For instance, I'd like to have a concern SlugHelpers as follows

```<code>module SlugHelpers
  extend ActiveSupport::Concern

  included do
     validates :slug, uniqueness: { case_sensitive: false, message: "Slug must be unique", scope: slug_scope }, presence: true,

  end

  class_methods do
    def slug_scope
      []
    end
  end

end

</code>```

But then have a model Post which overrides slug_scope, e.g.,

```<code>class Post < ApplicationRecord
  include SlugHelpers

  def self.slug_scope
     [:stream_id, :stream_type]
  end

</code>```

I want the slug_scope defined in Post to override the slug_scope used in the included do (though I might be calling that wrong, maybe I need self.class.slug_scope) but as written I think that this won't work (isn't the included do executed before the derived class defines its methods)?

Can I do this somehow using prepended do?  Or is the way I wrote this roughly correct?  I know that included modules are entered into inheritance chain before the derived class but I'm obviously kinda confused about when/where code in an included do block gets executed.

答:
As described by @mu_is_too_short you can just create a class method which adds the validations to the class when called:

```<code>module SlugHelpers
  extend ActiveSupport::Concern
  class_methods do
    def has_slug(name = :slug, scope: :default_value)
        validates_uniqueness_of name,
           case_sensitive: false,
           message: "Slug must be unique",
           scope: scope
        validates_presence_of name
    end
  end
end
</code>```

This is the generally preferred way in Ruby to make the behavior provided by modules configurable.

```<code>class Foo
  include SlugHelpers
  has_slug(scope: [:foo, :bar])
end
</code>```
```<code>class Bar
  include SlugHelpers
  has_slug(scope: [:baz, :bar])
end
</code>```

While you could actually call a method on the class when the module is included it would produce very strange results if you want to override the behavior in subclasses since it still would be evaluated just when the module was included.

Body:
This is probably a really easy question but I'd like to have a concern which adds a validation whose parameters depend on methods in the derived class.  For instance, I'd like to have a concern SlugHelpers as follows

module SlugHelpers
  extend ActiveSupport::Concern

  included do
     validates :slug, uniqueness: { case_sensitive: false, message: "Slug must be unique", scope: slug_scope }, presence: true,

  end

  class_methods do
    def slug_scope
      []
    end
  end

end

But then have a model Post which overrides slug_scope, e.g.,

class Post < ApplicationRecord
  include SlugHelpers

  def self.slug_scope
     [:stream_id, :stream_type]
  end

I want the slug_scope defined in Post to override the slug_scope used in the included do (though I might be calling that wrong, maybe I need self.class.slug_scope) but as written I think that this won't work (isn't the included do executed before the derived class defines its methods)?

Can I do this somehow using prepended do?  Or is the way I wrote this roughly correct?  I know that included modules are entered into inheritance chain before the derived class but I'm obviously kinda confused about when/where code in an included do block gets executed.

Body:
As described by @mu_is_too_short you can just create a class method which adds the validations to the class when called:

module SlugHelpers
  extend ActiveSupport::Concern
  class_methods do
    def has_slug(name = :slug, scope: :default_value)
        validates_uniqueness_of name,
           case_sensitive: false,
           message: "Slug must be unique",
           scope: scope
        validates_presence_of name
    end
  end
end

This is the generally preferred way in Ruby to make the behavior provided by modules configurable.

class Foo
  include SlugHelpers
  has_slug(scope: [:foo, :bar])
end

class Bar
  include SlugHelpers
  has_slug(scope: [:baz, :bar])
end

While you could actually call a method on the class when the module is included it would produce very strange results if you want to override the behavior in subclasses since it still would be evaluated just when the module was included.


问:
"Create App Packages" from Command Line instead of Visual Studio
Using Visual Studio 2022 I'm able to successfully create App Packages (MSIXBUNDLE) via a Windows Application Packaging Project.

Folder strucure/output:

https://learn.microsoft.com/en-us/windows/msix/desktop/desktop-to-uwp-packaging-dot-net

I'm trying to replicate this via the Command Line. I can't seem to find any basic documentation on how to perform this so it can be part of CI?

答:
```<code>msbuild MyApp.AppPkg/MyApp.AppPkg.wapproj /nologo /nr:false /p:AppxBundle=Always /p:UapAppxPackageBuildMode=Sideload /p:AppxBundlePlatforms="x64" /p:AppxPackageDir="C:\out\BuildTest" /p:platform="x64" /p:configuration="Release"
</code>```

Seems to be working for me!

Body:
msbuild MyApp.AppPkg/MyApp.AppPkg.wapproj /nologo /nr:false /p:AppxBundle=Always /p:UapAppxPackageBuildMode=Sideload /p:AppxBundlePlatforms="x64" /p:AppxPackageDir="C:\out\BuildTest" /p:platform="x64" /p:configuration="Release"

Seems to be working for me!


问:
Graph search with weight limit
I have a undirected, weighted graph with objects of an arbitrary type as nodes. The weight of an edge between two nodes A and B is the similarity of these two nodes in the interval (0, 1]. A similarity of 0 leads to no connection between to nodes, so the graph may be partitioned.

Given a target weight w and a start-node S,  which is an algorithm to find all nodes that have a weight > w. Subnodes (seen from S) should have the product of all weights on the path. I.e:

```<code>S --(0.9)-- N1 --(0.9)-- N2 --(0.6) -- N3
</code>```

Starting with S the nodes will have the following similarity values:

```<code>N1: 0.9
N2: 0.9 * 0.9 = 0.81
N3: 0.9 * 0.9 * 0.6 = 0.486
</code>```

So given S and the target weight 0.5 the search should return N1 and N3. Wheres a search starting from N2 would return S, N1 and N3.

Are their any algorithms that fit my needs?

答:
You could try using the Bellman-Ford algorithm, since it's working fine with both summation and multiplication of edges, as well as with minimums and maximums (you calculate the longest paths -- use the maximum -- by doing the inverted operation).

Also, if you take a logarithm of all your paths, the problem then reduces from multiplication to summation. After that, you could reverse the signs of the weights (to turn the problem from finding a minimum to finding the maximum) and use the Bellman-Ford algorithm on that graph. Since all your weights are initially between 0 and 1, after both of these transformations you should probably be able to use Dijkstra as well.

Then after calculating the paths, just revert the transformations back and check which "distances" suit you.

Title: Graph search with weight limit

Body:
I have a undirected, weighted graph with objects of an arbitrary type as nodes. The weight of an edge between two nodes A and B is the similarity of these two nodes in the interval (0, 1]. A similarity of 0 leads to no connection between to nodes, so the graph may be partitioned.

Given a target weight w and a start-node S,  which is an algorithm to find all nodes that have a weight > w. Subnodes (seen from S) should have the product of all weights on the path. I.e:

S --(0.9)-- N1 --(0.9)-- N2 --(0.6) -- N3

Starting with S the nodes will have the following similarity values:

N1: 0.9
N2: 0.9 * 0.9 = 0.81
N3: 0.9 * 0.9 * 0.6 = 0.486

So given S and the target weight 0.5 the search should return N1 and N3. Wheres a search starting from N2 would return S, N1 and N3.

Are their any algorithms that fit my needs?


问:
What is causing a NullPointerException in dispatchWindowVisibilityChanged for Flutter 2.10 app?
Since updating my app to the latest stable version of Flutter (2.10) targeting API 31, I am seeing in Crashlytics lots of exceptions similar to this:

Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.dispatchWindowVisibilityChanged(int)' on a null object reference
at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1619)
at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1619)
at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1619)
at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1619)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2646)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:2143)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:8665)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1037)
at android.view.Choreographer.doCallbacks(Choreographer.java:845)
at android.view.Choreographer.doFrame(Choreographer.java:780)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:1022)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7839)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)

The crash occurs mostly in the background. I saw some other posts about the Google ad control, but I am not serving ads. I do display a Google map control using hybrid composition, but I have no idea if that is even related. I need some ideas on what is causing this and how to track it down.

答:
This crash is a known issue with Flutter v2.10.

Please upgrade to v2.10.1 with flutter upgrade --force which resovles the issue.

Reference: https://github.com/flutter/flutter/issues/97679