问:
Detecting duplicate music files
I've got two directories containing ~20 GB of music files (mostly mp3, some ogg), and I would like to detect all duplicate songs. There are two complicating factors:

A song may have different filenames in the two directories.

Two files containing the same song may have different ID3 tags and thus have different checksums.

What is a good approach to solving this?

答:
I was faced with the same problem, so I wrote a command-line program that tries to detect similar audio files by comparing acoustic fingerprints: https://codeberg.org/derat/soundalike

It uses the fpcalc utility from Chromaprint to generate the fingerprints, and then builds a lookup table to find possible matches before comparing fingerprints more rigorously.

It worked pretty well when I ran against my music library, but there are various flags to tune its behavior if needed. If it works for you (or if it doesn't), let me know!

OwnerDisplayName: JesperE

Title: Detecting duplicate music files


来源: stackexchange

问:
How do I output the first character of all strings that are in a list?
For example if I have the list:

['Bob\n', "Joe\n", "Frank\n", "Bill"]

and want to get the output

B

J

F

B

答:
```<code>tmp = ['Bob\n', "Joe\n", "Frank\n", "Bill"]
print([i[0] for i in tmp])
</code>```

ContentLicense: CC BY-SA 4.0


问:
Remove outlier using quantile python
I need to remove outlier for a regression dataset. Lets say the dataset is consist in the following way

```<code># dataset named df
humidity     windspeed
 0.01          4.9
 4.5           20.0
 3.5           5.0
 50.0          4.0
 4.2           0.05
 3.4           3.9
 18.0          4.7

# code for outlier removal
def quantile(columns):
   for column in columns:
      lower_quantile = df[column].quantile(0.25)
      upper_quantile = df[column].quantile(0.75)
      df[column] = df[(df[column] >= lower_quantile) & df[column] <= upper_quantile)

columns = ['humidity', 'windspeed']
quantile(columns)
</code>```

With closer inspection, the column humidity has three outliers which are 50.0,18.0,0.01 but for windspeed column the outliers are 20 and 0.05 and both columns outliers are not in the same row. In this case if I remove my outlier with the code above, I would get the following error:

```<code>Value error: Columns must be same length as key
</code>```

From what I understand, the length of row in each column is not the same once the outlier is removed hence it return me the error. Is there any other way to overcome this issue?

答:
You may filter for both columns at the same time,

```<code>df[
    df['humidity'].between(df['humidity'].quantile(.25), df['humidity'].quantile(.75)) &\
    df['windspeed'].between(df['windspeed'].quantile(.25), df['windspeed'].quantile(.75))
]
</code>```

In this case all three of the df, the conditions for 'humidity' and that for 'windspeed' share the same length because they are all derived from the same df.

Title: Remove outlier using quantile python

Body:
I need to remove outlier for a regression dataset. Lets say the dataset is consist in the following way

# dataset named df
humidity     windspeed
 0.01          4.9
 4.5           20.0
 3.5           5.0
 50.0          4.0
 4.2           0.05
 3.4           3.9
 18.0          4.7

# code for outlier removal
def quantile(columns):
   for column in columns:
      lower_quantile = df[column].quantile(0.25)
      upper_quantile = df[column].quantile(0.75)
      df[column] = df[(df[column] >= lower_quantile) & df[column] <= upper_quantile)

columns = ['humidity', 'windspeed']
quantile(columns)

With closer inspection, the column humidity has three outliers which are 50.0,18.0,0.01 but for windspeed column the outliers are 20 and 0.05 and both columns outliers are not in the same row. In this case if I remove my outlier with the code above, I would get the following error:

Value error: Columns must be same length as key

From what I understand, the length of row in each column is not the same once the outlier is removed hence it return me the error. Is there any other way to overcome this issue?

Body:
You may filter for both columns at the same time,

df[
    df['humidity'].between(df['humidity'].quantile(.25), df['humidity'].quantile(.75)) &\
    df['windspeed'].between(df['windspeed'].quantile(.25), df['windspeed'].quantile(.75))
]

In this case all three of the df, the conditions for 'humidity' and that for 'windspeed' share the same length because they are all derived from the same df.


问:
SQL - Why am I getting an ORA-00918 Error? I defined a column that's duplicated
I'm trying to complete an exercise for an assignment for my Database Programming class using Oracle LiveSQL. I defined the column that appears in each of the 2 tables that are accessed. I do not understand why I'm getting the error. Where am I going wrong with my code?

```<code>SELECT
    orders.customer_id,
    cust_email,
    COUNT(order_id) AS num_orders
FROM
    oe.customers
    LEFT JOIN oe.orders
        ON oe.customers.customer_id = oe.orders.customer_id
GROUP BY
    customer_id
ORDER BY
    customer_id ASC;
</code>```

The table diagram with the 2 tables we are using:

答:
In general, whatever columns appear in the SELECT clause must also appear in GROUP BY, unless those columns appear inside aggregate functions.  Consider using this version:

SELECT
    c.customer_id,
    c.cust_email,
    COUNT(o.order_id) AS num_orders
FROM oe.customers c
LEFT JOIN oe.orders o
    ON c.customer_id = c.customer_id
GROUP BY
    c.customer_id,
    c.cust_email
ORDER BY
    c.customer_id;
```

Note also another problem you had was that customer_id is a column which appears in both tables.  You need an alias in order to qualify which table's column you want to include.

Body:
I'm trying to complete an exercise for an assignment for my Database Programming class using Oracle LiveSQL. I defined the column that appears in each of the 2 tables that are accessed. I do not understand why I'm getting the error. Where am I going wrong with my code?

SELECT
    orders.customer_id,
    cust_email,
    COUNT(order_id) AS num_orders
FROM
    oe.customers
    LEFT JOIN oe.orders
        ON oe.customers.customer_id = oe.orders.customer_id
GROUP BY
    customer_id
ORDER BY
    customer_id ASC;

The table diagram with the 2 tables we are using:

Body:
In general, whatever columns appear in the SELECT clause must also appear in GROUP BY, unless those columns appear inside aggregate functions.  Consider using this version:

SELECT
    c.customer_id,
    c.cust_email,
    COUNT(o.order_id) AS num_orders
FROM oe.customers c
LEFT JOIN oe.orders o
    ON c.customer_id = c.customer_id
GROUP BY
    c.customer_id,
    c.cust_email
ORDER BY
    c.customer_id;

Note also another problem you had was that customer_id is a column which appears in both tables.  You need an alias in order to qualify which table's column you want to include.


问:
Uncaught TypeError: router.afterEach is not a function
Trying to use this demo application:
https://github.com/skyronic/vue-spa

to start a Vuex project but I'm gettig this error Uncaught TypeError: router.afterEach is not a function

relating to vuex-router-sync.

Can anyone help because I cannot find anything online.

My main.js entry point is:

```<code>import App from './pages/App'
import router from './router'
import store from './vuex/store'
import { sync } from 'vuex-router-sync'

sync(store, router)

router.start(App, '#app')
</code>```

I am not actually calling the router.afterEach fucntion from within my example but it is used by the vuex-router-sync package. Sorry I'm not knowledgeable enough to pin point this in more detail.

The function is called by the package on line 25 https://github.com/vuejs/vuex-router-sync/blob/master/index.js

Thanks for everyone's help so far :)

答:
I had the same problem, but my project it's all ok, running without any error, and in some update it's appear. I solvented with an empty function, example of my app.js.

const router = require("./../public/bundles/fosjsrouting/js/router.min.js");
const routes = require("./../public/js/fos_js_routes.json");

router.afterEach = (to, from) => {
    // you code here some action
    console.log('* afterEach')
};

router.setRoutingData(routes);
```

ContentLicense: CC BY-SA 3.0

Body:
Trying to use this demo application:
https://github.com/skyronic/vue-spa

to start a Vuex project but I'm gettig this error Uncaught TypeError: router.afterEach is not a function

relating to vuex-router-sync.

Can anyone help because I cannot find anything online.

My main.js entry point is:

import App from './pages/App'
import router from './router'
import store from './vuex/store'
import { sync } from 'vuex-router-sync'

sync(store, router)

router.start(App, '#app')

I am not actually calling the router.afterEach fucntion from within my example but it is used by the vuex-router-sync package. Sorry I'm not knowledgeable enough to pin point this in more detail.

The function is called by the package on line 25 https://github.com/vuejs/vuex-router-sync/blob/master/index.js

Thanks for everyone's help so far :)


问:
Using Fetch to import JSON data and output to an HTML Table
I'm learning JavaScript and trying to master what should be a basic process, fetching data from a .json file and outputting it to an HTML Table.

No problem when I uncomment the first 7 lines of code and comment out the next 3 lines that use 'fetch' .  However when I try to 'fetch' and output the data from another file I get the error that I've indicated at line #39 (let data = Object.keys(mountains[0]. I checked the console.log and the 'names.json' file is there as expected so the problem is not with a file path or with the fetch request. I think my problem is at line 39 with the 'Object.keys function. I'm at a loss as to how to reference the json data that was fetched. Any help appreciated!

/*let mountains = [
    { name: "Monte Falco", height: 1658, place: "Parco Foreste Casentinesi" },
    { name: "Monte Falterona", height: 1654, place: "Parco Foreste Casentinesi" },
    { name: "Poggio Scali", height: 1520, place: "Parco Foreste Casentinesi" },
    { name: "Pratomagno", height: 1592, place: "Parco Foreste Casentinesi" },
    { name: "Monte Amiata", height: 1738, place: "Siena" }
  ]; */

 (fetch("names.json")
  .then(res => res.json()
  .then(json => console.log(json))))

  function generateTableHead(table, data) {
    let thead = table.createHead();
    let row = thead.insertRow();
    for (let key of data) {
      let th = document.createElement("th");
      let text = document.createTextNode(key);
      th.appendChild(text);
      row.appendChild(th);

    }
  }

  function generateTable(table, data) {
    for (let element of data) {
      let row = table.insertRow();
      for (key in element) {
        let cell = row.insertCell();
        let text = document.createTextNode(element[key]);
        cell.appendChild(text);
      }
    }
  }

let table = document.querySelector("table");
let data = Object.keys(mountains[0]); //****************************** Uncaught ReferenceError: mountains is not defined
generateTable(table, mountains); // generate the table first
generateTableHead(table, data); // then the head```

答:
You can try something like this:

fetch("names.json")
  .then(res => res.json())
  .then(json => {
    console.log(json)
    // you need to get mountains from json
    // if json is in the shape that is needed then leave as it is
    const mountains = json
    let table = document.querySelector("table");
    let data = Object.keys(mountains[0]);
    generateTable(table, mountains); // generate the table first
    generateTableHead(table, data); // then the head
  })
```


问:
Converting multi digit char to int in C++
While I know that you can convert single digits that are characters to integers by doing, for example:

```<code>int main()
{
    char var = '5';
    int num_var = var - 48;
}
</code>```

I know you can't do the same thing for a character with a value which is say, '148'. Is there an easy way to convert this character value to an integer value of 148?

答: You can't store more than one character in a char. Use a char array instead, like char var[] = "3232". Then use the atoi function to convert to integer. int val = atoi(var). Make sure to include the header <stdlib.h>.

Body:
While I know that you can convert single digits that are characters to integers by doing, for example:

int main()
{
    char var = '5';
    int num_var = var - 48;
}

I know you can't do the same thing for a character with a value which is say, '148'. Is there an easy way to convert this character value to an integer value of 148?


问:
record the computation time for each epoch during model.fit()
I am using the standard keras process to train a model:

```<code>model.compile(optimizer = 'adam', loss = 'mean_squared_error')
model.fit(x_train, y_train, epochs = 50)

</code>```

And the output is something like:

```<code>Epoch 1/50
52/52 [==============================] - 8s 90ms/step - loss: 0.0027
Epoch 2/50
52/52 [==============================] - 5s 90ms/step - loss: 0.0023
</code>```

How can I calculate elapsed time for each Epoch?

I will have more than one experiment so I want to compare times.

答:
You need to create a simple custom callback. Documentation for that is here. My code to do that is shown below

```<code>import time
class etimer(keras.callbacks.Callback):
    def __init__ (self): # initialization of the callback
        super(etimer, self).__init__()
    def on_epoch_begin(self,epoch, logs=None):
        self.now= time.time()
    def on_epoch_end(self,epoch, logs=None):
        later=time.time()
        duration=later-self.now
        print('\nfor epoch ', epoch +1, ' the duration was ', duration, ' seconds')
</code>```

in model.fit add  callbacks=callbacks

Body:
I am using the standard keras process to train a model:

model.compile(optimizer = 'adam', loss = 'mean_squared_error')
model.fit(x_train, y_train, epochs = 50)

And the output is something like:

Epoch 1/50
52/52 [==============================] - 8s 90ms/step - loss: 0.0027
Epoch 2/50
52/52 [==============================] - 5s 90ms/step - loss: 0.0023

How can I calculate elapsed time for each Epoch?

I will have more than one experiment so I want to compare times.

Body:
You need to create a simple custom callback. Documentation for that is here. My code to do that is shown below

import time
class etimer(keras.callbacks.Callback):
    def __init__ (self): # initialization of the callback
        super(etimer, self).__init__()
    def on_epoch_begin(self,epoch, logs=None):
        self.now= time.time()
    def on_epoch_end(self,epoch, logs=None):
        later=time.time()
        duration=later-self.now
        print('\nfor epoch ', epoch +1, ' the duration was ', duration, ' seconds')

in model.fit add  callbacks=callbacks


问:
Increase parent div height when more child is added
I have a parent div with multiple child divs. Currently, the child divs are spaced around the parent div in order to fit the parent div equally and it works fine but what I'm trying to achieve is when more child divs are added the parent divs height increases in size but the child divs height stays the same. How can I achieve this? What it currently does when you add more child divs is the parent height stays the same but the child divs height will get shorter in order to fit the parent div but what I want is the other way around. When more child div is added I want the parent div to increase in height kinda like the parent div having a height of auto. How can I achieve this? Any help is appreciated. Thanks in advance.

.items {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  position: absolute;
  top: 6%;
  left: 15%;
  width: 70%;
  height: 60%;
  background-color: gold;
}

.data {
  width: 100%;
  height: 35%;
  background-color: #187bcd;
  border-top: 2px solid #000000;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="items">
  <div class="data">

  </div>
  <div class="data">

  </div>
  <div class="data">

  </div>
  <div class="data">

  </div>
</div></code>```

答:
You can apply a non-parentally-relative length unit (like em and px) to do that, if that's what you want:

.items {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  position: absolute;
  top: 6%;
  left: 15%;
  width: 70%;
  background-color: gold;
}

.data {
  width: 100%;
  height: 2em;
  background-color: #187bcd;
  border-top: 2px solid #000000;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="items">
  <div class="data">

  </div>
  <div class="data">

  </div>
  <div class="data">

  </div>
  <div class="data">

  </div>
    <div class="data">

  </div>
  <div class="data">

  </div>
  <div class="data">

  </div>
  <div class="data">

  </div>
</div></code>```

Body:
You can apply a non-parentally-relative length unit (like em and px) to do that, if that's what you want:

.items {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  position: absolute;
  top: 6%;
  left: 15%;
  width: 70%;
  background-color: gold;
}

.data {
  width: 100%;
  height: 2em;
  background-color: #187bcd;
  border-top: 2px solid #000000;
}

<div class="items">
  <div class="data">

  </div>
  <div class="data">

  </div>
  <div class="data">

  </div>
  <div class="data">

  </div>
    <div class="data">

  </div>
  <div class="data">

  </div>
  <div class="data">

  </div>
  <div class="data">

  </div>
</div>


问:
InstaPy error, can't follow or unfollow users "~user is inaccessible"
I've installed Instapy dependency from https://pypi.org/project/instapy/ and I really enjoyed it.
There are two operations I really can't figure out why it's not working, I've followed the oficial documentation to do it, youtube videos and it isn't working.

Actually the warning message says the user is not acessible, but I don't know why, every user happen this, so I can't unfollow the unfollowers:

```<code>INFO [2022-02-11 20:05:41] [gorilafreela]  Ongoing Unfollow [1/3]: now unfollowing 'b'antonio_fpessoa''...
WARNING [2022-02-11 20:06:35] [gorilafreela]  --> Couldn't unfollow 'antonio_fpessoa'!  ~user is inaccessible
</code>```

The same issue happen if I try to follow someone new, happens the same warning I said before.

```<code>import json
from instapy import InstaPy
from instapy import smart_run
import userData
import util
from selenium import webdriver

# data
userInfo = userData.getUserPassword()

# session
session = InstaPy(username=userInfo['user'], password=userInfo['password'])
session.login()

session.unfollow_users(amount=3,nonFollowers=True,unfollow_after=10,sleep_delay=60)
session.end()
</code>```

Anyone has any ideia how can I fix this problem.

答: A fix can be found in the following link</p>

Body:
I've installed Instapy dependency from https://pypi.org/project/instapy/ and I really enjoyed it.
There are two operations I really can't figure out why it's not working, I've followed the oficial documentation to do it, youtube videos and it isn't working.

Actually the warning message says the user is not acessible, but I don't know why, every user happen this, so I can't unfollow the unfollowers:

INFO [2022-02-11 20:05:41] [gorilafreela]  Ongoing Unfollow [1/3]: now unfollowing 'b'antonio_fpessoa''...
WARNING [2022-02-11 20:06:35] [gorilafreela]  --> Couldn't unfollow 'antonio_fpessoa'!  ~user is inaccessible

The same issue happen if I try to follow someone new, happens the same warning I said before.

import json
from instapy import InstaPy
from instapy import smart_run
import userData
import util
from selenium import webdriver

# data
userInfo = userData.getUserPassword()

# session
session = InstaPy(username=userInfo['user'], password=userInfo['password'])
session.login()

session.unfollow_users(amount=3,nonFollowers=True,unfollow_after=10,sleep_delay=60)
session.end()

Anyone has any ideia how can I fix this problem.


答: min-height: (less than or equals the height of the child element)</p>

Title: Increase parent div height when more child is added

Body:
I have a parent div with multiple child divs. Currently, the child divs are spaced around the parent div in order to fit the parent div equally and it works fine but what I'm trying to achieve is when more child divs are added the parent divs height increases in size but the child divs height stays the same. How can I achieve this? What it currently does when you add more child divs is the parent height stays the same but the child divs height will get shorter in order to fit the parent div but what I want is the other way around. When more child div is added I want the parent div to increase in height kinda like the parent div having a height of auto. How can I achieve this? Any help is appreciated. Thanks in advance.

.items {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  position: absolute;
  top: 6%;
  left: 15%;
  width: 70%;
  height: 60%;
  background-color: gold;
}

.data {
  width: 100%;
  height: 35%;
  background-color: #187bcd;
  border-top: 2px solid #000000;
}


问:
How can I install the VS2017 version of msbuild on a build server without installing the IDE?
Historically, this has been done with the Microsoft Build Tools. But it seems that the Build Tools may not be available for versions after 2015. The replacement appears to be the Visual Studio build tools, which doesn't seem to have a real homepage yet.

I downloaded the VS2017 Professional installer, and went to the Individual Components tab. Right away, the summary is telling me that the Visual Studio core editor is there, taking up 753MB. I don't want the editor. Just msbuild. There is no way to unselect the editor.

Is there a way I can install the latest version of msbuild without also installing the Visual Studio IDE?

答:
For MsBuild 17, which is part of VS2022, you need to download the Build tools for VS2022 here (which is actually just the installer):

https://aka.ms/vs/17/release/vs_BuildTools.exe

(This link can be found by going to https://visualstudio.microsoft.com/downloads and scrolling all the way down to "Build Tools for Visual Studio 2022".)

Once downloaded you can install by typing:

```<code>vs_buildtools.exe --add Microsoft.VisualStudio.Workload.MSBuildTools --quiet --wait
</code>```

Depending on your needs you might also need to specify --includeRecommended and possibly --includeOptional.

If you are doing web development you probably also want to add --add Microsoft.VisualStudio.Workload.WebBuildTools.

Input parameters and return codes are available here:

https://learn.microsoft.com/en-us/visualstudio/install/use-command-line-parameters-to-install-visual-studio?view=vs-2022

Body:
For MsBuild 17, which is part of VS2022, you need to download the Build tools for VS2022 here (which is actually just the installer):

https://aka.ms/vs/17/release/vs_BuildTools.exe

(This link can be found by going to https://visualstudio.microsoft.com/downloads and scrolling all the way down to "Build Tools for Visual Studio 2022".)

Once downloaded you can install by typing:

vs_buildtools.exe --add Microsoft.VisualStudio.Workload.MSBuildTools --quiet --wait

Depending on your needs you might also need to specify --includeRecommended and possibly --includeOptional.

If you are doing web development you probably also want to add --add Microsoft.VisualStudio.Workload.WebBuildTools.

Input parameters and return codes are available here:

https://learn.microsoft.com/en-us/visualstudio/install/use-command-line-parameters-to-install-visual-studio?view=vs-2022


问:
Need for try catch within a constructor
The link http://gotw.ca/gotw/066.htm states that

Moral #1: Constructor function-try-block handlers have only one purpose -- to translate an exception. (And maybe to do logging or some other side effects.) They are not useful for any other purpose.

While http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.8

If a constructor throws an exception, the object's destructor is not run. If your object has already done something that needs to be undone (such as allocating some memory, opening a file, or locking a semaphore), this "stuff that needs to be undone" must be remembered by a data member inside the object.

Are these 2 statements not contradictory?  The first one kind of implies that the try catch within a constructor is pretty much useless while the second says that it is needed to free resources.  What am i missing here?

答:
Are these 2 statements not contradictory?

No. The second one basically means if the constructor throws an exception which comes out of it (i.e the constructor), then the destructor doesn't get called. And the first one means that function-try-block doesn't let the exception come out of the constructor. It catches it inside the constructor itself, and handles it right there.

Title: Need for try catch within a constructor


问:
How to XOR two strings using Python?
If I have:

```<code>cipher_text1 =  "3b101c091d53320c000910"
cipher_text2 = "071d154502010a04000419"
</code>```

How do I XOR the two cipher texts using Python to get:

```<code>cipher_text1_XOR_cipher_text2 = "3c0d094c1f523808000d09"
</code>```

Thanks

答:
Try this out:

```<code>cipher_text1 = "3b101c091d53320c000910"
cipher_text2 = "071d154502010a04000419"

def xor_ciphers(cipher1, cipher2):
    bin1 = int(format(int(cipher1, 16), f'0{str(len(cipher1))}b'), 2)
    bin2 = int(format(int(cipher2, 16), f'0{str(len(cipher2))}b'), 2)
    return hex(bin1 ^ bin2)

print(xor_ciphers(cipher_text1, cipher_text2))
</code>```

Output:

```<code>0x3c0d094c1f523808000d09
</code>```

Title: How to XOR two strings using Python?

Body:
If I have:

cipher_text1 =  "3b101c091d53320c000910"
cipher_text2 = "071d154502010a04000419"

How do I XOR the two cipher texts using Python to get:

cipher_text1_XOR_cipher_text2 = "3c0d094c1f523808000d09"

Thanks

Body:
Try this out:

cipher_text1 = "3b101c091d53320c000910"
cipher_text2 = "071d154502010a04000419"

def xor_ciphers(cipher1, cipher2):
    bin1 = int(format(int(cipher1, 16), f'0{str(len(cipher1))}b'), 2)
    bin2 = int(format(int(cipher2, 16), f'0{str(len(cipher2))}b'), 2)
    return hex(bin1 ^ bin2)

print(xor_ciphers(cipher_text1, cipher_text2))

Output:

0x3c0d094c1f523808000d09


问:
Check balance of ERC20 token in Hardhat using Ethers.js
I'm writing unit tests using Hardhat's mainnet fork, and for a test I want to check the owner account's initial balance of an ERC20 token, in particular DAI. Here's my test so far:

const { ethers } = require("hardhat");

describe("Simple Test", function () {
    it("Check balance of DAI", async function () {
        const provider = ethers.provider;
        const [owner] = await ethers.getSigners();

        // Want to get initial DAI balance here so it can be compared later
    });
});
```

What's a simple way to do this?

答:
Found what I was looking for. First thing I did was save the DAI contract address at the top:

```<code>const DAI_ADDRESS = "0x6b175474e89094c44da98b954eedeac495271d0f";
</code>```

Then I had to use the ERC20 token ABI, which I placed in the same folder as my test:

```<code>const ERC20ABI = require('./ERC20.json');
</code>```

Then to get the owner account's DAI balance I just called balanceOf() from the DAI contract:

```<code>const DAI = new ethers.Contract(DAI_ADDRESS, ERC20ABI, provider);
DAIBalance = await DAI.balanceOf(owner.address);
</code>```

This should work for any ERC20 token as well.

Body:
I'm writing unit tests using Hardhat's mainnet fork, and for a test I want to check the owner account's initial balance of an ERC20 token, in particular DAI. Here's my test so far:

const { ethers } = require("hardhat");

describe("Simple Test", function () {
    it("Check balance of DAI", async function () {
        const provider = ethers.provider;
        const [owner] = await ethers.getSigners();

        // Want to get initial DAI balance here so it can be compared later
    });
});

What's a simple way to do this?

Body:
Found what I was looking for. First thing I did was save the DAI contract address at the top:

const DAI_ADDRESS = "0x6b175474e89094c44da98b954eedeac495271d0f";

Then I had to use the ERC20 token ABI, which I placed in the same folder as my test:

const ERC20ABI = require('./ERC20.json');

Then to get the owner account's DAI balance I just called balanceOf() from the DAI contract:

const DAI = new ethers.Contract(DAI_ADDRESS, ERC20ABI, provider);
DAIBalance = await DAI.balanceOf(owner.address);

This should work for any ERC20 token as well.


问:
Google reCAPTCHA: how to generate captcha token on the server side
I've added the Google reCAPTCHA enterprise to my auth endpoints, and now I want to cover them by integration tests. To do so, I need to generate a valid token and pass it to requests. But I can't find in the docs how to do that, they only offer to create a separate reCAPTCHA key for testing environment which is not suitable for me, because I want to test production too.</p>

答: I am not sure if I understood you, but I utilized test keys for testing Recaptcha using Cypress , here you can find them and more information about what you want</p>


问:
No qualifying bean of type 'springfox.documentation.schema.property.ModelPropertiesProvider' after obfuscation with proguard
My Swagger config works fine normally, but when I use proguard to obfuscate the code, I get the error

```<code>No qualifying bean of type 'springfox.documentation.schema.property.ModelPropertiesProvider'
</code>```

If I comment @Configuration, the spring boot project starts but swagger documentation doesn't work and I get another error

```<code>Unable to infer base url. This is common when using dynamic servlet registration or when the API is behind an API Gateway. The base url is the root of where all the swagger resources are served
</code>```

Here is my swagger config class

```<code>import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
@Profile("swagger")
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.any())
            .paths(PathSelectors.any())
            .build()
            .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
            .title("Spring REST TSU service with Swagger")
            .description("Spring REST TSU service with Swagger")
            .termsOfServiceUrl("...")
            .contact(new Contact("Test name", "", "test@asdf.com"))
            .version("1.0")
            .build();
    }

}
</code>```

答:
Solved for me! Override the method buildDefaultBeanName in class AnnotationBeanNameGenerator. eg.

```<code>@ServletComponentScan
@SpringBootApplication
public class WebApplication {

public static void run() {
    new SpringApplicationBuilder(WebApplication.class)
            .beanNameGenerator(new ProGuardBeanNameGenerator()).run();
}

static class ProGuardBeanNameGenerator extends AnnotationBeanNameGenerator {
    @Override
    protected String buildDefaultBeanName(BeanDefinition definition) {
        return definition.getBeanClassName();
    }
}
</code>```

}

Body:
My Swagger config works fine normally, but when I use proguard to obfuscate the code, I get the error

No qualifying bean of type 'springfox.documentation.schema.property.ModelPropertiesProvider'

If I comment @Configuration, the spring boot project starts but swagger documentation doesn't work and I get another error

Unable to infer base url. This is common when using dynamic servlet registration or when the API is behind an API Gateway. The base url is the root of where all the swagger resources are served

Here is my swagger config class

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
@Profile("swagger")
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.any())
            .paths(PathSelectors.any())
            .build()
            .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
            .title("Spring REST TSU service with Swagger")
            .description("Spring REST TSU service with Swagger")
            .termsOfServiceUrl("...")
            .contact(new Contact("Test name", "", "test@asdf.com"))
            .version("1.0")
            .build();
    }

}

