问:
Awaiting before an if statement
I have built a multi-step wizard that sometimes has step-dependant validation, i.e. checking that an address exists and then navigating away from the wizard if the values do not pass validation. However, not all steps require validation and, as such, it is not possible to return the validation function inside handleSubmit. I originally wrote the following:

```<code>const handleSubmit = async (values) => {
    const { handleValidation } = props
    let success = handleStepValidation
        ? await handleStepValidation(values)
        : true;
    if (success) {
        nextStep();
    }
}
</code>```

However, the above didn't work because it wasn't waiting for the validation to finish before the if statement. I am somewhat new to async/await and I currently have the .then/.catch in each handleStepValidation function because the wizard is a generic wrapper for all steps. I have settled on the following code, but it seems somewhat ugly and I wanted any advice/help on how I could improve it:

```<code>const handleSubmit = async (values) => {
    const { handleValidation } = props
    if (handleValidation && (await handleValidation(values))) {
        nextStep();
    } else {
        nextStep();
    }
}
</code>```

I appreciate any help in advance. Many thanks!

答:
```<code>const handleSubmit = async (values) => {
  const { handleValidation } = props;
  let success = true;

  // Only call the async if it's necessary
  if (handleValidation) {
    success = await handleStepValidation(values);
  }

  if (success) {
    nextStep();
  }
}

</code>```

Title: Awaiting before an if statement

Body:
I have built a multi-step wizard that sometimes has step-dependant validation, i.e. checking that an address exists and then navigating away from the wizard if the values do not pass validation. However, not all steps require validation and, as such, it is not possible to return the validation function inside handleSubmit. I originally wrote the following:

const handleSubmit = async (values) => {
    const { handleValidation } = props
    let success = handleStepValidation
        ? await handleStepValidation(values)
        : true;
    if (success) {
        nextStep();
    }
}

However, the above didn't work because it wasn't waiting for the validation to finish before the if statement. I am somewhat new to async/await and I currently have the .then/.catch in each handleStepValidation function because the wizard is a generic wrapper for all steps. I have settled on the following code, but it seems somewhat ugly and I wanted any advice/help on how I could improve it:

const handleSubmit = async (values) => {
    const { handleValidation } = props
    if (handleValidation && (await handleValidation(values))) {
        nextStep();
    } else {
        nextStep();
    }
}

I appreciate any help in advance. Many thanks!


来源: stackexchange

问:
ASP.NET Core MVC: asp-for is rendering incomplete id and name attributes
When I iterate over a list in my .cshtml file, for some reason the id and name attribute values are rendered incomplete. For example:

```<code> @for (int i = 0; i < Model.product.ProductDetail.Count(); i++)
{
    <input type="text"
    asp-for="product.ProductDetail.ElementAt(i).Sku"
    class="form-control"
    placeholder="@SharedLocalizer["Sku"]" />
}
</code>```

Is rendered as:

```<code><input type="text" class="form-control" placeholder="Sku" id="Sku" name="Sku">
</code>```

Instead of:

```<code><input type="text" id="product.ProductDetail_0__Sku" name="product.ProductDetail[0].Sku" class="form-control" placeholder="Sku">
</code>```

I am using Entity Framework Core 3.1.3, here is my model:

Product:

```<code>public partial class Product
{
     public Product()
     {
          ProductDetail = new HashSet<ProductDetail>();
     }

     /* More properties here... */

     public virtual ICollection<ProductDetail> ProductDetail { get; set; }
}
</code>```

ProductDetail:

```<code>public partial class ProductDetail
{
    /* More properties here... */
    public string Sku { get; set; }
}
</code>```

ProductViewModel:

```<code>public class ProductViewModel
{
    public Product product { get; set; }
    /* More properties here... */
}
</code>```

Do you know why is this happening?

答:
Firstly, using asp-for="product.ProductDetail[i].Sku" as CalC shared could work for me with testing model data.

If it indeed doesn’t work for you, you can try to manually set id, name and value attributes for your input fields, like below.

Here is my code of Model:

products:

```<code>public class Products
{
    public Product product { get; set; }
}
</code>```

Product:

```<code>public class Product
{
    public List<ProductDetail> ProductDetail { get; set; }
}
</code>```

ProductDetail:

```<code>public class ProductDetail
{
    public string Sku { get; set; }
}
</code>```

view:

```<code><div>
    @for (int i = 0; i < Model.product.ProductDetail.Count(); i++)
    {
        <input type="text"
               asp-for="product.ProductDetail[i].Sku"
               class="form-control"
               placeholder="@SharedLocalizer["Sku"]"/>
    }
    @for (int i = 0; i < Model.product.ProductDetail.Count(); i++)
    {
        <input type="text"
               id="product_ProductDetail_@(i)__Sku"
               name="product.ProductDetail[@(i)].Sku"
               value="@Model.product.ProductDetail.ElementAt(i).Sku"
               class="form-control"
               placeholder="@SharedLocalizer["Sku"]"/>
    }
</div>
</code>```

And this is the result:

ContentLicense: CC BY-SA 4.0

Body:
When I iterate over a list in my .cshtml file, for some reason the id and name attribute values are rendered incomplete. For example:

 @for (int i = 0; i < Model.product.ProductDetail.Count(); i++)
{
    <input type="text"
    asp-for="product.ProductDetail.ElementAt(i).Sku"
    class="form-control"
    placeholder="@SharedLocalizer["Sku"]" />
}

Is rendered as:

<input type="text" class="form-control" placeholder="Sku" id="Sku" name="Sku">

Instead of:

<input type="text" id="product.ProductDetail_0__Sku" name="product.ProductDetail[0].Sku" class="form-control" placeholder="Sku">

I am using Entity Framework Core 3.1.3, here is my model:

Product:

public partial class Product
{
     public Product()
     {
          ProductDetail = new HashSet<ProductDetail>();
     }

     /* More properties here... */

     public virtual ICollection<ProductDetail> ProductDetail { get; set; }
}

ProductDetail:

public partial class ProductDetail
{
    /* More properties here... */
    public string Sku { get; set; }
}

ProductViewModel:

public class ProductViewModel
{
    public Product product { get; set; }
    /* More properties here... */
}

Do you know why is this happening?

Body:
Firstly, using asp-for="product.ProductDetail[i].Sku" as CalC shared could work for me with testing model data.

If it indeed doesn’t work for you, you can try to manually set id, name and value attributes for your input fields, like below.

Here is my code of Model:

products:

public class Products
{
    public Product product { get; set; }
}

Product:

public class Product
{
    public List<ProductDetail> ProductDetail { get; set; }
}

ProductDetail:

public class ProductDetail
{
    public string Sku { get; set; }
}

view:

<div>
    @for (int i = 0; i < Model.product.ProductDetail.Count(); i++)
    {
        <input type="text"
               asp-for="product.ProductDetail[i].Sku"
               class="form-control"
               placeholder="@SharedLocalizer["Sku"]"/>
    }
    @for (int i = 0; i < Model.product.ProductDetail.Count(); i++)
    {
        <input type="text"
               id="product_ProductDetail_@(i)__Sku"
               name="product.ProductDetail[@(i)].Sku"
               value="@Model.product.ProductDetail.ElementAt(i).Sku"
               class="form-control"
               placeholder="@SharedLocalizer["Sku"]"/>
    }
</div>

And this is the result:


问:
(OFF Line MAP) how to download osm tiles to use OFF LINE MAP in react-native-maps
Respected sir/ma'am I want to implement offline osm map in my project. but i don't found any proper documentation for how to download tiles for offline usage. i am currently using react-native-maps package for implementing custom Tile Overlay</p>

```<code>import { LocalTile } from 'react-native-maps';

<MapView
  region={this.state.region}
  onRegionChange={this.onRegionChange}
>
  <LocalTile
   /**
    * The path template of the locally stored tiles. The patterns {x} {y} {z} will be replaced at runtime
    * For example, /storage/emulated/0/mytiles/{z}/{x}/{y}.png
    */
   pathTemplate={this.state.pathTemplate}
   /**
    * The size of provided local tiles (usually 256 or 512).
    */
   tileSize={256}
  />
</MapView>
</code>```

答:
There is no straightforward approach for downloading offline raster tiles for OSM. Rendering these tiles is very resource intensive and depending on the zoom level the download and storage size of raster tiles will become huge. In other words: raster tiles should be avoided for offline use. You should consider using vector tiles instead.

Possible solutions:

Render your own raster tiles, for example by using Maperitive

Switch to a library supporting vector tiles and download them, for example from OpenMapTiles.com

Body:
Respected sir/ma'am I want to implement offline osm map in my project. but i don't found any proper documentation for how to download tiles for offline usage. i am currently using react-native-maps package for implementing custom Tile Overlay

import { LocalTile } from 'react-native-maps';

<MapView
  region={this.state.region}
  onRegionChange={this.onRegionChange}
>
  <LocalTile
   /**
    * The path template of the locally stored tiles. The patterns {x} {y} {z} will be replaced at runtime
    * For example, /storage/emulated/0/mytiles/{z}/{x}/{y}.png
    */
   pathTemplate={this.state.pathTemplate}
   /**
    * The size of provided local tiles (usually 256 or 512).
    */
   tileSize={256}
  />
</MapView>


问:
Dynamically inject the current date into PostgreSQL query with copy export
Is there a way I can dynamically inject the date in YYYYMMDD format into this PostgreSQL query that I am using with copy inside psql?

```<code>copy (SELECT
        course.id, course.area, course.status, course.type,
        customer.firstname, customer.lastname, customer.email
      FROM course
      JOIN customer_course
      ON customer_course.course_id = course.id
      JOIN customer
      ON customer.id = customer_course.customer_id
      WHERE course.type LIKE '%heathland%'
      AND course.status = 'open'
    ) TO '~/Dropbox/CRMPicco/prod-customer-courses-' . (SELECT NOW()::date) . '.csv' WITH CSV;
</code>```

When I run that query I get the following error:

```<code>ERROR:  syntax error at or near "."
LINE 1: ...ace%' AND course.status = 'open' ) TO STDOUT . (SELECT ...
</code>```

It would be advantageous if I could create this CSV with the current date without having to manually edit the query.

答:
In psql you can set a variable to the name of the output file:

