问:
Do unused functions get optimized out?
Compilers these days tend to do a significant amount of optimizations. Do they also remove unused functions from the final output?</p>

答:
Many compilers do, but it depends on the particular implementation.  Debug builds will often include all functions, to allow them to be invoked or examined from within the debugger.  Many embedded systems compilers, for reasons I don't totally understand(*), will include all of the functions in an object file if they include any, but will omit entirely any object files that aren't used at all.

Note that in languages which support reflection (e.g., Java, C#, VB.NET, etc.) it's possible, given the name of a function, to create a reference to it at runtime even if no references exist in the code.  For example, a routine could accept a string from the console, munge it in some fashion, and generate a call to a function by that name.  There wouldn't be any way for a compiler or linker to know what names might be so generated, and thus no way to know what functions may be safely omitted from the code.

No such difficulty exists in C or C++, however, since there is no defined way for code to create a reference to a function, variable, or constant without an explicit reference existing in the code.  Some implementations may arrange things so that consecutively-declared constants or variables will be stored consecutively, and one might thus create a reference to a later-declared one by adding an offset to an earlier-declared one, but the behavior of such tricks is explicitly not guaranteed by the C or C++ standards.

(*)I understand that it makes compiling and linking easier, but today's computers should have no trouble running more sophisticated compiling and linking algorithms than would have been practical in decades past.  If nothing else, a two-pass pre-compile/pre-link/compile/link method could on the pre-compile/link phase produce a list of things that are used, and then on the "real" compile/link phase omit those that are not.

Title: Do unused functions get optimized out?


来源: stackexchange

问:
Formatting a date in R without leading zeros
Is there a way to use the format function on a date object, specifically an object of class POSIXlt, POSIXct, or Date, with the format %Y, %m, %d such that leading zeros are stripped from each of those 3 fields?

For example, I would like format(as.Date("1998-09-02"), "%Y, %m, %d") to return 1998, 9, 2 and not 1998, 09, 02.

答:
You can do this with a simple change to your strftime format string. However, it depends on your platform (Unix or Windows).

Unix

Insert a minus sign (-) before each term you'd like to remove leading zeros from:

format(as.Date("2020-06-02"), "%Y, %-m, %-d")
[1] "2020, 6, 2"
```
<h3>Windows</h3>
<p>Insert a pound sign (<code>#</code>) before each desired term:</p>
<pre class="lang-r prettyprint-override"><code>format(as.Date("2020-06-02"), "%Y, %#m, %#d")
[1] "2020, 6, 2"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can do this with a simple change to your strftime format string. However, it depends on your platform (Unix or Windows).

Unix

Insert a minus sign (-) before each term you'd like to remove leading zeros from:

format(as.Date("2020-06-02"), "%Y, %-m, %-d")
[1] "2020, 6, 2"

Windows

Insert a pound sign (#) before each desired term:

format(as.Date("2020-06-02"), "%Y, %#m, %#d")
[1] "2020, 6, 2"

ContentLicense: CC BY-SA 4.0


问:
How to extract Facebook direct Video url in HD & SD Android
I am trying to download Facebook video with both HD and SD qualitys Like this app

on Google play. I am beginner and don't know much more about java. I have searched a lot but can't find any solution. Any help will be appreciated!

答:
FacebookUrlExtractor

Example

```<code>  new FacebookExtractor(this,"Video Url",false)
    {
        @Override
        protected void onExtractionComplete(FacebookFile facebookFile) {
            Log.e("TAG","---------------------------------------");
            Log.e("TAG","facebookFile AutherName :: "+facebookFile.getAuthor());
            Log.e("TAG","facebookFile FileName :: "+facebookFile.getFilename());
            Log.e("TAG","facebookFile Ext :: "+facebookFile.getExt());
            Log.e("TAG","facebookFile SD :: "+facebookFile.getSdUrl());
            Log.e("TAG","facebookFile HD :: "+facebookFile.getHdUrl());
            Log.e("TAG","---------------------------------------");
        }

        @Override
        protected void onExtractionFail(Exception error) {
            Log.e("Error","Error :: "+error.getMessage());
            error.printStackTrace();
        }
    };
</code>```

gradle

```<code>dependencies
 {
    implementation 'com.github.Ashusolanki:FacebookUrlExtractor:0.0.5'
 }
</code>```

For More https://github.com/Ashusolanki/FacebookUrlExtractor

Body:
FacebookUrlExtractor

Example

  new FacebookExtractor(this,"Video Url",false)
    {
        @Override
        protected void onExtractionComplete(FacebookFile facebookFile) {
            Log.e("TAG","---------------------------------------");
            Log.e("TAG","facebookFile AutherName :: "+facebookFile.getAuthor());
            Log.e("TAG","facebookFile FileName :: "+facebookFile.getFilename());
            Log.e("TAG","facebookFile Ext :: "+facebookFile.getExt());
            Log.e("TAG","facebookFile SD :: "+facebookFile.getSdUrl());
            Log.e("TAG","facebookFile HD :: "+facebookFile.getHdUrl());
            Log.e("TAG","---------------------------------------");
        }

        @Override
        protected void onExtractionFail(Exception error) {
            Log.e("Error","Error :: "+error.getMessage());
            error.printStackTrace();
        }
    };

gradle

dependencies
 {
    implementation 'com.github.Ashusolanki:FacebookUrlExtractor:0.0.5'
 }

For More https://github.com/Ashusolanki/FacebookUrlExtractor


问:
Pandas - Calculate row values based on prior row value, update the result to be the new row value (and so on)

Below is some dummy data that reflects the data I am working with.

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

random.seed(30)

# Dummy data that represents a percent change
datelist = pd.date_range(start='1983-01-01', end='1994-01-01', freq='Y')
df1 = pd.DataFrame({"P Change_1": np.random.uniform(low=-0.55528, high=0.0396181, size=(11,)),
                   "P Change_2": np.random.uniform(low=-0.55528, high=0.0396181, size=(11,))})
#This dataframe contains the rows we want to operate on
df2 = pd.DataFrame({
    'Loc1': [None, None, None, None, None, None, None, None, None, None, 2.5415],
    'Loc2': [None, None, None, None, None, None, None, None, None, None, 3.2126],})

#Set the datetime index
df1 = df1.set_index(datelist)
df2 = df2.set_index(datelist)
</code>```

df1:

```<code>            P Change_1  P Change_2
1984-12-31   -0.172080   -0.231574
1985-12-31   -0.328773   -0.247018
1986-12-31   -0.160834   -0.099079
1987-12-31   -0.457924    0.000266
1988-12-31    0.017374   -0.501916
1989-12-31   -0.349052   -0.438816
1990-12-31    0.034711    0.036164
1991-12-31   -0.415445   -0.415372
1992-12-31   -0.206852   -0.413107
1993-12-31   -0.313341   -0.181030
1994-12-31   -0.474234   -0.118058
</code>```

df2:

```<code>              Loc1    Loc2
1984-12-31     NaN     NaN
1985-12-31     NaN     NaN
1986-12-31     NaN     NaN
1987-12-31     NaN     NaN
1988-12-31     NaN     NaN
1989-12-31     NaN     NaN
1990-12-31     NaN     NaN
1991-12-31     NaN     NaN
1992-12-31     NaN     NaN
1993-12-31     NaN     NaN
1994-12-31  2.5415  3.2126
</code>```

DataFrame details:

First off, Loc1 will correspond with P Change_1 and Loc2 corresponds to P Change_2, etc. Looking at Loc1 first, I want to either fill up the DataFrame containing Loc1 and Loc2 with the relevant values or compute a new dataframe that has columns Calc1 and Calc2.

The calculation:

I want to start with the 1994 value of Loc1 and calculate a new value for 1993 by taking Loc1 1993 = Loc1 1994 + (Loc1 1994 * P Change_1 1993).  With the values filled in it would be 2.5415 +(-0.313341 * 2.5415) which equals about 1.74514.

This 1.74514 value will replace the NaN value in 1993, and then I want to use that calculated value to get a value for 1992.  This means we now compute Loc1 1992 = Loc1 1993 + (Loc1 1993 * P Change_1 1992).  I want to carry out this operation row-wise until it gets the earliest value in the timeseries.

What is the best way to go about implementing this row-wise equation?  I hope this makes some sense and any help is greatly appreciated!

答:
```<code>df = pd.merge(df1, df2, how='inner', right_index=True, left_index=True)   # merging dataframes on date index
df['count'] = range(len(df))    # creating a column, count for easy operation

# divides dataframe in two part, one part above the not NaN row and one below
da1 = df[df['count']<=df.dropna().iloc[0]['count']]
da2 = df[df['count']>=df.dropna().iloc[0]['count']]

da1.sort_values(by=['count'],ascending=False, inplace=True)
g=[da1,da2]
num_col=len(df1.columns)

for w in range(len(g)):
    list_of_col=[]
    count = 0
    list_of_col=[list() for i in range(len(g[w]))]
    for item, rows in g[w].iterrows():
        n=[]
        if count==0:
            for p in range(1,num_col+1):
                n.append(rows[f'Loc{p}'])
        else:
            for p in range(1,num_col+1):
                n.append(list_of_col[count-1][p-1]+  list_of_col[count-1][p-1]* rows[f'P Change_{p}'])
        list_of_col[count].extend(n)
        count+=1
    tmp=[list() for i in range(num_col)]
    for d_ in range(num_col):
        for x_ in range(len(list_of_col)):
            tmp[d_].append(list_of_col[x_][d_])
    z1=[]
    z1.extend(tmp)
    for i in range(num_col):
        g[w][f'Loc{i+1}']=z1[i]

da1.sort_values(by=['count'] ,inplace=True)
final_df = pd.concat([da1, da2[1:]])

calc_df = pd.DataFrame()
for i in range(num_col):
    calc_df[f'Calc{i+1}']=final_df[f'Loc{i+1}']
print(calc_df)
</code>```

I have tried to include all the obscure thing I have done in the comment. I have edited my code to let initial dataframes remain unaffected.

[Edited] : I have edited the code to include any number of columns in the given dataframe.

[Edited:]If the name of columns are arbitrary in df1 and df2, please run this block of code before running the upper code. I have renamed the columns name using list comprehension!

```<code>df1.columns = [f'P Change_{i+1}' for i in range(len(df1.columns))]
df2.columns = [f'Loc{i+1}' for i in range(len(df2.columns))]
</code>```

Body:
Below is some dummy data that reflects the data I am working with.

import pandas as pd
import numpy as np
from numpy import random

random.seed(30)

# Dummy data that represents a percent change
datelist = pd.date_range(start='1983-01-01', end='1994-01-01', freq='Y')
df1 = pd.DataFrame({"P Change_1": np.random.uniform(low=-0.55528, high=0.0396181, size=(11,)),
                   "P Change_2": np.random.uniform(low=-0.55528, high=0.0396181, size=(11,))})
#This dataframe contains the rows we want to operate on
df2 = pd.DataFrame({
    'Loc1': [None, None, None, None, None, None, None, None, None, None, 2.5415],
    'Loc2': [None, None, None, None, None, None, None, None, None, None, 3.2126],})

#Set the datetime index
df1 = df1.set_index(datelist)
df2 = df2.set_index(datelist)

df1:

            P Change_1  P Change_2
1984-12-31   -0.172080   -0.231574
1985-12-31   -0.328773   -0.247018
1986-12-31   -0.160834   -0.099079
1987-12-31   -0.457924    0.000266
1988-12-31    0.017374   -0.501916
1989-12-31   -0.349052   -0.438816
1990-12-31    0.034711    0.036164
1991-12-31   -0.415445   -0.415372
1992-12-31   -0.206852   -0.413107
1993-12-31   -0.313341   -0.181030
1994-12-31   -0.474234   -0.118058

df2:

              Loc1    Loc2
1984-12-31     NaN     NaN
1985-12-31     NaN     NaN
1986-12-31     NaN     NaN
1987-12-31     NaN     NaN
1988-12-31     NaN     NaN
1989-12-31     NaN     NaN
1990-12-31     NaN     NaN
1991-12-31     NaN     NaN
1992-12-31     NaN     NaN
1993-12-31     NaN     NaN
1994-12-31  2.5415  3.2126

DataFrame details:

First off, Loc1 will correspond with P Change_1 and Loc2 corresponds to P Change_2, etc. Looking at Loc1 first, I want to either fill up the DataFrame containing Loc1 and Loc2 with the relevant values or compute a new dataframe that has columns Calc1 and Calc2.

The calculation:

I want to start with the 1994 value of Loc1 and calculate a new value for 1993 by taking Loc1 1993 = Loc1 1994 + (Loc1 1994 * P Change_1 1993).  With the values filled in it would be 2.5415 +(-0.313341 * 2.5415) which equals about 1.74514.

This 1.74514 value will replace the NaN value in 1993, and then I want to use that calculated value to get a value for 1992.  This means we now compute Loc1 1992 = Loc1 1993 + (Loc1 1993 * P Change_1 1992).  I want to carry out this operation row-wise until it gets the earliest value in the timeseries.

What is the best way to go about implementing this row-wise equation?  I hope this makes some sense and any help is greatly appreciated!

Body:
df = pd.merge(df1, df2, how='inner', right_index=True, left_index=True)   # merging dataframes on date index
df['count'] = range(len(df))    # creating a column, count for easy operation

# divides dataframe in two part, one part above the not NaN row and one below
da1 = df[df['count']<=df.dropna().iloc[0]['count']]
da2 = df[df['count']>=df.dropna().iloc[0]['count']]

da1.sort_values(by=['count'],ascending=False, inplace=True)
g=[da1,da2]
num_col=len(df1.columns)

for w in range(len(g)):
    list_of_col=[]
    count = 0
    list_of_col=[list() for i in range(len(g[w]))]
    for item, rows in g[w].iterrows():
        n=[]
        if count==0:
            for p in range(1,num_col+1):
                n.append(rows[f'Loc{p}'])
        else:
            for p in range(1,num_col+1):
                n.append(list_of_col[count-1][p-1]+  list_of_col[count-1][p-1]* rows[f'P Change_{p}'])
        list_of_col[count].extend(n)
        count+=1
    tmp=[list() for i in range(num_col)]
    for d_ in range(num_col):
        for x_ in range(len(list_of_col)):
            tmp[d_].append(list_of_col[x_][d_])
    z1=[]
    z1.extend(tmp)
    for i in range(num_col):
        g[w][f'Loc{i+1}']=z1[i]

da1.sort_values(by=['count'] ,inplace=True)
final_df = pd.concat([da1, da2[1:]])

calc_df = pd.DataFrame()
for i in range(num_col):
    calc_df[f'Calc{i+1}']=final_df[f'Loc{i+1}']
print(calc_df)

I have tried to include all the obscure thing I have done in the comment. I have edited my code to let initial dataframes remain unaffected.

[Edited] : I have edited the code to include any number of columns in the given dataframe.

[Edited:]If the name of columns are arbitrary in df1 and df2, please run this block of code before running the upper code. I have renamed the columns name using list comprehension!

df1.columns = [f'P Change_{i+1}' for i in range(len(df1.columns))]
df2.columns = [f'Loc{i+1}' for i in range(len(df2.columns))]


问:
Is there a way to integrate stencil components into frameworks locally without publishing to NPM?
I am currently testing stencil js. For now I want to write stencil components and include them within a VUE/React project. The official website of stencil already shows how to integrate them within a framework (https://stenciljs.com/docs/overview). But they assume that your own stencil component library has already been published to npm.

Is there a way to integrate stencil components locally into a framework to test them without publishing them first?

答:
Instead of publishing or packing your packages, you could utilize TypeScript's path mapping feature.

This allows you to write your import statements just as you would with a published package, but behind the scenes TypeScript maps the imports to their given source code location.

Here's an example of a tsconfig.json with path mapping added to the compiler options:

```<code>{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "ui-components": ["libs/ui-components"],
      "ui-components/loader": ["libs/ui-components/dist/loader/index.cjs.js"],
      "ui-components-react": ["generated/ui-components-react/src/components.ts"]
    },
    ...
</code>```

As you can see, it has 3 mappings: the path to the core Stencil components ui-components, the path to the generated React components which are exposed as ui-components-react, as well as the generated loader ui-components/loader which provides the bridge between the Custom elements and the React wrappers.

I created a full working example for Stencil Web Components with generated bindings and wrappers for React that comes without the need of publishing any package: Nx Stencil React.

Please note that this answer is based on @stencil/core 1.14.0 or below. Future versions may have a different approach on generating the framework integrations.

Body:
Instead of publishing or packing your packages, you could utilize TypeScript's path mapping feature.

This allows you to write your import statements just as you would with a published package, but behind the scenes TypeScript maps the imports to their given source code location.

Here's an example of a tsconfig.json with path mapping added to the compiler options:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "ui-components": ["libs/ui-components"],
      "ui-components/loader": ["libs/ui-components/dist/loader/index.cjs.js"],
      "ui-components-react": ["generated/ui-components-react/src/components.ts"]
    },
    ...

As you can see, it has 3 mappings: the path to the core Stencil components ui-components, the path to the generated React components which are exposed as ui-components-react, as well as the generated loader ui-components/loader which provides the bridge between the Custom elements and the React wrappers.

I created a full working example for Stencil Web Components with generated bindings and wrappers for React that comes without the need of publishing any package: Nx Stencil React.

Please note that this answer is based on @stencil/core 1.14.0 or below. Future versions may have a different approach on generating the framework integrations.


问:
Build condition comparison for if statement
Is this possible?

```<code>$var_1 = 1;
$var_2 = 10;
$comparison = '>';

if($var_1 $comparison $var_2) {
    // do something...
}
</code>```

The syntax right now is not valid but is there a way to do this?

答:
You could also create a few functions like isGreaterThan($arg1, $arg2), isLessThan($arg1, $arg2), and then store the name of the function you want in the variable $comparison. Then you would use call_user_func_array() when you want to use it.  Like so :

```<code>function isGreaterThan($val1, $val2) {
    return $val1 > $val2;
}

/////////////

$var_1 = 1;
$var_2 = 10;
$comparison = "isGreaterThan";

if(call_user_func_array($comparison, array($var_1, var_2))) {
    //do something
}
</code>```

Sounds like you've got a few options.  Hope this helps.

Body:
Is this possible?

$var_1 = 1;
$var_2 = 10;
$comparison = '>';

if($var_1 $comparison $var_2) {
    // do something...
}

The syntax right now is not valid but is there a way to do this?

Body:
You could also create a few functions like isGreaterThan($arg1, $arg2), isLessThan($arg1, $arg2), and then store the name of the function you want in the variable $comparison. Then you would use call_user_func_array() when you want to use it.  Like so :

function isGreaterThan($val1, $val2) {
    return $val1 > $val2;
}

/////////////

$var_1 = 1;
$var_2 = 10;
$comparison = "isGreaterThan";

if(call_user_func_array($comparison, array($var_1, var_2))) {
    //do something
}

Sounds like you've got a few options.  Hope this helps.


问:
Unable to load data in express server which is coming from front end
Whenever I send data from front end data is going to the back-end but I'm receiving empty object in body. I user body parser also but I'm getting same error. Below is my server code.

Error

```<code>Error!
HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:8080/sms", ok: false, …}
error: {error: SyntaxError: Unexpected token Y in JSON at position 0 at JSON.parse (<anonymous>) at XMLHtt…, text: "You sent: undefined to Express"}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure during parsing for http://localhost:8080/sms"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://localhost:8080/sms"
__proto__: HttpResponseBase
</code>```

app.js

```<code>const express = require("express");
var app = express();
const bodyparser=require("body-parser");
const cors=require("cors");
app.use(cors());

app.use(bodyparser.urlencoded({ extended: false }))

app.post('/sms', function (req, res) {
    const body = req.body.Body
    res.set('Content-Type', 'text/plain')
    res.send(`You sent: ${body} to Express`)
  })

app.get("/",(req,res) =>{
    res.send("We are in home");;

})

app.post("/users",(req,res) =>{
  console.log(req.body);

})

app.listen(8080);
</code>```

答:
Try adding

// parse application/x-www-form-urlencoded

```<code>app.use(bodyParser.urlencoded({ extended: false }))
</code>```

this too
// parse application/json

```<code>app.use(bodyParser.json())
</code>```

Body:
Whenever I send data from front end data is going to the back-end but I'm receiving empty object in body. I user body parser also but I'm getting same error. Below is my server code.

Error

Error!
HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:8080/sms", ok: false, …}
error: {error: SyntaxError: Unexpected token Y in JSON at position 0 at JSON.parse (<anonymous>) at XMLHtt…, text: "You sent: undefined to Express"}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure during parsing for http://localhost:8080/sms"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://localhost:8080/sms"
__proto__: HttpResponseBase

app.js

const express = require("express");
var app = express();
const bodyparser=require("body-parser");
const cors=require("cors");
app.use(cors());

app.use(bodyparser.urlencoded({ extended: false }))

app.post('/sms', function (req, res) {
    const body = req.body.Body
    res.set('Content-Type', 'text/plain')
    res.send(`You sent: ${body} to Express`)
  })

app.get("/",(req,res) =>{
    res.send("We are in home");;

})

app.post("/users",(req,res) =>{
  console.log(req.body);

})

app.listen(8080);

Body:
Try adding

// parse application/x-www-form-urlencoded

app.use(bodyParser.urlencoded({ extended: false }))

this too
// parse application/json

app.use(bodyParser.json())


问:
getBoundingClientRect is not a function on vueJs
I would like to find the top and bottom edge of a div when i move my cursor over it. The div is generated dynamically. However, it produced error message

getBoundingClientRect is not a function

<template>

                This is div {{ index }}

</template>

```

答:
You can use event.target as another user suggested which is, I think, the cleanest way

<template>

This is div {{ index }}

</template>

```
<hr />
<p>For your issue though, based on Vue.js documentation:</p>
<blockquote>
<p>When <code>ref</code> is used together with <code>v-for</code>, the <code>ref</code> you get will be an <strong>array</strong> containing the child components mirroring the data source.</p>
</blockquote>
<p>So you don't have to use the index on your <code>ref</code> creation, while you will end up with <code>divs.length</code> arrays which their first element will be your reference.</p>
<p>If you had to use <code>refs</code>:</p>
<pre class="lang-js prettyprint-override"><code><template>
  <div>
    <div v-for="(i, index) in divs" :key="index">
      <div ref="myDiv" @mouseover="divDragOver($event, index)">This is div {{ index }}</div>
    </div>
  </div>
</template>

<script>
export default {
  data: function() {
    return { divs: [1, 2, 3, 4] };
  },
  methods: {
    divDragOver(e, i) {
      console.log(this.$refs.myDiv); // this will be an array with all your refs, use i to access
    }
  }
};
</script>
</code>```

So you were getting an error because your element's ref was on this.$refs["ref_" + i][0]

Body:
You can use event.target as another user suggested which is, I think, the cleanest way

<template>
  <div>
    <div v-for="(i, index) in divs" :key="index">
      <div ref="myDiv" @mouseover="divDragOver">This is div {{ index }}</div>
    </div>
  </div>
</template>

<script>
export default {
  data: function() {
    return { divs: [1, 2, 3, 4] };
  },
  methods: {
    divDragOver(event) {
      console.log(event.target); // this will be your mouseover div
    }
  }
};
</script>

For your issue though, based on Vue.js documentation:

When ref is used together with v-for, the ref you get will be an array containing the child components mirroring the data source.

So you don't have to use the index on your ref creation, while you will end up with divs.length arrays which their first element will be your reference.

If you had to use refs:

<template>
  <div>
    <div v-for="(i, index) in divs" :key="index">
      <div ref="myDiv" @mouseover="divDragOver($event, index)">This is div {{ index }}</div>
    </div>
  </div>
</template>

<script>
export default {
  data: function() {
    return { divs: [1, 2, 3, 4] };
  },
  methods: {
    divDragOver(e, i) {
      console.log(this.$refs.myDiv); // this will be an array with all your refs, use i to access
    }
  }
};
</script>

So you were getting an error because your element's ref was on this.$refs["ref_" + i][0]


问:
Draw a circle with rectangles python turtle
I wanna draw (this shape) polygon with knowing rectangle length and width, and number of rectangles,

And Here's my code:

```<code>from turtle import *

color('black')
begin_fill()
length = 50
width = 20
num_of_rectangles = 8
for i in range(num_of_rectangles):
    forward(length)
    right(90)
    forward(width)
    right(90)
    forward(length)
    right(90)
    forward(width)
    right(90)
    penup()
    circle(50, 180/num_of_rectangles, 4)
    pendown()

done()
</code>```

But this code doesn't display the wanted shape, So how can i draw the shape above?

答:
Instead of drawing the rectangles as 4 strokes, you can draw it as 5, starting and finishing in the middle of one of the sides. You also need to get to the middle of that side with the pen up, then back to the center (again with the pen up):</p>

```<code>from turtle import *

color('black')
begin_fill()
length = 50
width = 20
num_of_rectangles = 8
penup()
for i in range(num_of_rectangles):
    # Get to middle of side and orient for drawing
    forward(width / 2)
    right(90)
    pendown()
    # Draw rectangle in 5 strokes
    forward(length / 2)
    right(90)
    forward(width)
    right(90)
    forward(length)
    right(90)
    forward(width)
    right(90)
    forward(length / 2)
    penup()
    # Reorient and get back to center
    left(90)
    backward(width / 2)
    right(180/num_of_rectangles)

done()
</code>```

Body:
I wanna draw (this shape) polygon with knowing rectangle length and width, and number of rectangles,

And Here's my code:

from turtle import *

color('black')
begin_fill()
length = 50
width = 20
num_of_rectangles = 8
for i in range(num_of_rectangles):
    forward(length)
    right(90)
    forward(width)
    right(90)
    forward(length)
    right(90)
    forward(width)
    right(90)
    penup()
    circle(50, 180/num_of_rectangles, 4)
    pendown()

done()

But this code doesn't display the wanted shape, So how can i draw the shape above?

Body:
Instead of drawing the rectangles as 4 strokes, you can draw it as 5, starting and finishing in the middle of one of the sides. You also need to get to the middle of that side with the pen up, then back to the center (again with the pen up):

from turtle import *

color('black')
begin_fill()
length = 50
width = 20
num_of_rectangles = 8
penup()
for i in range(num_of_rectangles):
    # Get to middle of side and orient for drawing
    forward(width / 2)
    right(90)
    pendown()
    # Draw rectangle in 5 strokes
    forward(length / 2)
    right(90)
    forward(width)
    right(90)
    forward(length)
    right(90)
    forward(width)
    right(90)
    forward(length / 2)
    penup()
    # Reorient and get back to center
    left(90)
    backward(width / 2)
    right(180/num_of_rectangles)

done()


问:
onComplete in AjaxUpload getting before server side code hits
I am working on some legacy code which is using Asp.net and ajax where we do one functionality to upload a pdf. To upload file our legacy code uses AjaxUpload, but I observed some weird behavior of AjaxUpload where onComplete event is getting called before actual file got uploaded by server side code because of this though the file got uploaded successfully still user gets an error message on screen saying upload failed.

And here the most weird thins is that same code was working fine till last week.

Code:

```<code>initFileUpload: function () {
      debugger;
  new AjaxUpload('aj-assetfile', {
    action: '/Util/FileUploadHandler.ashx?type=asset&signup=False&oldfile=' + assetObj.AssetPath + '&as=' + assetObj.AssetID,
    //action: ML.Assets.handlerPath + '?action=uploadfile',
    name: 'AccountSignupUploadContent',
    onSubmit: function (file, ext) {
      ML.Assets.isUploading = true;

      ML.Assets.toggleAsfMask(true);

      // change button text, when user selects file
      $asffile.val('Uploading');
      $astfileerror.hide();

      // If you want to allow uploading only 1 file at time,
      // you can disable upload button
      this.disable();

      // Uploding -> Uploading. -> Uploading...
      ML.Assets.interval = window.setInterval(function () {
        var text = $asffile.val();
        if (text.length < 13) {
          $asffile.val(text + '.');
        } else {
          $asffile.val('Uploading');
        }
      }, 200);

      //if url field block is visible
      if ($asseturlbkl.is(':visible')) {
        $asfurl.val(''); //reset values of url
        $asfurl.removeClass('requiref error'); //remove require field class
        $asfurlerror.hide(); //hide errors
      }
    },
      onComplete: function (file, responseJSON) {
          debugger;
      ML.Assets.toggleAsfMask(false);
      ML.Assets.isUploading = false;
      window.clearInterval(ML.Assets.interval);
      this.enable();

      var success = false;
      var responseMsg = '';
      try {
        var response = JSON.parse(responseJSON);
        if (response.status == 'success') { //(response.getElementsByTagName('status')[0].textContent == 'success') {
          success = true;
        } else {
          success = false;
          responseMsg = ': ' + response.message;
        }
      } catch (e) {
        success = false;
      }

      if (success) {
        assetObj.AssetMimeType = response.mimetype;
        $asffile.val(response.path);
        $asffile.valid(); //clear errors
        ML.Assets.madeChanges();

        if (ML.Assets.saveAfterUpload) { //if user submitted form while uploading
          ML.Assets.saveAsset(); //run the save callback
        }
      } else { //error
        assetObj.AssetMimeType = "";
        $asffile.val('');
        $astfileerror.show().text('Upload failed' + responseMsg);
        //if url field block is visible  and type is not free offer.
        if ($asseturlbkl.is(':visible') && this.type !== undefined && assetObj.AssetType != this.type.FREEOFFER) {
          $asfurl.addClass('requiref'); //remove require field class
        }
        ML.Assets.hideLoader();
      }
    }
  });
}
</code>```

答:
I was facing the same issue but I fixed it with some minor change in plugin.

When “iframeSrc” is set to “javascript:false” on https or http pages, Chrome now seems to cancel the request. Changing this to “about:blank” seems to resolve the issue.

Old Code:

```<code>var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');
</code>```

New Code with chagnes:

```<code>var iframe = toElement('<iframe src="about:blank;" name="' + id + '" />');
</code>```

After changing the code it's working fine. I hope it will work for you as well. :)

Reference (For more details): https://www.infomazeelite.com/ajax-file-upload-is-not-working-in-the-latest-chrome-version-83-0-4103-61-official-build-64-bit/

Body:
I am working on some legacy code which is using Asp.net and ajax where we do one functionality to upload a pdf. To upload file our legacy code uses AjaxUpload, but I observed some weird behavior of AjaxUpload where onComplete event is getting called before actual file got uploaded by server side code because of this though the file got uploaded successfully still user gets an error message on screen saying upload failed.

And here the most weird thins is that same code was working fine till last week.

Code:

initFileUpload: function () {
      debugger;
  new AjaxUpload('aj-assetfile', {
    action: '/Util/FileUploadHandler.ashx?type=asset&signup=False&oldfile=' + assetObj.AssetPath + '&as=' + assetObj.AssetID,
    //action: ML.Assets.handlerPath + '?action=uploadfile',
    name: 'AccountSignupUploadContent',
    onSubmit: function (file, ext) {
      ML.Assets.isUploading = true;

      ML.Assets.toggleAsfMask(true);

      // change button text, when user selects file
      $asffile.val('Uploading');
      $astfileerror.hide();

      // If you want to allow uploading only 1 file at time,
      // you can disable upload button
      this.disable();

      // Uploding -> Uploading. -> Uploading...
      ML.Assets.interval = window.setInterval(function () {
        var text = $asffile.val();
        if (text.length < 13) {
          $asffile.val(text + '.');
        } else {
          $asffile.val('Uploading');
        }
      }, 200);

      //if url field block is visible
      if ($asseturlbkl.is(':visible')) {
        $asfurl.val(''); //reset values of url
        $asfurl.removeClass('requiref error'); //remove require field class
        $asfurlerror.hide(); //hide errors
      }
    },
      onComplete: function (file, responseJSON) {
          debugger;
      ML.Assets.toggleAsfMask(false);
      ML.Assets.isUploading = false;
      window.clearInterval(ML.Assets.interval);
      this.enable();

      var success = false;
      var responseMsg = '';
      try {
        var response = JSON.parse(responseJSON);
        if (response.status == 'success') { //(response.getElementsByTagName('status')[0].textContent == 'success') {
          success = true;
        } else {
          success = false;
          responseMsg = ': ' + response.message;
        }
      } catch (e) {
        success = false;
      }

      if (success) {
        assetObj.AssetMimeType = response.mimetype;
        $asffile.val(response.path);
        $asffile.valid(); //clear errors
        ML.Assets.madeChanges();

        if (ML.Assets.saveAfterUpload) { //if user submitted form while uploading
          ML.Assets.saveAsset(); //run the save callback
        }
      } else { //error
        assetObj.AssetMimeType = "";
        $asffile.val('');
        $astfileerror.show().text('Upload failed' + responseMsg);
        //if url field block is visible  and type is not free offer.
        if ($asseturlbkl.is(':visible') && this.type !== undefined && assetObj.AssetType != this.type.FREEOFFER) {
          $asfurl.addClass('requiref'); //remove require field class
        }
        ML.Assets.hideLoader();
      }
    }
  });
}

Body:
I was facing the same issue but I fixed it with some minor change in plugin.

When “iframeSrc” is set to “javascript:false” on https or http pages, Chrome now seems to cancel the request. Changing this to “about:blank” seems to resolve the issue.

Old Code:

var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');

New Code with chagnes:

var iframe = toElement('<iframe src="about:blank;" name="' + id + '" />');

After changing the code it's working fine. I hope it will work for you as well. :)

Reference (For more details): https://www.infomazeelite.com/ajax-file-upload-is-not-working-in-the-latest-chrome-version-83-0-4103-61-official-build-64-bit/


问:
Javascript required attribute not working with e.preventDefault
I have a form with inputs that have the required attribute.However, I dont want the form to be submitted normally, but it uses ajax.Thus, I set the form action to javascript:void(0) .But doing so, renders the required attribute useless.It doesn't work

How can I fix that?

This is my form

```<code><form action="javascript:void(0)"> <input name="email" required> </form>`
</code>```

答:
do it like this may help you

<form name="myForm">
  <input name="email" required>
  <input type="submit" value="submit">
</form>
```

Body:
I have a form with inputs that have the required attribute.However, I dont want the form to be submitted normally, but it uses ajax.Thus, I set the form action to javascript:void(0) .But doing so, renders the required attribute useless.It doesn't work

How can I fix that?

This is my form

<form action="javascript:void(0)"> <input name="email" required> </form>`

Body:
do it like this may help you

<form name="myForm">
  <input name="email" required>
  <input type="submit" value="submit">
</form>
<script>
  document.myForm.onsubmit = e => {
    e.preventDefault();
  }
</script>


问:
Reactstrap Dropdown Menu in NavBar is contained within NavBar, doesn't overlay main page
I am using Reactstrap.  I have a vertical NavBar in a Column with a Dropdown which displays a menu to the right when clicked.

The Dropdown menu is contained within the NavBar.  Some of it is cutoff depending on how wide the NavBar is.  In fact, it covers the NavBar menu itself if the NavBar is narrow.

I would like the Drowndown menu to overlay the main page.

Amazon has a horizontal NavBar, and when you hover over the DropDown menu, it overlays over the main page.

That's the effect I want, except my NavBar is vertical.

Are there any guidelines for how I can do that?

答: I had the NavBar in a "Col" on the left.  I removed the Col.  </p>


问:
Windows workflow foundation and ASP.NET
I am going to develop an easy workflow application using C#. I am planning to use Windows workflow foundation technology and develop it as an ASP.net web application.

As i read in some web sites in order to invoke windows workflow foundation with asp.net, it should be used the MVC approach. Is it possible to do it without the MVC approach?

You have to consider that i have no experience with MVC approach. Is it more easy to develop it as Windows forms application instead of using ASP.NET?

答:
No, you don't have to use ASP.NET MVC with Windows Workflow Foundation.

If you've never worked with ASP.NET MVC before, you'll probably find the initial learning curve to be quite steep. But there is plenty of help to be found online.

Developing it in Windows Forms or ASP.NET Webforms may be easier for you, depending on your level of experience.

Title: Windows workflow foundation and ASP.NET


问:
Select Person with only one value in the column
I can't correctly write a query.
I need to select a person who has only one value in the column. For example,

```<code>select * (
select PersonID, sum(TotalAmount)
from  Table1
group by PersonID
HAVING sum(TotalAmount) = 0 )
where Group = A
</code>```

It means that I would select all customers that belong to ONLY 'A' group...

Could someone help me?

答:
If you want the persons with only one value, then having count(*) = 1 comes to mind:

```<code>select personid
from table1
group by personid
having count(*) = 1;
</code>```

Body:
I can't correctly write a query.
I need to select a person who has only one value in the column. For example,

select * (
select PersonID, sum(TotalAmount)
from  Table1
group by PersonID
HAVING sum(TotalAmount) = 0 )
where Group = A

It means that I would select all customers that belong to ONLY 'A' group...

Could someone help me?

Body:
If you want the persons with only one value, then having count(*) = 1 comes to mind:

select personid
from table1
group by personid
having count(*) = 1;


问:
How to inject a service into an attribute to lookup roles in DB
I'm setting up a new way of authenticating using Azure AD (AAD), but role based authorization still needs to be retrieved from a legacy system.
The AAD authentication is in place and that works like a charm. The token also includes a claim, lets call it userid for the sake of argument.

What I want to create is am Attribute that can contact the legacy system, without disregarding the default implementations for AAD token verification.

I was able to create the following attribute, which I can use on my methods with [LegacyRole("MyRole", "MyOtherRole")] while still having [Authorize] on my class that handles the token correctly, so far so good:

```<code>public class LegacyRoleAttribute : AuthorizeAttribute, IAuthorizationFilter
{
    private string[] _roles;
    private ILegacyRoleService _service;
    public LegacyRoleAttribute(params string[] roles) : base()
    {
        _roles = roles;
        _service = new LegacyRoleService(); //This instantiation, I want to get rid off.
    }

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var user = context.HttpContext.User;
        string userID = user.Claims.FirstOrDefault(c => c.Type == "userid").Value;
        if (string.IsNullOrEmpty(userID))
        {
            context.Result = new UnauthorizedResult();
            return;
        }
        if (!_service.HasAnyRole(userID, _roles))
        {
            context.Result = new UnauthorizedResult();
            return;
        }
    }
}
</code>```

But I want to inject the service properly, instead of using a new statement in the construction. Off course I do not want to change the format of the attribute, so nothing like [LegacyRole(serviceInstance,"MyRole", "MyOtherRole")] or so.

Any way to do this properly?

答:
If you want to instantiation of LegacyRoleService() method then please declare its class(where the method is decclared) as Static.

For Example,

```<code>Public Static LegacyRoleServiceclass()
</code>```

Body:
I'm setting up a new way of authenticating using Azure AD (AAD), but role based authorization still needs to be retrieved from a legacy system.
The AAD authentication is in place and that works like a charm. The token also includes a claim, lets call it userid for the sake of argument.

What I want to create is am Attribute that can contact the legacy system, without disregarding the default implementations for AAD token verification.

I was able to create the following attribute, which I can use on my methods with [LegacyRole("MyRole", "MyOtherRole")] while still having [Authorize] on my class that handles the token correctly, so far so good:

public class LegacyRoleAttribute : AuthorizeAttribute, IAuthorizationFilter
{
    private string[] _roles;
    private ILegacyRoleService _service;
    public LegacyRoleAttribute(params string[] roles) : base()
    {
        _roles = roles;
        _service = new LegacyRoleService(); //This instantiation, I want to get rid off.
    }

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var user = context.HttpContext.User;
        string userID = user.Claims.FirstOrDefault(c => c.Type == "userid").Value;
        if (string.IsNullOrEmpty(userID))
        {
            context.Result = new UnauthorizedResult();
            return;
        }
        if (!_service.HasAnyRole(userID, _roles))
        {
            context.Result = new UnauthorizedResult();
            return;
        }
    }
}