Body:
Solved for me! Override the method buildDefaultBeanName in class AnnotationBeanNameGenerator. eg.

@ServletComponentScan
@SpringBootApplication
public class WebApplication {

public static void run() {
    new SpringApplicationBuilder(WebApplication.class)
            .beanNameGenerator(new ProGuardBeanNameGenerator()).run();
}

static class ProGuardBeanNameGenerator extends AnnotationBeanNameGenerator {
    @Override
    protected String buildDefaultBeanName(BeanDefinition definition) {
        return definition.getBeanClassName();
    }
}

}


问:
PHP equivalent of javascript JSON.stringify()
As I notice PHP's json_encode($array) mess things up on diacritics.
If I update my database column type text with javascript-created JSON passed over HTTP, everything looks good. but when I create the JSON into PHP, some characters get encoded weirdly.

I have this array;

```<code>$array = ['M-am întîlnit ieri cu','fosta mea profă de matematică'];

$text = implode(",",$array); // this looks good in db
$json = json_encode($array); // this don't and returns error when try to decode later.
</code>```

答:
First off, it's worth pointing out that PHP is not "messing up" anything. It's escaping characters, which may look weird, but it is perfectly valid and when you json_decode it later it will be just the same as it was originally. See here: https://3v4l.org/Smj2F