postgres=#> select '~/Dropbox/CRMPicco/prod-customer-courses-'||current_date||'.csv' as fname
postgres=#> \gset
postgres=#> copy (...) to :'fname';
```

Note the missing ; after the first select, you have to terminate that statement with  \gset. The variable name is defined through the column alias of the "source".

Body:
Is there a way I can dynamically inject the date in YYYYMMDD format into this PostgreSQL query that I am using with copy inside psql?

copy (SELECT
        course.id, course.area, course.status, course.type,
        customer.firstname, customer.lastname, customer.email
      FROM course
      JOIN customer_course
      ON customer_course.course_id = course.id
      JOIN customer
      ON customer.id = customer_course.customer_id
      WHERE course.type LIKE '%heathland%'
      AND course.status = 'open'
    ) TO '~/Dropbox/CRMPicco/prod-customer-courses-' . (SELECT NOW()::date) . '.csv' WITH CSV;

When I run that query I get the following error:

ERROR:  syntax error at or near "."
LINE 1: ...ace%' AND course.status = 'open' ) TO STDOUT . (SELECT ...

It would be advantageous if I could create this CSV with the current date without having to manually edit the query.

Body:
In psql you can set a variable to the name of the output file:

postgres=#> select '~/Dropbox/CRMPicco/prod-customer-courses-'||current_date||'.csv' as fname
postgres=#> \gset
postgres=#> copy (...) to :'fname';

Note the missing ; after the first select, you have to terminate that statement with  \gset. The variable name is defined through the column alias of the "source".


问:
Format a date by reversing the position of the year, month and days
The value received from the Date Picker is in the format "02-06-2020" (formatted with mask = "DD-MM-YYYY" in q-date).

I need to convert it to "2020-06-02" format to send it to the server.

I tried the following, but I get undefined.

Example:

```<code>let myDate = "02-06-2020";
console.log(date.formatDate(myDate, "YYYY-MM-DD")) //undefined
</code>```

I would appreciate suggestions for finding a solution.
Thanks.

答:
You can use moment js.

```<code>moment(moment('13-01-2020', 'DD-MM-YYYY')).format('YYYY-MM-DD');
</code>```

or

```<code>date.split("-").reverse().join("-");
</code>```

Body:
The value received from the Date Picker is in the format "02-06-2020" (formatted with mask = "DD-MM-YYYY" in q-date).

I need to convert it to "2020-06-02" format to send it to the server.

I tried the following, but I get undefined.

Example:

let myDate = "02-06-2020";
console.log(date.formatDate(myDate, "YYYY-MM-DD")) //undefined

I would appreciate suggestions for finding a solution.
Thanks.

Body:
You can use moment js.

moment(moment('13-01-2020', 'DD-MM-YYYY')).format('YYYY-MM-DD');

or

date.split("-").reverse().join("-");


问:
Password invalid for sqlplus copy command but it is the correct password. Please guide me on it
I am using this command .

```<code>COPY FROM username/[pwd]@identifier
  INSERT SCHEMA_NAME.TABLE_NAME USING SELECT * FROM SCHEMA_NAME.TABLE_NAME;
</code>```

and my password contains +, ) .

it is showing me this error ORA-01017.

The password and the username and all are other details are true.

Please help me on this and any guidance on it is deeply appreciated.

答:
If your password has the special characters then in cmd.exe, it should be something like this:

```<code>username/\"password\"@tns_alias
</code>```

here \" is used for denoting the double-quotes. so your password is wrapped in double-quotes.

Body:
I am using this command .

COPY FROM username/[pwd]@identifier
  INSERT SCHEMA_NAME.TABLE_NAME USING SELECT * FROM SCHEMA_NAME.TABLE_NAME;

and my password contains +, ) .

it is showing me this error ORA-01017.

The password and the username and all are other details are true.

Please help me on this and any guidance on it is deeply appreciated.

Body:
If your password has the special characters then in cmd.exe, it should be something like this:

username/\"password\"@tns_alias

here \" is used for denoting the double-quotes. so your password is wrapped in double-quotes.


问:
Remove empty brackets ( ) from string
I had a problem in removing empty brackets from string, I tried few methods didn't work. kindly help

here is the dataframe

```<code>data = {'disc': ['( ) -2,4-dichloro-a- ( chloromethyl ) -benzenemethanol methanesulfonate','( ) ( s ) -isopropyl 2 ','( 2s3s ) -12-epoxy-3- ( boc-amino ) -4-phenylbutane ( ) boc-epoxideide']}
df1 = pd.DataFrame(data)
print(df1)
</code>```

which have multiple occurrence of ( ) need to remove only empty brackets.

input:

```<code>      disc
0   ( ) -2,4-dichloro-a- ( chloromethyl ) -benzenemethanol methanesulfonate
1   ( ) ( s ) -isopropyl 2
2   ( 2s3s ) -12-epoxy-3- ( boc-amino ) -4-p
</code>```

output:

```<code>     disc
0   -2,4-dichloro-a- ( chloromethyl ) -benzenemethanol methanesulfonate
1   ( s ) -isopropyl 2
2   ( 2s3s ) -12-epoxy-3- ( boc-amino ) -4-phenylbutane boc-epoxideide
</code>```

using replace is not helping because it will remove all brackets there in the string.

答:
import re
You can try using regex module

```<code>df1["disc"] = df1["disc"].str.replace("\(\\s+\)", "")
</code>```

\\s+  means it will detect one or spaces between two brackets

```<code> -2,4-dichloro-a- ( chloromethyl ) -benzenemethanol methanesulfonate
 ( s ) -isopropyl 2
( 2s3s ) -12-epoxy-3- ( boc-amino ) -4-phenylbutane  boc-epoxideide
</code>```

Title: Remove empty brackets ( ) from string

Body:
I had a problem in removing empty brackets from string, I tried few methods didn't work. kindly help

here is the dataframe

data = {'disc': ['( ) -2,4-dichloro-a- ( chloromethyl ) -benzenemethanol methanesulfonate','( ) ( s ) -isopropyl 2 ','( 2s3s ) -12-epoxy-3- ( boc-amino ) -4-phenylbutane ( ) boc-epoxideide']}
df1 = pd.DataFrame(data)
print(df1)

which have multiple occurrence of ( ) need to remove only empty brackets.

input:

      disc
0   ( ) -2,4-dichloro-a- ( chloromethyl ) -benzenemethanol methanesulfonate
1   ( ) ( s ) -isopropyl 2
2   ( 2s3s ) -12-epoxy-3- ( boc-amino ) -4-p

output:

     disc
0   -2,4-dichloro-a- ( chloromethyl ) -benzenemethanol methanesulfonate
1   ( s ) -isopropyl 2
2   ( 2s3s ) -12-epoxy-3- ( boc-amino ) -4-phenylbutane boc-epoxideide

using replace is not helping because it will remove all brackets there in the string.

Body:
import re
You can try using regex module

df1["disc"] = df1["disc"].str.replace("\(\\s+\)", "")

\\s+  means it will detect one or spaces between two brackets

 -2,4-dichloro-a- ( chloromethyl ) -benzenemethanol methanesulfonate
 ( s ) -isopropyl 2
( 2s3s ) -12-epoxy-3- ( boc-amino ) -4-phenylbutane  boc-epoxideide


问:
C++: Indicating a function may throw

Possible Duplicate:

  Is there a generally accepted idiom for indicating C++ code can throw exceptions?

How do you indicate in your code when a C++ function is possible to throw something? I don't mean through documentation, but through syntax.

For example I tried placing a throw(std::exception) at the end of the function declaration, but that gave me a warning saying that "C++ exception specification ignored except to indicate a function is not __declspec(nothrow)", which I guess means the compiler ignored the throw and proceeded as if it were not there.

I also tried adding a throw() (without anything in the parenthesis) at the end of the declaration, but — contrary to my expectations — that means the function is expected to never throw anything: "function assumed not to throw an exception but does".

Atm I'm using throw(...) to syntactically indicate the function may throw as this doesn't give me any errors or warnings. Do you have any other suggestions as to how I might indicate this through syntax?

答:
You don't. Exception specifiers do not mean "Here's what I can throw", they mean "if anything other than this gets thrown, go to std::terminate". This behavior is counterintuitive to the point that MSVC++ does not and will not support them.

The semantics of C++ is that you must assume a function can always throw.

ContentLicense: CC BY-SA 3.0

Title: C++: Indicating a function may throw


问:
How to solve TeamCity GitVersion infinte loop error?
I have strange error with GitVersion procedure in TeamCity. It fall into infinte loop consisting of code below.

The branch0 is a parent for branch1 and branch2.
I am trying to deploy branch2 and there is an error related to branch1 displayed, where it should not have any connection to it at all.

Also I am curious what is the difference betwen 'develop' and 'origin/develop' in this context, as to me they both should be the same remote branch, shouldn't they?

I suspect there might be some issue with the way the branches relate to each other, but couldn't really figure it out. The curious part is that when i delete branch1, then I can easily deploy branch0 and branch2. Once I create the branch1 again from branch0, then yet again it fails.

```<code>Falling back to branch1 branch config
[15:07:52][Step 1/1]             INFO [05/25/20 15:07:52:16] No branch configuration found for branch branch1, falling back to default configuration
[15:07:52][Step 1/1]             INFO [05/25/20 15:07:52:16] Begin: Attempting to inherit branch configuration from parent branch
[15:07:52][Step 1/1]               INFO [05/25/20 15:07:52:16] HEAD is merge commit, this is likely a pull request using master as base
[15:07:52][Step 1/1]               INFO [05/25/20 15:07:52:17] Begin: Finding branch source of 'master'
[15:07:52][Step 1/1]                 INFO [05/25/20 15:07:52:17] Multiple source branches have been found, picking the first one (develop).
[15:07:52][Step 1/1] This may result in incorrect commit counting.
[15:07:52][Step 1/1] Options were:
[15:07:52][Step 1/1]  develop, origin/develop
[15:07:52][Step 1/1]               INFO [05/25/20 15:07:52:17] End: Finding branch source of 'master' (Took: 1.00ms)
[15:07:52][Step 1/1]               INFO [05/25/20 15:07:52:17] Begin: Getting branches containing the commit 'hash1'.
[15:07:52][Step 1/1]                 INFO [05/25/20 15:07:52:17] Trying to find direct branches.
[15:07:52][Step 1/1]                 INFO [05/25/20 15:07:52:17] No direct branches found, searching through tracked branches.
[15:07:52][Step 1/1]                 INFO [05/25/20 15:07:52:17] Searching for commits reachable from 'develop'.
[15:07:52][Step 1/1]                 INFO [05/25/20 15:07:52:20] The branch 'develop' has a matching commit.
[15:07:52][Step 1/1]                 INFO [05/25/20 15:07:52:20] Searching for commits reachable from 'origin/develop'.
[15:07:52][Step 1/1]                 INFO [05/25/20 15:07:52:24] The branch 'origin/develop' has a matching commit.
[15:07:52][Step 1/1]               INFO [05/25/20 15:07:52:24] End: Getting branches containing the commit 'hash1'. (Took: 68.00ms)
[15:07:52][Step 1/1]               INFO [05/25/20 15:07:52:24] Begin: Getting branches containing the commit 'hash2'.
[15:07:52][Step 1/1]                 INFO [05/25/20 15:07:52:24] Trying to find direct branches.
[15:07:52][Step 1/1]                 INFO [05/25/20 15:07:52:24] No direct branches found, searching through tracked branches.
[15:07:52][Step 1/1]                 INFO [05/25/20 15:07:52:24] Searching for commits reachable from 'develop'.
[15:07:52][Step 1/1]                 INFO [05/25/20 15:07:52:27] The branch 'develop' has a matching commit.
[15:07:52][Step 1/1]                 INFO [05/25/20 15:07:52:27] Searching for commits reachable from 'origin/develop'.
[15:07:52][Step 1/1]                 INFO [05/25/20 15:07:52:30] The branch 'origin/develop' has a matching commit.
[15:07:52][Step 1/1]               INFO [05/25/20 15:07:52:30] End: Getting branches containing the commit 'hash1'. (Took: 66.00ms)
[15:07:52][Step 1/1]               INFO [05/25/20 15:07:52:30] Found possible parent branches:
[15:07:52][Step 1/1]               WARN [05/25/20 15:07:52:30] Failed to inherit Increment branch configuration, no branches found.```
```