But I want to inject the service properly, instead of using a new statement in the construction. Off course I do not want to change the format of the attribute, so nothing like [LegacyRole(serviceInstance,"MyRole", "MyOtherRole")] or so.

Any way to do this properly?

Body:
If you want to instantiation of LegacyRoleService() method then please declare its class(where the method is decclared) as Static.

For Example,

Public Static LegacyRoleServiceclass()


问:
Is it a good practice to keep one CLLocationManager inside my AppDelegate?
My app monitors user location, including some background location monitoring.

I had one location manager inside my App Delegate mainly for initial launch location and also for the background updates. Then I had another manager inside my view controller (map) for more specific events and quick reference.

I was wondering if it was a good practice to refactor this into one instance, kept in App Delegate, and refer to it throughout the app using:

```<code>self.appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

[self.appDelegate.locationManager startUpdatingLocation];
</code>```

答:
CLLocationManager was designed to work as multiple instances so create one for each feature in your app. They are all lightweight so don't worry about creating lots of them and they all communicate with one private location client that starts and stops the GPS depending on how many managers there are.

Refactoring it into a single instance is undoing all the hard work Apple did to make it work as multiple instances.

Body:
My app monitors user location, including some background location monitoring.

I had one location manager inside my App Delegate mainly for initial launch location and also for the background updates. Then I had another manager inside my view controller (map) for more specific events and quick reference.