If you don't like the escaping though, you can use the JSON_UNESCAPED_UNICODE flag:

https://www.php.net/function.json-encode

This flag will "encode multibyte Unicode characters literally" according to https://www.php.net/manual/en/json.constants.php.

So you can do:

```<code>json_encode($array, JSON_UNESCAPED_UNICODE);
</code>```

And it will give you the following output:

```<code>["M-am întîlnit ieri cu","fosta mea profă de matematică"]
</code>```

Working example: https://3v4l.org/daETG

Body:
As I notice PHP's json_encode($array) mess things up on diacritics.
If I update my database column type text with javascript-created JSON passed over HTTP, everything looks good. but when I create the JSON into PHP, some characters get encoded weirdly.

I have this array;

$array = ['M-am întîlnit ieri cu','fosta mea profă de matematică'];

$text = implode(",",$array); // this looks good in db
$json = json_encode($array); // this don't and returns error when try to decode later.

Body:
First off, it's worth pointing out that PHP is not "messing up" anything. It's escaping characters, which may look weird, but it is perfectly valid and when you json_decode it later it will be just the same as it was originally. See here: https://3v4l.org/Smj2F

If you don't like the escaping though, you can use the JSON_UNESCAPED_UNICODE flag:

https://www.php.net/function.json-encode

This flag will "encode multibyte Unicode characters literally" according to https://www.php.net/manual/en/json.constants.php.

So you can do:

json_encode($array, JSON_UNESCAPED_UNICODE);

And it will give you the following output:

["M-am întîlnit ieri cu","fosta mea profă de matematică"]

Working example: https://3v4l.org/daETG


问:
GCP - How to update api specification in API Gateway
I have created an API Gateway and created an API config as well associated with it which lists a set of APIs. Now I want to add/modify a set of APIs. How do I update the same API config of this gateway?</p>