答: After some trial and error it seems like the best solution here was to update the ignore timestamp for git commits in the GitVersionConfig.yaml file</p>

Body:
I have strange error with GitVersion procedure in TeamCity. It fall into infinte loop consisting of code below.

The branch0 is a parent for branch1 and branch2.
I am trying to deploy branch2 and there is an error related to branch1 displayed, where it should not have any connection to it at all.

Also I am curious what is the difference betwen 'develop' and 'origin/develop' in this context, as to me they both should be the same remote branch, shouldn't they?

I suspect there might be some issue with the way the branches relate to each other, but couldn't really figure it out. The curious part is that when i delete branch1, then I can easily deploy branch0 and branch2. Once I create the branch1 again from branch0, then yet again it fails.

Falling back to branch1 branch config
[15:07:52][Step 1/1]             INFO [05/25/20 15:07:52:16] No branch configuration found for branch branch1, falling back to default configuration
[15:07:52][Step 1/1]             INFO [05/25/20 15:07:52:16] Begin: Attempting to inherit branch configuration from parent branch
[15:07:52][Step 1/1]               INFO [05/25/20 15:07:52:16] HEAD is merge commit, this is likely a pull request using master as base
[15:07:52][Step 1/1]               INFO [05/25/20 15:07:52:17] Begin: Finding branch source of 'master'
[15:07:52][Step 1/1]                 INFO [05/25/20 15:07:52:17] Multiple source branches have been found, picking the first one (develop).
[15:07:52][Step 1/1] This may result in incorrect commit counting.
[15:07:52][Step 1/1] Options were:
[15:07:52][Step 1/1]  develop, origin/develop
[15:07:52][Step 1/1]               INFO [05/25/20 15:07:52:17] End: Finding branch source of 'master' (Took: 1.00ms)
[15:07:52][Step 1/1]               INFO [05/25/20 15:07:52:17] Begin: Getting branches containing the commit 'hash1'.
[15:07:52][Step 1/1]                 INFO [05/25/20 15:07:52:17] Trying to find direct branches.
[15:07:52][Step 1/1]                 INFO [05/25/20 15:07:52:17] No direct branches found, searching through tracked branches.
[15:07:52][Step 1/1]                 INFO [05/25/20 15:07:52:17] Searching for commits reachable from 'develop'.
[15:07:52][Step 1/1]                 INFO [05/25/20 15:07:52:20] The branch 'develop' has a matching commit.
[15:07:52][Step 1/1]                 INFO [05/25/20 15:07:52:20] Searching for commits reachable from 'origin/develop'.
[15:07:52][Step 1/1]                 INFO [05/25/20 15:07:52:24] The branch 'origin/develop' has a matching commit.
[15:07:52][Step 1/1]               INFO [05/25/20 15:07:52:24] End: Getting branches containing the commit 'hash1'. (Took: 68.00ms)
[15:07:52][Step 1/1]               INFO [05/25/20 15:07:52:24] Begin: Getting branches containing the commit 'hash2'.
[15:07:52][Step 1/1]                 INFO [05/25/20 15:07:52:24] Trying to find direct branches.
[15:07:52][Step 1/1]                 INFO [05/25/20 15:07:52:24] No direct branches found, searching through tracked branches.
[15:07:52][Step 1/1]                 INFO [05/25/20 15:07:52:24] Searching for commits reachable from 'develop'.
[15:07:52][Step 1/1]                 INFO [05/25/20 15:07:52:27] The branch 'develop' has a matching commit.
[15:07:52][Step 1/1]                 INFO [05/25/20 15:07:52:27] Searching for commits reachable from 'origin/develop'.
[15:07:52][Step 1/1]                 INFO [05/25/20 15:07:52:30] The branch 'origin/develop' has a matching commit.
[15:07:52][Step 1/1]               INFO [05/25/20 15:07:52:30] End: Getting branches containing the commit 'hash1'. (Took: 66.00ms)
[15:07:52][Step 1/1]               INFO [05/25/20 15:07:52:30] Found possible parent branches:
[15:07:52][Step 1/1]               WARN [05/25/20 15:07:52:30] Failed to inherit Increment branch configuration, no branches found.```


问:
ERROR 1524 (HY000): Plugin 'unix_socket' is not loaded - Laragon
I'm migrating my production wordpress website to my local environment on Laragon.  I did the following:

Opened Laragon's Terminal:

Menu > Laragon > Terminal

Ran this command:

scp user@your-remote-host:/dump.sql C:/laragon/tmp/dump.sql

Imported sql-dump to my local database:

mysql -u root -p your-database < C:\laragon\tmp\dump.sql

Then I cloned my git repo to the root at C:\Laragon\www\

Started it up and at first it displayed a replica of the live server's homepage, but gave an error when attempting to go to another page.

I stopped all services and when I restarted I was given the error ERROR 1524 (HY000): Plugin 'unix_socket' is not loaded

Then when I tried to do mysql -u root -p from the terminal I received the same error.

With the services started the web page now showed 'error establishing database' and displayed the Error 1524

Here is the output of my.ini file which is the same as my.cnf

```<code>[client]
#password=your_password
port=3306
socket=/tmp/mysql.sock

[mysqld]
port=3306
socket=/tmp/mysql.sock
key_buffer_size=256M
max_allowed_packet=512M
table_open_cache=256
sort_buffer_size=1M
read_buffer_size=1M
read_rnd_buffer_size=4M
myisam_sort_buffer_size=64M
thread_cache_size=8
datadir= "C:/laragon/data/mysql"
plugin-load-add = auth_socket.so

secure-file-priv=""
explicit_defaults_for_timestamp=1
datadir= "C:/laragon/data/mysql"

[mysqldump]
quick
max_allowed_packet=512M
</code>```

答:
unix_socket, aka auth_socket is non-windows authentication plugin.

I'd start with the variable skip-grant-tables set, and change the root authentication using:

```<code>ALTER USER root@localhost IDENTIFIED VIA mysql_native_password USING PASSWORD("verysecret")
</code>```

Then remove the 'skip-grant-tables' option and restart.

Body:
I'm migrating my production wordpress website to my local environment on Laragon.  I did the following:

Opened Laragon's Terminal:

Menu > Laragon > Terminal

Ran this command:

scp user@your-remote-host:/dump.sql C:/laragon/tmp/dump.sql

Imported sql-dump to my local database:

mysql -u root -p your-database < C:\laragon\tmp\dump.sql

Then I cloned my git repo to the root at C:\Laragon\www\

Started it up and at first it displayed a replica of the live server's homepage, but gave an error when attempting to go to another page.

I stopped all services and when I restarted I was given the error ERROR 1524 (HY000): Plugin 'unix_socket' is not loaded

Then when I tried to do mysql -u root -p from the terminal I received the same error.

With the services started the web page now showed 'error establishing database' and displayed the Error 1524

Here is the output of my.ini file which is the same as my.cnf

[client]
#password=your_password
port=3306
socket=/tmp/mysql.sock

[mysqld]
port=3306
socket=/tmp/mysql.sock
key_buffer_size=256M
max_allowed_packet=512M
table_open_cache=256
sort_buffer_size=1M
read_buffer_size=1M
read_rnd_buffer_size=4M
myisam_sort_buffer_size=64M
thread_cache_size=8
datadir= "C:/laragon/data/mysql"
plugin-load-add = auth_socket.so

secure-file-priv=""
explicit_defaults_for_timestamp=1
datadir= "C:/laragon/data/mysql"

[mysqldump]
quick
max_allowed_packet=512M

Body:
unix_socket, aka auth_socket is non-windows authentication plugin.

I'd start with the variable skip-grant-tables set, and change the root authentication using:

ALTER USER root@localhost IDENTIFIED VIA mysql_native_password USING PASSWORD("verysecret")

Then remove the 'skip-grant-tables' option and restart.


问:
How to access token through Powershell or Postman by User ID rather than Client ID
Is there a way either in powershell or Postman to get access of myself either through login to particular tenant. I see lot of samples around getting access token either client ID or secret. But I want to run either commands or make REST call to get access token once myself get authenticated.I tried looking into graph explorer but no luck .</p>

答:
The client id is required for AAD authorization.

If you want to get an access token including your own information, you should implement OAuth 2.0 authorization code flow. It will perform interactive login as @Gaurav Mantri-AIS mentioned.

We can simply get the access token in Postman like this:

After clicking on "Request Token", it will pop up a login window. Enter your username and password. Then you will get the access token.

When we log into Graph explorer, we will see the access token here:

In fact, Microsoft has registered an Azure AD application and provided the client id in the login request URL.

In short, we have to use the client id.


问:
There is an error when importing data using the data table
Use the data table to import data from the database.
However, if there is Hangul in the data, an error occurs. Why is that?

in this script code

```<code>jQuery(document).ready(function() {
    var table = jQuery('#developers').dataTable({
        "bProcessing": true,
        "sAjaxSource": "load_data.php",
        "bPaginate": true,
        "sPaginationType": "full_numbers",
        "iDisplayLength": 5,
        "aoColumns": [
            { mData: 'id' },
            { mData: 'name' },
            { mData: 'age' },
            { mData: 'gender' },
            { mData: 'address' },
            { mData: 'designation' },
            { mData: 'skills' }
        ]
    });
});
</code>```

in this ajax load code

```<code><?php
include_once("db_connect.php");
$sql_query = "SELECT id, name, gender, skills, address, designation, age FROM developers LIMIT 20";
$resultset = mysqli_query($conn, $sql_query) or die("database error:". mysqli_error($conn));
$developers_record = array();
// echo $developers_record;
while( $developer = mysqli_fetch_assoc($resultset) ) {
    $developers_record[] = $developer;
}
$developer_data = array(
    "sEcho" => 1,
"iTotalRecords" => count($developers_record),
"iTotalDisplayRecords" => count($developers_record),
  "aaData"=>$developers_record);

echo json_encode($developer_data);