I was wondering if it was a good practice to refactor this into one instance, kept in App Delegate, and refer to it throughout the app using:

self.appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

[self.appDelegate.locationManager startUpdatingLocation];


问:
WCF - Inspect the messages being sent/received?
I have 2 solutions:
 - Server Solution
 - Client Solution

The server registers itself to my localhost IIS: http://localhost/MyApp/

The client adds WCF Services (Service References) from the localhost application: http://localhost/MyApp/MyService.svc

When I'm running the client I want to be able to see the messages being passed back and forth. I downloaded Fiddler, but it doesn't seem to want to show me any traffic being sent unless I actually use a web browser. Am I using Fiddler wrong or is there another tool I should be using for this?

To clarify, what I'm looking to do is to see the actual messages being passed in. I don't want to do anything with them except see them visually with my own eyes.

I like the WCF Service Log Utility, but I don't think I have the correct setting on there. I can't see the actual soap message, just that a message was received.

And also to clarify further, I don't care what tool I use as long as I can easily see the messages themselves.

答:
If you want to inspect messages programattically, you can implement an IClientMessageInspector interface and register it with your client.

This allows you access to all of the messages, no matter what binding you are using, whereas using tools like Fiddler will only allow you to inspect messages using the HTTP transport channel.

Note, that using this technique, you can do much actually modify the messages or do much more (fire off notifications, for example).  If all you wish to do is put your eyes on the message, then using tracing might be an easier approach for you.