答:
Referencing the official documentation, it states that:

NOTE: Only the name and labels may be updated on an API config.

Therefore, you would need to create a new API config if you want to add/modify a set of APIs.


问:
Navigation Title is not showing on SwiftUI
The navigationTitle is not working.
I use Swift5.5.2
In the preview there is no sign of the navigation title just an empty space.

```<code>
struct ContentView: View {

    @State private var firstname = ""
    @State private var lastname = ""
    @State private var birthdate = Date()
    @State private var shouldSendNewsletter = false

    var body: some View {
        NavigationView {
            Form {
                Section(header: Text("Personal Information")) {
                    TextField("First Name", text: $firstname)
                    TextField("Last Name", text: $lastname)
                    DatePicker("Birth Date", selection: $birthdate, displayedComponents: .date)

                    Section(header: Text("Actions")) {
                        Toggle("Send Newsletter", isOn: $shouldSendNewsletter)
                    }//:Actions

                }
            }//:Form
        }//: NAVIGATION VIEW
        .navigationTitle("ABC")
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
</code>```

Preview of navigation title

答:
.navigationTitle("ABC") should be attached to the topmost view inside your NavigationView:

```<code>NavigationView {
    Form {
        Section(header: Text("Personal Information")) {
            TextField("First Name", text: $firstname)
            TextField("Last Name", text: $lastname)
            DatePicker("Birth Date", selection: $birthdate, displayedComponents: .date)

            Section(header: Text("Actions")) {
                Toggle("Send Newsletter", isOn: $shouldSendNewsletter)
            } //: Actions
        }
    } //: Form
    .navigationTitle("ABC") /// <- here!
} //: NAVIGATION VIEW
</code>```

Body:
The navigationTitle is not working.
I use Swift5.5.2
In the preview there is no sign of the navigation title just an empty space.

struct ContentView: View {

    @State private var firstname = ""
    @State private var lastname = ""
    @State private var birthdate = Date()
    @State private var shouldSendNewsletter = false