exit;
?>
</code>```

If there is Korean in the data, the following error occurs:

how do fix in this error??

add result

If there is not Korean language in the data , it is marked as follows.

but If there is Korean language in the data, it is expressed as follows.
Nothing is marked.

答:
Change the single quotes to double quotes like this:

```<code>{
    "bProcessing": true,
    "sAjaxSource": "load_data.php",
    "bPaginate": true,
    "sPaginationType": "full_numbers",
    "iDisplayLength": 5,
    "aoColumns": [{
            "mData": "id"
        },
        {
            "mData": "name"
        },
        {
            "mData": "age"
        },
        {
            "mData": "gender"
        },
        {
            "mData": "address"
        },
        {
            "mData": "designation"
        },
        {
            "mData": "skills"
        }
    ]
}
</code>```

It could be the problem. The json standard says: "A value can be a string in double quotes, or a number, or true or false or null, or an object or an array." Maybe it solves the problem.

Body:
Use the data table to import data from the database.
However, if there is Hangul in the data, an error occurs. Why is that?

in this script code

jQuery(document).ready(function() {
    var table = jQuery('#developers').dataTable({
        "bProcessing": true,
        "sAjaxSource": "load_data.php",
        "bPaginate": true,
        "sPaginationType": "full_numbers",
        "iDisplayLength": 5,
        "aoColumns": [
            { mData: 'id' },
            { mData: 'name' },
            { mData: 'age' },
            { mData: 'gender' },
            { mData: 'address' },
            { mData: 'designation' },
            { mData: 'skills' }
        ]
    });
});

in this ajax load code

<?php
include_once("db_connect.php");
$sql_query = "SELECT id, name, gender, skills, address, designation, age FROM developers LIMIT 20";
$resultset = mysqli_query($conn, $sql_query) or die("database error:". mysqli_error($conn));
$developers_record = array();
// echo $developers_record;
while( $developer = mysqli_fetch_assoc($resultset) ) {
    $developers_record[] = $developer;
}
$developer_data = array(
    "sEcho" => 1,
"iTotalRecords" => count($developers_record),
"iTotalDisplayRecords" => count($developers_record),
  "aaData"=>$developers_record);

echo json_encode($developer_data);

exit;
?>

If there is Korean in the data, the following error occurs:

how do fix in this error??

add result

If there is not Korean language in the data , it is marked as follows.

but If there is Korean language in the data, it is expressed as follows.
Nothing is marked.

Body:
Change the single quotes to double quotes like this:

{
    "bProcessing": true,
    "sAjaxSource": "load_data.php",
    "bPaginate": true,
    "sPaginationType": "full_numbers",
    "iDisplayLength": 5,
    "aoColumns": [{
            "mData": "id"
        },
        {
            "mData": "name"
        },
        {
            "mData": "age"
        },
        {
            "mData": "gender"
        },
        {
            "mData": "address"
        },
        {
            "mData": "designation"
        },
        {
            "mData": "skills"
        }
    ]
}

It could be the problem. The json standard says: "A value can be a string in double quotes, or a number, or true or false or null, or an object or an array." Maybe it solves the problem.


问:
Is there a way to open an IE window with a user-defined name. When same URL opened, already opened IE window comes to foreground
Here is my requirement which I intend to implement. There is one window application showing some icons which take me to different web sites. When I click on one of the icons, it should open an IE window and append a customized name to it.

So, before opening any website after I click on website icon, I want to check if there is already an IE window open with that customized name, if yes, bring that already opened window to the foreground. If not, open a new IE window.

I have checked various questions posted which are related to what I am looking to achieve, but am somehow not able to get it right. Below is my attempt.

```<code>For Each e In shellWins
    If InStr(1, e.GetProperty("IEWindowName"), namedWindow, CompareMethod.Text) <> 0 Then
        hWnd = e.HWND
        myIE = e
    End If
Next

If hWnd == -1
    Dim p As New Process
        Dim psi As New ProcessStartInfo(IEPath, webSiteURL)
        p.StartInfo = psi  'Trying to open a new IE window
        p.Start()

        For Each ie In shellWins
            If ie.hwdn = p.MainWindowHandle Then
                ie.PutProperty("IEWindowName", namedWindow)
            End If
        Next
End if

Else
myIE.BringToForeground()
</code>```

This sometime works and sometimes does not. Is there any better way to do it?

答:
It doesn't work in which situation? Does there any error throw when it doesn't work? If there is, please tell us the detailed error information and in which line it occurs.

Besides, you could try to compare the url to check if the website is already open in IE like this:

```<code>Sub Main()
        Dim shellWins As SHDocVw.ShellWindows
        Dim explorer As SHDocVw.InternetExplorer

        shellWins = New SHDocVw.ShellWindows
        Dim SQuery As String = "https://www.example.com/"
        For Each explorer In shellWins
            If explorer.Application.Name = "Internet Explorer" And explorer.LocationURL.Contains(SQuery) Then
                explorer.BringToForeground()
            End If
        Next

        shellWins = Nothing
        explorer = Nothing
End Sub
</code>```

Body:
Here is my requirement which I intend to implement. There is one window application showing some icons which take me to different web sites. When I click on one of the icons, it should open an IE window and append a customized name to it.

So, before opening any website after I click on website icon, I want to check if there is already an IE window open with that customized name, if yes, bring that already opened window to the foreground. If not, open a new IE window.

I have checked various questions posted which are related to what I am looking to achieve, but am somehow not able to get it right. Below is my attempt.

For Each e In shellWins
    If InStr(1, e.GetProperty("IEWindowName"), namedWindow, CompareMethod.Text) <> 0 Then
        hWnd = e.HWND
        myIE = e
    End If
Next

If hWnd == -1
    Dim p As New Process
        Dim psi As New ProcessStartInfo(IEPath, webSiteURL)
        p.StartInfo = psi  'Trying to open a new IE window
        p.Start()

        For Each ie In shellWins
            If ie.hwdn = p.MainWindowHandle Then
                ie.PutProperty("IEWindowName", namedWindow)
            End If
        Next
End if

Else
myIE.BringToForeground()

This sometime works and sometimes does not. Is there any better way to do it?

Body:
It doesn't work in which situation? Does there any error throw when it doesn't work? If there is, please tell us the detailed error information and in which line it occurs.

Besides, you could try to compare the url to check if the website is already open in IE like this:

Sub Main()
        Dim shellWins As SHDocVw.ShellWindows
        Dim explorer As SHDocVw.InternetExplorer

        shellWins = New SHDocVw.ShellWindows
        Dim SQuery As String = "https://www.example.com/"
        For Each explorer In shellWins
            If explorer.Application.Name = "Internet Explorer" And explorer.LocationURL.Contains(SQuery) Then
                explorer.BringToForeground()
            End If
        Next

        shellWins = Nothing
        explorer = Nothing
End Sub


问:
Avoid Using Master Branch for BitBucket Pipeline
I'm setting up a CI pipeline on a BitBucket Repository based around docker. I'm running build commands then up then test, basically. This all works so far, but the issue I'm having is BitBucket only commits or lets me edit changes to the bitbucket-pipelines.yaml file on the master branch.

I'm not the only developer on the project, and right now our master is our staging/ready for prod branch, and we've all agreed to use other branches for things and let one of us manage master and merges into it.

My question is, can I use another, different branch than master to "manage" my pipelines file on, like our active development branch? For some reason, I can't find a way to add a pipeline to another branch, and pushing up a bitbucket-pipelines.yaml file on the develop branch won't trigger a build.

For reference, my pipeline yaml:

```<code>image: atlassian/default-image:2

pipelines:
  # pull-requests:
  #   'feature/*':
  #     - step:
  #       services:
  #         - docker
  branches:
    develop:
      # each step starts a new Docker container with a clone of your repository
      - step:
        services:
          - docker
        script:
          - (cd app/laravel/ ; npm install)
          - (cd app/laravel/ ; npm run production)
          - docker build -t myApp -f app/Dockerfile app/
          - docker stack up -c docker/docker-compose.yaml myApp
</code>```

答:
You should be able to have a pipeline in any branch you want.

From the troubleshooting section:

My branch doesn't build

Make sure that there is a bitbucket-pipelines.yml file in the root of your branch.

To build a branch, you must specify a default or a branch-specific pipeline configuration.

For more information, see Configure bitbucket-pipelines.yml.

I would test that, following branch workflow, with a simplified yaml first (one which does just an echo for a given branch), for testing.

As the OP RoboBear confirms in the comments, the bitbucket-pipelines.yml must use the .yml extension, not .yaml.

Body:
I'm setting up a CI pipeline on a BitBucket Repository based around docker. I'm running build commands then up then test, basically. This all works so far, but the issue I'm having is BitBucket only commits or lets me edit changes to the bitbucket-pipelines.yaml file on the master branch.

I'm not the only developer on the project, and right now our master is our staging/ready for prod branch, and we've all agreed to use other branches for things and let one of us manage master and merges into it.

My question is, can I use another, different branch than master to "manage" my pipelines file on, like our active development branch? For some reason, I can't find a way to add a pipeline to another branch, and pushing up a bitbucket-pipelines.yaml file on the develop branch won't trigger a build.

For reference, my pipeline yaml:

image: atlassian/default-image:2

pipelines:
  # pull-requests:
  #   'feature/*':
  #     - step:
  #       services:
  #         - docker
  branches:
    develop:
      # each step starts a new Docker container with a clone of your repository
      - step:
        services:
          - docker
        script:
          - (cd app/laravel/ ; npm install)
          - (cd app/laravel/ ; npm run production)
          - docker build -t myApp -f app/Dockerfile app/
          - docker stack up -c docker/docker-compose.yaml myApp


问:
How to remove item from array in image adapter. Xamarin gallery
```<code>public class ImageAdapter : BaseAdapter
{
    Context context;

    public ImageAdapter (Context conn)
    {
          context = conn;
    }

    public override int Count { get { return thumbIds.Length; } }

    public override Java.Lang.Object GetItem (int position)
    {
          return null;
    }

    public override long GetItemId (int position)
    {
          return 0;
    }

    // create a new ImageView for each item referenced by the Adapter
    public override View GetView (int position, View convertView, ViewGroup parent)
    {
          ImageView pic = new ImageView (context);

          pic.SetImageResource (thumbIds[position]);
          pic.LayoutParameters = new Gallery.LayoutParams (500, 500);
          pic.SetScaleType (ImageView.ScaleType.FitXy);

          return pic;
    }

    // references to our images
    int[] thumbIds = {
            Resource.Drawable.image_1,
            Resource.Drawable.image_2,
            Resource.Drawable.image_3,
            Resource.Drawable.image_4,
            Resource.Drawable.image_5,
            Resource.Drawable.image_6,
            Resource.Drawable.image_7
     };
}
</code>```

How to remove item from array
https://learn.microsoft.com/en-us/xamarin/android/user-interface/controls/gallery
Gallery

答:
Do you want to achieve the result like following GIF?

I advice your to use List<int> to replace of int[], then you can add a method called removeItem in the ImageAdapter like following code.

```<code>public void removeItem(int numToRemove)
        {

            if (numToRemove < thumbIds.Count)
            {
                thumbIds.RemoveAt(numToRemove);
                this.NotifyDataSetChanged();
            }

        }
</code>```

Here is code about ImageAdapter.cs

```<code>using Android.Views;
using Android.Widget;
using Java.Lang;
using System.Collections.Generic;
using System.Linq;

namespace App25
{
    internal class ImageAdapter : BaseAdapter
    {
        private MainActivity mainActivity;

        public ImageAdapter(MainActivity mainActivity)
        {
            this.mainActivity = mainActivity;
        }

        public override int Count { get { return thumbIds.Count; } }

        public override Java.Lang.Object GetItem(int position)
        {
            return thumbIds[position];
        }

        public override long GetItemId(int position)
        {
            return position;
        }