问:
Scraping using selenium
Hi I am trying to scrape this website I originally was using Bs4 and that was fine to get certain elements. Sector, name etc. But I am not able to use it to get the financial data. Below I have copied some of the page_source the "-" should be in this case 0.0663. I believe I am trying to scrape javascript and I have looked around and none of the solutions I have seen have worked for me. I was wondering if someone could help me crack this.

Although I will be grateful if someone can post some working code I would also really appreciate if you can point me in the right direction as well to understand what to look for in the html which shows me what I need to do and how to get it kinda thing.

URL: https://www.tradingview.com/symbols/LSE-TSCO/

HTML:

    Return on Equity (TTM)

    —

```

<p>Python Code:</p>

<pre class="lang-py prettyprint-override"><code>url = "https://www.tradingview.com/symbols/LSE-TSCO/"
options = webdriver.ChromeOptions()
options.add_argument('headless')
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get(url)
html = driver.page_source
</code>```

答:
You can get the return on equity using xpath</p>

```<code>equity = driver.find_element_by_xpath('/html/body/div[2]/div[4]/div/div/div/div/div/div[2]/div[2]/div[2]/div/div[2]/div[1]/div/div/div[1]/div[3]/div[3]/span[2]').text
print(equity)
</code>```

Title: Scraping using selenium