    var body: some View {
        NavigationView {
            Form {
                Section(header: Text("Personal Information")) {
                    TextField("First Name", text: $firstname)
                    TextField("Last Name", text: $lastname)
                    DatePicker("Birth Date", selection: $birthdate, displayedComponents: .date)

                    Section(header: Text("Actions")) {
                        Toggle("Send Newsletter", isOn: $shouldSendNewsletter)
                    }//:Actions

                }
            }//:Form
        }//: NAVIGATION VIEW
        .navigationTitle("ABC")
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Preview of navigation title

Body:
.navigationTitle("ABC") should be attached to the topmost view inside your NavigationView:

NavigationView {
    Form {
        Section(header: Text("Personal Information")) {
            TextField("First Name", text: $firstname)
            TextField("Last Name", text: $lastname)
            DatePicker("Birth Date", selection: $birthdate, displayedComponents: .date)

            Section(header: Text("Actions")) {
                Toggle("Send Newsletter", isOn: $shouldSendNewsletter)
            } //: Actions
        }
    } //: Form
    .navigationTitle("ABC") /// <- here!
} //: NAVIGATION VIEW


问:
React native failed to launch emulator
While trying to test the android app am creating with React native, I run into this error

info Launching emulator...
error Failed to launch emulator. Reason: No emulators found as an output of `emulator -list-avds`.
warn Please launch an emulator manually or connect a device. Otherwise app may fail to launch.
```

I have the emulator(the AMD version) installed in the android studio.

How can I solve this problem

答: This also may be there is not enough space to run avd, make sure enoug space in hard disk. in my case  freed atlest 9gb.</p>

Title: React native failed to launch emulator

Body:
While trying to test the android app am creating with React native, I run into this error

info Launching emulator...
error Failed to launch emulator. Reason: No emulators found as an output of `emulator -list-avds`.
warn Please launch an emulator manually or connect a device. Otherwise app may fail to launch.

I have the emulator(the AMD version) installed in the android studio.

How can I solve this problem


问:
Configure eslint to read common types in src/types/types.d.ts vue3
My eslint .eslintrc.js, now properly in the src folder, is the following:

```<code>module.exports = {
  env: {
    browser: true,
    commonjs: true,
    es2021: true
  },
  extends: [
    'plugin:vue/vue3-recommended',
    'standard',
    'prettier'
  ],
  parserOptions: {
    ecmaVersion: 2020,
    parser: '@typescript-eslint/parser',
    'ecmaFeatures': {
      'jsx': true
    }
  },
  plugins: [
    'vue',
    '@typescript-eslint'
  ],
  rules: {
    'import/no-unresolved': 'error'
  },
  settings: {
    'import/parsers': {
      '@typescript-eslint/parser': ['.ts', '.tsx']
    },
    'import/resolver': {
      'typescript': {
        'alwaysTryTypes': true,
      }
    }
  }
}
</code>```

I'm attempting to use eslint-import-resolver-typescript, but the documentation is a bit opaque.

I currently get errors on lines where a externally defined type is used (StepData in this example):

```<code>setup() {
   const data = inject("StepData") as StepData;
   return {
     data,
   };
},
</code>```

答:
The answer was the following. In types.d.ts (or other file if you want to have different collections of your custom types):

```<code>export interface MyType {
  positioner: DOMRect;
  content: DOMRect;
  arrow: DOMRect;
  window: DOMRect;
}

export interface SomeOtherType {
.. and so on
</code>```

Then in the .vue files, import the types I need for the component:

```<code>import type { MyType, SomeOtherType } from "../types/types";
</code>```

Before I was not using the export keyword and the types just worked without being imported. They have to be imported like this if you use export. It's kind of amazing how you are just expected to know this, the documentation for Typescript or Vue is sorely lacking in examples.

Body:
My eslint .eslintrc.js, now properly in the src folder, is the following:

module.exports = {
  env: {
    browser: true,
    commonjs: true,
    es2021: true
  },
  extends: [
    'plugin:vue/vue3-recommended',
    'standard',
    'prettier'
  ],
  parserOptions: {
    ecmaVersion: 2020,
    parser: '@typescript-eslint/parser',
    'ecmaFeatures': {
      'jsx': true
    }
  },
  plugins: [
    'vue',
    '@typescript-eslint'
  ],
  rules: {
    'import/no-unresolved': 'error'
  },
  settings: {
    'import/parsers': {
      '@typescript-eslint/parser': ['.ts', '.tsx']
    },
    'import/resolver': {
      'typescript': {
        'alwaysTryTypes': true,
      }
    }
  }
}

I'm attempting to use eslint-import-resolver-typescript, but the documentation is a bit opaque.

I currently get errors on lines where a externally defined type is used (StepData in this example):

setup() {
   const data = inject("StepData") as StepData;
   return {
     data,
   };
},

Body:
The answer was the following. In types.d.ts (or other file if you want to have different collections of your custom types):

export interface MyType {
  positioner: DOMRect;
  content: DOMRect;
  arrow: DOMRect;
  window: DOMRect;
}

export interface SomeOtherType {
.. and so on

Then in the .vue files, import the types I need for the component:

import type { MyType, SomeOtherType } from "../types/types";

Before I was not using the export keyword and the types just worked without being imported. They have to be imported like this if you use export. It's kind of amazing how you are just expected to know this, the documentation for Typescript or Vue is sorely lacking in examples.


问:
An error from compiling the psych engine!!! WELP
Error: source/Achievements.hx:126: characters 30-54 : Warning : FlxCamera.defaultCameras is deprecated, use FlxG.cameras.setDefaultDrawTarget instead
source/MainMenuState.hx:73: characters 3-39 : Warning : FlxCamera.defaultCameras is deprecated, use FlxG.cameras.setDefaultDrawTarget instead
source/PlayState.hx:341: characters 3-39 : Warning : FlxCamera.defaultCameras is deprecated, use FlxG.cameras.setDefaultDrawTarget instead
source/editors/CharacterEditorState.hx:93: characters 3-41 : Warning : FlxCamera.defaultCameras is deprecated, use FlxG.cameras.setDefaultDrawTarget instead
source/editors/DialogueCharacterEditorState.hx:81: characters 3-40 : Warning : FlxCamera.defaultCameras is deprecated, use FlxG.cameras.setDefaultDrawTarget instead
C:/HaxeToolkit/haxe/lib/hscript/2,4,0/hscript/Interp.hx:145: characters 8-18 : Warning : Std.is is deprecated. Use Std.isOfType instead.
C:/HaxeToolkit/haxe/lib/hscript/2,4,0/hscript/Interp.hx:180: characters 8-18 : Warning : Std.is is deprecated. Use Std.isOfType instead.
C:/HaxeToolkit/haxe/lib/hscript/2,4,0/hscript/Interp.hx:221: characters 8-18 : Warning : Std.is is deprecated. Use Std.isOfType instead.
C:/HaxeToolkit/haxe/lib/hscript/2,4,0/hscript/Interp.hx:515: characters 8-18 : Warning : Std.is is deprecated. Use Std.isOfType instead.
C:/HaxeToolkit/haxe/lib/hscript/2,4,0/hscript/Interp.hx:483: characters 37-56 : Warning : Std.is is deprecated. Use Std.isOfType instead.
C:/HaxeToolkit/haxe/lib/hscript/2,4,0/hscript/Interp.hx:484: characters 31-47 : Warning : Std.is is deprecated. Use Std.isOfType instead.
C:/HaxeToolkit/haxe/lib/hscript/2,4,0/hscript/Interp.hx:646: characters 10-42 : Warning : Std.is is deprecated. Use Std.isOfType instead.

答: Those are not errors, they're warnings. They don't cause any problems. You can safely ignore them.</p>


问:
Can a list of strings be supplied to Capistrano tasks?
I have a task whose command in 'run' is the same except for a single value. This value would out of a list of potential values. What I would like to do is create a task which would use this list of values to define the task and then use that same value in the command defined in 'run'. The point is that it would be great to define the task in such a way where I don't have to repeat nearly identical task definitions for each value.

For example: I want a task that will get the status of a single program from a list of programs that I have defined in an array. I would like to define task to be something like this:

```<code>set programs = %w["postfix", "nginx", "pgpool"]
programs.each do |program|
  desc "#{program} status"
  task :#{program} do
    run "/etc/init.d/#{program} status"
  end
end
</code>```

This obviously doesn't work, but hopefully it shows what I am attempting here.

Thoughts?

答:
Well, I answered my own question... with a little trial and error. I also did the same thing with namespace so the control of services is nice and elegant. It works quite nicely!</p>

```<code>set :programs, %w[postfix nginx pgpool]
set :init_commands, %w[status start stop]

# init.d service control
init_commands.each do |init_command|
  namespace :"#{init_command}" do
    programs.each do |program|
      desc "#{program} #{init_command}"
      task :"#{program}" do
        run "/etc/init.d/#{program} #{init_command}"
      end
    end
  end
end
</code>```

Body:
I have a task whose command in 'run' is the same except for a single value. This value would out of a list of potential values. What I would like to do is create a task which would use this list of values to define the task and then use that same value in the command defined in 'run'. The point is that it would be great to define the task in such a way where I don't have to repeat nearly identical task definitions for each value.

For example: I want a task that will get the status of a single program from a list of programs that I have defined in an array. I would like to define task to be something like this:

set programs = %w["postfix", "nginx", "pgpool"]
programs.each do |program|
  desc "#{program} status"
  task :#{program} do
    run "/etc/init.d/#{program} status"
  end
end

This obviously doesn't work, but hopefully it shows what I am attempting here.

Thoughts?

Body:
Well, I answered my own question... with a little trial and error. I also did the same thing with namespace so the control of services is nice and elegant. It works quite nicely!

set :programs, %w[postfix nginx pgpool]
set :init_commands, %w[status start stop]

# init.d service control
init_commands.each do |init_command|
  namespace :"#{init_command}" do
    programs.each do |program|
      desc "#{program} #{init_command}"
      task :"#{program}" do
        run "/etc/init.d/#{program} #{init_command}"
      end
    end
  end
end


问:
python how to generate permutations of putting a singular character into a word
No idea how to word this so the title sucks my bad,

Basically, I have a 4 letter word and I want to generate every permutation of putting a dash in it.

So if my word was Cats, I want to get every permutation of it having a dash in it,

Example:

```<code>c-ats
ca-ts
-c-ats
etc,
</code>```

Is anybody able to help me?

答:
```<code>word = input("Enter the word: ")

def insert_into_str(s, index, in_str):
    arr = list(s)
    arr.insert(index, in_str)
    return "".join(arr)

permutations = []

for i in range(len(word)+1):
    permutations.append(insert_into_str(word, i, "-"))

print(permutations)

>>> Enter the word: cats
>>> ['-cats', 'c-ats', 'ca-ts', 'cat-s', 'cats-']
</code>```

Body:
No idea how to word this so the title sucks my bad,

Basically, I have a 4 letter word and I want to generate every permutation of putting a dash in it.

So if my word was Cats, I want to get every permutation of it having a dash in it,

Example:

c-ats
ca-ts
-c-ats
etc,

Is anybody able to help me?


问:
How can I restore a MySQL Docker container that has crashed
After updating, my WordPress stopped connecting to the MySQL DB on docker.

So as of now, I start Docker, see the following logs:

```<code>2022-02-14 02:28:07+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.28-1debian10 started.

2022-02-14 02:28:07+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'

2022-02-14 02:28:07+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.28-1debian10 started.

2022-02-14T02:28:08.102455Z 0 [Warning] [MY-010918] [Server] 'default_authentication_plugin' is deprecated and will be removed in a future release. Please use authentication_policy instead.

2022-02-14T02:28:08.102491Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.28) starting as process 1

2022-02-14T02:28:08.144825Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.

2022-02-14T02:28:08.625666Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.

2022-02-14T02:28:58.896407Z 1 [ERROR] [MY-013178] [Server] Execution of server-side SQL statement 'DROP SCHEMA IF EXISTS dd_upgrade_garbage_80028' failed with error code = 3664, error message = 'Failed to delete SDI 'dd_upgrade_garbage_80028.columns' in tablespace 'mysql'.'.

2022-02-14T02:28:58.905477Z 0 [ERROR] [MY-010020] [Server] Data Dictionary initialization failed.

2022-02-14T02:28:58.905864Z 0 [ERROR] [MY-010119] [Server] Aborting

2022-02-14T02:28:59.332262Z 0 [System] [MY-010910] [Server] /usr/sbin/mysqld: Shutdown complete (mysqld 8.0.28)  MySQL Community Server - GPL.
</code>```

Now as its a docker with a volume attached to /var/lib/mysql

I have all the data files, but as the server keeps on restarting, I have a very small window to run any commands on docker.

答:
This problem may occur if the MySQL container stops abnormally

First, make a backup of the data directory of MySQL container

You can try to upgrade the MySQL container version. Can you fix this problem

Body:
After updating, my WordPress stopped connecting to the MySQL DB on docker.

So as of now, I start Docker, see the following logs:

2022-02-14 02:28:07+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.28-1debian10 started.

2022-02-14 02:28:07+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'

2022-02-14 02:28:07+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.28-1debian10 started.

2022-02-14T02:28:08.102455Z 0 [Warning] [MY-010918] [Server] 'default_authentication_plugin' is deprecated and will be removed in a future release. Please use authentication_policy instead.

2022-02-14T02:28:08.102491Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.28) starting as process 1

2022-02-14T02:28:08.144825Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.

2022-02-14T02:28:08.625666Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.

2022-02-14T02:28:58.896407Z 1 [ERROR] [MY-013178] [Server] Execution of server-side SQL statement 'DROP SCHEMA IF EXISTS dd_upgrade_garbage_80028' failed with error code = 3664, error message = 'Failed to delete SDI 'dd_upgrade_garbage_80028.columns' in tablespace 'mysql'.'.

2022-02-14T02:28:58.905477Z 0 [ERROR] [MY-010020] [Server] Data Dictionary initialization failed.

2022-02-14T02:28:58.905864Z 0 [ERROR] [MY-010119] [Server] Aborting

2022-02-14T02:28:59.332262Z 0 [System] [MY-010910] [Server] /usr/sbin/mysqld: Shutdown complete (mysqld 8.0.28)  MySQL Community Server - GPL.

Now as its a docker with a volume attached to /var/lib/mysql

I have all the data files, but as the server keeps on restarting, I have a very small window to run any commands on docker.


问:
Invalid date format issue in Generic Inquiry in Acumatica mobile
I created a Generic Inquiry and Exposed to the Mobile Application. However, I keep getting "String was not recognized as a valid DateTime." whenever I open up Filter in mobile app but it works smoothly in web.

Parameters:

Conditions

My Appointments screen in Mobile

Error in Mobile App when go to Filters:

I checked parameters and conditions with other existing GIs and looks similar to me.

答: In your paramter StartDate... try @Today-1  That will get you yesterday's date</p>


问:
How to use this for 'if' statement in jinja2 template
I'm trying to write an if statement in a Jinja2 template:

```<code>let temp_html = `<div class="card">
    <div class="card-body">
        <blockquote class="blockquote mb-0">
            <p>${comment}</p>
            <footer class="blockquote-footer">${name}</footer>
            {% if session['user_id'] == ? %}
            <div class="modify">modify</div>
            {% endif %}
        </blockquote>
    </div>
</div>`
</code>```

=> in the ajax

I want to compare ${name} to session['user_id'] using the {% if ~ %} as I wrote.

How can I write ${name} in the 'if' statement within the Jinja2 template?

答: session['user_id'] ? 'if true' : 'if false'```

Body:
I'm trying to write an if statement in a Jinja2 template:

let temp_html = `

${comment}

            ${name}
            {% if session['user_id'] == ? %}

modify

            {% endif %}

`

=> in the ajax

I want to compare ${name} to session['user_id'] using the {% if ~ %} as I wrote.

How can I write ${name} in the 'if' statement within the Jinja2 template?


问:
How to inspect positional-only parameters?
How can I know if a parameter is positional-only or not? To be more specific, I just want a function to tell me a is a positional-only parameter, while b is not, as in the following example.

from inspect import getfullargspec
from typing import get_type_hints

def add(a: int, /, b: int):
    raise NotImplementedError

print(get_type_hints(add))
# {'b': <class 'int'>, 'a': <class 'int'>}

print(getfullargspec(add))
# FullArgSpec(args=['a', 'b'], varargs=None, varkw=None, defaults=None, kwonlyargs=[], kwonlydefaults=None, annotations={'a': <class 'int'>, 'b': <class 'int'>})
```

I have tried get_type_hints and getfullargspec, but seems none of them return relevant information.

答:
You can inspect the signature via the following, which I based on a similar example in the docs:

```<code>import inspect
signature = inspect.signature(add)
positional_only_args = [param
                        for param in signature.parameters.values()
                        if param.kind == param.POSITIONAL_ONLY]
# [<Parameter "a: int">]
</code>```

If you want strictly the name of the parameter, then you can use param.name.

Body:
How can I know if a parameter is positional-only or not? To be more specific, I just want a function to tell me a is a positional-only parameter, while b is not, as in the following example.

from inspect import getfullargspec
from typing import get_type_hints

def add(a: int, /, b: int):
    raise NotImplementedError

print(get_type_hints(add))
# {'b': <class 'int'>, 'a': <class 'int'>}

print(getfullargspec(add))
# FullArgSpec(args=['a', 'b'], varargs=None, varkw=None, defaults=None, kwonlyargs=[], kwonlydefaults=None, annotations={'a': <class 'int'>, 'b': <class 'int'>})

I have tried get_type_hints and getfullargspec, but seems none of them return relevant information.

Body:
You can inspect the signature via the following, which I based on a similar example in the docs:

import inspect
signature = inspect.signature(add)
positional_only_args = [param
                        for param in signature.parameters.values()
                        if param.kind == param.POSITIONAL_ONLY]
# [<Parameter "a: int">]

If you want strictly the name of the parameter, then you can use param.name.


问:
Copy & paste folded text in Visual Studio Code
Given the following text

```<code>Node1_L1
  Node1_L2
  Node2_L2
Node2_L1
  Node3_L2
    Node1_L3
    Node2_L3
  Node4_L2
    Node3_L3
    Node4_L3
Node3_L1
  Node5_L2
  Node6_L2
</code>```

I can use vscode's built-in folding feature to fold it to look like so

```<code>+ Node1_L1
  Node2_L1
+   Node3_L2
+   Node4_L2
  Node3_L1
    Node5_L2
    Node6_L2
</code>```

but when I now select the folded text and copy & paste it then it actually grabbed all text - also the hidden one. The result of copy & paste of the first 4 lines of the folded text above would therefore be

```<code>Node1_L1
  Node1_L2
  Node2_L2
Node2_L1
  Node3_L2
    Node1_L3
    Node2_L3
  Node4_L2
</code>```

whereas I would like to have

```<code>Node1_L1
Node2_L1
  Node3_L2
  Node4_L2
</code>```

Hope that makes sense and someone knows a way to do it. Thanks!

答:
If the selection doesn't include the new line and carriage return, folded content will not be copied.

The selection must go to the start of the next line to select the folded text ( hidden text )

https://github.com/Microsoft/vscode/issues/41922#issuecomment-359368290

The op actually wants to select 'unfolded' text ignoring the folded text so they need to use a multi-line select where each selection will span a single line

Body:
Given the following text

Node1_L1
  Node1_L2
  Node2_L2
Node2_L1
  Node3_L2
    Node1_L3
    Node2_L3
  Node4_L2
    Node3_L3
    Node4_L3
Node3_L1
  Node5_L2
  Node6_L2

I can use vscode's built-in folding feature to fold it to look like so

+ Node1_L1
  Node2_L1
+   Node3_L2
+   Node4_L2
  Node3_L1
    Node5_L2
    Node6_L2

but when I now select the folded text and copy & paste it then it actually grabbed all text - also the hidden one. The result of copy & paste of the first 4 lines of the folded text above would therefore be

Node1_L1
  Node1_L2
  Node2_L2
Node2_L1
  Node3_L2
    Node1_L3
    Node2_L3
  Node4_L2

whereas I would like to have

Node1_L1
Node2_L1
  Node3_L2
  Node4_L2

Hope that makes sense and someone knows a way to do it. Thanks!


问:
I have an string and i want to delete from a specific character to the end of the string in JavaScript
i have this string => someRandomText&ab_channel=thisPartCanChange and i want to delete all from & (inclusive) to the end [this part: &ab_channel=thisPartCanChange].

How can i do this?

答:
You van try something like:

console.log("someRandomText&ab_channel=thisPartCanChange".split("&")[0])
```


问:
Avoid deletion of an object (using IObjectWillBeRemovedEvent) and do a redirect to a custom view/template?
I would like to abort the deletion of an object (A custom Content-Type), and redirect to a page (a view) that sets the workflow to a custom state named Unavailable, shows a message to the user "You succesfully deleted the object!". The object will still be on ZODB, but for some groups it'll simply not be seen, as if it was really deleted.

I can do a raise in a subscriber using IObjectWillBeRemovedEvent, but trying to use raise zExceptions.Redirect("url") doesn't work. The raise call avoids the deletion, but a message "The object could not be deleted" is shown instead of the redirection.

Anyone has a solution to this scenario?

答:
As you can see Plone / Zope 2 object management is messy (yes, I am willing to burn karma just to say this). You need to override delete action in the user interface level, not on the object level.

Try to figure out how to customize delete actions in Plone user interface.

Make sure the default Delete actions is no longer visible and available (e.g. set higher needed permission for it e.g. cmf.ManagePortal)

Create another Delete action which goes according to your specialized workflow

I believe Delete can be configured from portal_actions, but there might be separate cases for deleting one object (Actions menu) and deleting multiple objects (folder_contents).


问:
Increase parent div height when more child is added
I have a parent div with multiple child divs. Currently, the child divs are spaced around the parent div in order to fit the parent div equally and it works fine but what I'm trying to achieve is when more child divs are added the parent divs height increases in size but the child divs height stays the same. How can I achieve this? What it currently does when you add more child divs is the parent height stays the same but the child divs height will get shorter in order to fit the parent div but what I want is the other way around. When more child div is added I want the parent div to increase in height kinda like the parent div having a height of auto. How can I achieve this? Any help is appreciated. Thanks in advance.

.items {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  position: absolute;
  top: 6%;
  left: 15%;
  width: 70%;
  height: 60%;
  background-color: gold;
}

.data {
  width: 100%;
  height: 35%;
  background-color: #187bcd;
  border-top: 2px solid #000000;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="items">
  <div class="data">

  </div>
  <div class="data">

  </div>
  <div class="data">

  </div>
  <div class="data">

  </div>
</div></code>```

答:
Just remove the % height from your .items div, then set a fixed height on your child elems.

<button>Add div</button>

```

Body:
Just remove the % height from your .items div, then set a fixed height on your child elems.

<button>Add div</button>
<div class="items">
    <div class="data"></div>
    <div class="data"></div>
</div>

<style>
    .items {
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        align-items: center;
        position: absolute;
        top: 6%;
        left: 15%;
        width: 70%;
        background-color: gold;
    }

    .data {
        width: 100%;
        height: 75px; /* Fixed height here */
        background-color: #187bcd;
        border-top: 2px solid #000000;
    }
</style>

<script>
    const button = document.querySelector('button');
    const div = document.querySelector('div.items');

    button.addEventListener('click', () => {
        const newDiv = document.createElement('div');
        newDiv.className = 'data';
        div.appendChild(newDiv);
    });
</script>


问:
How to correctly pass IconData as and argument to a custom widget
I have a custom wrapper around the TextFormField widget, I want to be able to pass in a material Icon as an argument to the constructor. However, when trying to pass the IconData into the Icon constructor I get an error: Arguments of constant creation must be constant expressions.

```<code>import 'package:flutter/material.dart';

class LoginFormField extends StatelessWidget {
   const LoginFormField({Key? key,
    required this.fillColor,
    required this.textColor,
    required this.borderColor,
    required this.onChanged,
    required this.validateField,
    required this.icon
  }) : super(key: key);

  final Color fillColor;
  final Color textColor;
  final Color borderColor;
  final Function(String) onChanged;
  final FormFieldValidator validateField;
  final IconData icon;

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      decoration: InputDecoration(
        fillColor: fillColor,
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8),
          borderSide: BorderSide(width: 16, color: borderColor)
        ),
        labelText: 'Enter your username',
        prefixIcon: const Padding(
          padding: EdgeInsets.only(top: 15), // add padding to adjust icon
          child: Icon(icon)
        ),
      ),
      validator: validateField,
      onChanged: onChanged,
    );
  }
}
</code>```

Any help on how to correctly pass in an icon as an argument?

答:
You're passing icondata correctly.
The error is telling you the that prefixicon can not be const.

```<code>prefixIcon: const Padding(
  padding: EdgeInsets.only(top: 15), // add padding to adjust icon
  child: Icon(icon)
),
</code>```

Remove the const as icon is argument to your widget which is not const. Make it

```<code>prefixIcon: Padding(
  padding: EdgeInsets.only(top: 15), // add padding to adjust icon
  child: Icon(icon)
),
</code>```

Body:
I have a custom wrapper around the TextFormField widget, I want to be able to pass in a material Icon as an argument to the constructor. However, when trying to pass the IconData into the Icon constructor I get an error: Arguments of constant creation must be constant expressions.

import 'package:flutter/material.dart';

class LoginFormField extends StatelessWidget {
   const LoginFormField({Key? key,
    required this.fillColor,
    required this.textColor,
    required this.borderColor,
    required this.onChanged,
    required this.validateField,
    required this.icon
  }) : super(key: key);

  final Color fillColor;
  final Color textColor;
  final Color borderColor;
  final Function(String) onChanged;
  final FormFieldValidator validateField;
  final IconData icon;

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      decoration: InputDecoration(
        fillColor: fillColor,
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8),
          borderSide: BorderSide(width: 16, color: borderColor)
        ),
        labelText: 'Enter your username',
        prefixIcon: const Padding(
          padding: EdgeInsets.only(top: 15), // add padding to adjust icon
          child: Icon(icon)
        ),
      ),
      validator: validateField,
      onChanged: onChanged,
    );
  }
}