        // create a new ImageView for each item referenced by the Adapter
        public override View GetView(int position, View convertView, ViewGroup parent)
        {
            ImageView pic = new ImageView(mainActivity);

            pic.SetImageResource(thumbIds[position]);
            pic.LayoutParameters = new Gallery.LayoutParams(500, 500);
            pic.SetScaleType(ImageView.ScaleType.FitXy);

            return pic;
        }
        public void removeItem(int numToRemove)
        {

            if (numToRemove < thumbIds.Count)
            {
                thumbIds.RemoveAt(numToRemove);
                this.NotifyDataSetChanged();
            }

        }
        // references to our images
        List<int> thumbIds = new List<int> {
            Resource.Drawable.faded_div,
            Resource.Drawable.icon,
            Resource.Drawable.faded_div1,
            Resource.Drawable.icon1,
            Resource.Drawable.faded_div,
            Resource.Drawable.icon2,
            Resource.Drawable.faded_div
     };
    }
}
</code>```

Here is MainActivity.cs

```<code>   [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
    public class MainActivity : AppCompatActivity
    {
        ImageAdapter imageAdapter;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.activity_main);
            Gallery gallery = (Gallery)FindViewById<Gallery>(Resource.Id.gallery1);
            Button button1 = FindViewById<Button>(Resource.Id.button1);
            imageAdapter = new ImageAdapter(this);
            gallery.Adapter = imageAdapter;
            button1.Click += Button1_Click;

        }
        int removeItem = 0;
        private void Button1_Click(object sender, System.EventArgs e)
        {

            imageAdapter.removeItem(removeItem);

        }
  }
</code>```

Here is my activity_main.xml.

```<code>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="remove"
            android:id="@+id/button1"
        />
        <Gallery
        android:id="@+id/gallery1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>
</code>```

=============Update==================

If you want to achieve the long click ,push alert, then delete the item, you can refer to achieve a longclick event for your gallery like following code.

```<code>  gallery.ItemLongClick += Gallery_ItemLongClick;

  private void Gallery_ItemLongClick(object sender, AdapterView.ItemLongClickEventArgs e)
        {
            // throw new System.NotImplementedException();

            Android.App.AlertDialog.Builder dialog = new Android.App.AlertDialog.Builder(this);
            Android.App.AlertDialog alert = dialog.Create();
            alert.SetTitle("Title");
            alert.SetMessage("Do you want to remove this select item");
            alert.SetButton("OK", (c, ev) =>
            {
                // Ok button click task
                imageAdapter.removeItem(e.Position);
            });
            alert.Show();

        }

</code>```

Here is my running GIF.

Body:
public class ImageAdapter : BaseAdapter
{
    Context context;

    public ImageAdapter (Context conn)
    {
          context = conn;
    }

    public override int Count { get { return thumbIds.Length; } }

    public override Java.Lang.Object GetItem (int position)
    {
          return null;
    }

    public override long GetItemId (int position)
    {
          return 0;
    }

    // create a new ImageView for each item referenced by the Adapter
    public override View GetView (int position, View convertView, ViewGroup parent)
    {
          ImageView pic = new ImageView (context);

          pic.SetImageResource (thumbIds[position]);
          pic.LayoutParameters = new Gallery.LayoutParams (500, 500);
          pic.SetScaleType (ImageView.ScaleType.FitXy);

          return pic;
    }

    // references to our images
    int[] thumbIds = {
            Resource.Drawable.image_1,
            Resource.Drawable.image_2,
            Resource.Drawable.image_3,
            Resource.Drawable.image_4,
            Resource.Drawable.image_5,
            Resource.Drawable.image_6,
            Resource.Drawable.image_7
     };
}

How to remove item from array
https://learn.microsoft.com/en-us/xamarin/android/user-interface/controls/gallery
Gallery

Body:
Do you want to achieve the result like following GIF?

I advice your to use List<int> to replace of int[], then you can add a method called removeItem in the ImageAdapter like following code.

public void removeItem(int numToRemove)
        {

            if (numToRemove < thumbIds.Count)
            {
                thumbIds.RemoveAt(numToRemove);
                this.NotifyDataSetChanged();
            }

        }

Here is code about ImageAdapter.cs

using Android.Views;
using Android.Widget;
using Java.Lang;
using System.Collections.Generic;
using System.Linq;

namespace App25
{
    internal class ImageAdapter : BaseAdapter
    {
        private MainActivity mainActivity;

        public ImageAdapter(MainActivity mainActivity)
        {
            this.mainActivity = mainActivity;
        }

        public override int Count { get { return thumbIds.Count; } }

        public override Java.Lang.Object GetItem(int position)
        {
            return thumbIds[position];
        }

        public override long GetItemId(int position)
        {
            return position;
        }

        // create a new ImageView for each item referenced by the Adapter
        public override View GetView(int position, View convertView, ViewGroup parent)
        {
            ImageView pic = new ImageView(mainActivity);

            pic.SetImageResource(thumbIds[position]);
            pic.LayoutParameters = new Gallery.LayoutParams(500, 500);
            pic.SetScaleType(ImageView.ScaleType.FitXy);

            return pic;
        }
        public void removeItem(int numToRemove)
        {

            if (numToRemove < thumbIds.Count)
            {
                thumbIds.RemoveAt(numToRemove);
                this.NotifyDataSetChanged();
            }

        }
        // references to our images
        List<int> thumbIds = new List<int> {
            Resource.Drawable.faded_div,
            Resource.Drawable.icon,
            Resource.Drawable.faded_div1,
            Resource.Drawable.icon1,
            Resource.Drawable.faded_div,
            Resource.Drawable.icon2,
            Resource.Drawable.faded_div
     };
    }
}

Here is MainActivity.cs

   [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
    public class MainActivity : AppCompatActivity
    {
        ImageAdapter imageAdapter;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.activity_main);
            Gallery gallery = (Gallery)FindViewById<Gallery>(Resource.Id.gallery1);
            Button button1 = FindViewById<Button>(Resource.Id.button1);
            imageAdapter = new ImageAdapter(this);
            gallery.Adapter = imageAdapter;
            button1.Click += Button1_Click;

        }
        int removeItem = 0;
        private void Button1_Click(object sender, System.EventArgs e)
        {

            imageAdapter.removeItem(removeItem);

        }
  }

Here is my activity_main.xml.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="remove"
            android:id="@+id/button1"
        />
        <Gallery
        android:id="@+id/gallery1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>

=============Update==================

If you want to achieve the long click ,push alert, then delete the item, you can refer to achieve a longclick event for your gallery like following code.

  gallery.ItemLongClick += Gallery_ItemLongClick;

  private void Gallery_ItemLongClick(object sender, AdapterView.ItemLongClickEventArgs e)
        {
            // throw new System.NotImplementedException();

            Android.App.AlertDialog.Builder dialog = new Android.App.AlertDialog.Builder(this);
            Android.App.AlertDialog alert = dialog.Create();
            alert.SetTitle("Title");
            alert.SetMessage("Do you want to remove this select item");
            alert.SetButton("OK", (c, ev) =>
            {
                // Ok button click task
                imageAdapter.removeItem(e.Position);
            });
            alert.Show();

        }

Here is my running GIF.


问:
Delayed receiving the email message using the SMTP server
I already deployed the Email Service I developed on the Chicago Server. Last Friday 11:30pm in Philippine time, I tested the sending and it run's properly, but when I checked my email there's no message in inbox or spam. And then, Saturday 1:30am, I've noticed that I received the message that I tested last Friday.

Please advice me guys! thanks!

My Questions is:

a.) Do I need to configure something on the Server to make the real time receiving on emails?

here's my code:

```<code> //send email
MailMessage objEmail = new MailMessage(new MailAddress(ConfigurationManager.AppSettings["emailAdd"].ToString()), new MailAddress(ConfigurationManager.AppSettings["emailAdd"].ToString()));
objEmail.Subject = "Test";
objEmail.Body = "CODE:" + _Message;
objEmail.Priority = MailPriority.High;
SmtpClient SmtpMail = new SmtpClient();
SmtpMail.Host = "localhost";
SmtpMail.Send(objEmail);
</code>```

答:
Put this one on your code:

SmtpMail.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;

And also, configure the relay restrictions on the SMTP server that will allow your 120.0.0.1/localhost..

Last, configure the firewall and port forwarding on the server.

I hope this will help you..

Body:
I already deployed the Email Service I developed on the Chicago Server. Last Friday 11:30pm in Philippine time, I tested the sending and it run's properly, but when I checked my email there's no message in inbox or spam. And then, Saturday 1:30am, I've noticed that I received the message that I tested last Friday.

Please advice me guys! thanks!

My Questions is:

a.) Do I need to configure something on the Server to make the real time receiving on emails?

here's my code:

 //send email
MailMessage objEmail = new MailMessage(new MailAddress(ConfigurationManager.AppSettings["emailAdd"].ToString()), new MailAddress(ConfigurationManager.AppSettings["emailAdd"].ToString()));
objEmail.Subject = "Test";
objEmail.Body = "CODE:" + _Message;
objEmail.Priority = MailPriority.High;
SmtpClient SmtpMail = new SmtpClient();
SmtpMail.Host = "localhost";
SmtpMail.Send(objEmail);


问:
Why the output is a string array even after assigning the variable as number in typescript?
Code:

```<code>function fun(example:string|number|string[])
{
    if(typeof example == "string")
    {
        console.log("Example is String " + example);
    }
    else if(typeof example == "number")
    {
        console.log("Example is Number " + example);
    }
    else{
        console.log("Example is String Array " + example);
    }
}
var example:number; //Here i have assigned the var as a number
fun(example);
</code>```

Output:

```<code>Example is String Array undefined
</code>```

I have given the var type as a "number", but why the output screen shows "String array"?

答:
In TypeScript, indeed we can assign the "type" to a variable at the start; however, as we all know that ultimately a TypeScript file gets converted into the JavaScript (so that our browser can understand and work over that) and the default value assigned to a variable which hasn't assigned any value is undefined.

var example:number; line assigns the variable type but doesn't assigns the value to variable example and hence it gets the undefined at execution time and enters the last else condition and prints: Example is String Array undefined.

Body:
Code:

function fun(example:string|number|string[])
{
    if(typeof example == "string")
    {
        console.log("Example is String " + example);
    }
    else if(typeof example == "number")
    {
        console.log("Example is Number " + example);
    }
    else{
        console.log("Example is String Array " + example);
    }
}
var example:number; //Here i have assigned the var as a number
fun(example);

Output:

Example is String Array undefined

I have given the var type as a "number", but why the output screen shows "String array"?


问:
How to specify a different return type based on number of arguments passed to rest parameter function
How do I create an arrow function with rest parameters that have different return types based on the number of passed arguments?

E.g. I want a safeId() that has the following return types:

```<code>safeId() // () => string
safeId('foo') // (obj: any) => string
safeId('foo', 4, {}, ['hi']) // (...obj: any[]) => string[]