Body:
Hi I am trying to scrape this website I originally was using Bs4 and that was fine to get certain elements. Sector, name etc. But I am not able to use it to get the financial data. Below I have copied some of the page_source the "-" should be in this case 0.0663. I believe I am trying to scrape javascript and I have looked around and none of the solutions I have seen have worked for me. I was wondering if someone could help me crack this.

Although I will be grateful if someone can post some working code I would also really appreciate if you can point me in the right direction as well to understand what to look for in the html which shows me what I need to do and how to get it kinda thing.

URL: https://www.tradingview.com/symbols/LSE-TSCO/

HTML:

    Return on Equity (TTM)

    —

Python Code:

url = "https://www.tradingview.com/symbols/LSE-TSCO/"
options = webdriver.ChromeOptions()
options.add_argument('headless')
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get(url)
html = driver.page_source

Body:
You can get the return on equity using xpath

equity = driver.find_element_by_xpath('/html/body/div[2]/div[4]/div/div/div/div/div/div[2]/div[2]/div[2]/div/div[2]/div[1]/div/div/div[1]/div[3]/div[3]/span[2]').text
print(equity)


问:
In Swift, how to ignore a part of the code when running from an App Extension target?
There's a similar question that works on Objective-C, but I tried the same code in Swift and it never executes, neither in the main app, nor in the action extension.

My situation is similar to the one in the question above, that is, when running from the main app I want to use UIApplication.shared.open to open a link in Safari, but I want to ignore this part of the code on the App Extension.

The problem isn't finding out whether the app is running from an App Extension or not, but ignoring the code when building for the App Extension, so that the compiler does not give me the following error on build:

答:
You could introduce a new Custom Flag (similar to the DEBUG flag) for the extension target. In your Build Settings look for the Custom Flags and add a new one (e.g. "EXTENSION"). Like here in the screenshot, but also do it for release.

In your Code you could then do something like

```<code>#if EXTENSION
    // here goes code that is only compiled in the extension
#else
    // here goes code that is only compiled outside the extension
#endif
</code>```

Body:
You could introduce a new Custom Flag (similar to the DEBUG flag) for the extension target. In your Build Settings look for the Custom Flags and add a new one (e.g. "EXTENSION"). Like here in the screenshot, but also do it for release.

In your Code you could then do something like

#if EXTENSION
    // here goes code that is only compiled in the extension
#else
    // here goes code that is only compiled outside the extension
#endif


问:
Why does this c# code only accept input once?
I'm trying to write a program to keep track of how many times I die in a game. The program runs, accepts user input, and keeps track of the information. When I run the program, it works, but you can only enter one key. For example, if you start it up and then press "D," it will add one to the "deaths" variable, but then you won't be able to type in anything else. Here's the code:</p>

```<code>Console.WriteLine(
      "To add one to Deaths stat, press D. To add one to Charms Stat, press C. " +
      "To see all stats, press S.");

int deaths = 0;
int charms = 23;

ConsoleKeyInfo datKey;
datKey = Console.ReadKey();

if (datKey.Key == ConsoleKey.D)
{
    deaths = deaths + 1;
    Console.WriteLine();
    Console.WriteLine("Death Added");
}
if (datKey.Key == ConsoleKey.C)
{
    charms = charms + 1;
    Console.WriteLine();
    Console.WriteLine("Charm Added");
}
if (datKey.Key == ConsoleKey.S)
{
    Console.WriteLine();
    Console.WriteLine($"You have {charms} charms \nYou have died {deaths} times");
</code>```

答:
Try this:

```<code>using System;

namespace TestApp
{
   class Program
   {
      static void Main()
      {

         Console.WriteLine("To add one to Deaths stat, press D. To add one to Charms Stat, press C (like you'll have to use that one). To see all stats, press S.");

         int deaths = 0;
         int charms = 23;

         ConsoleKeyInfo datKey;

         do
         {
            datKey = Console.ReadKey();
            switch(datKey.Key)
            {
               case ConsoleKey.D:
                  deaths++;
                  Console.WriteLine();
                  Console.WriteLine("Death Added");
                  break;
               case ConsoleKey.C:
                  charms++;
                  Console.WriteLine();
                  Console.WriteLine("Charm Added");
                  break;
               case ConsoleKey.S:
                  Console.WriteLine();
                  Console.WriteLine($"You have {charms} charms \nYou have died {deaths} times sence starting this program");
                  break;
               default:
                  Console.WriteLine();
                  Console.WriteLine("A useless key pressed");
                  break;
            }
         } while (datKey.Key != ConsoleKey.S);

         Console.ReadKey();

      }
   }
}
</code>```

As you can see, I have encapsulated your request for a user input (datKey = Console.ReadKey();) in a loop, so the program will continue to ask the user to type a key. Only is the user has type the S, the loop is breaked. Furthermore I have changed your many if-statements to switch-struture, which is better to use in this situation

Body:
I'm trying to write a program to keep track of how many times I die in a game. The program runs, accepts user input, and keeps track of the information. When I run the program, it works, but you can only enter one key. For example, if you start it up and then press "D," it will add one to the "deaths" variable, but then you won't be able to type in anything else. Here's the code:

Console.WriteLine(
      "To add one to Deaths stat, press D. To add one to Charms Stat, press C. " +
      "To see all stats, press S.");

int deaths = 0;
int charms = 23;

ConsoleKeyInfo datKey;
datKey = Console.ReadKey();