Any help on how to correctly pass in an icon as an argument?

Body:
You're passing icondata correctly.
The error is telling you the that prefixicon can not be const.

prefixIcon: const Padding(
  padding: EdgeInsets.only(top: 15), // add padding to adjust icon
  child: Icon(icon)
),

Remove the const as icon is argument to your widget which is not const. Make it

prefixIcon: Padding(
  padding: EdgeInsets.only(top: 15), // add padding to adjust icon
  child: Icon(icon)
),


问:
how to double array size (error on second time)
Some help here, trying to double the array in cpp

on the second resize I got this (messy output)

```<code>% ./sample
[5] 1 2 3 4 5
[20] 1 2 3 4 0 6 7 -1610612736 1 2 3 4 14 0 0 0 0 -1610612736 0 0
</code>```

the same removing the memset (to zero's the remaining positions)

```<code>#include <iostream>
#include <cstdlib>

using namespace std;

void resize(int* v, int* size){ // double the array size
    int newSize = (*size) * 2;
    v = (int *) realloc(v, (size_t) newSize);
    memset(v+(*size), 0, sizeof(int) * (newSize - *size) );
    *size = newSize;
}

int main(){
    int size = 5;
    int* v = new(nothrow) int[size]();

    v[0] = 1; v[1] = 2; v[2] = 3; v[3] = 4; v[4] = 5;

    cout << "[" << size << "] ";
    for(int i = 0; i < size; i++) cout << v[i] << " "; cout << endl;

    resize(v, &size);
    resize(v, &size);   // <- messy output

    v[5] = 6; v[6] = 7;

    cout << "[" << size << "] ";
    for(int i = 0; i < size; i++) cout << v[i] << " "; cout << endl;

    return 0;
}
</code>```

thanks for the help,

答:
for reference the working version</p>
```<code>#include <iostream>
using namespace std;

void resize(int*& v, int* size){ // double the array size
    int newSize = (*size) * 2;
    int* tmp = new(nothrow) int[newSize]();  // zeroing on the next line is redundant?
    for(int i = 0; i < newSize; i++) tmp[i] = (i < *size) ? v[i] : 0;
    delete[] v;
    v = tmp;
    *size = newSize;
}

int main(){
    int size = 5;
    int* v = new(nothrow) int[size]();

    v[0] = 1; v[1] = 2; v[2] = 3; v[3] = 4; v[4] = 5;

    cout << "[" << size << "] ";
    for(int i = 0; i < size; i++) cout << v[i] << " "; cout << endl;

    resize(v, &size);
    resize(v, &size);   // <- NOW, working output
    //resize(v, &size);

    v[5] = 6; v[6] = 7;

    cout << "[" << size << "] ";
    for(int i = 0; i < size; i++) cout << v[i] << " "; cout << endl;

    return 0;
}
</code>```

Body:
Some help here, trying to double the array in cpp

on the second resize I got this (messy output)

% ./sample
[5] 1 2 3 4 5
[20] 1 2 3 4 0 6 7 -1610612736 1 2 3 4 14 0 0 0 0 -1610612736 0 0

the same removing the memset (to zero's the remaining positions)

#include <iostream>
#include <cstdlib>

using namespace std;

void resize(int* v, int* size){ // double the array size
    int newSize = (*size) * 2;
    v = (int *) realloc(v, (size_t) newSize);
    memset(v+(*size), 0, sizeof(int) * (newSize - *size) );
    *size = newSize;
}

int main(){
    int size = 5;
    int* v = new(nothrow) int[size]();

    v[0] = 1; v[1] = 2; v[2] = 3; v[3] = 4; v[4] = 5;

    cout << "[" << size << "] ";
    for(int i = 0; i < size; i++) cout << v[i] << " "; cout << endl;

    resize(v, &size);
    resize(v, &size);   // <- messy output

    v[5] = 6; v[6] = 7;

    cout << "[" << size << "] ";
    for(int i = 0; i < size; i++) cout << v[i] << " "; cout << endl;

    return 0;
}

thanks for the help,

Body:
for reference the working version

#include <iostream>
using namespace std;

void resize(int*& v, int* size){ // double the array size
    int newSize = (*size) * 2;
    int* tmp = new(nothrow) int[newSize]();  // zeroing on the next line is redundant?
    for(int i = 0; i < newSize; i++) tmp[i] = (i < *size) ? v[i] : 0;
    delete[] v;
    v = tmp;
    *size = newSize;
}

int main(){
    int size = 5;
    int* v = new(nothrow) int[size]();

    v[0] = 1; v[1] = 2; v[2] = 3; v[3] = 4; v[4] = 5;

    cout << "[" << size << "] ";
    for(int i = 0; i < size; i++) cout << v[i] << " "; cout << endl;

    resize(v, &size);
    resize(v, &size);   // <- NOW, working output
    //resize(v, &size);

    v[5] = 6; v[6] = 7;

    cout << "[" << size << "] ";
    for(int i = 0; i < size; i++) cout << v[i] << " "; cout << endl;

    return 0;
}


问:
Xamarin.Android Keeps Stopping
I am new both to MVVM pattern and Xamarin platform.
Im trying to crate a bindable interface by using a view model.
I started with a very simple task: Take the Entry input from the user, and send it to the label text after clicking the button.

ViewModel ---> Commands ---> EntryCommand.cs

```<code>namespace HelloWorld.ViewModel.Commands
{
    public class EntryCommand : ICommand
    {
        public ViewModel VM { get; set; }
        public EntryCommand( ViewModel vm)
        {
            VM = vm;
        }

        public event EventHandler CanExecuteChanged;

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public void Execute(object parameter)
        {
            VM.ChangeLabelText();
        }
    }
}
</code>```

ViewModel.cs

```<code>namespace HelloWorld.ViewModel
{
    public class ViewModel: INotifyPropertyChanged
    {
        public EntryCommand EntryCommand { get; set; }
        public event PropertyChangedEventHandler PropertyChanged;

        public ViewModel()
        {
            EntryCommand = new EntryCommand(this);
        }

        private void OnPropertyChanged(string PropertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
        }

        public string LabelText { get; set; }
        public string Name
        {
            get { return Name; }
            set
            {
                Name = value;
                OnPropertyChanged("Name");
            }
        }
        public void ChangeLabelText()
        {
            if(Name!=null)
            {
                LabelText = Name;
            }
        }

    }
}
</code>```

Bindable Xaml file:

MainPage.xaml

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="HelloWorld.MainPage"
             xmlns:ViewModel="clr-namespace:HelloWorld.ViewModel" x:DataType="ViewModel:ViewModel">

    <ContentPage.Resources>
        <ViewModel:ViewModel x:Key="vm"/>
    </ContentPage.Resources>

    <StackLayout BindingContext="{StaticResource vm}" BackgroundColor="AliceBlue"
                 Margin="15">

        <Label Text="{Binding Name, Mode=TwoWay}"/>
        <Entry Placeholder="Enter Your Name" Text="{Binding Name, Mode=TwoWay}"/>
        <Button Text="Enter" Command="{Binding EntryCommand}"/>

    </StackLayout>

</ContentPage>
</code>```

Now, I don't get any errors but emulator keeps stopping before building the UI:

enter image description here

答:
I think you're using the ViewModel incorrectly.

Depending on your needs,there is no need to create EntryCommand: ICommand.

You can do like this:

```<code>public ICommand EntryCommand => new Command(DoSomething);

public void DoSomething() {

        // do some thing here
    }
</code>```

Besides, the use of Name is also incorrect, you need to create another variable (e.g. private string _name;)

```<code>    private string _name;
    public string Name
    {
        set { SetProperty(ref _name, value); }
        get { return _name; }
    }
</code>```

You can refer to the full sample code here:

```<code>   public class MyViewModel: INotifyPropertyChanged
    {
        public ICommand EntryCommand => new Command(DoSomething);

        public MyViewModel() {
            Name = "abc123";

        }

        public void DoSomething() {

            // do some thing here
        }

        public string LabelText { get; set; }

        private string _name;
        public string Name
        {
            set { SetProperty(ref _name, value); }
            get { return _name; }
        }

        public void ChangeLabelText()
        {
            if (Name != null)
            {
                LabelText = Name;
            }
        }

        bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
        {
            if (Object.Equals(storage, value))
                return false;

            storage = value;
            OnPropertyChanged(propertyName);
            return true;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string PropertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
        }

    }
</code>```

When using it in xaml, you can set the BindingContext as follows:

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:testapp0211="clr-namespace:TestApp0211"
             x:Class="TestApp0211.MainPage">

    <ContentPage.BindingContext>
        <testapp0211:MyViewModel />
    </ContentPage.BindingContext>

    <StackLayout  BackgroundColor="AliceBlue"
                 Margin="15">

        <Label Text="{Binding Name, Mode=TwoWay}"/>
        <Entry Placeholder="Enter Your Name" Text="{Binding Name, Mode=TwoWay}"/>
        <Button Text="Enter" Command="{Binding EntryCommand}"/>

    </StackLayout>
</ContentPage>
</code>```

Note:

It is recommended that you rename the class ViewModel (e.g. MyViewModel)to better distinguish between different viewModels.

Title: Xamarin.Android Keeps Stopping

Body:
I am new both to MVVM pattern and Xamarin platform.
Im trying to crate a bindable interface by using a view model.
I started with a very simple task: Take the Entry input from the user, and send it to the label text after clicking the button.

ViewModel ---> Commands ---> EntryCommand.cs

namespace HelloWorld.ViewModel.Commands
{
    public class EntryCommand : ICommand
    {
        public ViewModel VM { get; set; }
        public EntryCommand( ViewModel vm)
        {
            VM = vm;
        }

        public event EventHandler CanExecuteChanged;

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public void Execute(object parameter)
        {
            VM.ChangeLabelText();
        }
    }
}

ViewModel.cs

namespace HelloWorld.ViewModel
{
    public class ViewModel: INotifyPropertyChanged
    {
        public EntryCommand EntryCommand { get; set; }
        public event PropertyChangedEventHandler PropertyChanged;

        public ViewModel()
        {
            EntryCommand = new EntryCommand(this);
        }

        private void OnPropertyChanged(string PropertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
        }

        public string LabelText { get; set; }
        public string Name
        {
            get { return Name; }
            set
            {
                Name = value;
                OnPropertyChanged("Name");
            }
        }
        public void ChangeLabelText()
        {
            if(Name!=null)
            {
                LabelText = Name;
            }
        }

    }
}

Bindable Xaml file:

MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="HelloWorld.MainPage"
             xmlns:ViewModel="clr-namespace:HelloWorld.ViewModel" x:DataType="ViewModel:ViewModel">

    <ContentPage.Resources>
        <ViewModel:ViewModel x:Key="vm"/>
    </ContentPage.Resources>

    <StackLayout BindingContext="{StaticResource vm}" BackgroundColor="AliceBlue"
                 Margin="15">

        <Entry Placeholder="Enter Your Name" Text="{Binding Name, Mode=TwoWay}"/>
        <Button Text="Enter" Command="{Binding EntryCommand}"/>

    </StackLayout>

</ContentPage>

Now, I don't get any errors but emulator keeps stopping before building the UI:

enter image description here

Body:
I think you're using the ViewModel incorrectly.

Depending on your needs,there is no need to create EntryCommand: ICommand.

You can do like this:

public ICommand EntryCommand => new Command(DoSomething);

public void DoSomething() {

        // do some thing here
    }

Besides, the use of Name is also incorrect, you need to create another variable (e.g. private string _name;)

    private string _name;
    public string Name
    {
        set { SetProperty(ref _name, value); }
        get { return _name; }
    }

You can refer to the full sample code here:

   public class MyViewModel: INotifyPropertyChanged
    {
        public ICommand EntryCommand => new Command(DoSomething);

        public MyViewModel() {
            Name = "abc123";

        }

        public void DoSomething() {

            // do some thing here
        }

        public string LabelText { get; set; }

        private string _name;
        public string Name
        {
            set { SetProperty(ref _name, value); }
            get { return _name; }
        }

        public void ChangeLabelText()
        {
            if (Name != null)
            {
                LabelText = Name;
            }
        }

        bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
        {
            if (Object.Equals(storage, value))
                return false;

            storage = value;
            OnPropertyChanged(propertyName);
            return true;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string PropertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
        }

    }

When using it in xaml, you can set the BindingContext as follows:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:testapp0211="clr-namespace:TestApp0211"
             x:Class="TestApp0211.MainPage">

    <ContentPage.BindingContext>
        <testapp0211:MyViewModel />
    </ContentPage.BindingContext>

    <StackLayout  BackgroundColor="AliceBlue"
                 Margin="15">

        <Label Text="{Binding Name, Mode=TwoWay}"/>
        <Entry Placeholder="Enter Your Name" Text="{Binding Name, Mode=TwoWay}"/>
        <Button Text="Enter" Command="{Binding EntryCommand}"/>

    </StackLayout>
</ContentPage>

Note:

It is recommended that you rename the class ViewModel (e.g. MyViewModel)to better distinguish between different viewModels.


答:
I would do a regex replacement on &.*$ and replace with empty string.

var inputs = ["someRandomText&ab_channel=thisPartCanChange", "someRandomText"];
inputs.forEach(x => console.log(x.replace(/&.*$/, "")));```

Note that the above approach is robust with regard to strings which don't even have a & component.

Title: I have an string and i want to delete from a specific character to the end of the string in JavaScript

Body:
i have this string => someRandomText&ab_channel=thisPartCanChange and i want to delete all from & (inclusive) to the end [this part: &ab_channel=thisPartCanChange].

How can i do this?

Body:
I would do a regex replacement on &.*$ and replace with empty string.

var inputs = ["someRandomText&ab_channel=thisPartCanChange", "someRandomText"];
inputs.forEach(x => console.log(x.replace(/&.*$/, "")));

Note that the above approach is robust with regard to strings which don't even have a & component.


问:
Browser (Extension Script) Module not found: Error: Can't resolve 'fs'
I am requiring a module (chinese-tokenizer) that uses fs. Webpack prompts an error that fs is not found. All solutions that I found online suggest to use target: 'node', however my application is meant for the 'web'.

Is there a way to avoid this error while still have the module work?

答:
The issue probably happened because you are using Webpack 5. Traditionally, Webpack used to polyfill the core Node.js modules when the bundle was being created for browser/web. But that is no longer the case.

To address this, essentially, you will have to tell Webpack to polyfill this module. There are multiple options to do this.

First, you can use node-polyfill-webpack-plugin that takes cares of bundling any core Node.js module that Webpack encounters.

In you Webpack configuration, webpack.config.js file, just add this plugin:

```<code>const NodePolyfillPlugin = require("node-polyfill-webpack-plugin")

module.exports = {
  // Other config...
  plugins: [
    new NodePolyfillPlugin()
  ]
};
</code>```

Second, you can write your own configuration to tell Webpack about this module:

```<code>// webpack.config.js
module.exports = {
  // Other configuration
  resolve: {
    fallback: {
      fs: require.resolve('fs')
    }
  }
};
</code>```

Third, instead of using actual module, you can provide your own mocked implementation. This is what you should use as bundling actual fs modules doesn't make any sense for browser code and probably there will be transitive dependencies of fs modules that Webpack may fail to bundle. See this link for more details.

Also, make sure that you are not using the loadFile function provided by the  chinese-tokenizer module. That is the only function using the Node's fs module.

Body:
The issue probably happened because you are using Webpack 5. Traditionally, Webpack used to polyfill the core Node.js modules when the bundle was being created for browser/web. But that is no longer the case.

To address this, essentially, you will have to tell Webpack to polyfill this module. There are multiple options to do this.

First, you can use node-polyfill-webpack-plugin that takes cares of bundling any core Node.js module that Webpack encounters.

In you Webpack configuration, webpack.config.js file, just add this plugin:

const NodePolyfillPlugin = require("node-polyfill-webpack-plugin")

module.exports = {
  // Other config...
  plugins: [
    new NodePolyfillPlugin()
  ]
};

Second, you can write your own configuration to tell Webpack about this module:

// webpack.config.js
module.exports = {
  // Other configuration
  resolve: {
    fallback: {
      fs: require.resolve('fs')
    }
  }
};

Third, instead of using actual module, you can provide your own mocked implementation. This is what you should use as bundling actual fs modules doesn't make any sense for browser code and probably there will be transitive dependencies of fs modules that Webpack may fail to bundle. See this link for more details.

Also, make sure that you are not using the loadFile function provided by the  chinese-tokenizer module. That is the only function using the Node's fs module.


答:
const yourString = 'SomeRandomText&ab_channel=thisPartCanChange'
console.log(yourString.split('&ab_channel')[0])```


问:
how to make loops from smallest to largest number?
```<code>a = int(input("first number: "))
b = int(input("second number: "))
for x in range (a,b):
    print(x, end = ' ')
</code>```

I am making a program that would display a number from smallest to largest.

For example: the first number is 10 then the second number is 1.

My expected result is: 1,2,3,4,5,6,7,8,9.

The program that I did is not working if a is lower than b, but is working if the a is higher than b.

答:
If you want it to always go from min to max regardless of which one is min and which is max you could do something like this:</p>
```<code>for x in range(min(a, b), max(a, b)):
</code>```

Body:
a = int(input("first number: "))
b = int(input("second number: "))
for x in range (a,b):
    print(x, end = ' ')

I am making a program that would display a number from smallest to largest.

For example: the first number is 10 then the second number is 1.

My expected result is: 1,2,3,4,5,6,7,8,9.

The program that I did is not working if a is lower than b, but is working if the a is higher than b.

Body:
If you want it to always go from min to max regardless of which one is min and which is max you could do something like this:

for x in range(min(a, b), max(a, b)):


答:
It is because you're setting the widget as const.

Remove const from the following code:

```<code>prefixIcon: const Padding(
  padding: EdgeInsets.only(top: 15), // add padding to adjust icon
  child: Icon(icon)
),
</code>```

it becomes:

```<code>prefixIcon: Padding(
  padding: EdgeInsets.only(top: 15), // add padding to adjust icon
  child: Icon(icon)
),
</code>```

Title: How to correctly pass IconData as and argument to a custom widget

Body:
It is because you're setting the widget as const.

Remove const from the following code:

prefixIcon: const Padding(
  padding: EdgeInsets.only(top: 15), // add padding to adjust icon
  child: Icon(icon)
),

it becomes:

prefixIcon: Padding(
  padding: EdgeInsets.only(top: 15), // add padding to adjust icon
  child: Icon(icon)
),


问:
Django url path matching not working as expected
I have problem with Django model get_absolute_url reverse methods.
I have a url pattern that works perfectly but the problem for example

when I visit example.com/blog/python/first-post the path works perfectly, but
when I try a random path like, example.com/blog/python-randomr9353/first-post
it still works correctly even though it shouldn't because, python-randomr9353 is not
a valid path and it should return a page not found error.

Here is my code.

Models

class ArticleSeries(models.Model):
    title = models.CharField(max_length=200)
    series_slug = AutoSlugField(populate_from='title')

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('blog:article_list', kwargs={'series_slug': self.series_slug})

class Tag(models.Model):
    title = models.CharField(max_length=50)

    def __str__(self):
        return self.title

class Article(models.Model):
    title = models.CharField(max_length=200)
    article_slug = AutoSlugField(populate_from='title')
    tag = models.ManyToManyField(Tag, default=1, verbose_name='Tag')
    series = models.ForeignKey(ArticleSeries, default=1, verbose_name='Series', on_delete=models.SET_DEFAULT)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('blog:article_detail', args=(self.series.series_slug, self.article_slug))

```
<h2>url patterns</h2>
<pre class="lang-py prettyprint-override"><code>app_name = 'blog'
urlpatterns = [
    path('', views.IndexView.as_view(), name='index_view'),
    path('blog', views.BlogView.as_view(), name='blog_view'),
    path('blog/<slug:series_slug>', views.ArticleListView.as_view(), name='article_list'),
    path('blog/<slug:series_slug>/<slug:article_slug>', views.ArticleDetailView.as_view(), name='article_detail'),
]
</code>```

Views

class IndexView(TemplateView):
    template_name = 'blog/index.html'
    extra_context = {}

class BlogView(ListView):
    model = ArticleSeries
    template_name = 'blog/blog_view.html'
    context_object_name = 'series_list'

    def get_queryset(self):
        series = ArticleSeries.objects.all()
        return get_list_or_404(series)

class ArticleListView(ListView):
    model = Article
    template_name = 'blog/article_list.html'
    context_object_name = 'article_list'

    def get_queryset(self):
        slug = self.kwargs['series_slug']
        articles = Article.objects.filter(series__series_slug=slug)
        return get_list_or_404(articles)

class ArticleDetailView(DetailView):
    model = Article
    template_name = 'blog/article_detail.html'
    context_object_name = 'article'
    slug_field = 'article_slug'
    slug_url_kwarg = 'article_slug'

    def get_object(self, queryset=None):
        slug = self.kwargs.get('article_slug')
        return get_object_or_404(Article, article_slug=slug)

```

答:
Try using path('blog/python/<slug:article_slug>', views.ArticleDetailView.as_view(), name='article_detail') in the urls.py instead of path('blog/<slug:series_slug>/<slug:article_slug>', views.ArticleDetailView.as_view(), name='article_detail').

EDIT:

At the point where you obtain the value of series_slug, validate this there itself.

```<code>...
validSeries = ['python', 'c', 'cpp', 'js'] # etc
if series_slug not in validSeries:
    # Raise a page not found error
</code>```

Body:
I have problem with Django model get_absolute_url reverse methods.
I have a url pattern that works perfectly but the problem for example

when I visit example.com/blog/python/first-post the path works perfectly, but
when I try a random path like, example.com/blog/python-randomr9353/first-post
it still works correctly even though it shouldn't because, python-randomr9353 is not
a valid path and it should return a page not found error.

Here is my code.

Models

class ArticleSeries(models.Model):
    title = models.CharField(max_length=200)
    series_slug = AutoSlugField(populate_from='title')

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('blog:article_list', kwargs={'series_slug': self.series_slug})

class Tag(models.Model):
    title = models.CharField(max_length=50)

    def __str__(self):
        return self.title

class Article(models.Model):
    title = models.CharField(max_length=200)
    article_slug = AutoSlugField(populate_from='title')
    tag = models.ManyToManyField(Tag, default=1, verbose_name='Tag')
    series = models.ForeignKey(ArticleSeries, default=1, verbose_name='Series', on_delete=models.SET_DEFAULT)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('blog:article_detail', args=(self.series.series_slug, self.article_slug))

url patterns

app_name = 'blog'
urlpatterns = [
    path('', views.IndexView.as_view(), name='index_view'),
    path('blog', views.BlogView.as_view(), name='blog_view'),
    path('blog/<slug:series_slug>', views.ArticleListView.as_view(), name='article_list'),
    path('blog/<slug:series_slug>/<slug:article_slug>', views.ArticleDetailView.as_view(), name='article_detail'),
]

Views

class IndexView(TemplateView):
    template_name = 'blog/index.html'
    extra_context = {}

class BlogView(ListView):
    model = ArticleSeries
    template_name = 'blog/blog_view.html'
    context_object_name = 'series_list'

    def get_queryset(self):
        series = ArticleSeries.objects.all()
        return get_list_or_404(series)

class ArticleListView(ListView):
    model = Article
    template_name = 'blog/article_list.html'
    context_object_name = 'article_list'

    def get_queryset(self):
        slug = self.kwargs['series_slug']
        articles = Article.objects.filter(series__series_slug=slug)
        return get_list_or_404(articles)

class ArticleDetailView(DetailView):
    model = Article
    template_name = 'blog/article_detail.html'
    context_object_name = 'article'
    slug_field = 'article_slug'
    slug_url_kwarg = 'article_slug'

    def get_object(self, queryset=None):
        slug = self.kwargs.get('article_slug')
        return get_object_or_404(Article, article_slug=slug)

Body:
Try using path('blog/python/<slug:article_slug>', views.ArticleDetailView.as_view(), name='article_detail') in the urls.py instead of path('blog/<slug:series_slug>/<slug:article_slug>', views.ArticleDetailView.as_view(), name='article_detail').

EDIT:

At the point where you obtain the value of series_slug, validate this there itself.

...
validSeries = ['python', 'c', 'cpp', 'js'] # etc
if series_slug not in validSeries:
    # Raise a page not found error