// Currently my return type isn't specific:
const safeId = (...objects: any[]) => string | string[] => {
  // Simplified
  if (objects.length > 1) return sanitizedObjectIds(objects) // string[]
  return 'id'
}
</code>```

答:
Simply declare all the forms of your function, and be careful that the implementation can handle all of them:

function safeId(id?: string): string
function safeId(id: string, num: number, ...rest: any[]): string[]
function safeId(...objects: any[]): string | string[] {
  // Simplified
  if (objects.length > 1) return sanitizedObjectIds(objects) // string[]
  return 'id'
}
```

<p>Note that to prevent all ambiguity, I added a 2nd mandatory parameter in the second form of the function. If not, this form would also fit with a single parameter (rest would simply be an empty array).</p>

<p>EDIT: If you want to use arrow function, unfortunately, compiler will complain about the return type. IMHO, this is a bug from <em>TypeScript</em>. So, the only way to do it is to disable type check by returning <code>any</code>:</p>

<pre class="lang-js prettyprint-override"><code>type SafeId = {
  (id?: string): string
  (id: string, num: number, ...rest: any[]): string[]
}

const safeId: SafeId = (...objects: any[]): any => {
  // Simplified
  if (objects.length > 1) return sanitizedObjectIds(objects) // string[]
  return 'id'
}
</code>```

Note that there is an open issue for this in TypeScript repository.

Body:
How do I create an arrow function with rest parameters that have different return types based on the number of passed arguments?

E.g. I want a safeId() that has the following return types:

safeId() // () => string
safeId('foo') // (obj: any) => string
safeId('foo', 4, {}, ['hi']) // (...obj: any[]) => string[]

// Currently my return type isn't specific:
const safeId = (...objects: any[]) => string | string[] => {
  // Simplified
  if (objects.length > 1) return sanitizedObjectIds(objects) // string[]
  return 'id'
}

Body:
Simply declare all the forms of your function, and be careful that the implementation can handle all of them:

function safeId(id?: string): string
function safeId(id: string, num: number, ...rest: any[]): string[]
function safeId(...objects: any[]): string | string[] {
  // Simplified
  if (objects.length > 1) return sanitizedObjectIds(objects) // string[]
  return 'id'
}

Note that to prevent all ambiguity, I added a 2nd mandatory parameter in the second form of the function. If not, this form would also fit with a single parameter (rest would simply be an empty array).

EDIT: If you want to use arrow function, unfortunately, compiler will complain about the return type. IMHO, this is a bug from TypeScript. So, the only way to do it is to disable type check by returning any:

type SafeId = {
  (id?: string): string
  (id: string, num: number, ...rest: any[]): string[]
}

const safeId: SafeId = (...objects: any[]): any => {
  // Simplified
  if (objects.length > 1) return sanitizedObjectIds(objects) // string[]
  return 'id'
}

Note that there is an open issue for this in TypeScript repository.


问:
Python ThreadPoolExecutor with continuous unbounded input
I have a folder in a server which will continuously receive some files throughout the day. I need to watch the directory and once a file is received need to start some processing on that file. Sometime, processing can take a bit longer based on file size which can reach upto 20 GB.

I am using concurrent.futures.ThreadPoolExecutor to process multiple files at a go. But, I need some help in understanding how to handle the below scenario :-

I have received 5 files (4 small and 1 huge file) at once, ThreadPoolExecutor picks up all the 5 files for processing. It takes few seconds to process 4 small files but it takes 20 mins to process the large file. Now, I have another 10 files waiting in the folder while the large file is being processed.

I have set max_workers=5 but only one ThreadPoolExecutor worker runs now to process the large file, which blocks the execution of next set of files. How can we start processing the other files while 4 workers are free that time.

import os
import time
import random
import concurrent.futures
import datetime
import functools

def process_file(file1, input_num):
    # Do some processing
    os.remove(os.path.join('C:\\temp\\abcd',file1))
    time.sleep(10)

def main():
    print("Start Time is ",datetime.datetime.now())

    #It will be a continuous loop which will watch a directory for incoming file
    while True:
        #Get the list of files in directory
        file_list = os.listdir('C:\\temp\\abcd')
        print("file_list is", file_list)
        input_num = random.randint(1000000000,9999999999)

        with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
            process_file_arg = functools.partial(process_file, input_num = input_num)
            executor.map(process_file_arg, file_list)

        time.sleep(10)

if __name__ == '__main__':
    main()

```

the main() function continuously watch a directory and calls ThreadPoolExecutor

答:
I ran into the same problem, this answer may help you.

concurrent.futures.wait returns the futures into a named 2-tuple of sets, done and not_done, so we can remove done part and add new tasks into the not_done thread list to make the parallel job be continuous, here is an example snippet:

```<code>thread_list = []
with open(input_filename, 'r') as fp_in:
    with concurrent.futures.ThreadPoolExecutor(max_workers=THREAD_LIMIT) as executor:
        for para_list in fp_in:
            thread_list.append(executor.submit(your_thread_func, para_list))
            if len(thread_list) >= THREAD_LIMIT:
                done, not_done = concurrent.futures.wait(thread_list, timeout=1,
                                                     return_when=concurrent.futures.FIRST_COMPLETED)
                # consume finished
                done_res = [i.result() for i in done]
                # and keep unfinished
                thread_list = list(not_done)
</code>```

Body:
I have a folder in a server which will continuously receive some files throughout the day. I need to watch the directory and once a file is received need to start some processing on that file. Sometime, processing can take a bit longer based on file size which can reach upto 20 GB.

I am using concurrent.futures.ThreadPoolExecutor to process multiple files at a go. But, I need some help in understanding how to handle the below scenario :-

I have received 5 files (4 small and 1 huge file) at once, ThreadPoolExecutor picks up all the 5 files for processing. It takes few seconds to process 4 small files but it takes 20 mins to process the large file. Now, I have another 10 files waiting in the folder while the large file is being processed.

I have set max_workers=5 but only one ThreadPoolExecutor worker runs now to process the large file, which blocks the execution of next set of files. How can we start processing the other files while 4 workers are free that time.

import os
import time
import random
import concurrent.futures
import datetime
import functools

def process_file(file1, input_num):
    # Do some processing
    os.remove(os.path.join('C:\\temp\\abcd',file1))
    time.sleep(10)

def main():
    print("Start Time is ",datetime.datetime.now())

    #It will be a continuous loop which will watch a directory for incoming file
    while True:
        #Get the list of files in directory
        file_list = os.listdir('C:\\temp\\abcd')
        print("file_list is", file_list)
        input_num = random.randint(1000000000,9999999999)

        with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
            process_file_arg = functools.partial(process_file, input_num = input_num)
            executor.map(process_file_arg, file_list)

        time.sleep(10)

if __name__ == '__main__':
    main()

the main() function continuously watch a directory and calls ThreadPoolExecutor

Body:
I ran into the same problem, this answer may help you.

concurrent.futures.wait returns the futures into a named 2-tuple of sets, done and not_done, so we can remove done part and add new tasks into the not_done thread list to make the parallel job be continuous, here is an example snippet:

thread_list = []
with open(input_filename, 'r') as fp_in:
    with concurrent.futures.ThreadPoolExecutor(max_workers=THREAD_LIMIT) as executor:
        for para_list in fp_in:
            thread_list.append(executor.submit(your_thread_func, para_list))
            if len(thread_list) >= THREAD_LIMIT:
                done, not_done = concurrent.futures.wait(thread_list, timeout=1,
                                                     return_when=concurrent.futures.FIRST_COMPLETED)
                # consume finished
                done_res = [i.result() for i in done]
                # and keep unfinished
                thread_list = list(not_done)


问:
What does this one liner means in lambda function in Python?
I'm stuck in this lambda one-liner. This one-liner is for sorting the string in a list but don't know how this actually functions? Kindly help me to understand this.
This is the motive of the below function:

sort_item_list_by_author(): Accepts the new list of books and returns it sorted in the alphabetical order of their author names. Note: While sorting the author names in alphabetical order, ignore the special characters including space, if there are any.

```<code>    def sort_item_list_by_author(self,new_item_list):
       new_item_list.sort(key=lambda x:''.join(e for e in x.get_author_name() if e.isalnum())) #problem causing line

    item11=Item("Broken Wing","Sarojini Naidu",2012)
    item12=Item("Guide","R.K.Narayanan",2001)
    item13=Item("Indian Summers","John Mathews",2001)
    item14=Item("Innocent in Death","J.D.Robb",2010)
    item15=Item("Life of Pi","Yann Martel",2010 )
    item16=Item("Sustainability","Johny",2016)
    item17=Item("Look Ahead","E.M.Freddy",2012 )

    new_item_list=[item11,item12,item13,item14,item15,item16,item17]
    new_item_list_sorted=library.sort_item_list_by_author(new_item_list)
</code>```

答:
lambda you are talking about is the key to the sort function, which means that it is being you used to compare the values in the list.