if (datKey.Key == ConsoleKey.D)
{
    deaths = deaths + 1;
    Console.WriteLine();
    Console.WriteLine("Death Added");
}
if (datKey.Key == ConsoleKey.C)
{
    charms = charms + 1;
    Console.WriteLine();
    Console.WriteLine("Charm Added");
}
if (datKey.Key == ConsoleKey.S)
{
    Console.WriteLine();
    Console.WriteLine($"You have {charms} charms \nYou have died {deaths} times");

Body:
Try this:

using System;

namespace TestApp
{
   class Program
   {
      static void Main()
      {

         Console.WriteLine("To add one to Deaths stat, press D. To add one to Charms Stat, press C (like you'll have to use that one). To see all stats, press S.");

         int deaths = 0;
         int charms = 23;

         ConsoleKeyInfo datKey;

         do
         {
            datKey = Console.ReadKey();
            switch(datKey.Key)
            {
               case ConsoleKey.D:
                  deaths++;
                  Console.WriteLine();
                  Console.WriteLine("Death Added");
                  break;
               case ConsoleKey.C:
                  charms++;
                  Console.WriteLine();
                  Console.WriteLine("Charm Added");
                  break;
               case ConsoleKey.S:
                  Console.WriteLine();
                  Console.WriteLine($"You have {charms} charms \nYou have died {deaths} times sence starting this program");
                  break;
               default:
                  Console.WriteLine();
                  Console.WriteLine("A useless key pressed");
                  break;
            }
         } while (datKey.Key != ConsoleKey.S);

         Console.ReadKey();

      }
   }
}

As you can see, I have encapsulated your request for a user input (datKey = Console.ReadKey();) in a loop, so the program will continue to ask the user to type a key. Only is the user has type the S, the loop is breaked. Furthermore I have changed your many if-statements to switch-struture, which is better to use in this situation


问:
Gradle sync failed: Failed to create parent directory - Android Studio
I have facing the unexpected error in Android Studio and i can't able to run my app.

```<code> 'C:\Users\.gradle\caches\modules-2\metadata-2.71\descriptors\com.android.tools.build\gradle' when creating directory 'C:\Users\.gradle\caches\modules-2\metadata-2.71\descriptors\com.android.tools.build\gradle\3.6.3\fc7e8eef251519086b6ee9788cba4dd2'
</code>```

There is something happen in Android studio and not able to run my app and App configuration have facing problem even.

答:
Delete these folder entirely at the path:

```<code>  C:\Users\.gradle\caches\
</code>```

You are getting this error due to the corrupt caches stored in the studio.

Deleting and rebuilding the project again will fix your issue.

Body:
I have facing the unexpected error in Android Studio and i can't able to run my app.

 'C:\Users\.gradle\caches\modules-2\metadata-2.71\descriptors\com.android.tools.build\gradle' when creating directory 'C:\Users\.gradle\caches\modules-2\metadata-2.71\descriptors\com.android.tools.build\gradle\3.6.3\fc7e8eef251519086b6ee9788cba4dd2'

There is something happen in Android studio and not able to run my app and App configuration have facing problem even.

Body:
Delete these folder entirely at the path:

  C:\Users\.gradle\caches\

You are getting this error due to the corrupt caches stored in the studio.

Deleting and rebuilding the project again will fix your issue.


问:
Trying to get all paths in a YAML file
I've got an input YAML file (test.yml) as follows:

```<code># sample set of lines
foo:
  x: 12
  y: hello world
  ip_range['initial']: 1.2.3.4
  ip_range[]: tba
  array['first']: Cluster1

array2[]: bar
</code>```

The source contains square brackets for some keys (possibly empty).

I'm trying to get a line by line list of all the paths in the file, ideally like:

```<code>foo.x: 12
foo.y: hello world
foo.ip_range['initial']: 1.2.3.4
foo.ip_range[]: tba
foo.array['first']: Cluster1
array2[]: bar

</code>```

I've used the yamlpaths library and the yaml-paths CLI, but can't get the desired output. Trying this:

```<code>yaml-paths -m -s =foo -K test.yml
</code>```

outputs:

```<code>foo.x
foo.y
foo.ip_range\[\'initial\'\]
foo.ip_range\[\]
foo.array\[\'first\'\]
</code>```

Each path is on one line, but the output has all the escape characters ( \ ). Modifying the call to remove the -m option ("expand matching parent nodes") fixes that problem but the output is then not one path per line:

```<code>yaml-paths -s =foo -K test.yml
</code>```

gives:

```<code>foo: {"x": 12, "y": "hello world", "ip_range['initial']": "1.2.3.4", "ip_range[]": "tba", "array['first']": "Cluster1"}

</code>```

Any ideas how I can get the one line per path entry but without the escape chars? I was wondering if there is anything for path querying in the ruamel modules?

答:
Your "paths" are nothing more than the joined string representation of the keys (and probably indices) of the
mappings (and potentially sequences) in your YAML document.

That can be trivially generated from data loaded from YAML with a recursive function:

```<code>import sys
import ruamel.yaml

yaml_str = """\
# sample set of lines
foo:
  x: 12
  y: hello world
  ip_range['initial']: 1.2.3.4
  ip_range[]: tba
  array['first']: Cluster1

array2[]: bar
"""

def pathify(d, p=None, paths=None, joinchar='.'):
    if p is None:
        paths = {}
        pathify(d, "", paths, joinchar=joinchar)
        return paths
    pn = p
    if p != "":
        pn += '.'
    if isinstance(d, dict):
        for k in d:
            v = d[k]
            pathify(v, pn + k, paths, joinchar=joinchar)
    elif isinstance(d, list):
        for idx, e in enumerate(d):
            pathify(e, pn + str(idx), paths, joinchar=joinchar)
    else:
        paths[p] = d

yaml = ruamel.yaml.YAML(typ='safe')
paths = pathify(yaml.load(yaml_str))

for p, v in paths.items():
    print(f'{p} -> {v}')
</code>```

which gives:

```<code>foo.x -> 12
foo.y -> hello world
foo.ip_range['initial'] -> 1.2.3.4
foo.ip_range[] -> tba
foo.array['first'] -> Cluster1
array2[] -> bar
</code>```

Title: Trying to get all paths in a YAML file

Body:
I've got an input YAML file (test.yml) as follows:

# sample set of lines
foo:
  x: 12
  y: hello world
  ip_range['initial']: 1.2.3.4
  ip_range[]: tba
  array['first']: Cluster1

array2[]: bar

The source contains square brackets for some keys (possibly empty).

I'm trying to get a line by line list of all the paths in the file, ideally like:

foo.x: 12
foo.y: hello world
foo.ip_range['initial']: 1.2.3.4
foo.ip_range[]: tba
foo.array['first']: Cluster1
array2[]: bar

I've used the yamlpaths library and the yaml-paths CLI, but can't get the desired output. Trying this:

yaml-paths -m -s =foo -K test.yml

outputs:

foo.x
foo.y
foo.ip_range\[\'initial\'\]
foo.ip_range\[\]
foo.array\[\'first\'\]

Each path is on one line, but the output has all the escape characters ( \ ). Modifying the call to remove the -m option ("expand matching parent nodes") fixes that problem but the output is then not one path per line:

yaml-paths -s =foo -K test.yml

gives:

foo: {"x": 12, "y": "hello world", "ip_range['initial']": "1.2.3.4", "ip_range[]": "tba", "array['first']": "Cluster1"}

Any ideas how I can get the one line per path entry but without the escape chars? I was wondering if there is anything for path querying in the ruamel modules?

Body:
Your "paths" are nothing more than the joined string representation of the keys (and probably indices) of the
mappings (and potentially sequences) in your YAML document.

That can be trivially generated from data loaded from YAML with a recursive function:

import sys
import ruamel.yaml

yaml_str = """\
# sample set of lines
foo:
  x: 12
  y: hello world
  ip_range['initial']: 1.2.3.4
  ip_range[]: tba
  array['first']: Cluster1

array2[]: bar
"""

def pathify(d, p=None, paths=None, joinchar='.'):
    if p is None:
        paths = {}
        pathify(d, "", paths, joinchar=joinchar)
        return paths
    pn = p
    if p != "":
        pn += '.'
    if isinstance(d, dict):
        for k in d:
            v = d[k]
            pathify(v, pn + k, paths, joinchar=joinchar)
    elif isinstance(d, list):
        for idx, e in enumerate(d):
            pathify(e, pn + str(idx), paths, joinchar=joinchar)
    else:
        paths[p] = d

yaml = ruamel.yaml.YAML(typ='safe')
paths = pathify(yaml.load(yaml_str))

for p, v in paths.items():
    print(f'{p} -> {v}')

which gives:

foo.x -> 12
foo.y -> hello world
foo.ip_range['initial'] -> 1.2.3.4
foo.ip_range[] -> tba
foo.array['first'] -> Cluster1
array2[] -> bar


问:
How to create model allowing infinite submodels in django?
Im creating a site where you can write down your goals, you should be able to split every goal into subgoals if chosen, and allow those subgoals to be split into subgoals infinitely.

This code below shows what i came up with first for the models, the first model is for creating a goal, the second model can either either be a subgoal of the goal or a subgoal of the subgoal.
But it seems like a really bad way to go around this problem.

Django semi-newbie BTW...

```<code>from django.db import models

from django.contrib.auth.models import User

class Goal(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, default=None)
    title = models.CharField(max_length=70, null=True)
    content = models.TextField(blank=True)
    slug = models.SlugField(max_length=50, editable=False)

    date_created = models.DateTimeField(auto_now_add=True, null=True)

    class Meta:
        unique_together = ['user', 'title']

    def __str__(self):
        return self.user.username + " - " + self.title

    def save(self, *args, **kwargs):
        self.slug = self.title.replace(' ', '-').lower()
        super(Goal, self).save(*args, **kwargs)

class SubGoal(models.Model):
    goal = models.ForeignKey(
        Goal, on_delete=models.CASCADE, null=True, blank=True)
    parent = models.ForeignKey(
        "SubGoal", on_delete=models.CASCADE, null=True, blank=True)
    title = models.CharField(max_length=70)
    content = models.TextField(blank=True)

    date_created = models.DateTimeField(auto_now_add=True, null=True)

    def __str__(self):
        try:
            return self.goal.title + " - " + self.title
        except:
            return self.parent.title + " - " + self.title
</code>```

答:
You can make a ForeignKey to self. If the ForeignKey is NULL, then that goal has no parent, otherwise it refers to the parent:

```<code>from django.db import models

from django.contrib.auth.models import User
from django.conf import settings
django.utils.text import slugify

class Goal(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length=70)
    content = models.TextField(blank=True)
    slug = models.SlugField(max_length=50, editable=False)
    date_created = models.DateTimeField(auto_now_add=True)
    <b>parent</b> = models.ForeignKey(
        <b>'self'</b>,
        on_delete=models.SET_NULL,
        null=True,
        default=None,
        related_name='subgoals'
    )

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['user', 'title'], name='user_title')
        ]

    def __str__(self):
        if self.parent_id is None:
            return '{}-{}'.format(self.user.username, self.title)
        else:
            return '{}-{}'.format(str(self.parent), self.title)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super(Goal, self).save(*args, **kwargs)</code>```

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Body:
Im creating a site where you can write down your goals, you should be able to split every goal into subgoals if chosen, and allow those subgoals to be split into subgoals infinitely.

This code below shows what i came up with first for the models, the first model is for creating a goal, the second model can either either be a subgoal of the goal or a subgoal of the subgoal.
But it seems like a really bad way to go around this problem.

Django semi-newbie BTW...

from django.db import models

from django.contrib.auth.models import User

class Goal(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, default=None)
    title = models.CharField(max_length=70, null=True)
    content = models.TextField(blank=True)
    slug = models.SlugField(max_length=50, editable=False)

    date_created = models.DateTimeField(auto_now_add=True, null=True)

    class Meta:
        unique_together = ['user', 'title']

    def __str__(self):
        return self.user.username + " - " + self.title

    def save(self, *args, **kwargs):
        self.slug = self.title.replace(' ', '-').lower()
        super(Goal, self).save(*args, **kwargs)

class SubGoal(models.Model):
    goal = models.ForeignKey(
        Goal, on_delete=models.CASCADE, null=True, blank=True)
    parent = models.ForeignKey(
        "SubGoal", on_delete=models.CASCADE, null=True, blank=True)
    title = models.CharField(max_length=70)
    content = models.TextField(blank=True)

    date_created = models.DateTimeField(auto_now_add=True, null=True)

    def __str__(self):
        try:
            return self.goal.title + " - " + self.title
        except:
            return self.parent.title + " - " + self.title

Body:
You can make a ForeignKey to self. If the ForeignKey is NULL, then that goal has no parent, otherwise it refers to the parent:

from django.db import models

from django.contrib.auth.models import User
from django.conf import settings
django.utils.text import slugify

class Goal(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length=70)
    content = models.TextField(blank=True)
    slug = models.SlugField(max_length=50, editable=False)
    date_created = models.DateTimeField(auto_now_add=True)
    parent = models.ForeignKey(
        'self',
        on_delete=models.SET_NULL,
        null=True,
        default=None,
        related_name='subgoals'
    )

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['user', 'title'], name='user_title')
        ]

    def __str__(self):
        if self.parent_id is None:
            return '{}-{}'.format(self.user.username, self.title)
        else:
            return '{}-{}'.format(str(self.parent), self.title)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super(Goal, self).save(*args, **kwargs)

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.


问:
Opening detailed page when clicking planet in list
The below code renders a list of planets (from this API: https://swapi.dev/).I'm trying to find a way to make my planets clickable. When a specific planet is clicked in the list, it should open up a detail page with specific info (pulled from API) on the planet that has been clicked. Can I do this with  or ? What is the best practice way to do this?

```<code>import React, { PureComponent } from 'react'
import axios from "axios";

class Home extends PureComponent {
    constructor(props) {
        super(props)

        this.state = {
            planets: [],
            filteredPlanets: []
        }

        this.handleChange = this.handleChange.bind(this)
    }

    handleChange(e){ // eslint-disable-next-line
        let planetssearchlist = this.state.planets.filter(planet => {
             if(planet.name){
                if(planet.name.toLowerCase().includes(e.target.value.toLowerCase())){
                    return true
                }
            }
        })
        this.setState({
            filteredPlanets: planetssearchlist
        })
    }

    componentDidMount(){
        axios({
            method: "GET",
            url: "https://swapi.dev/api/planets/"
        })
        .then(response => {
            console.log(response)
            let planetslist = response.data.results;
            this.setState({planets: planetslist, filteredPlanets: planetslist})
        })
        .catch(error => {
            console.log("You've made an error with the planets load charles: ",error)
        })
    }

    render() {
        return (

        <div>
            <h1>Star Wars Planets</h1>

            <form>
                <input placeholder="searchbar" type="text" onChange={this.handleChange}></input>
            </form>

            {
                this.state.filteredPlanets.map((planet,i) => (
                        <p key={i}>{planet.name}</p>
                ))
            }

        </div>

        )
    }
}

export default Home
</code>```

答:
Add a new function to get the planet info. In your map add onClick event handler to get the planet info for the clicked planet.

Add two new variable to your state

```<code>this.state = {
  planets: [],
  filteredPlanets: [],
  planetInfo: {},
  isGettingPlanetInfo: false,
};
</code>```

Add a function to get the planet info

```<code>getPlanetInfo = url => {

  this.setState({
    isGettingPlanetInfo: true
  })

  axios({
    method: "GET",
    url: url
  })
    .then(response => {
      console.log(response.data)
      this.setState({
        planetInfo: response.data,
        isGettingPlanetInfo: false,
      })
    })
    .catch(error => {
      this.setState({
        isGettingPlanetInfo: false
      })
      console.log(
        "You've made an error with the planets load charles: ",
        error
      );
    });
};
</code>```

Add on click event handler to the planet

```<code>{this.state.filteredPlanets.map((planet, i) => (
  <p onClick={() => this.getPlanetInfo(planet.url)} key={i}>
    {planet.name}
  </p>
))}
</code>```

Home component

```<code>import React, { PureComponent } from 'react';
import axios from 'axios';

export default class Home extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      planets: [],
      filteredPlanets: [],
      planetInfo: {},
      isGettingPlanetInfo: false,
    };

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    // eslint-disable-next-line
    let planetssearchlist = this.state.planets.filter((planet) => {
      if (planet.name) {
        if (planet.name.toLowerCase().includes(e.target.value.toLowerCase())) {
          return true;
        }
      }
    });
    this.setState({
      filteredPlanets: planetssearchlist,
    });
  }

  getPlanetInfo = (url) => {
    this.setState({
      isGettingPlanetInfo: true,
    });

    axios({
      method: 'GET',
      url: url,
    })
      .then((response) => {
        console.log(response.data);
        this.setState({
          planetInfo: response.data,
          isGettingPlanetInfo: false,
        });
      })
      .catch((error) => {
        this.setState({
          isGettingPlanetInfo: false,
        });
        console.log(
          "You've made an error with the planets load charles: ",
          error
        );
      });
  };

  componentDidMount() {
    axios({
      method: 'GET',
      url: 'https://swapi.dev/api/planets/',
    })
      .then((response) => {
        console.log(response);
        let planetslist = response.data.results;
        this.setState({ planets: planetslist, filteredPlanets: planetslist });
      })
      .catch((error) => {
        console.log(
          "You've made an error with the planets load charles: ",
          error
        );
      });
  }

  render() {
    return (
      <div>
        <h1>Star Wars Planets</h1>

        <form>
          <input
            placeholder='searchbar'
            type='text'
            onChange={this.handleChange}
          />
        </form>

        {this.state.filteredPlanets.map((planet, i) => (
          <p onClick={() => this.getPlanetInfo(planet.url)} key={i}>
            {planet.name}
          </p>
        ))}

        <hr />

        {this.state.isGettingPlanetInfo ? (
          <p>getting planet info...</p>
        ) : typeof this.state.planetInfo === 'object' &&
          Object.keys(this.state.planetInfo).length ? (
          <div>
            <p>name: {this.state.planetInfo.name}</p>
            <p>climate: {this.state.planetInfo.climate}</p>
            <p>population: {this.state.planetInfo.population}</p>
          </div>
        ) : (
          ''
        )}
      </div>
    );
  }
}
</code>```

With react router

```<code>import React, { PureComponent } from "react";
import axios from "axios";

import { BrowserRouter, Route, Switch, Link } from "react-router-dom";

class PlanetInfo extends React.Component {
  state = {
    url: "",
    planetInfo: {},
    isGettingPlanetInfo: false
  };

  getPlanetInfo = () => {
    this.setState({
      isGettingPlanetInfo: true
    });

    axios({
      method: "GET",
      url: this.state.url
    })
      .then(response => {
        console.log(response.data);
        this.setState({
          planetInfo: response.data,
          isGettingPlanetInfo: false
        });
      })
      .catch(error => {
        this.setState({
          isGettingPlanetInfo: false
        });
        console.log(
          "You've made an error with the planets load charles: ",
          error
        );
      });
  };

  componentDidMount = () => {
    this.setState(
      {
        url: this.props.location.state.planet.url
      },
      this.getPlanetInfo
    );
  };

  render() {
    return (
      <div>
        {this.state.isGettingPlanetInfo ? (
          <p>getting planet info...</p>
        ) : typeof this.state.planetInfo === "object" &&
          Object.keys(this.state.planetInfo).length ? (
          <div>
            <p>name: {this.state.planetInfo.name}</p>
            <p>climate: {this.state.planetInfo.climate}</p>
            <p>population: {this.state.planetInfo.population}</p>
          </div>
        ) : (
          ""
        )}
      </div>
    );
  }
}

class Home extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      planets: [],
      filteredPlanets: []
    };

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    // eslint-disable-next-line
    let planetssearchlist = this.state.planets.filter(planet => {
      if (planet.name) {
        if (planet.name.toLowerCase().includes(e.target.value.toLowerCase())) {
          return true;
        }
      }
    });
    this.setState({
      filteredPlanets: planetssearchlist
    });
  }

  componentDidMount() {
    axios({
      method: "GET",
      url: "https://swapi.dev/api/planets/"
    })
      .then(response => {
        console.log(response);
        let planetslist = response.data.results;
        this.setState({ planets: planetslist, filteredPlanets: planetslist });
      })
      .catch(error => {
        console.log(
          "You've made an error with the planets load charles: ",
          error
        );
      });
  }

  render() {
    return (
      <div>
        <h1>Star Wars Planets</h1>

        <form>
          <input
            placeholder="searchbar"
            type="text"
            onChange={this.handleChange}
          />
        </form>

        {this.state.filteredPlanets.map((planet, i) => (
          <Link to={{ pathname: "/info", state: { planet: planet } }}>
            <p key={i}>{planet.name}</p>
          </Link>
        ))}
      </div>
    );
  }
}

export default function Navigation() {
  return (
    <BrowserRouter>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route exact path="/info" component={PlanetInfo} />
      </Switch>
    </BrowserRouter>
  );
}
</code>```

Body:
The below code renders a list of planets (from this API: https://swapi.dev/).I'm trying to find a way to make my planets clickable. When a specific planet is clicked in the list, it should open up a detail page with specific info (pulled from API) on the planet that has been clicked. Can I do this with  or ? What is the best practice way to do this?

import React, { PureComponent } from 'react'
import axios from "axios";

class Home extends PureComponent {
    constructor(props) {
        super(props)

        this.state = {
            planets: [],
            filteredPlanets: []
        }

        this.handleChange = this.handleChange.bind(this)
    }

    handleChange(e){ // eslint-disable-next-line
        let planetssearchlist = this.state.planets.filter(planet => {
             if(planet.name){
                if(planet.name.toLowerCase().includes(e.target.value.toLowerCase())){
                    return true
                }
            }
        })
        this.setState({
            filteredPlanets: planetssearchlist
        })
    }

    componentDidMount(){
        axios({
            method: "GET",
            url: "https://swapi.dev/api/planets/"
        })
        .then(response => {
            console.log(response)
            let planetslist = response.data.results;
            this.setState({planets: planetslist, filteredPlanets: planetslist})
        })
        .catch(error => {
            console.log("You've made an error with the planets load charles: ",error)
        })
    }

    render() {
        return (

Star Wars Planets

            <form>
                <input placeholder="searchbar" type="text" onChange={this.handleChange}></input>
            </form>

            {
                this.state.filteredPlanets.map((planet,i) => (

{planet.name}

                ))
            }

        )
    }
}

export default Home

Body:
Add a new function to get the planet info. In your map add onClick event handler to get the planet info for the clicked planet.

Add two new variable to your state

this.state = {
  planets: [],
  filteredPlanets: [],
  planetInfo: {},
  isGettingPlanetInfo: false,
};

Add a function to get the planet info

getPlanetInfo = url => {

  this.setState({
    isGettingPlanetInfo: true
  })

  axios({
    method: "GET",
    url: url
  })
    .then(response => {
      console.log(response.data)
      this.setState({
        planetInfo: response.data,
        isGettingPlanetInfo: false,
      })
    })
    .catch(error => {
      this.setState({
        isGettingPlanetInfo: false
      })
      console.log(
        "You've made an error with the planets load charles: ",
        error
      );
    });
};

Add on click event handler to the planet

{this.state.filteredPlanets.map((planet, i) => (
  <p onClick={() => this.getPlanetInfo(planet.url)} key={i}>
    {planet.name}
  </p>
))}

Home component

import React, { PureComponent } from 'react';
import axios from 'axios';

export default class Home extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      planets: [],
      filteredPlanets: [],
      planetInfo: {},
      isGettingPlanetInfo: false,
    };

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    // eslint-disable-next-line
    let planetssearchlist = this.state.planets.filter((planet) => {
      if (planet.name) {
        if (planet.name.toLowerCase().includes(e.target.value.toLowerCase())) {
          return true;
        }
      }
    });
    this.setState({
      filteredPlanets: planetssearchlist,
    });
  }

  getPlanetInfo = (url) => {
    this.setState({
      isGettingPlanetInfo: true,
    });

    axios({
      method: 'GET',
      url: url,
    })
      .then((response) => {
        console.log(response.data);
        this.setState({
          planetInfo: response.data,
          isGettingPlanetInfo: false,
        });
      })
      .catch((error) => {
        this.setState({
          isGettingPlanetInfo: false,
        });
        console.log(
          "You've made an error with the planets load charles: ",
          error
        );
      });
  };

  componentDidMount() {
    axios({
      method: 'GET',
      url: 'https://swapi.dev/api/planets/',
    })
      .then((response) => {
        console.log(response);
        let planetslist = response.data.results;
        this.setState({ planets: planetslist, filteredPlanets: planetslist });
      })
      .catch((error) => {
        console.log(
          "You've made an error with the planets load charles: ",
          error
        );
      });
  }

  render() {
    return (
      <div>
        <h1>Star Wars Planets</h1>

        <form>
          <input
            placeholder='searchbar'
            type='text'
            onChange={this.handleChange}
          />
        </form>

        {this.state.filteredPlanets.map((planet, i) => (
          <p onClick={() => this.getPlanetInfo(planet.url)} key={i}>
            {planet.name}
          </p>
        ))}

        <hr />

        {this.state.isGettingPlanetInfo ? (
          <p>getting planet info...</p>
        ) : typeof this.state.planetInfo === 'object' &&
          Object.keys(this.state.planetInfo).length ? (
          <div>
            <p>name: {this.state.planetInfo.name}</p>
            <p>climate: {this.state.planetInfo.climate}</p>
            <p>population: {this.state.planetInfo.population}</p>
          </div>
        ) : (
          ''
        )}
      </div>
    );
  }
}

With react router

import React, { PureComponent } from "react";
import axios from "axios";

import { BrowserRouter, Route, Switch, Link } from "react-router-dom";

class PlanetInfo extends React.Component {
  state = {
    url: "",
    planetInfo: {},
    isGettingPlanetInfo: false
  };

  getPlanetInfo = () => {
    this.setState({
      isGettingPlanetInfo: true
    });

    axios({
      method: "GET",
      url: this.state.url
    })
      .then(response => {
        console.log(response.data);
        this.setState({
          planetInfo: response.data,
          isGettingPlanetInfo: false
        });
      })
      .catch(error => {
        this.setState({
          isGettingPlanetInfo: false
        });
        console.log(
          "You've made an error with the planets load charles: ",
          error
        );
      });
  };

  componentDidMount = () => {
    this.setState(
      {
        url: this.props.location.state.planet.url
      },
      this.getPlanetInfo
    );
  };

  render() {
    return (
      <div>
        {this.state.isGettingPlanetInfo ? (
          <p>getting planet info...</p>
        ) : typeof this.state.planetInfo === "object" &&
          Object.keys(this.state.planetInfo).length ? (
          <div>
            <p>name: {this.state.planetInfo.name}</p>
            <p>climate: {this.state.planetInfo.climate}</p>
            <p>population: {this.state.planetInfo.population}</p>
          </div>
        ) : (
          ""
        )}
      </div>
    );
  }
}