lambda x:''.join(e for e in x.get_author_name() if e.isalnum()

So for every element of the list, this lambda function is called. Here x represents the parameter of the lambda function(in this case, it is list item).
Now the body of the lambda function is pretty simple in itself, we get the author name, and loop over it character by character, and select only those characters which are alpha-numeric(means we are ignoring spaces and all), then we join all the obtained chars in one string.

Using the lambda function, for all the items in the list, such strings(alpha-num part of author's name) are created, which is used for sorting out the list.
The lambda translates to something like this:

```<code>x = item() #fill the fields here
s = ''
for e in x.get_author_name():
    if e.isalnum():
       s += e
</code>```

Body:
I'm stuck in this lambda one-liner. This one-liner is for sorting the string in a list but don't know how this actually functions? Kindly help me to understand this.
This is the motive of the below function:

sort_item_list_by_author(): Accepts the new list of books and returns it sorted in the alphabetical order of their author names. Note: While sorting the author names in alphabetical order, ignore the special characters including space, if there are any.

    def sort_item_list_by_author(self,new_item_list):
       new_item_list.sort(key=lambda x:''.join(e for e in x.get_author_name() if e.isalnum())) #problem causing line

    item11=Item("Broken Wing","Sarojini Naidu",2012)
    item12=Item("Guide","R.K.Narayanan",2001)
    item13=Item("Indian Summers","John Mathews",2001)
    item14=Item("Innocent in Death","J.D.Robb",2010)
    item15=Item("Life of Pi","Yann Martel",2010 )
    item16=Item("Sustainability","Johny",2016)
    item17=Item("Look Ahead","E.M.Freddy",2012 )

    new_item_list=[item11,item12,item13,item14,item15,item16,item17]
    new_item_list_sorted=library.sort_item_list_by_author(new_item_list)

Body:
lambda you are talking about is the key to the sort function, which means that it is being you used to compare the values in the list.

lambda x:''.join(e for e in x.get_author_name() if e.isalnum()

So for every element of the list, this lambda function is called. Here x represents the parameter of the lambda function(in this case, it is list item).
Now the body of the lambda function is pretty simple in itself, we get the author name, and loop over it character by character, and select only those characters which are alpha-numeric(means we are ignoring spaces and all), then we join all the obtained chars in one string.

Using the lambda function, for all the items in the list, such strings(alpha-num part of author's name) are created, which is used for sorting out the list.
The lambda translates to something like this:

x = item() #fill the fields here
s = ''
for e in x.get_author_name():
    if e.isalnum():
       s += e


问:
iPython: print() function supresses the direct variable output
It must be something simple that I just missed, but I'm still struggling to find the answer.
I use iPuthon. Suppose, I copied several lines at once from some other source, like a webpage. Also suppose, that the fragment has a variable on a separate line, in order to print it out (in accord with Python's syntax):

```<code>myList = ['Abc', 25, 'Yes', 'No']
myList
</code>```

The result, as I expect it (and as it comes out in fact):

```<code>Out[5]: ['Abc', 25, 'Yes', 'No']
</code>```

Now, let's add just one line to the end of this fragment:

```<code>myList = ['Abc', 25, 'Yes', 'No']
myList
print('voila!')
</code>```

and all of a sudden, there will be no trace of the list printed, but only the print('voila') output is visible:

```<code>In [6]: myList = ['Abc', 25, 'Yes', 'No']
   ...: myList
   ...: print('voila!')
voila!
</code>```

Exactly same thing happens in Jupyter, or in Komodo IDE, except there I don't even have a possibility (well, generally speaking) to enter the lines one-by-one. The workaround I was using, is to use print() function to output the object, but this is lousy - the native output in most cases is way more advanced.
My understanding is, the print() function spits it over the top of old output, thus in fact replacing what was there, but this, true or false, still doesn't help.
I tried googling, but w/no success - maybe, I could not formulate the search string well enough - you know, it is an art of a kind..
Please poke my nose into it!

答:
I'm not sure what's the issue.  In an IPython session:

```<code>In [61]: x = [1,2,3]
    ...: x
    ...:
    ...:
Out[61]: [1, 2, 3]
In [62]: x = [1,2,3]
    ...: x
    ...: print(x)
[1, 2, 3]
In [63]: None
In [64]:
</code>```

Out[61] is displayed, and added to the out history.  It's the last line of the of the [61] block.  In [62] the last line is a print, which displays text, and returns None.  None is not displayed or added to Out.

A plain interactive Python session the history is more limited, just '_'.  But even there the print output is not cached.

Here's further evidence that the last line (or last statement) is displayed and cached.  The print in [62] does over write x:

```<code>In [64]: x = [1,2,3]
    ...: x
    ...: 'yes'
Out[64]: 'yes'
In [65]: _
Out[65]: 'yes
In [66]: x = [1,2,3]; x; 'yes'
Out[66]: 'yes'
</code>```

I'm not quite sure what you mean by "native output", but may be it's the repr display.  The default for print is the str, which may be more compact.  For example with an array:

```<code>In [67]: x = np.array([1,2,3])
In [68]: print(x)
[1 2 3]
In [69]: x
Out[69]: array([1, 2, 3])
In [70]: print(repr(x))
array([1, 2, 3])
In [71]: print(str(x))
[1 2 3]
</code>```

I usually use the terminal ipython so don't see the fancier display.  But I just realized that in a notebook I can use

```<code>display(df)
print(df)
</code>```

and get both the highlighted display and the plain text.

in the plain console:

```<code>In [84]: display(x);print(x)
array([1, 2, 3])
[1 2 3]
</code>```

Body:
It must be something simple that I just missed, but I'm still struggling to find the answer.
I use iPuthon. Suppose, I copied several lines at once from some other source, like a webpage. Also suppose, that the fragment has a variable on a separate line, in order to print it out (in accord with Python's syntax):

myList = ['Abc', 25, 'Yes', 'No']
myList

The result, as I expect it (and as it comes out in fact):

Out[5]: ['Abc', 25, 'Yes', 'No']

Now, let's add just one line to the end of this fragment:

myList = ['Abc', 25, 'Yes', 'No']
myList
print('voila!')

and all of a sudden, there will be no trace of the list printed, but only the print('voila') output is visible:

In [6]: myList = ['Abc', 25, 'Yes', 'No']
   ...: myList
   ...: print('voila!')
voila!

Exactly same thing happens in Jupyter, or in Komodo IDE, except there I don't even have a possibility (well, generally speaking) to enter the lines one-by-one. The workaround I was using, is to use print() function to output the object, but this is lousy - the native output in most cases is way more advanced.
My understanding is, the print() function spits it over the top of old output, thus in fact replacing what was there, but this, true or false, still doesn't help.
I tried googling, but w/no success - maybe, I could not formulate the search string well enough - you know, it is an art of a kind..
Please poke my nose into it!

Body:
I'm not sure what's the issue.  In an IPython session:

In [61]: x = [1,2,3]
    ...: x
    ...:
    ...:
Out[61]: [1, 2, 3]
In [62]: x = [1,2,3]
    ...: x
    ...: print(x)
[1, 2, 3]
In [63]: None
In [64]:

Out[61] is displayed, and added to the out history.  It's the last line of the of the [61] block.  In [62] the last line is a print, which displays text, and returns None.  None is not displayed or added to Out.

A plain interactive Python session the history is more limited, just '_'.  But even there the print output is not cached.

Here's further evidence that the last line (or last statement) is displayed and cached.  The print in [62] does over write x:

In [64]: x = [1,2,3]
    ...: x
    ...: 'yes'
Out[64]: 'yes'
In [65]: _
Out[65]: 'yes
In [66]: x = [1,2,3]; x; 'yes'
Out[66]: 'yes'

I'm not quite sure what you mean by "native output", but may be it's the repr display.  The default for print is the str, which may be more compact.  For example with an array:

In [67]: x = np.array([1,2,3])
In [68]: print(x)
[1 2 3]
In [69]: x
Out[69]: array([1, 2, 3])
In [70]: print(repr(x))
array([1, 2, 3])
In [71]: print(str(x))
[1 2 3]

I usually use the terminal ipython so don't see the fancier display.  But I just realized that in a notebook I can use

display(df)
print(df)

and get both the highlighted display and the plain text.

in the plain console:

In [84]: display(x);print(x)
array([1, 2, 3])
[1 2 3]


问:
Ban and Unban commands to work in all servers
I've been programming a discord bot letely, and for its ban command here is the code i use:

```<code>@client.command(aliases=['Ban'])
async def ban(ctx, member: discord.Member, days: int = 1):
    if get(ctx.author.roles, id=548841535223889923):
        await member.ban(delete_message_days=days)
        await ctx.send("Banned {}".format(ctx.author))
    else:
        await ctx.send(ctx.author.mention + " you don't have permission to use this command.".format(ctx.author))
</code>```

However, if i try to use this on other servers, it just tells me i dont have the required role..
So how do I get the role ID for a new server the bot joins automatically or is there some other way to make this work?

答:
you can use a has_permission, like this:

@client.command(aliases=["Ban"])
@commands.has_permission(administrator=True)
async def ban(ctx, member: discord.Member, days: int = 1):
    await member.ban(delete_message_days=days)
    await ctx.send("Banned {}".format(ctx.author))
```

<p>You can then add a missing permissions error handler:</p>

<pre class="lang-py prettyprint-override"><code>@client.event
async def on_command_error(ctx, error):
  if isinstance(error, commands.MissingPermissions):
    await ctx.send("You do not have the permissions required for this command.")
    return

  raise error
</code>```

Body:
I've been programming a discord bot letely, and for its ban command here is the code i use:

@client.command(aliases=['Ban'])
async def ban(ctx, member: discord.Member, days: int = 1):
    if get(ctx.author.roles, id=548841535223889923):
        await member.ban(delete_message_days=days)
        await ctx.send("Banned {}".format(ctx.author))
    else:
        await ctx.send(ctx.author.mention + " you don't have permission to use this command.".format(ctx.author))

However, if i try to use this on other servers, it just tells me i dont have the required role..
So how do I get the role ID for a new server the bot joins automatically or is there some other way to make this work?

Body:
you can use a has_permission, like this:

@client.command(aliases=["Ban"])
@commands.has_permission(administrator=True)
async def ban(ctx, member: discord.Member, days: int = 1):
    await member.ban(delete_message_days=days)
    await ctx.send("Banned {}".format(ctx.author))

You can then add a missing permissions error handler:

@client.event
async def on_command_error(ctx, error):
  if isinstance(error, commands.MissingPermissions):
    await ctx.send("You do not have the permissions required for this command.")
    return

  raise error


问:
Azure DevOps IIS Deploy Pipelines - where do variable values source from in templates?
I oversee some teams, and one team has an Azure DevOps pipeline leveraging the YAML pipeline setup. Unfortunately, due to Covid-19, we have had to release a lot of staff, including the entire DevOps team. That has left my team with no DevOps knowledge and an established YAML pipeline that we're struggling to get acquainted with.

So far, we've make progress and have learned a lot. However, while trying to troubleshoot an IIS web site deployment task, we have had some trouble figuring out where some of the parameters passed to each stage are sourced from.

For example, a snippet from a template:

```<code>      - task: IISWebAppManagementOnMachineGroup@0
        displayName: 'Create Or Update IIS Website'
        inputs:
          EnableIIS: true
          WebsiteName: ${{ parameters.WebsiteName }}
          WebsitePhysicalPath: ${{ parameters.WebsitePhysicalPath }}
          AddBinding: ${{ parameters.AddWebsiteBinding }}
          **Bindings: ${{ parameters.WebsiteBindings }}**
          CreateOrUpdateAppPoolForWebsite: ${{ parameters.CreateOrUpdateAppPoolForWebsite }}
          AppPoolNameForWebsite: ${{ parameters.WebsiteName }}
          DotNetVersionForWebsite: ${{ parameters.DotNetVersionForWebsite }}
          PipeLineModeForWebsite: ${{ parameters.PipeLineModeForWebsite }}
          AppPoolIdentityForWebsite: ${{ parameters.AppPoolIdentityForWebsite }}
          AppPoolUsernameForWebsite: ${{ parameters.AppPoolUsernameForWebsite }}
</code>```

"WebsiteBindings" is one that we're interested in ... and I can work back to where the template is being used, and see this:

WebsiteBindings: '$(DevOps:IISWebsiteBindings)'

Problem is - I want to see what is being passed in here, and I cannot seem to figure out where the above value comes from. I am sure the answer is simple, but none of us have any Azzure DevOps experience, and we're kind of stuck on this simple problem. Is there anything in the above syntax that can clue me in as to where the values are located?

Other areas in the pipeline are referencing Azure AppConfig Key/Value storage for config transforms, and there are some pipeline variables set, but none line up with any of the values I am looking for.

Can anyone provide any insight here? Thank you in advance.

答:
Problem is - I want to see what is being passed in here, and I cannot
  seem to figure out where the above value comes from.

You can add a powershell task and output these variables through Write-Host to see what is passed here . For example : Write-Host "$(parameters.WebsiteBindings)"

According to the syntax of ${{ parameters.WebsiteBindings }}, I speculate that this variable comes from the template parameters.

In a pipeline, template expression variables (${{ variables.var }}) get processed at compile time, before runtime starts. You can use template expression syntax to expand both template parameters and variables . Template expressions are designed for reusing parts of YAML as templates.

Body:
I oversee some teams, and one team has an Azure DevOps pipeline leveraging the YAML pipeline setup. Unfortunately, due to Covid-19, we have had to release a lot of staff, including the entire DevOps team. That has left my team with no DevOps knowledge and an established YAML pipeline that we're struggling to get acquainted with.

So far, we've make progress and have learned a lot. However, while trying to troubleshoot an IIS web site deployment task, we have had some trouble figuring out where some of the parameters passed to each stage are sourced from.

For example, a snippet from a template:

      - task: IISWebAppManagementOnMachineGroup@0
        displayName: 'Create Or Update IIS Website'
        inputs:
          EnableIIS: true
          WebsiteName: ${{ parameters.WebsiteName }}
          WebsitePhysicalPath: ${{ parameters.WebsitePhysicalPath }}
          AddBinding: ${{ parameters.AddWebsiteBinding }}
          **Bindings: ${{ parameters.WebsiteBindings }}**
          CreateOrUpdateAppPoolForWebsite: ${{ parameters.CreateOrUpdateAppPoolForWebsite }}
          AppPoolNameForWebsite: ${{ parameters.WebsiteName }}
          DotNetVersionForWebsite: ${{ parameters.DotNetVersionForWebsite }}
          PipeLineModeForWebsite: ${{ parameters.PipeLineModeForWebsite }}
          AppPoolIdentityForWebsite: ${{ parameters.AppPoolIdentityForWebsite }}
          AppPoolUsernameForWebsite: ${{ parameters.AppPoolUsernameForWebsite }}

"WebsiteBindings" is one that we're interested in ... and I can work back to where the template is being used, and see this:

WebsiteBindings: '$(DevOps:IISWebsiteBindings)'

Problem is - I want to see what is being passed in here, and I cannot seem to figure out where the above value comes from. I am sure the answer is simple, but none of us have any Azzure DevOps experience, and we're kind of stuck on this simple problem. Is there anything in the above syntax that can clue me in as to where the values are located?

Other areas in the pipeline are referencing Azure AppConfig Key/Value storage for config transforms, and there are some pipeline variables set, but none line up with any of the values I am looking for.

Can anyone provide any insight here? Thank you in advance.


问:
Confusing output of two different Char Array

Problem : Although I declared two char strings , whose contents are the same , Outputs are different.

#include <stdio.h>

int main(void)
{
    /* Initialization of two different array that We deal with */

    char arr1[10]={'0','1','2','3','4','5','6','7','8','9'};
    char arr2[10]="0123456789";

    /* Initialization End */

    for(int i = 0 ; i < 11 ; ++i)
    {
        printf("arr1[%d] is %c \t\t",i,arr1[i]);
        printf("arr2[%d] is %c\n",i,arr2[i]);

        if(arr1[i]=='\0')
            printf("%d . character is \\0 of arr1 \n",i);

        if(arr2[i]=='\0')
            printf("%d . character is \\0 of arr2 \n",i);
    }

    return 0;
}
```

<blockquote>
  <p><strong>Expectation</strong> : I expected that both if statements are going to be true for any kind of value of 'i'.</p>
</blockquote>

<p><strong>Output :</strong> <em>It is an output that I got it.</em></p>

<pre class="lang-c prettyprint-override"><code>arr1[0] is 0        arr2[0] is 0
arr1[1] is 1        arr2[1] is 1
arr1[2] is 2        arr2[2] is 2
arr1[3] is 3        arr2[3] is 3
arr1[4] is 4        arr2[4] is 4
arr1[5] is 5        arr2[5] is 5
arr1[6] is 6        arr2[6] is 6
arr1[7] is 7        arr2[7] is 7
arr1[8] is 8        arr2[8] is 8
arr1[9] is 9        arr2[9] is 9
arr1[10] is 0       arr2[10] is
10 . character is \0 of arr2
</code>```

答:
when a character array is initialized with a double quoted string and array size is not specified, compiler automatically allocates one extra space for string terminator ‘\0’

Ref

Body:
Problem : Although I declared two char strings , whose contents are the same , Outputs are different.

#include <stdio.h>

int main(void)
{
    /* Initialization of two different array that We deal with */

    char arr1[10]={'0','1','2','3','4','5','6','7','8','9'};
    char arr2[10]="0123456789";

    /* Initialization End */

    for(int i = 0 ; i < 11 ; ++i)
    {
        printf("arr1[%d] is %c \t\t",i,arr1[i]);
        printf("arr2[%d] is %c\n",i,arr2[i]);

        if(arr1[i]=='\0')
            printf("%d . character is \\0 of arr1 \n",i);

        if(arr2[i]=='\0')
            printf("%d . character is \\0 of arr2 \n",i);
    }

    return 0;
}

Expectation : I expected that both if statements are going to be true for any kind of value of 'i'.

Output : It is an output that I got it.

arr1[0] is 0        arr2[0] is 0
arr1[1] is 1        arr2[1] is 1
arr1[2] is 2        arr2[2] is 2
arr1[3] is 3        arr2[3] is 3
arr1[4] is 4        arr2[4] is 4
arr1[5] is 5        arr2[5] is 5
arr1[6] is 6        arr2[6] is 6
arr1[7] is 7        arr2[7] is 7
arr1[8] is 8        arr2[8] is 8
arr1[9] is 9        arr2[9] is 9
arr1[10] is 0       arr2[10] is
10 . character is \0 of arr2


问:
Xcode- Image View Not Changing
I am trying to update a UIImageView using a for loop, however, the image only shows up on the last iteration of the loop. The code is intended to display a QR code, wait 4 seconds, then display a different QR code, however it only shows the last QR code.</p>

```<code>            for record in 1...importedrecords.count-3 {
            let qrCode = importedrecords[record][0] + " " + importedrecords[record][1] + " " + importedrecords[record][7]
            print("QR Code is: " + qrCode)

            let data = qrCode.data(using: .ascii, allowLossyConversion: false)
            let filter = CIFilter(name: "CIQRCodeGenerator")
            filter?.setValue(data, forKey: "InputMessage")

            let ciImage = filter?.outputImage

            let transform = CGAffineTransform(scaleX: 10, y: 10)
            let transformImage = ciImage?.transformed(by: transform)

            let image = UIImage(ciImage: transformImage!)
            self.myImageView.image = image

            do {
                sleep(4)
            }
        }
</code>```

答:
I suggest to use Timer for this. Using sleep is not recommended, especially on the main thread, since it stops all the work being done on the thread.

```<code>    var timer: Timer?
    var recordIndex = 0
    var importedRecords = [[String]]()

    // Call this when you want to start updating
    func startUpdate() {
        timer = Timer.scheduledTimer(timeInterval: 4, target: self, selector:#selector(updateQR), userInfo: nil, repeats: true)
    }

    // Call this when you want to stop and reset updating
    func stopUpdate() {
        timer?.invalidate()
        recordIndex = 0
    }

    @objc
    func updateQR() {
        let qrCode = importedRecords[recordIndex][0] + " " + importedRecords[recordIndex][1] + " " + importedRecords[recordIndex][7]
        print("QR Code is: " + qrCode)

        let data = qrCode.data(using: .ascii, allowLossyConversion: false)
        let filter = CIFilter(name: "CIQRCodeGenerator")
        filter?.setValue(data, forKey: "InputMessage")

        let ciImage = filter?.outputImage
        let transform = CGAffineTransform(scaleX: 10, y: 10)
        let transformImage = ciImage?.transformed(by: transform)

        let image = UIImage(ciImage: transformImage!)
        myImageView.image = image

        // This will prevent out of bounds crash
        if recordIndex < importedRecords.count {
            recordIndex += 1
        } else {
            stopUpdate()
        }
    }
</code>```

Title: Xcode- Image View Not Changing

Body:
I am trying to update a UIImageView using a for loop, however, the image only shows up on the last iteration of the loop. The code is intended to display a QR code, wait 4 seconds, then display a different QR code, however it only shows the last QR code.

            for record in 1...importedrecords.count-3 {
            let qrCode = importedrecords[record][0] + " " + importedrecords[record][1] + " " + importedrecords[record][7]
            print("QR Code is: " + qrCode)

            let data = qrCode.data(using: .ascii, allowLossyConversion: false)
            let filter = CIFilter(name: "CIQRCodeGenerator")
            filter?.setValue(data, forKey: "InputMessage")

            let ciImage = filter?.outputImage

            let transform = CGAffineTransform(scaleX: 10, y: 10)
            let transformImage = ciImage?.transformed(by: transform)

            let image = UIImage(ciImage: transformImage!)
            self.myImageView.image = image

            do {
                sleep(4)
            }
        }

Body:
I suggest to use Timer for this. Using sleep is not recommended, especially on the main thread, since it stops all the work being done on the thread.

    var timer: Timer?
    var recordIndex = 0
    var importedRecords = [[String]]()

    // Call this when you want to start updating
    func startUpdate() {
        timer = Timer.scheduledTimer(timeInterval: 4, target: self, selector:#selector(updateQR), userInfo: nil, repeats: true)
    }

    // Call this when you want to stop and reset updating
    func stopUpdate() {
        timer?.invalidate()
        recordIndex = 0
    }

    @objc
    func updateQR() {
        let qrCode = importedRecords[recordIndex][0] + " " + importedRecords[recordIndex][1] + " " + importedRecords[recordIndex][7]
        print("QR Code is: " + qrCode)

        let data = qrCode.data(using: .ascii, allowLossyConversion: false)
        let filter = CIFilter(name: "CIQRCodeGenerator")
        filter?.setValue(data, forKey: "InputMessage")

        let ciImage = filter?.outputImage
        let transform = CGAffineTransform(scaleX: 10, y: 10)
        let transformImage = ciImage?.transformed(by: transform)

        let image = UIImage(ciImage: transformImage!)
        myImageView.image = image

        // This will prevent out of bounds crash
        if recordIndex < importedRecords.count {
            recordIndex += 1
        } else {
            stopUpdate()
        }
    }


问:
How do I modify my .gitignore file by adding !*.css at the end?
I'm new to pulling/pushing code and gitignore, and I can't figure out how to modify the .gitignore file.</p>

答:
You can simply do:

```<code>echo "!*.css" >> .gitignore
git add .gitignore
git commit -m "Whitelist css files"
git push -u origin master
</code>```

That would update your .gitignore file.

Body:
You can simply do:

echo "!*.css" >> .gitignore
git add .gitignore
git commit -m "Whitelist css files"
git push -u origin master

That would update your .gitignore file.


问:
How can I request pipeline processors in Apache Wicket?
Is there any way to request pipeline processors in Apache Wicket? Possibly with an open-source framework that integrates with Wicket?

I want to check requests before my web pages are rendered.

答:
In Wicket 1.4.x, you have to extend [Web]RequestCycle, so that you an override the hook methods (onBeginRequest(), onEndRequest(), onAfterTargetsDetached(), etc.), and override Application.newRequestCycle() to return the custom class.

In Wicket 1.5.x, this mechanism has been refactored, so you can just implement the RequestCycleListener, which provides the same hooks. This new mechanism is much better, since you can compose and reuse listeners.