class Home extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      planets: [],
      filteredPlanets: []
    };

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    // eslint-disable-next-line
    let planetssearchlist = this.state.planets.filter(planet => {
      if (planet.name) {
        if (planet.name.toLowerCase().includes(e.target.value.toLowerCase())) {
          return true;
        }
      }
    });
    this.setState({
      filteredPlanets: planetssearchlist
    });
  }

  componentDidMount() {
    axios({
      method: "GET",
      url: "https://swapi.dev/api/planets/"
    })
      .then(response => {
        console.log(response);
        let planetslist = response.data.results;
        this.setState({ planets: planetslist, filteredPlanets: planetslist });
      })
      .catch(error => {
        console.log(
          "You've made an error with the planets load charles: ",
          error
        );
      });
  }

  render() {
    return (
      <div>
        <h1>Star Wars Planets</h1>

        <form>
          <input
            placeholder="searchbar"
            type="text"
            onChange={this.handleChange}
          />
        </form>

        {this.state.filteredPlanets.map((planet, i) => (
          <Link to={{ pathname: "/info", state: { planet: planet } }}>
            <p key={i}>{planet.name}</p>
          </Link>
        ))}
      </div>
    );
  }
}

export default function Navigation() {
  return (
    <BrowserRouter>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route exact path="/info" component={PlanetInfo} />
      </Switch>
    </BrowserRouter>
  );
}


问:
How to run nodemon + forever in the background
Good morning!

I need my node.js server running in the background. I just saw this answer: Forever + Nodemon running together

I understand the idea, and I think that it's great, but when I use

```<code>forever -c "nodemon --exitcrash" app.js
</code>```

the nodemon console stills visible. How can I hide the console?

Thank you everyone!

答:
Try using pm2 pm2 guides

With pm2 your application runs in the background and:-

Can auto-start on server reboots

You can even set pm2 to watch for file changes and reload your application

You can monitor your application and see resource utilization

You can view logs

You can run your application in cluster and load-balance requests using pm2

Body:
Good morning!

I need my node.js server running in the background. I just saw this answer: Forever + Nodemon running together

I understand the idea, and I think that it's great, but when I use

forever -c "nodemon --exitcrash" app.js

the nodemon console stills visible. How can I hide the console?

Thank you everyone!


问:
How to create a vector of variables using summarise?
Here is a beginner's problem:

I like using summarise(), but sometimes I find it difficult storing the results.
For example, I know I can store 1 value in the following manner:

```<code>stdv <- Data %>%
 filter(x == 1) %>%
 summarise(stdv = sd(y))
</code>```

But I get in trouble if I try to do so for more than 1 variable.
I think it's something to do with creating a vector o variables in the beginning but this doesn't work:

```<code>c(dog, cat) <- Data %>%
 filter(x == 1) %>%
 summarise(dog = sd(y),
           cat = mean(y))
</code>```

Can someone help? Thank ya

Body:
Here is a beginner's problem:

I like using summarise(), but sometimes I find it difficult storing the results.
For example, I know I can store 1 value in the following manner:

stdv <- Data %>%
 filter(x == 1) %>%
 summarise(stdv = sd(y))

But I get in trouble if I try to do so for more than 1 variable.
I think it's something to do with creating a vector o variables in the beginning but this doesn't work:

c(dog, cat) <- Data %>%
 filter(x == 1) %>%
 summarise(dog = sd(y),
           cat = mean(y))

Can someone help? Thank ya

Body:
We can use base R methods

with(df, c(dog = sd(id), cat = var(id)))
#    dog      cat
#1.636392 2.677778

data

df <- structure(list(id = c("1", "4", "3", "4", "6", "3", "5", "6",
"2", "3")), row.names = c(NA, -10L), class = c("tbl_df", "tbl",
"data.frame"))


问:
XSD to apply different restriction to last item in a list?
If have an XML format of the form:

```<code><msg>
   <item id="0" valueType="xxx"/>
   <item id="1" valueType="xxx"/>
   <item id="2" valueType="xxx"/>
   ...
   <item id="n" valueType="yyy"/>
</msg>
</code>```

The items are complex types with elements and attributes policed by a schema.
The valueType attribute can take one of a number of strings defined in an enumeration. However one of those valueType strings may only be used in the last item in the list.

Is there a clean way of adding such a restriction in the schema?

( I could create an itemLast type almost identical to item but with a different enumeration for valueType but that feels messy and adds additional complications to any XSLT file. )

答:
Your itemLast idea would be needed to treat the last item differently from the others in XSD 1.0, where dependent types are not supported.

If you can use XSD 1.1, you can add an assertion to the content model of msg to impose a special restriction on the last item:

```<code><xs:assert test="item[last()]/@valueType = 'yyy'"/>
</code>```

This assertion would be placed just before the closing xs:complexType tag for the msg type definition.

Here's an improvement to the above assertion to allow an empty list of item elements:

```<code><xs:assert test="not(item) or item[last()]/@valueType = 'yyy'"/>
</code>```

Thanks to @MichaelKay for noting the uncovered case.

Body:
If have an XML format of the form:

<msg>
   <item id="0" valueType="xxx"/>
   <item id="1" valueType="xxx"/>
   <item id="2" valueType="xxx"/>
   ...
   <item id="n" valueType="yyy"/>
</msg>

The items are complex types with elements and attributes policed by a schema.
The valueType attribute can take one of a number of strings defined in an enumeration. However one of those valueType strings may only be used in the last item in the list.

Is there a clean way of adding such a restriction in the schema?

( I could create an itemLast type almost identical to item but with a different enumeration for valueType but that feels messy and adds additional complications to any XSLT file. )

Body:
Your itemLast idea would be needed to treat the last item differently from the others in XSD 1.0, where dependent types are not supported.

If you can use XSD 1.1, you can add an assertion to the content model of msg to impose a special restriction on the last item:

<xs:assert test="item[last()]/@valueType = 'yyy'"/>

This assertion would be placed just before the closing xs:complexType tag for the msg type definition.

Here's an improvement to the above assertion to allow an empty list of item elements:

<xs:assert test="not(item) or item[last()]/@valueType = 'yyy'"/>

Thanks to @MichaelKay for noting the uncovered case.


问:
document.forms["button1"].submit() not work when timer expired
When timer expired form not submited. Here is my code.</p>

```<code><!DOCTYPE html>
<html>
<head>
    <title>
        How to call PHP function
        on the click of a Button ?
    </title>
</head>
<body style="text-align:center;">
    <h4>
        How to call PHP function
        on the click of a Button ?
    </h4>
    <form action="test1.php" method="post">
        <input type="submit" name="button1" id="button1"
                class="button" value="Button" />
    </form>
    <div id="timer"></div>
    <script type='text/javascript'>
        var start = new Date();
        var x=setInterval(function() {
            // check time elapsed given target time of 10 mins from now
            var timeLeft = (6000 - (new Date() - start))/1000;
            // update timer
            document.getElementById('timer').innerHTML = Math.floor(timeLeft/60) + ":" + Math.floor(timeLeft%60);

            // check if timer has elapsed, and submit form
            if (timeLeft < 0) {
                document.forms["button1"].submit();
            }
        }, 1000);
    </script>
</body>
</html>
</code>```

答:
You're trying to "submit" the button, not the form.  You can click a button, but you can't submit one.  The submit event is for forms.

(Side note: Open your browser's debugging console and observe that document.forms["button1"] returned undefined because there's no form with that identifier.  Always check the console for errors when something isn't working.)

Give the form an identifier and update that line of code to fetch it by that identifier:

var start = new Date();
var x=setInterval(function() {
    // check time elapsed given target time of 10 mins from now
    var timeLeft = (6000 - (new Date() - start))/1000;
    // update timer
    document.getElementById('timer').innerHTML = Math.floor(timeLeft/60) + ":" + Math.floor(timeLeft%60);

    // check if timer has elapsed, and submit form
    if (timeLeft < 0) {
        document.forms["form1"].submit();
    }
}, 1000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="test1.php" method="post" id="form1">
  <input type="submit" name="button1" id="button1" class="button" value="Button" />
</form>

<div id="timer"></div></code>```

Body:
When timer expired form not submited. Here is my code.

<!DOCTYPE html>

    <title>
        How to call PHP function
        on the click of a Button ?
    </title>

        How to call PHP function
        on the click of a Button ?

    <form action="test1.php" method="post">
        <input type="submit" name="button1" id="button1"
                class="button" value="Button" />
    </form>

Body:
You're trying to "submit" the button, not the form.  You can click a button, but you can't submit one.  The submit event is for forms.

(Side note: Open your browser's debugging console and observe that document.forms["button1"] returned undefined because there's no form with that identifier.  Always check the console for errors when something isn't working.)

Give the form an identifier and update that line of code to fetch it by that identifier:

var start = new Date();
var x=setInterval(function() {
    // check time elapsed given target time of 10 mins from now
    var timeLeft = (6000 - (new Date() - start))/1000;
    // update timer
    document.getElementById('timer').innerHTML = Math.floor(timeLeft/60) + ":" + Math.floor(timeLeft%60);

    // check if timer has elapsed, and submit form
    if (timeLeft < 0) {
        document.forms["form1"].submit();
    }
}, 1000);

<form action="test1.php" method="post" id="form1">
  <input type="submit" name="button1" id="button1" class="button" value="Button" />
</form>

<div id="timer"></div>