问:
Issues exposing Http Client logs with Log4j2
Problems exposing HTTP client logs through Log4j2.
I was able to expose the logs with log4j v1, but it's not working with log4j2.

Checked the transactive dependencies of http client v4 and it uses common logging. So I passed log4j-jcl.jar at runtime since its a bridge. But it's not working

Dependencies used:

Http Dependencies:

```<code><dependency>
                <groupId>com.dictao.util</groupId>
                <artifactId>dictao-util-net</artifactId>
                <version>${dictao.common.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
                <version>4.5.6</version>
           </dependency>
           <dependency>
            <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpmime</artifactId>
                <version>4.5.6</version>
           </dependency>
</code>```

Bridge Dependency:

```<code><dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-jcl</artifactId>
  <version>2.11.2</version>
<scope>runtime</scope>
</dependency>
</code>```

For Log4j1:

```<code>log4j.logger.org.apache.http.impl.conn=DEBUG
log4j.logger.org.apache.http.impl.client=DEBUG
log4j.logger.org.apache.http.client=DEBUG
log4j.logger.org.apache.http=DEBUG
</code>```

Passing the same thing in Log4j2,but no result.

Output: No error and no log file is generated.

答:
You need to add log4j-core to your dependencies

Log4j2 is divided into api and core module (whereas log4j1 was monolitihic).
When you add your bridge dependency, you transitively pull in only log4j2 api, but there is no actual logging engine (log4j-core module).

To back my words: http://central.maven.org/maven2/org/apache/logging/log4j/log4j-jcl/2.11.2/log4j-jcl-2.11.2.pom

Body:
Problems exposing HTTP client logs through Log4j2.
I was able to expose the logs with log4j v1, but it's not working with log4j2.

Checked the transactive dependencies of http client v4 and it uses common logging. So I passed log4j-jcl.jar at runtime since its a bridge. But it's not working

Dependencies used:

Http Dependencies:

<dependency>
                <groupId>com.dictao.util</groupId>
                <artifactId>dictao-util-net</artifactId>
                <version>${dictao.common.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
                <version>4.5.6</version>
           </dependency>
           <dependency>
            <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpmime</artifactId>
                <version>4.5.6</version>
           </dependency>

Bridge Dependency:

<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-jcl</artifactId>
  <version>2.11.2</version>
<scope>runtime</scope>
</dependency>

For Log4j1:

log4j.logger.org.apache.http.impl.conn=DEBUG
log4j.logger.org.apache.http.impl.client=DEBUG
log4j.logger.org.apache.http.client=DEBUG
log4j.logger.org.apache.http=DEBUG

Passing the same thing in Log4j2,but no result.

Output: No error and no log file is generated.


来源: stackexchange

问:
Connect from python3 - pyodbc (linux) to a firebird 2.5 (windows) ODBC DSN on remote machine
I am trying to connect to a customer's DB via ODBC. The ODBC DSN was setup on the the Windows machine. I don't know the path to the DB or the DB name so I have to rely on the DSN.

From what I've seen in general this does not seem to be possible, but I know Pervasive ODBC allows it and seems like MSSQL also allows it.

Question is, does Firebird 2.5 allow this? If it does could you please help me with the connection string

I've set up a Firebird DB on a local windows machine, created an ODBC DSN (and tested the connection locally).

I then tested connections from unixODBC (isql) and python pyodbc and they all connect fine, but I have to specify DB location and name and credentials.

I need to connect to the remote (windows) Firebird ODBC DSN from python 3.6 pyodbc (linux)

答:
What you want isn't possible*. An ODBC DSN exists only on the machine where it is defined. It is basically a connection configuration that is decoupled from your application, and your application references the configuration by a name.

You can't use a DSN remotely (if that were possible, that would be a pretty big security leak). You will need to define a DSN (or use a DSN-less connection string), on your specific machine to be able to use it from that machine.

Given you're using Python, consider using FDB or pyfirebirdsql instead of using pyODBC.

* Or at least, not possible without some middleware service on the remote machine that mediates between your application and the ODBC DSN on the remote machine.

ContentLicense: CC BY-SA 4.0


问:
How do you implement FIDO U2F using Webauthn APIs?
I am currently using the window.u2f APIs to implement U2F two-factor authentication with my website. These are natively available in Firefox (when the about:config flag is enabled) and through Chromium with the u2f-api.js library.

My implementation uses window.u2f.register(...) during key setup and window.u2f.sign(...) during logins.

I have read that the new Web Authentication API is backwards compatible and supports FIDO U2F as well, however, I cannot find any information on how to implement it. All the samples only seem to demonstrate FIDO2 passwordless login, which is not what I want to do.

How do I implement FIDO U2F with the equivalent window.u2f.register and window.u2f.sign functions using the Web Authentication APIs?

答:
You can read this to understand what they mean by backward compatibility

Thing to be highlighted for you

CTAP1/U2F authenticator returns a command error or improperly
  formatted CBOR response. For any failure, platform may fall back to
  CTAP1/U2F protocol.

WebAuthn communicates with authenticator by CBOR messages. If authenticator doesn't support FIDO2, authenticator will return error code, then WebAuthn will talk with authenticator by U2F raw messages.

You can just implement WebAuthn like what you have read. Web Authentication API

You can refer this for your implementation


问:
Using memtier_benchmark; every key is missed
My misses/sec are populated and there are no hits.

Data contains keys range from 1 to 300 K and data stored is string type

```<code>memtier_benchmark -s xx.xxx.xxx.xxx -p xxxxx -P redis -t 1 -n 1 --ratio 0:1 -c 1 -x 2 --key-pattern S:S --authenticate=xxxxxxx --key-prefix=
</code>```

答:
memtier_benchmark is pretty poorly documented in this regard. If you use it out of the box on first run, it won't simulate any cache hits, which is pretty useless in terms of a tool designed to test cache performance.

The 2 key parameters here are:

```<code>--key-pattern=[SET:GET]
--ratio=[SET:GET]
</code>```

--key-pattern defines the names given to keys that are set and the names of keys requested. For instance, if you use S:S, that means that the software will set the first key as memtier-0 and then immediately request memtier-1, then set memtier-1, then request memtier-2 (Go figure...). That's why you get a 100% miss result.

If you set R:R, that means the software will randomly set the digit in the keyname in both the Set and the Get. This will typically result in a miss ratio of > 90%, depending on how many clients and threads you set. If you're operating a cache with a miss ratio of > 90%, it questionable whether or not you should be running a cache at all, so again, this is pretty useless.

To simulate what a real world cache should be doing, you want to have a miss ratio of < 50%. To achieve this, you need to expand the number of Gets over Sets. The default for memtier_benchmark is 1:10, but again, on first run (or if you're persistently running this against a cold cache) with --key-pattern=S:S as default, you're still going to get a very high miss ratio. If you keep repeating the test against the same cache you are continually populating, you should see your miss ratio being to fall, but again, that may not be something you can rely on if you're testing in an ephemeral environment.

To get a lower miss ratio on a first run, I use:

```<code>--key-pattern=S:R --ratio=1:20
</code>```

This should result in a miss ratio < 50%. That's as good as I've been able to simulate. My actual cache will have a miss ratio of < 5%. I'm still trying to figure out a way to test that with memtier_benchmark.

Also, use --hide-histogram to get rid of the annoying dump of test results.

EDIT:

For a full blown 100% hit / 0% miss ratio, do the following:

Start with a cold, empty cache

Run a test that uses the -ratio= parameter so that only Sets are included in the test, in a very narrow key range:

```<code>--hide-histogram --key-pattern=S:S --key-minimum=1 --key-maximum=50 --ratio=1:0
</code>```

Now, run the test again, and this time, flip the ratio so that only Gets are included:

```<code>--hide-histogram --key-pattern=S:S --key-minimum=1 --key-maximum=50 --ratio=0:1
</code>```

You can then tune the hit/miss ratio by re-running both parts and expanding the --key-maximum= value

ContentLicense: CC BY-SA 3.0

Body:
My misses/sec are populated and there are no hits.

Data contains keys range from 1 to 300 K and data stored is string type

memtier_benchmark -s xx.xxx.xxx.xxx -p xxxxx -P redis -t 1 -n 1 --ratio 0:1 -c 1 -x 2 --key-pattern S:S --authenticate=xxxxxxx --key-prefix=

Body:
memtier_benchmark is pretty poorly documented in this regard. If you use it out of the box on first run, it won't simulate any cache hits, which is pretty useless in terms of a tool designed to test cache performance.

The 2 key parameters here are:

--key-pattern=[SET:GET]
--ratio=[SET:GET]

--key-pattern defines the names given to keys that are set and the names of keys requested. For instance, if you use S:S, that means that the software will set the first key as memtier-0 and then immediately request memtier-1, then set memtier-1, then request memtier-2 (Go figure...). That's why you get a 100% miss result.

If you set R:R, that means the software will randomly set the digit in the keyname in both the Set and the Get. This will typically result in a miss ratio of > 90%, depending on how many clients and threads you set. If you're operating a cache with a miss ratio of > 90%, it questionable whether or not you should be running a cache at all, so again, this is pretty useless.

To simulate what a real world cache should be doing, you want to have a miss ratio of < 50%. To achieve this, you need to expand the number of Gets over Sets. The default for memtier_benchmark is 1:10, but again, on first run (or if you're persistently running this against a cold cache) with --key-pattern=S:S as default, you're still going to get a very high miss ratio. If you keep repeating the test against the same cache you are continually populating, you should see your miss ratio being to fall, but again, that may not be something you can rely on if you're testing in an ephemeral environment.

To get a lower miss ratio on a first run, I use:

--key-pattern=S:R --ratio=1:20

This should result in a miss ratio < 50%. That's as good as I've been able to simulate. My actual cache will have a miss ratio of < 5%. I'm still trying to figure out a way to test that with memtier_benchmark.

Also, use --hide-histogram to get rid of the annoying dump of test results.

EDIT:

For a full blown 100% hit / 0% miss ratio, do the following:

Start with a cold, empty cache

Run a test that uses the -ratio= parameter so that only Sets are included in the test, in a very narrow key range:

--hide-histogram --key-pattern=S:S --key-minimum=1 --key-maximum=50 --ratio=1:0

Now, run the test again, and this time, flip the ratio so that only Gets are included:

--hide-histogram --key-pattern=S:S --key-minimum=1 --key-maximum=50 --ratio=0:1

You can then tune the hit/miss ratio by re-running both parts and expanding the --key-maximum= value


问:
Geolocation redirect to same page on different domain?
I'm trying to figure out how use geolocation to reidirect people from a .CA domain to a .US domain and keep them on the same page they were viewing.
For example if I post something to social media such as this: http://www.band-brand.ca/products/the-agonist-machine
US residents who click on that get redirected to the main .US domain.
How can I allow them to click on that link and just have it change over to the .US domain (http://www.band-brand.US/products/the-agonist-machine)
Here's the basic code I have:

```<code>     <script>
jQuery.ajax( {
  url: '//freegeoip.net/json/',
  type: 'POST',
  dataType: 'jsonp',
  success: function(location) {
    // If the visitor is browsing from United States.
    if (location.country_code === 'US') {
      // Redirect him to the american store.
      window.location.href = 'www.band-brand.us';
    }
  }
} );
</script>
</code>```

Thanks in advance for any help/advice,
Jon

答:
You can't change your domain name, without buying one. So, if you want to do that, you would have to buy a hosting plan that has unlimited plans. This will cost much more money, yes, but it achieves your goal.

Also, if you don't want to spend that much money, you can make subdomains, such as en.example.com. You can do this if your host provider allows. The cost is still somewhat expensive.

The best way to do this is by just putting the code on index.html, then, according to their country, redirect them to caindex.html, or such.

Body:
I'm trying to figure out how use geolocation to reidirect people from a .CA domain to a .US domain and keep them on the same page they were viewing.
For example if I post something to social media such as this: http://www.band-brand.ca/products/the-agonist-machine
US residents who click on that get redirected to the main .US domain.
How can I allow them to click on that link and just have it change over to the .US domain (http://www.band-brand.US/products/the-agonist-machine)
Here's the basic code I have:

Thanks in advance for any help/advice,
Jon


问:
Set Button Click handler with a DataTrigger
I'm trying to update some visual properties and the click handler on a button in response to the value of an enum. The visual properties are easy enough, but the click handler is giving me trouble.

The enum has 4 values: Launching, Launched, Terminating, Terminated. The button will launch or kill a process based on the current state. Here's what I have for the visual properties:

<Button>
    <Button.Style>

        </Style>
    </Button.Style>
</Button>
```

The problem is that Style.Triggers doesn't support EventSetter so I can't update Button.Click with this approach. Now, I could using a single click handler and branch based on the enum, but I want to understand what is possible from the XAML side.

I also tried creating 4 separate styles in Button.Resources then swapping out the styles with DataTrigger but then you end up trying to change the button style using a style and I'm not convinced that works either.

Is there a reasonable way to change Button.Click from XAML in response to a changing data value?

答:
Is there a reasonable way to change Button.Click from XAML in response to a changing data value?

No, there isn't. Using a single click handler and branch based on the enum sounds like a good idea. Alternatively, if you are familiar with the MVVM design pattern, you could bind to a command of a view model and handle your logic in there. It is indeed possible to set the Command property using a Setter in a Style, but remember that XAML is a markup language and just because you possible can do certain things in pure XAML, it doesn't mean that you always should.

Body:
I'm trying to update some visual properties and the click handler on a button in response to the value of an enum. The visual properties are easy enough, but the click handler is giving me trouble.

The enum has 4 values: Launching, Launched, Terminating, Terminated. The button will launch or kill a process based on the current state. Here's what I have for the visual properties:

<Button>
    <Button.Style>

        </Style>
    </Button.Style>
</Button>

The problem is that Style.Triggers doesn't support EventSetter so I can't update Button.Click with this approach. Now, I could using a single click handler and branch based on the enum, but I want to understand what is possible from the XAML side.

I also tried creating 4 separate styles in Button.Resources then swapping out the styles with DataTrigger but then you end up trying to change the button style using a style and I'm not convinced that works either.

Is there a reasonable way to change Button.Click from XAML in response to a changing data value?


问:
How to merge two rectangles given arrays of their coordinates?
Say I have two arrays of coordinates (x,y) of two rectangles, for example [(0, 0), (0, 1), (2, 1), (2, 0)] and [(1, 0), (1, 2), (3, 2), (3, 0)], how would I merge these two coordinate arrays into one array that represents the resulting polygon?

It might look like this, graphically:

```<code>   _ _
 _|_  |
|_|_|_|
</code>```

to

```<code>   _ _
 _|   |
|_ _ _|
</code>```

with resulting array [(0, 0), (0, 1), (1, 1), (1, 2), (3, 2), (3, 0)].

I'm trying to design some sort of merge algorithm but I'm not sure where to get started.

For input, there will be two arrays, and this method will return one merged array.

I'm just totally lost on where to start.

答:
First, make sure that the bottom-left corner of the first rectange isn't inside the other rectange. If it is, swap them. The corners can overlap or the corner can be on a side of the other rectange, it is fine.

Then, start walking alongside the left rectange counter clock wise, so to the right on the bottom side. check if you will end because you:

reach the end first

hit the left wall of the other rectangle first

If you reach the end, continue walking up on the right edge of the first rectange. If you hit the other rectange, walk down on the left wall of the other rectangle.

Repeat until you hot the left-bottom corner of the first rectangle again. At each point you need to remember: which way you are going / on which side are you going (since you always travel counter clock wise, one can easily be computed from the other) and what rectange are you on.

If you don't hit the other rectange at all on your walk, it means that the rectanges eigter don't touch, or the second rectangle is inside the first one.

Make sure do think through the ineualities that you will use, example:

```<code> ______
|  |_| |
|      |
|______|
</code>```

Should these 2 ractangle merge as one, or a 6-polygon with 3 lines in a straight line? Or should this:

```<code> _
|_|_
  |_|
</code>```

Be 2 diferent rectangles, or 1 8-polygon with 2 same points?

Body:
Say I have two arrays of coordinates (x,y) of two rectangles, for example [(0, 0), (0, 1), (2, 1), (2, 0)] and [(1, 0), (1, 2), (3, 2), (3, 0)], how would I merge these two coordinate arrays into one array that represents the resulting polygon?

It might look like this, graphically:

   _ _
 _|_  |
|_|_|_|

to

   _ _
 _|   |
|_ _ _|

with resulting array [(0, 0), (0, 1), (1, 1), (1, 2), (3, 2), (3, 0)].

I'm trying to design some sort of merge algorithm but I'm not sure where to get started.

For input, there will be two arrays, and this method will return one merged array.

I'm just totally lost on where to start.

Body:
First, make sure that the bottom-left corner of the first rectange isn't inside the other rectange. If it is, swap them. The corners can overlap or the corner can be on a side of the other rectange, it is fine.

Then, start walking alongside the left rectange counter clock wise, so to the right on the bottom side. check if you will end because you:

reach the end first

hit the left wall of the other rectangle first

If you reach the end, continue walking up on the right edge of the first rectange. If you hit the other rectange, walk down on the left wall of the other rectangle.

Repeat until you hot the left-bottom corner of the first rectangle again. At each point you need to remember: which way you are going / on which side are you going (since you always travel counter clock wise, one can easily be computed from the other) and what rectange are you on.

If you don't hit the other rectange at all on your walk, it means that the rectanges eigter don't touch, or the second rectangle is inside the first one.

Make sure do think through the ineualities that you will use, example:

 ______
|  |_| |
|      |
|______|

Should these 2 ractangle merge as one, or a 6-polygon with 3 lines in a straight line? Or should this:

 _
|_|_
  |_|

Be 2 diferent rectangles, or 1 8-polygon with 2 same points?


问:
Having count of open patches , but has to rename the branch
I have to rename my branch , but having lots of open patches in that branch. How to move those open patches to new branch without cherrypick.

Cherrypick is one of the option , but has to cherry pick every patch.

答:
You can use the REST API to automate this task. You can find the open changes using the Query Changes endpoint (or just the "Search" field in the Gerrit UI) and than change their destination branch using the Move Change endpoint.

For example, you could put all open changes in a file (one change number in each line) and execute the following command:

```<code>for c in $(cat CHANGE-FILE)
do
    curl -s --request POST --user USER:PASSWORD --data @- --header Content-Type:application/json GERRIT-SERVER/a/changes/CHANGE/move << EOF
    {
        "destination_branch" : "NEW-BRANCH"
    }
EOF
done
</code>```

Body:
You can use the REST API to automate this task. You can find the open changes using the Query Changes endpoint (or just the "Search" field in the Gerrit UI) and than change their destination branch using the Move Change endpoint.

For example, you could put all open changes in a file (one change number in each line) and execute the following command:

for c in $(cat CHANGE-FILE)
do
    curl -s --request POST --user USER:PASSWORD --data @- --header Content-Type:application/json GERRIT-SERVER/a/changes/CHANGE/move << EOF
    {
        "destination_branch" : "NEW-BRANCH"
    }
EOF
done


问:
How can I return a struct if a condition is true and an int if the condition is false
First a simple example:

```<code>typedef struct
{
    char article[DIM_STRING];
    double price;
    char buyer[DIM_STRING];
}Order;

Order algorithm(int a, int b){
    if(a == b) return -1;   //Error
    else return ord;    //Returns the Order ord
}
</code>```

The question is: is it possible to return an int OR a struct? If not how can I make an escamotage to avoid the problem?

I thought I could've use pointers and return a pointer BUT pointer must have a type.

答:
The question is: is it possible to return an int OR a struct?

No.

However, there is a workaround. Create a union that can contain your struct or an int. Then you create a wrapper struct containing one such union and one variable that you use to determine the return type. You can do like this:

```<code>struct myStruct {
   int a, b;
};

union myEnum {
    struct myStruct s;
    int i;
};

struct myContainer {
    union myEnum e;
    int retType;
};

struct myContainer myFunc() {
    struct myContainer ret;
    if(...) {
        ret.e.s.a = 42;
        ret.e.s.b = 99;
        ret.retType = 0;
    } else {
        ret.e.i = 55;
        ret.retType = 1;
    }
    return ret;
}
</code>```

And then use it something like this:

```<code>struct myContainer x = myFunc();
if(x.retType == 0) {
     struct myStruct w = x.e.s;
     // Do whatever you want to do if a struct is returned
} else if(x.retType == 1) {
     int w = x.e.i;
     // Do whatever you want to do if an int is returned
} else { /* Error */ }
</code>```

You can use a struct instead of a union. The only drawback is that it will use a little bit more memory.

This is a generic solution that you can use. If you think it clutters the code, you can instead add two fields to your existing struct:

```<code>typedef struct
{
    // Old fields
    char article[DIM_STRING];
    double price;
    char buyer[DIM_STRING];

    // The integer you want to return
    int integerValue;

    // Used to determine which fields to use
    int retType;
} Order;
</code>```

Body:
First a simple example:

typedef struct
{
    char article[DIM_STRING];
    double price;
    char buyer[DIM_STRING];
}Order;

Order algorithm(int a, int b){
    if(a == b) return -1;   //Error
    else return ord;    //Returns the Order ord
}

The question is: is it possible to return an int OR a struct? If not how can I make an escamotage to avoid the problem?

I thought I could've use pointers and return a pointer BUT pointer must have a type.

Body:
The question is: is it possible to return an int OR a struct?

No.

However, there is a workaround. Create a union that can contain your struct or an int. Then you create a wrapper struct containing one such union and one variable that you use to determine the return type. You can do like this:

struct myStruct {
   int a, b;
};

union myEnum {
    struct myStruct s;
    int i;
};

struct myContainer {
    union myEnum e;
    int retType;
};

struct myContainer myFunc() {
    struct myContainer ret;
    if(...) {
        ret.e.s.a = 42;
        ret.e.s.b = 99;
        ret.retType = 0;
    } else {
        ret.e.i = 55;
        ret.retType = 1;
    }
    return ret;
}

And then use it something like this:

struct myContainer x = myFunc();
if(x.retType == 0) {
     struct myStruct w = x.e.s;
     // Do whatever you want to do if a struct is returned
} else if(x.retType == 1) {
     int w = x.e.i;
     // Do whatever you want to do if an int is returned
} else { /* Error */ }

You can use a struct instead of a union. The only drawback is that it will use a little bit more memory.

This is a generic solution that you can use. If you think it clutters the code, you can instead add two fields to your existing struct:

typedef struct
{
    // Old fields
    char article[DIM_STRING];
    double price;
    char buyer[DIM_STRING];

    // The integer you want to return
    int integerValue;

    // Used to determine which fields to use
    int retType;
} Order;


问:
Perform search with filled textboxes only
I have a search bar with different search options, I want the SQL query to only search with the filled textboxes

I made a simple SP that worked fine when I had a search bar with only two search options (Name and Code) using if statements (not the best practice). However now that I had search bbars with 4-5 elements the IF statements don't seem like the best practice for performance

This is the procedure I made for the case where I only had 2 search options:

```<code>@Code_client nvarchar(50),
@Intitule_client varchar(100)
as
IF (@Code_client is not NULL AND @Code_client!='')
   BEGIN
   IF (@Intitule_client IS not NULL AND @Intitule_client!='')
      select * from Clients where Code_client=@Code_client and Intitule_client=@Intitule_client
   ELSE
      select * from Clients where Code_client=@Code_client
   END
ELSE IF (@Intitule_client is not null AND @Intitule_client!='')
    BEGIN
    select * from Clients where Intitule_client=@Intitule_client
    END
</code>```

But for this case, I have 4 search options like this:

```<code><div id="chercher_employe" class="Rechercher">
                <ul>
                    <li>
                        <asp:TextBox runat="server" ID="chercher_employe_Nom" CssClass="Input" placeholder="Nom employe"></asp:TextBox>
                    </li>

                    <li>
                        <asp:TextBox runat="server" ID="chercher_employe_Departement" CssClass="Input" placeholder="Departement"></asp:TextBox>
                    </li>

                    <li>
                        <asp:TextBox runat="server" ID="chercher_employe_occupation" CssClass="Input" placeholder="Occupation"></asp:TextBox>
                    </li>

                    <li>
                        <asp:TextBox runat="server" ID="chercher_employe_IntituleProfil" CssClass="Input" placeholder="Profil"></asp:TextBox>
                    </li>

                    <li>
                        <asp:LinkButton runat="server" CssClass="button">  <i class="fas fa-search"></i> </asp:LinkButton>
                    </li>
                </ul>
            </div>
</code>```

I can't figure out another way except for using the if statements with C# or SQL, any suggestions please?

答:
An if statement is nothing more than a logical implication

a -> b if a then b

which can also be written as

!a or b not a or b

So your if statement

```<code>IF (@Intitule_client IS not NULL AND @Intitule_client!='')
      select * from Clients where Code_client=@Code_client and Intitule_client=@Intitule_client
</code>```

can be translated to (using De Morgan's Laws to simplify double negation (not(a or b) <=> not(a) and not(b))

```<code>SELECT *
FROM Clients
WHERE (@Intitule_client IS NULL OR @Intitule_client = '' OR Intitule_client = @Intitule_client) AND Code_client = @Code_client
</code>```

You can then use this pattern to construct more complex queries.

Body:
I have a search bar with different search options, I want the SQL query to only search with the filled textboxes

I made a simple SP that worked fine when I had a search bar with only two search options (Name and Code) using if statements (not the best practice). However now that I had search bbars with 4-5 elements the IF statements don't seem like the best practice for performance

This is the procedure I made for the case where I only had 2 search options:

@Code_client nvarchar(50),
@Intitule_client varchar(100)
as
IF (@Code_client is not NULL AND @Code_client!='')
   BEGIN
   IF (@Intitule_client IS not NULL AND @Intitule_client!='')
      select * from Clients where Code_client=@Code_client and Intitule_client=@Intitule_client
   ELSE
      select * from Clients where Code_client=@Code_client
   END
ELSE IF (@Intitule_client is not null AND @Intitule_client!='')
    BEGIN
    select * from Clients where Intitule_client=@Intitule_client
    END

But for this case, I have 4 search options like this:

                        <asp:TextBox runat="server" ID="chercher_employe_Nom" CssClass="Input" placeholder="Nom employe"></asp:TextBox>

                        <asp:TextBox runat="server" ID="chercher_employe_Departement" CssClass="Input" placeholder="Departement"></asp:TextBox>

                        <asp:TextBox runat="server" ID="chercher_employe_occupation" CssClass="Input" placeholder="Occupation"></asp:TextBox>

                        <asp:TextBox runat="server" ID="chercher_employe_IntituleProfil" CssClass="Input" placeholder="Profil"></asp:TextBox>

                        <asp:LinkButton runat="server" CssClass="button">   </asp:LinkButton>

I can't figure out another way except for using the if statements with C# or SQL, any suggestions please?

Body:
An if statement is nothing more than a logical implication

a -> b if a then b

which can also be written as

!a or b not a or b

So your if statement

IF (@Intitule_client IS not NULL AND @Intitule_client!='')
      select * from Clients where Code_client=@Code_client and Intitule_client=@Intitule_client

can be translated to (using De Morgan's Laws to simplify double negation (not(a or b) <=> not(a) and not(b))

SELECT *
FROM Clients
WHERE (@Intitule_client IS NULL OR @Intitule_client = '' OR Intitule_client = @Intitule_client) AND Code_client = @Code_client

You can then use this pattern to construct more complex queries.


问:
WPF ProgressBar doesn't update?
I am trying to update my progressbar by using data bindings. The XAML file contains the progressbar:

```<code><ProgressBar Height="23" Name="progressBar" VerticalAlignment="Bottom" Margin="207,444,0,0" Minimum="0" Maximum="{Binding ProgressBarMax}" Value="{Binding ProgressBarValue}" />
</code>```

My relevant C# class contains the getter & setter:

```<code>    private int progressBarMax;
    public int ProgressBarMax
    {
        get
        {
            if (this.progressBarMax == 0)
                this.progressBarMax = 1;
            return this.progressBarMax;
        }
        set
        {
            this.progressBarMax = value;
        }
    }

    private int progressBarValue;
    public int ProgressBarValue
    {
        get
        {
            return progressBarValue;
        }
        set
        {
            progressBarValue = value;
        }
    }
</code>```

In my "update" method the maximum is being set. For example like this.progressBarMax = 100;. In a loop the progressbar value is getting the value += 1. To see the updates I used Application.DoEvents(), later I will implement threads. The data binding has to be correct, because I have other components that work fine.

So why doesn't my progressbar update?

Thank you for your help.

答:
What about INotifyPropertyChanged to make your UI controls detect updated values?

//daniel

Title: WPF ProgressBar doesn't update?

Body:
I am trying to update my progressbar by using data bindings. The XAML file contains the progressbar:

<ProgressBar Height="23" Name="progressBar" VerticalAlignment="Bottom" Margin="207,444,0,0" Minimum="0" Maximum="{Binding ProgressBarMax}" Value="{Binding ProgressBarValue}" />

My relevant C# class contains the getter & setter:

    private int progressBarMax;
    public int ProgressBarMax
    {
        get
        {
            if (this.progressBarMax == 0)
                this.progressBarMax = 1;
            return this.progressBarMax;
        }
        set
        {
            this.progressBarMax = value;
        }
    }

    private int progressBarValue;
    public int ProgressBarValue
    {
        get
        {
            return progressBarValue;
        }
        set
        {
            progressBarValue = value;
        }
    }

In my "update" method the maximum is being set. For example like this.progressBarMax = 100;. In a loop the progressbar value is getting the value += 1. To see the updates I used Application.DoEvents(), later I will implement threads. The data binding has to be correct, because I have other components that work fine.

So why doesn't my progressbar update?

Thank you for your help.


问:
Allow GridView to overlap SliverAppBar
I am trying to reproduce the following example from the earlier Material design specifications (open for animated demo):

Until now I was able to produce the scrolling effect, but the overlap of the content is still missing. I couldn't find out how to do this properly.

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

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        slivers: <Widget>[
          SliverAppBar(
            title: Text('Title'),
            expandedHeight: 200.0,
            primary: true,
            pinned: true,
          ),
          SliverFixedExtentList(
            itemExtent: 30.0,
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int i) => Text('Item $i')
            ),
          ),
        ],
      ),
    );
  }
}
</code>```

答:
I had the same problem and could not solve it with slivers. This example from another stackoverflow question solved my problem.

flutter - App bar scrolling with overlapping content in Flexible space

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

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Scroll demo',
      home: new Scaffold(
        appBar: new AppBar(elevation: 0.0),
        body: new CustomScroll(),
      ),
    );
  }
}

class CustomScroll extends StatefulWidget {
  @override
  State createState() => new CustomScrollState();
}

class CustomScrollState extends State<CustomScroll> {
  ScrollController scrollController;
  double offset = 0.0;
  static const double kEffectHeight = 100.0;

  @override
  Widget build(BuildContext context) {
    return new Stack(
      alignment: AlignmentDirectional.topCenter,
      children: <Widget> [
        new Container(
          color: Colors.blue,
          height: (kEffectHeight - offset * 0.5).clamp(0.0, kEffectHeight),
        ),
        new Positioned(
          child: new Container(
            width: 200.0,
            child: new ListView.builder(
              itemCount: 100,
              itemBuilder: buildListItem,
              controller: scrollController,
            ),
          ),
        ),
      ],
    );
  }

  Widget buildListItem(BuildContext context, int index) {
    return new Container(
      color: Colors.white,
      child: new Text('Item $index')
    );
  }

  void updateOffset() {
    setState(() {
      offset = scrollController.offset;
    });
  }

  @override
  void initState() {
    super.initState();
    scrollController = new ScrollController();
    scrollController.addListener(updateOffset);
  }

  @override
  void dispose() {
    super.dispose();
    scrollController.removeListener(updateOffset);
  }
}
</code>```

Change the list to a grid and its what you want

Title: Allow GridView to overlap SliverAppBar

Body:
I am trying to reproduce the following example from the earlier Material design specifications (open for animated demo):

Until now I was able to produce the scrolling effect, but the overlap of the content is still missing. I couldn't find out how to do this properly.

import 'package:flutter/material.dart';

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        slivers: <Widget>[
          SliverAppBar(
            title: Text('Title'),
            expandedHeight: 200.0,
            primary: true,
            pinned: true,
          ),
          SliverFixedExtentList(
            itemExtent: 30.0,
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int i) => Text('Item $i')
            ),
          ),
        ],
      ),
    );
  }
}

Body:
I had the same problem and could not solve it with slivers. This example from another stackoverflow question solved my problem.

flutter - App bar scrolling with overlapping content in Flexible space

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Scroll demo',
      home: new Scaffold(
        appBar: new AppBar(elevation: 0.0),
        body: new CustomScroll(),
      ),
    );
  }
}

class CustomScroll extends StatefulWidget {
  @override
  State createState() => new CustomScrollState();
}

class CustomScrollState extends State<CustomScroll> {
  ScrollController scrollController;
  double offset = 0.0;
  static const double kEffectHeight = 100.0;

  @override
  Widget build(BuildContext context) {
    return new Stack(
      alignment: AlignmentDirectional.topCenter,
      children: <Widget> [
        new Container(
          color: Colors.blue,
          height: (kEffectHeight - offset * 0.5).clamp(0.0, kEffectHeight),
        ),
        new Positioned(
          child: new Container(
            width: 200.0,
            child: new ListView.builder(
              itemCount: 100,
              itemBuilder: buildListItem,
              controller: scrollController,
            ),
          ),
        ),
      ],
    );
  }

  Widget buildListItem(BuildContext context, int index) {
    return new Container(
      color: Colors.white,
      child: new Text('Item $index')
    );
  }

  void updateOffset() {
    setState(() {
      offset = scrollController.offset;
    });
  }

  @override
  void initState() {
    super.initState();
    scrollController = new ScrollController();
    scrollController.addListener(updateOffset);
  }

  @override
  void dispose() {
    super.dispose();
    scrollController.removeListener(updateOffset);
  }
}

Change the list to a grid and its what you want


问:
react-admin: How to overwrite a field's value by code in Edit view?
Can I overwrite a field's value by code, before user can edit it?

I have tried to overwrite record property of xxxInput, but not work -

```<code>export const PrefillInput = ({ record, children, prefill, ...rest }) => {
return cloneElement(children, {
    record: { ...record, ...prefill },
    ...rest
})
</code>```

}

答:
I find what's wrong.
PrefillInput should be applied to Form, not XXXInput.</p>

Body:
Can I overwrite a field's value by code, before user can edit it?

I have tried to overwrite record property of xxxInput, but not work -

export const PrefillInput = ({ record, children, prefill, ...rest }) => {
return cloneElement(children, {
    record: { ...record, ...prefill },
    ...rest
})

}


问:
How to automatically download file in IE in locked screen
I am using selenium webdriver to do some automation on IE11 and am stuck on auto-downloading file while screen is locked.

The file download starts after pressing a button. That button does not link to a url for the download file, but seemed to link to a javascript function. I have managed everything until pressing the button but am stuck on the bottom bar prompt from IE11 (open or save). For security reasons I have to use IE11 and do the automation in locked screen. I have tried to send Alt+S using WScript.Shell, but it only seemed to work after I unlock the screen. Here's what I've tried.

```<code>shell = win32.Dispatch("WScript.Shell")

config = Path(localpath + localfile)

#confirm file exists
while not config.is_file():
    shell.SendKeys("%s", 0)
    time.sleep(2)
</code>```

Is there a way to bypass the IE prompt and automatically save the file to the download folder during locked screen?

答:
As far as I know, WebDriver has no capability to access the IE Download dialog boxes presented by browsers when you click on a download link or button. But, we can bypass these dialog boxes using a separate program called "wget".

we can use command-line program and this wget to download the file. Code as below (the following code is C# code, you could convert it to Python):

```<code>            var options = new InternetExplorerOptions()
            {
                InitialBrowserUrl = URL,  // "http://demo.guru99.com/test/yahoo.html";
                IntroduceInstabilityByIgnoringProtectedModeSettings = true
            };

            //IE_DRIVER_PATH: @"D:\Downloads\webdriver\IEDriverServer_x64_3.14.0";
            var driver = new InternetExplorerDriver(IE_DRIVER_PATH, options);
            driver.Navigate();
            Thread.Sleep(5000);

            //get the download file link.
            String sourceLocation = driver.FindElementById("messenger-download").GetAttribute("href");
            Console.WriteLine(sourceLocation);

            //using command-line program to execute the script and download file.
            String wget_command = @"cmd /c D:\\temp\\wget.exe -P D:\\temp --no-check-certificate " + sourceLocation;

            try
            {
                Process exec = Process.Start("CMD.exe", wget_command);
                exec.WaitForExit();
                Console.WriteLine("success");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            driver.Close(); // closes browser
            driver.Quit(); // closes IEDriverServer process
</code>```

More details, you could refer to this article.

Edit: Since you are using python, you could use the find_element_by_id method to find the element, then using the get_attribute method to get the value. More details, you could check these articles:

Get Element Attribute

Python + Selenium for Dummies like Me

WebDriver API

Get value of an input box using Selenium (Python)

Body:
I am using selenium webdriver to do some automation on IE11 and am stuck on auto-downloading file while screen is locked.

The file download starts after pressing a button. That button does not link to a url for the download file, but seemed to link to a javascript function. I have managed everything until pressing the button but am stuck on the bottom bar prompt from IE11 (open or save). For security reasons I have to use IE11 and do the automation in locked screen. I have tried to send Alt+S using WScript.Shell, but it only seemed to work after I unlock the screen. Here's what I've tried.

shell = win32.Dispatch("WScript.Shell")

config = Path(localpath + localfile)

#confirm file exists
while not config.is_file():
    shell.SendKeys("%s", 0)
    time.sleep(2)

Is there a way to bypass the IE prompt and automatically save the file to the download folder during locked screen?

Body:
As far as I know, WebDriver has no capability to access the IE Download dialog boxes presented by browsers when you click on a download link or button. But, we can bypass these dialog boxes using a separate program called "wget".

we can use command-line program and this wget to download the file. Code as below (the following code is C# code, you could convert it to Python):

            var options = new InternetExplorerOptions()
            {
                InitialBrowserUrl = URL,  // "http://demo.guru99.com/test/yahoo.html";
                IntroduceInstabilityByIgnoringProtectedModeSettings = true
            };

            //IE_DRIVER_PATH: @"D:\Downloads\webdriver\IEDriverServer_x64_3.14.0";
            var driver = new InternetExplorerDriver(IE_DRIVER_PATH, options);
            driver.Navigate();
            Thread.Sleep(5000);

            //get the download file link.
            String sourceLocation = driver.FindElementById("messenger-download").GetAttribute("href");
            Console.WriteLine(sourceLocation);

            //using command-line program to execute the script and download file.
            String wget_command = @"cmd /c D:\\temp\\wget.exe -P D:\\temp --no-check-certificate " + sourceLocation;

            try
            {
                Process exec = Process.Start("CMD.exe", wget_command);
                exec.WaitForExit();
                Console.WriteLine("success");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            driver.Close(); // closes browser
            driver.Quit(); // closes IEDriverServer process

More details, you could refer to this article.

Edit: Since you are using python, you could use the find_element_by_id method to find the element, then using the get_attribute method to get the value. More details, you could check these articles:

Get Element Attribute

Python + Selenium for Dummies like Me

WebDriver API

Get value of an input box using Selenium (Python)


问:
How do I access the result of a callback function from Google Sheets API?
I'm using Google Sheets API to copy a sheet, and I want to pass the ID of the new sheet into a variable.

I can successfully get the sheet ID within the callback function (using result.data.sheetId), but I'm struggling to use it outside of the function.

I'm using async / await syntax, and I have also experimented with utils.promisify, with no luck!

```<code>async function copySheet(jwt, apiKey, spreadsheetId, range) {

  const sheets = google.sheets({ version: 'v4' });

  let newSheetId = await sheets.spreadsheets.sheets.copyTo({
    "spreadsheetId": spreadsheetId,
    "sheetId": 0,
    "auth": jwt,
    "key": apiKey,
    "resource": {
      "destinationSpreadsheetId": spreadsheetId,
    }
  }, function (err, result) {
    if (err) {
      throw err;
    }
    console.log(result.data.sheetId);
    return result.data.sheetId;
  });

  console.log(newSheetId);

}
</code>```

The first console.log shows the number I want, but the second logs undefined.

Do you have any suggestions to allow me to use the sheetId outside of the callback function?

答:
How about this modification? Please think of this as just one of several answers.

Modified script:

Please modify your script as follows.

From:

```<code>let newSheetId = await sheets.spreadsheets.sheets.copyTo({
  "spreadsheetId": spreadsheetId,
  "sheetId": 0,
  "auth": jwt,
  "key": apiKey,
  "resource": {
    "destinationSpreadsheetId": spreadsheetId,
  }
}, function (err, result) {
  if (err) {
    throw err;
  }
  console.log(result.data.sheetId);
  return result.data.sheetId;
});

console.log(newSheetId);
</code>```

To:

```<code>let res = await sheets.spreadsheets.sheets.copyTo({
  "spreadsheetId": spreadsheetId,
  "sheetId": 0,
  "auth": jwt,
  "key": apiKey,
  "resource": {
    "destinationSpreadsheetId": spreadsheetId,
  }
});

let newSheetId = res.data.sheetId;
console.log(newSheetId);
</code>```

Note:

From your question, I could confirm that you have already been able to use Sheets API.

spreadsheets.sheets.copyTo() uses POST method. So in this case, API key cannot be used. I think that even when key: apiKey is removed, the script works.

Reference:

spreadsheets.sheets.copyTo

If this was not the result you want, I apologize.

Body:
I'm using Google Sheets API to copy a sheet, and I want to pass the ID of the new sheet into a variable.

I can successfully get the sheet ID within the callback function (using result.data.sheetId), but I'm struggling to use it outside of the function.

I'm using async / await syntax, and I have also experimented with utils.promisify, with no luck!

async function copySheet(jwt, apiKey, spreadsheetId, range) {

  const sheets = google.sheets({ version: 'v4' });

  let newSheetId = await sheets.spreadsheets.sheets.copyTo({
    "spreadsheetId": spreadsheetId,
    "sheetId": 0,
    "auth": jwt,
    "key": apiKey,
    "resource": {
      "destinationSpreadsheetId": spreadsheetId,
    }
  }, function (err, result) {
    if (err) {
      throw err;
    }
    console.log(result.data.sheetId);
    return result.data.sheetId;
  });

  console.log(newSheetId);

}

The first console.log shows the number I want, but the second logs undefined.

Do you have any suggestions to allow me to use the sheetId outside of the callback function?

Body:
How about this modification? Please think of this as just one of several answers.

Modified script:

Please modify your script as follows.

From:

let newSheetId = await sheets.spreadsheets.sheets.copyTo({
  "spreadsheetId": spreadsheetId,
  "sheetId": 0,
  "auth": jwt,
  "key": apiKey,
  "resource": {
    "destinationSpreadsheetId": spreadsheetId,
  }
}, function (err, result) {
  if (err) {
    throw err;
  }
  console.log(result.data.sheetId);
  return result.data.sheetId;
});

console.log(newSheetId);

To:

let res = await sheets.spreadsheets.sheets.copyTo({
  "spreadsheetId": spreadsheetId,
  "sheetId": 0,
  "auth": jwt,
  "key": apiKey,
  "resource": {
    "destinationSpreadsheetId": spreadsheetId,
  }
});

let newSheetId = res.data.sheetId;
console.log(newSheetId);

Note:

From your question, I could confirm that you have already been able to use Sheets API.

spreadsheets.sheets.copyTo() uses POST method. So in this case, API key cannot be used. I think that even when key: apiKey is removed, the script works.

Reference:

spreadsheets.sheets.copyTo

If this was not the result you want, I apologize.


问:
Pass a string to RGB Colour format
I have a dict like this:

```<code>colour_dict={'Red': '0xFF, 0x00, 0x00','Green':'0x00, 0xFF, 0x00','White':'0xFF, 0xFF, 0xFF','Yellow':'0xff, 0xff, 0x00'}
</code>```

I need to pass value of this dict to this code and it works right:

```<code>from pptx.dml.color import RGBColor
RGBColor(0xFF, 0x00, 0x00)
</code>```

When I do below to achieve the same:

```<code>RGBColor(colour_dict["Red"])
</code>```

It throws me an error as this is a string and this just want in straight number format.

I already tried converting this string to int format but nothing is working.

Overall  Problem:

How to pass the value to RGBColor using dict?

答:
colour_dict["Red"] is the string "0xFF, 0x00, 0x00", which of course can't be directly converted to an int.

You need to convert each piece in the string and pass those values to the RGBColor constructor:

```<code>color = RGBColor(*map(lambda v : int(v, 16), colour_dict["Red"].split(',')))
</code>```

NOTE: There's a lot going on in that line, so I'll break it down and explain:

colour_dict["Red"].split(',') extracts the color values substrings: ['0xFF', '0x00', '0x00']

map() applies the function passed as first argument to each value in the iterable passed as second argument.

lambda v : int(v, 16) converts v from hex string to int

* before map mans "unpack the values in the iterable that follows". it's a convenient way to pass a list with the RGB values instead of calling RGBColor(R_val, G_val, B_val).

Python 2 version:

Since python 2 doesn't support the asterisk operator, you need to split the statement in two:

```<code>r,g,b = map(lambda v : int(v, 16), colour_dict["Red"].split(','))
color = RGBColor(r,g,b)
</code>```

Title: Pass a string to RGB Colour format

Body:
I have a dict like this:

colour_dict={'Red': '0xFF, 0x00, 0x00','Green':'0x00, 0xFF, 0x00','White':'0xFF, 0xFF, 0xFF','Yellow':'0xff, 0xff, 0x00'}

I need to pass value of this dict to this code and it works right:

from pptx.dml.color import RGBColor
RGBColor(0xFF, 0x00, 0x00)

When I do below to achieve the same:

RGBColor(colour_dict["Red"])

It throws me an error as this is a string and this just want in straight number format.

I already tried converting this string to int format but nothing is working.

Overall  Problem:

How to pass the value to RGBColor using dict?

Body:
colour_dict["Red"] is the string "0xFF, 0x00, 0x00", which of course can't be directly converted to an int.

You need to convert each piece in the string and pass those values to the RGBColor constructor:

color = RGBColor(*map(lambda v : int(v, 16), colour_dict["Red"].split(',')))

NOTE: There's a lot going on in that line, so I'll break it down and explain:

colour_dict["Red"].split(',') extracts the color values substrings: ['0xFF', '0x00', '0x00']

map() applies the function passed as first argument to each value in the iterable passed as second argument.

lambda v : int(v, 16) converts v from hex string to int

* before map mans "unpack the values in the iterable that follows". it's a convenient way to pass a list with the RGB values instead of calling RGBColor(R_val, G_val, B_val).

Python 2 version:

Since python 2 doesn't support the asterisk operator, you need to split the statement in two:

r,g,b = map(lambda v : int(v, 16), colour_dict["Red"].split(','))
color = RGBColor(r,g,b)


问:
How convert Bitmap to byte array and back without quality reduction?
When I convert a picture into bytes and back, the quality deteriorates a lot. How to do it without reducing quality?

I need to save the photo in the database or send it to the server. I can consider other options to do this.

```<code>public static byte[] fromBitmap(Bitmap bitmap) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
    return stream.toByteArray();
}
public static Bitmap toBitmap(byte[] bytes) {
    return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
</code>```

答:
How to do it without reducing quality?

Use a lossless image format, such as PNG.

Body:
When I convert a picture into bytes and back, the quality deteriorates a lot. How to do it without reducing quality?

I need to save the photo in the database or send it to the server. I can consider other options to do this.

public static byte[] fromBitmap(Bitmap bitmap) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
    return stream.toByteArray();
}
public static Bitmap toBitmap(byte[] bytes) {
    return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}


问:
Is Apple In-App Purchase required for apps using auto-renewing subscription?
I am developing an iOS application where all payment related things are on existing website, our app don't have any payment related thing in it. A user adds payment details on website and select appropriate plan and can use it on both website and iOS app.

So please tell me that if i have nothing on app for using In-App purchase then it will be get approved on app store or get rejected just because app is not giving them their 30% share?

I need some expert advise...

答:
The link on App Store Review Guidelines mentions:

3.1.3(b) Multiplatform Services: Apps that operate across multiple platforms may allow users to access content, subscriptions, or features they have acquired
  elsewhere, including consumable items in multi-platform games, provided those
  items are also available as in-app purchases within the app. You must not directly or indirectly target iOS users to use a purchasing method other than in-app purchase, and your general communications about other purchasing methods must not discourage use of in-app purchase.

I am not sure how Netflix does this. New users cannot signup on iOS App, but can sign up on website, purchase subscriptions and use in iOS App.


问:
Exception in Tkinter Callback: Bool type object not callable
So I was working on this Tkinter login-register interface, when I ran into an error on my registration side. I initially thought it to be because of poorly implemented classes, but that wasn't it.
Here is my code:

```<code>def getinfo(event):
    register_window = Tk(screenName='RegisterWindow')
    register_hfont = Font(root=register_window, family='product sans', size=18)
    register_nfont = Font(root=register_window, family='product sans', size=10)
    head_label = Label(register_window, text='Welcome!')
    head_label.grid(row=0)
    head_label.configure(font=register_hfont)
    user_label = Label(register_window, text='Username ')
    user_label.grid(row=2)
    username_entry = Entry(register_window)
    username_entry.grid(row=2, column=2)
    user_label.configure(font=register_nfont)
    pass_label = Label(register_window, text='Password ')
    pass_label.grid(row=3)
    password_entry = Entry(register_window)
    password_entry.grid(row=3, column=2)
    pass_label.configure(font=register_nfont)
    email_label = Label(register_window, text='Email ')
    email_label.grid(row=4)
    email_entry = Entry(register_window)
    email_entry.grid(row=4, column=2)
    email_label.configure(font=register_nfont)
    name_label = Label(register_window, text='Name ')
    name_label.grid(row=5)
    name_entry = Entry(register_window)
    name_entry.grid(row=5, column=2)
    name_label.configure(font=register_nfont)

    print('data submissions successful')
    submit_button = Button(register_window, text='Register')
    submit_button.bind('<Button-1>', register(username_entry, password_entry, name_entry, email_entry))
    submit_button.grid(row=7, column=1)
    register_window.mainloop()
    if RegisterVar:
        register_window.destroy()
    else:
        pass

def register(eusername, epassword, ename, eemail):
    uid = eusername.get()
    pwd = epassword.get()
    name = ename.get()
    email = eemail.get()
    print('function called')
    register_command = 'insert into logininfo values("'+uid+'","'+pwd+'","'+name+'","'+email+'");'
    cursor.execute(register_command)
    RegisterVar = True
    print('Registration Successful!')
    return True
</code>```

When i clicked the submit_button object, i ran into this error:

```<code>Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\adity\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
TypeError: 'bool' object is not callable
</code>```

Any help is appreciated!

答: You are passing submit_button.bind the result of calling register as opposed to the function itself (which tinter will call).

Body:
So I was working on this Tkinter login-register interface, when I ran into an error on my registration side. I initially thought it to be because of poorly implemented classes, but that wasn't it.
Here is my code:

def getinfo(event):
    register_window = Tk(screenName='RegisterWindow')
    register_hfont = Font(root=register_window, family='product sans', size=18)
    register_nfont = Font(root=register_window, family='product sans', size=10)
    head_label = Label(register_window, text='Welcome!')
    head_label.grid(row=0)
    head_label.configure(font=register_hfont)
    user_label = Label(register_window, text='Username ')
    user_label.grid(row=2)
    username_entry = Entry(register_window)
    username_entry.grid(row=2, column=2)
    user_label.configure(font=register_nfont)
    pass_label = Label(register_window, text='Password ')
    pass_label.grid(row=3)
    password_entry = Entry(register_window)
    password_entry.grid(row=3, column=2)
    pass_label.configure(font=register_nfont)
    email_label = Label(register_window, text='Email ')
    email_label.grid(row=4)
    email_entry = Entry(register_window)
    email_entry.grid(row=4, column=2)
    email_label.configure(font=register_nfont)
    name_label = Label(register_window, text='Name ')
    name_label.grid(row=5)
    name_entry = Entry(register_window)
    name_entry.grid(row=5, column=2)
    name_label.configure(font=register_nfont)

    print('data submissions successful')
    submit_button = Button(register_window, text='Register')
    submit_button.bind('<Button-1>', register(username_entry, password_entry, name_entry, email_entry))
    submit_button.grid(row=7, column=1)
    register_window.mainloop()
    if RegisterVar:
        register_window.destroy()
    else:
        pass

def register(eusername, epassword, ename, eemail):
    uid = eusername.get()
    pwd = epassword.get()
    name = ename.get()
    email = eemail.get()
    print('function called')
    register_command = 'insert into logininfo values("'+uid+'","'+pwd+'","'+name+'","'+email+'");'
    cursor.execute(register_command)
    RegisterVar = True
    print('Registration Successful!')
    return True

When i clicked the submit_button object, i ran into this error:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\adity\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
TypeError: 'bool' object is not callable

Any help is appreciated!


问:
How to use actix_web with a cassandra-sys-rs connection pool?
How in the program execution, cassandra established connection, waiting to be processed?
Because of my architecture, combined with actix_web and cassandra-sys-rs processing, but such a method, the input of a url to establish a connection.
If I want to connect with cassandra always, instead of re-establishing the request every time send it. The actix_web document explains the use of Diesel, but it does not support cassandra applications, so how do I use this?

code

答: You should probably take a look at r2d2 -- I think this is what most Diesel projects use. From the README, it does not seem to support Cassandra yet, but maybe you can add support?</p>


问:
Generate Logs in a new directory daily according to each hour in log4j2?
I want to create a directory {date}.dir and inside this directory, I need logs for each hour in a new separate file as 0000.log, 0100.log ...2300.log.

I used rolling file appender, but it only work to create a single log file and compressed the last one. I'm using time-based triggering policy with interval = 1, which gives me a new file every day and compress the last day's.

<RollingFile name="eventLogger" fileName="/Log/webservices/linpub.log" filePattern="/Log/webservices/linpub-%d{MM-dd-yyyy}.log.gz">
        <PatternLayout>
                <Pattern>%d{MM/dd/yy HH:mm:ss.SSS} %-5p [%t] %c{1} %X{trioOperation} - %m %throwable %n</Pattern>
        </PatternLayout>
        <Policies>
            <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
        </Policies>
</RollingFile>
```

I want to create a new file with name as linpub-{date}.dir and inside the file, there should be a log file for each hour.

I'm using log4j2 2.3 version.

答:
Please use below configuration:</p>

```<code> <appender name="dailyFileAppender"
      class="org.apache.log4j.rolling.RollingFileAppender">
      <param name="append" value="true" />
      <param name="Threshold" value="INFO" />
      <rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
      <param name="FileNamePattern" value="/temp/logs/Project-Name_%d{yyyy-MM-
      dd-HH}.log" />
      </rollingPolicy>
      <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p
      %-10t [%-40.40c] %x - %m%n" />
      </layout>
  </appender>
</code>```

Body:
I want to create a directory {date}.dir and inside this directory, I need logs for each hour in a new separate file as 0000.log, 0100.log ...2300.log.

I used rolling file appender, but it only work to create a single log file and compressed the last one. I'm using time-based triggering policy with interval = 1, which gives me a new file every day and compress the last day's.

<RollingFile name="eventLogger" fileName="/Log/webservices/linpub.log" filePattern="/Log/webservices/linpub-%d{MM-dd-yyyy}.log.gz">
        <PatternLayout>
                <Pattern>%d{MM/dd/yy HH:mm:ss.SSS} %-5p [%t] %c{1} %X{trioOperation} - %m %throwable %n</Pattern>
        </PatternLayout>
        <Policies>
            <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
        </Policies>
</RollingFile>

I want to create a new file with name as linpub-{date}.dir and inside the file, there should be a log file for each hour.

I'm using log4j2 2.3 version.

Body:
Please use below configuration:

 <appender name="dailyFileAppender"
      class="org.apache.log4j.rolling.RollingFileAppender">
      <param name="append" value="true" />
      <param name="Threshold" value="INFO" />
      <rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
      <param name="FileNamePattern" value="/temp/logs/Project-Name_%d{yyyy-MM-
      dd-HH}.log" />
      </rollingPolicy>
      <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p
      %-10t [%-40.40c] %x - %m%n" />
      </layout>
  </appender>


答:
Replace

```<code>RGBColor(colour_dict["Red"])
</code>```

by

```<code>eval("RGBColor({})".format(colour_dict["Red"]))
</code>```

Title: Pass a string to RGB Colour format

Body:
Replace

RGBColor(colour_dict["Red"])

by

eval("RGBColor({})".format(colour_dict["Red"]))


问:
How to evaluate datatype and true_of_all_constants functions?
I am a beginner of sml and I'm taking programming language courses at Coursera. There's a datatype and function that I don't know how to evaluate:

```<code>datatype exp = constant of int
     | Negate of exp
     |Add of exp * exp
     |Multiply of exp * exp

fun true_of_all_constants(f,e) =
    case e of
    constant i => f i
      | Negate e1 => true_of_all_constants(f,e1)
      | Add(e1,e2) => true_of_all_constants(f,e1)
              andalso true_of_all_constants(f,e2)
      | Multiply(e1,e2) => true_of_all_constants(f,e1)
              andalso true_of_all_constants(f,e2)
</code>```

Trying to evaluate them, I always get errors:

```<code>true_of_all_constants [3,4,5];
true_of_all_constants 4;
true_of_all_constants (is_even 4, 5);
</code>```

where is_even is a little helper function:

```<code>fun is_even v =
(v mod 2 = 0)
</code>```

To test true_of_all_constants, what should e be replaced with? Also, could you explain what does datatype do here? I don't understand why we need "Negate" or "Add" here; why we have "exp*exp," rather than "exp+exp," for "Add?"

答:
Fixing whitespace, the data type definition and the definition of true_of_all_constants (p, e) become:

```<code>datatype exp =
    Constant of int
  | Negate of exp
  | Add of exp * exp
  | Multiply of exp * exp

fun true_of_all_constants (p, e) =
    let fun aux (Constant i)        = p i
          | aux (Negate e1)         = aux e1
          | aux (Add (e1, e2))      = aux e1 andalso aux e2
          | aux (Multiply (e1, e2)) = aux e1 andalso aux e2
    in aux e end
</code>```

Here constant has been renamed to Constant: Both will work, but naming constructors with an uppercase letter differentiates it visually from other identifiers. And I've used an inner function, aux, to shorten the recursive expressions a bit. Instead of f I called it p for predicate, but that's a taste thing.

Trying to evaluate them, I always get errors

Here are some examples of expressions and evaluating them:

```<code>- val two_plus_two = Add (Constant 2, Constant 2);
- true_of_all_constants (fn i => i = 2, two_plus_two);
> val it = true : bool

- val two_times_neg_two = Multiply (Constant 2, Constant ~2);
- true_of_all_constants (fn i => i > 0, two_times_neg_two);
> val it = false : bool

- val two_four_six = Add (Constant 2, Add (Constant 4, Constant 6));
- fun is_even x = x mod 2 = 0;
- true_of_all_constants (is_even, two_four_six);
> val it = true : bool
</code>```

could you explain what does datatype do here?

I think you should refer to a book or tutorial here.

For example, ML for the Working Programmer, ch. 4 (free PDF) deals with datatype definitions.

I don't understand why we need "Negate" or "Add" here

I don't know, either. The problem you're given in the course is entirely hypothetical.

Body:
I am a beginner of sml and I'm taking programming language courses at Coursera. There's a datatype and function that I don't know how to evaluate:

datatype exp = constant of int
     | Negate of exp
     |Add of exp * exp
     |Multiply of exp * exp

fun true_of_all_constants(f,e) =
    case e of
    constant i => f i
      | Negate e1 => true_of_all_constants(f,e1)
      | Add(e1,e2) => true_of_all_constants(f,e1)
              andalso true_of_all_constants(f,e2)
      | Multiply(e1,e2) => true_of_all_constants(f,e1)
              andalso true_of_all_constants(f,e2)

Trying to evaluate them, I always get errors:

true_of_all_constants [3,4,5];
true_of_all_constants 4;
true_of_all_constants (is_even 4, 5);

where is_even is a little helper function:

fun is_even v =
(v mod 2 = 0)

To test true_of_all_constants, what should e be replaced with? Also, could you explain what does datatype do here? I don't understand why we need "Negate" or "Add" here; why we have "exp*exp," rather than "exp+exp," for "Add?"

Body:
Fixing whitespace, the data type definition and the definition of true_of_all_constants (p, e) become:

datatype exp =
    Constant of int
  | Negate of exp
  | Add of exp * exp
  | Multiply of exp * exp

fun true_of_all_constants (p, e) =
    let fun aux (Constant i)        = p i
          | aux (Negate e1)         = aux e1
          | aux (Add (e1, e2))      = aux e1 andalso aux e2
          | aux (Multiply (e1, e2)) = aux e1 andalso aux e2
    in aux e end

Here constant has been renamed to Constant: Both will work, but naming constructors with an uppercase letter differentiates it visually from other identifiers. And I've used an inner function, aux, to shorten the recursive expressions a bit. Instead of f I called it p for predicate, but that's a taste thing.

Trying to evaluate them, I always get errors

Here are some examples of expressions and evaluating them:

- val two_plus_two = Add (Constant 2, Constant 2);
- true_of_all_constants (fn i => i = 2, two_plus_two);
> val it = true : bool

- val two_times_neg_two = Multiply (Constant 2, Constant ~2);
- true_of_all_constants (fn i => i > 0, two_times_neg_two);
> val it = false : bool

- val two_four_six = Add (Constant 2, Add (Constant 4, Constant 6));
- fun is_even x = x mod 2 = 0;
- true_of_all_constants (is_even, two_four_six);
> val it = true : bool

could you explain what does datatype do here?

I think you should refer to a book or tutorial here.

For example, ML for the Working Programmer, ch. 4 (free PDF) deals with datatype definitions.

I don't understand why we need "Negate" or "Add" here

I don't know, either. The problem you're given in the course is entirely hypothetical.


问:
How to create a global import to use in all the app?
I would like to find a way to import a pods / library once and not into all the classes in my app</p>

答:
Use this above the app delegate class or anywhere but it is better to put it above app delegate class.

@_exported import LibraryName


问:
Add hexdecimal values which are dictionary values and not convert them to decimal values
I have a dictionary who's values are in hexadecimal form. I need to add the values and the result should be in hexadecimal form. Please provide solution for adding hex values and result should be hex.

Using sum1 = sum(dict.values) provides only sum for values which are in int form. It doesn't work for hex.

dict = {'key1': '1C','key2': '14','key3': '4D'}

print("Value : %s" %  dict.values())
```

Value : dict_values(['1C', '14', '4D'])

答:
You cannot directly sum the hex values since they are strings. You need to convert them to int and then convert the answer back to hex. You can do that as follows:

```<code>hex(sum(map(lambda v: int(v, base=16), d.values())))
</code>```

(d is the name of the dict. Please avoid using dict as the variable name, since it is also the class name)

Body:
I have a dictionary who's values are in hexadecimal form. I need to add the values and the result should be in hexadecimal form. Please provide solution for adding hex values and result should be hex.

Using sum1 = sum(dict.values) provides only sum for values which are in int form. It doesn't work for hex.

dict = {'key1': '1C','key2': '14','key3': '4D'}

print("Value : %s" %  dict.values())

Value : dict_values(['1C', '14', '4D'])

Body:
You cannot directly sum the hex values since they are strings. You need to convert them to int and then convert the answer back to hex. You can do that as follows:

hex(sum(map(lambda v: int(v, base=16), d.values())))

(d is the name of the dict. Please avoid using dict as the variable name, since it is also the class name)


问:
How should i interpret a loop inside a numpy array?
I am wondering how this code does the job.I don't understand how n and i written in the for loops lead to [0 1].

If dpn=1 and conn=[0 1] then the result of below code will be eft=[0 1]

```<code>eft = numpy.array([dpn * n + i for n in conn for i in range(dpn)])
</code>```

答:
The numpy.array() call simply transforms a python list into a numpy array. The whole logic happens inside the list comprehension. You can read up on list comprehensions here:
https://hackernoon.com/list-comprehension-in-python-8895a785550b

A list comprehension can also be written as a for-loop, in this case there are two nested loops:

```<code>eft = []

for n in conn:
  for i in range(dpn):
    eft.append(dpn * n + i)
</code>```

It is basically just a concise way to create a new list based on some other iterable(s).

Body:
I am wondering how this code does the job.I don't understand how n and i written in the for loops lead to [0 1].

If dpn=1 and conn=[0 1] then the result of below code will be eft=[0 1]

eft = numpy.array([dpn * n + i for n in conn for i in range(dpn)])

Body:
The numpy.array() call simply transforms a python list into a numpy array. The whole logic happens inside the list comprehension. You can read up on list comprehensions here:
https://hackernoon.com/list-comprehension-in-python-8895a785550b

A list comprehension can also be written as a for-loop, in this case there are two nested loops:

eft = []

for n in conn:
  for i in range(dpn):
    eft.append(dpn * n + i)

It is basically just a concise way to create a new list based on some other iterable(s).


问:
Trying to add AutoMapper to .NetCore1.1 - not recognising services.AddAutoMapper()
I've installed the following Nuget packages into my project:

Automapper

AutoMapper.Extensions.Microsoft.DependencyInjection

I have added the line to ConfigureServices in Startup.cs.

```<code>public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();
    // . . .
    services.AddAutoMapper();
}
</code>```

I'm still getting a red line under services.AddAutoMapper(). It says:

The Call is ambiguous between the following methods or properties: ServiceCollectionExtensions.AddAutoMapper(IServiceCollection, params Assembly[]) and ServiceCollectionExtensions.AddAutoMapper(IServiceCollection, params Type[])

Why is this happening? All the .NET Core add automapper guides I've read show to do it this way.

答:
I had the same problem (in .NET Core 2.2, Visual Studio Code 1.34.0, Ubuntu OS) despite having installed AutoMapper package (v8.1.0) and the AutoMapper.Extensions.Microsoft.Dependencyinjection package (v6.1.0).

The problem was solved by changing version of the packages in project.csproj as follows:

```<code><PackageReference Include="AutoMapper" Version="8.0.0"/>
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="6.0.0"/>
</code>```

Somehow it looks like due to the package version mismatch.

Body:
I've installed the following Nuget packages into my project:

Automapper

AutoMapper.Extensions.Microsoft.DependencyInjection

I have added the line to ConfigureServices in Startup.cs.

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();
    // . . .
    services.AddAutoMapper();
}

I'm still getting a red line under services.AddAutoMapper(). It says:

The Call is ambiguous between the following methods or properties: ServiceCollectionExtensions.AddAutoMapper(IServiceCollection, params Assembly[]) and ServiceCollectionExtensions.AddAutoMapper(IServiceCollection, params Type[])

Why is this happening? All the .NET Core add automapper guides I've read show to do it this way.

Body:
I had the same problem (in .NET Core 2.2, Visual Studio Code 1.34.0, Ubuntu OS) despite having installed AutoMapper package (v8.1.0) and the AutoMapper.Extensions.Microsoft.Dependencyinjection package (v6.1.0).

The problem was solved by changing version of the packages in project.csproj as follows:

<PackageReference Include="AutoMapper" Version="8.0.0"/>
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="6.0.0"/>

Somehow it looks like due to the package version mismatch.


问:
how to save a doc file in PHP?
This is my example.php, using this i am generating a example.doc file and using header i can save that file in my local computer.

But i want to save one more copy in report folder (report and example.php are in same folder/same domain)

```<code><?php

 $html = preg_replace('%/[^\\s]+\\.(jpg|jpeg|png|gif)%i', 'http://www.asd.com\\0', $html);

    print "<html xmlns:v=\"urn:schemas-microsoft-com:vml\"";
    print "xmlns:o=\"urn:schemas-microsoft-com:office:office\"";
    print "xmlns:w=\"urn:schemas-microsoft-com:office:word\"";
    print "xmlns=\"http://www.w3.org/TR/REC-html40\">";
    print "<xml>
     <w:WordDocument>
      <w:View>Print</w:View>
      <w:DoNotHyphenateCaps/>
      <w:PunctuationKerning/>
      <w:DrawingGridHorizontalSpacing>9.35 pt</w:DrawingGridHorizontalSpacing>
      <w:DrawingGridVerticalSpacing>9.35 pt</w:DrawingGridVerticalSpacing>
     </w:WordDocument>
    </xml>
    ";
    print '<h1>hello world</h1>';
    header( 'Content-Type: application/msword' );
    header("Content-disposition: attachment; filename=example.doc");

?>
</code>```

答:
You need to add

header('Content-type: application/vnd.ms-word');
```

<p>instead of</p>

<pre class="lang-php prettyprint-override"><code>header('Content-Type: application/msword');
</code>```

Title: how to save a doc file in PHP?

Body:
This is my example.php, using this i am generating a example.doc file and using header i can save that file in my local computer.

But i want to save one more copy in report folder (report and example.php are in same folder/same domain)

<?php

 $html = preg_replace('%/[^\\s]+\\.(jpg|jpeg|png|gif)%i', 'http://www.asd.com\\0', $html);

    print "";
    print "<xml>
     <w:WordDocument>
      <w:View>Print</w:View>
      <w:DoNotHyphenateCaps/>
      <w:PunctuationKerning/>
      <w:DrawingGridHorizontalSpacing>9.35 pt</w:DrawingGridHorizontalSpacing>
      <w:DrawingGridVerticalSpacing>9.35 pt</w:DrawingGridVerticalSpacing>
     </w:WordDocument>
    </xml>
    ";
    print '
hello world
';
    header( 'Content-Type: application/msword' );
    header("Content-disposition: attachment; filename=example.doc");

?>

Body:
You need to add

header('Content-type: application/vnd.ms-word');

instead of

header('Content-Type: application/msword');


问:
C# foreach iterating rule for collections
How .NET decides for order of items when iterating through collections ?

For example:

```<code>list<string> myList = new List<string>();

myList.Add("a");
myList.Add("b");
myList.Add("c");

foreach (string item in myList)
{
    // What's the order of items? a -> b -> c ?
}
</code>```

I need this order (accessing collection members):

```<code>for (int i = 1; i < myList.Count; i++)
{
    string item = myList[i - 1]; // This is the order I need
}
</code>```

Can I safely use foreach with List? What about other types of collections?

答:
.NET doesn't decide it - the class implementing IEnumerable decides how it is being done. For List that is from index 0 to the last one. For Dictionary it depends on the hash value of the key I think.

List indexes are 0 based, so you can do this:

```<code>for (int i = 0; i < myList.Count; i++)
{
    string item = myList[i]; // This is the order I need
}
</code>```

and is the same result as foreach. However if you want to be explicit about it then just stick to the for loop. Nothing wrong with that.

Body:
How .NET decides for order of items when iterating through collections ?

For example:

list<string> myList = new List<string>();

myList.Add("a");
myList.Add("b");
myList.Add("c");

foreach (string item in myList)
{
    // What's the order of items? a -> b -> c ?
}

I need this order (accessing collection members):

for (int i = 1; i < myList.Count; i++)
{
    string item = myList[i - 1]; // This is the order I need
}

Can I safely use foreach with List? What about other types of collections?

Body:
.NET doesn't decide it - the class implementing IEnumerable decides how it is being done. For List that is from index 0 to the last one. For Dictionary it depends on the hash value of the key I think.

List indexes are 0 based, so you can do this:

for (int i = 0; i < myList.Count; i++)
{
    string item = myList[i]; // This is the order I need
}

and is the same result as foreach. However if you want to be explicit about it then just stick to the for loop. Nothing wrong with that.


问:
Storing a token acquired through a fetch in Local Storage and appending data from a fetch request in a html table
I'm currently working on a project with a couple of people using C#, HTML and Javascript.

We have to make the classic game Mastermind and make it multiplayer, I'm struggling with some things on the front end side. The backend is being done by the other people and it is pretty much finished.

We have to use fetch to make requests to our backend. I already made a system that allows for logging in and registering. We have to use a token for authentication and I can't seem to figure out how to get the token from the response from my fetch request and store in Local Storage. Another thing I'm struggling with is the lobbies for the game. I have to use fetch to ask my backend for the currently running lobbies, to create lobbies, and joining and leaving lobbies. As for the currently running lobbies, I have to convert the response I'm getting from my backend to a table on my HTML page but I can't figure out how to achieve this.

I have tried searching for possible solutions using Google but I don't really understand what the solutions do and how to mold them to work for my code.

```<code><script type="text/javascript">
document.getElementById('button').addEventListener("click", function (event) {
    event.preventDefault();
    getRooms();
    return false;
});

function getRooms() {
    let url = 'https://localhost:44317/api/waitingrooms';

    let table = document.createElement("TABLE");
    table.setAttribute("id", "waitingRooms");
    let tr = document.createElement("TR");
    tr.setAttribute("id", "myTR");

    fetch(url)
        .then(function (response)
=>
    {
        if (response.status == 200) {
            return response.json();

        } else {
            throw `error with status ${response.status}`;
        }
    }
)
.
    then(data => data);

.
    then

}
</code>```

答:
```<code>fetch(url)
    .then((resp) => resp.json()) // Transform the data into json
    .then((data) => {
    let {token,...otherinfo} = data; // if token is not nested and given directly
    localstorage.setItem('token',token); // if you want to store in local storage
    return token;
    })
 })
</code>```

but not sure how your response is coming from your server can you show response when you hit that api

Body:
fetch(url)
    .then((resp) => resp.json()) // Transform the data into json
    .then((data) => {
    let {token,...otherinfo} = data; // if token is not nested and given directly
    localstorage.setItem('token',token); // if you want to store in local storage
    return token;
    })
 })

but not sure how your response is coming from your server can you show response when you hit that api


问:
How can I access a record randomly in a list of 100 records through JMeter components and functions?
Say, in a list view there are 100 records. I'm landing on the list view page of 100 records through HTTP request and want to access a record randomly from the list? Please help.

Example:
- I'm using the Hubspot free CRM and I have created some contacts.
- The list view records appearance here. ListView
- First I'm landing to the HubSpot contacts list view page and I would like to randomly open any one of the contact records from the list. Open Record

答: Use a regular expression extractor element with valid regular expression and '0' in Match No.</p>


问:
How to detect touch device in 2019?
For my app, I need to radically change the entire UX for touch devices using an onscreen keyboard (eg. mobile, touch TV) vs mouse/kbd devices (eg. desktop, a mobile with a bluetooth mouse/kbd).

NB. I've already grokked responsive layout with CSS grid and media queries, so that aspect is dealt with. My issue isn't one of layout, it's that the entire UX needs to be fundamentally different. The best option I have so far is to listen for a mousemove on the whole viewport.

How can I do this using modern browsers?

Note I've already read the existing answers which are all several years old, and generally conclude that it can't be done.

答:
You can detect using Javascript using a simple condition here

```<code>if(('ontouchstart' in window) || (navigator.msMaxTouchPoints > 0) || (navigator.maxTouchPoints > 0)) {
    //this is a touch device you can any action here
}else {
    //it's not a touch device another code here
}
</code>```

Also, the following link here https://ctrlq.org/code/19616-detect-touch-screen-javascript

Title: How to detect touch device in 2019?

Body:
You can detect using Javascript using a simple condition here

if(('ontouchstart' in window) || (navigator.msMaxTouchPoints > 0) || (navigator.maxTouchPoints > 0)) {
    //this is a touch device you can any action here
}else {
    //it's not a touch device another code here
}

Also, the following link here https://ctrlq.org/code/19616-detect-touch-screen-javascript


问:
How do I insert values of different type to columns in my table?
The question title might sound ridiculous, but I would explain what I want to do with example table below:

```<code>+------------+------------+----------------+----------+-------------------------+
|  recvtime  | entitytype |    attrname    | attrtype |        attrvalue        |
+------------+------------+----------------+----------+-------------------------+
| 2019-05-27 | Noise      | measurand      | Number   | 51.7                    |
| 2019-05-27 | Noise      | sonometerClass | Text     | 1                       |
| 2019-05-27 | Noise      | name           | Text     | City Centre             |
| 2019-05-27 | Noise      | longitude      | Number   | -8.65915                |
| 2019-05-27 | Noise      | latitude       | Number   | 41.1591                 |
| 2019-05-27 | Noise      | dateObserved   | DateTime | 2016-05-24T18:38:15.00Z |
+------------+------------+----------------+----------+-------------------------+
</code>```

Now would like to insert more values to attrname and attrvalue columns ONLY, in which the values correspond to the following:

```<code>+----------------+-------------------------+
|    attrname    |        attrvalue        |
+----------------+-------------------------+
| measurand      | 38.7                    |
| sonometerClass | 2                       |
| name           | London Street           |
| longitude      | -8.603257               |
| latitude       | 41.183778               |
| dateObserved   | 2016-05-24T18:38:15.00Z |
+----------------+-------------------------+
</code>```

How do I achieve this in SQL? I really don't mind keep all other columns with the values as they are(i.e. repeating their values).

EDIT

While I acknowledge the answer by Gordon Linoff, it wouldn't solve my problem because these values are actually read from a csv file of the form:

```<code>measurand,sonometerClass,name,longitude,latitude,dateObserved
38.7,2,London Street,-8.603257,41.183778,2016-05-24T18:38:15.00Z
90.4,1,Hospital de S. Joao,-8.603257,41.183778,2014-07-12T6:18:15.00Z
59.3,0,City Campus,-8.594866,41.178031,2014-08-12T16:10:10.00Z
64.5,1,ABC Beach,-8.607085,41.15001,2015-10-11T16:10:10.00Z
</code>```

The values are not coming directly from user input, but read from the csv file whose form is as above.

EDIT-2:

I understand I would use postgres copy command, in fact I'm  using postgres copy_from in the python script.
My specific problem is reading the values from the csv file  such that for each line of the csv file, values are inserted into attrvalue column with corresponding attrname updated, so that:

```<code>For line1: 38.7,2,London Street,-8.603257,41.183778,2016-05-24T18:38:15.00Z
</code>```

I get the following correspondance(attrname set to like):

```<code>measurand = 38.7
sonometerClass = 2
name = London Street
longitude = -8.603257
latitude = 41.183778
dateObserved = 2016-05-24T18:38:15.00Z
</code>```

Similarly,

```<code>For line2: 90.4,1,Hospital de S. Joao,-8.603257,41.183778,2014-07-12T6:18:15.00Z
</code>```

I get the following:

```<code>measurand = 90.4
sonometerClass = 1
name = Hospital de S. Joao
longitude = -8.603257
latitude = 41.183778
dateObserved = 2014-07-12T6:18:15.00Z
</code>```

All other columns remain as they are.

Body:
The question title might sound ridiculous, but I would explain what I want to do with example table below:

+------------+------------+----------------+----------+-------------------------+
|  recvtime  | entitytype |    attrname    | attrtype |        attrvalue        |
+------------+------------+----------------+----------+-------------------------+
| 2019-05-27 | Noise      | measurand      | Number   | 51.7                    |
| 2019-05-27 | Noise      | sonometerClass | Text     | 1                       |
| 2019-05-27 | Noise      | name           | Text     | City Centre             |
| 2019-05-27 | Noise      | longitude      | Number   | -8.65915                |
| 2019-05-27 | Noise      | latitude       | Number   | 41.1591                 |
| 2019-05-27 | Noise      | dateObserved   | DateTime | 2016-05-24T18:38:15.00Z |
+------------+------------+----------------+----------+-------------------------+

Now would like to insert more values to attrname and attrvalue columns ONLY, in which the values correspond to the following:

+----------------+-------------------------+
|    attrname    |        attrvalue        |
+----------------+-------------------------+
| measurand      | 38.7                    |
| sonometerClass | 2                       |
| name           | London Street           |
| longitude      | -8.603257               |
| latitude       | 41.183778               |
| dateObserved   | 2016-05-24T18:38:15.00Z |
+----------------+-------------------------+

How do I achieve this in SQL? I really don't mind keep all other columns with the values as they are(i.e. repeating their values).

EDIT

While I acknowledge the answer by Gordon Linoff, it wouldn't solve my problem because these values are actually read from a csv file of the form:

measurand,sonometerClass,name,longitude,latitude,dateObserved
38.7,2,London Street,-8.603257,41.183778,2016-05-24T18:38:15.00Z
90.4,1,Hospital de S. Joao,-8.603257,41.183778,2014-07-12T6:18:15.00Z
59.3,0,City Campus,-8.594866,41.178031,2014-08-12T16:10:10.00Z
64.5,1,ABC Beach,-8.607085,41.15001,2015-10-11T16:10:10.00Z

The values are not coming directly from user input, but read from the csv file whose form is as above.

EDIT-2:

I understand I would use postgres copy command, in fact I'm  using postgres copy_from in the python script.
My specific problem is reading the values from the csv file  such that for each line of the csv file, values are inserted into attrvalue column with corresponding attrname updated, so that:

For line1: 38.7,2,London Street,-8.603257,41.183778,2016-05-24T18:38:15.00Z

I get the following correspondance(attrname set to like):

measurand = 38.7
sonometerClass = 2
name = London Street
longitude = -8.603257
latitude = 41.183778
dateObserved = 2016-05-24T18:38:15.00Z

Similarly,

For line2: 90.4,1,Hospital de S. Joao,-8.603257,41.183778,2014-07-12T6:18:15.00Z

I get the following:

measurand = 90.4
sonometerClass = 1
name = Hospital de S. Joao
longitude = -8.603257
latitude = 41.183778
dateObserved = 2014-07-12T6:18:15.00Z

All other columns remain as they are.

Body:
My first guess would be:

insert into t (recvtime, entitytype, attrname, attrtype,       attrvalue)
    values ('2019-05-27', 'Noise', 'measurand', 'number', '38.7'),
           ('2019-05-27', 'Noise', 'sonometerClass', 'text', '2'),
           ('2019-05-27', 'Noise', 'name', 'text', 'London Street'),
           ('2019-05-27', 'Noise', 'longitude', 'number', '-8.603257'),
           ('2019-05-27', 'Noise', 'latitude', 'number', '41.183778'),
           ('2019-05-27', 'Noise', 'dateobserved', 'datetime', '2016-05-24T18:38:15.00Z');


问:
Electron desktop application that support high FPS animation
I simulate a high FPS camera and was requested for a desktop app that supports screen drawing in 100 Hertz.

Now it's implemented in .Net (winforms) and I want to learn a new technology. Therefore, I need to show that there aren't performance issues using Electron framework with JS UI.

I searched quite a bit and the max FPS where 60.
Is it possible?

答:
Since Electron is using Chromium for rendering, it should be possible.

You could check this by setting the show FPS flag and running a short test:

Show FPS meter Chrome 33


问:
How to replace 0 values in a numpy array to other values based on column range?
I have a dataset in the following format:

[[ 226      600   3.33    915.     92.6    98.6 ]
  [ 217      700   3.34    640.    93.7    98.5 ]
  [ 213      900   3.35    662.    88.8    96.  ]
  ...
  [ 108      600    2.31   291.     64.     70.4 ]
  [ 125      800    3.36   1094.    65.5    84.1 ]
  [ 109      400    2.44   941.     52.3    68.7 ]]

Each column is a separate criteria that has its own value range. How can I impute values that are 0 to a value that is more than zero based on its column range? In other words the worst minimal value other than 0.

I have written the following code but it can only either change the 0 to the minimal value in the column (which is of course 0) or max. The max varies by column. Thanks for your help!

```<code># Impute 0 values -- give them the worst value for that column

I, J = np.nonzero(scores == 0)
scores[I,J] = scores.min(axis=0)[J] # can only do min or max
</code>```

答:
I think the numpy.ma.masked_equal function is what you need.

consider an array:

```<code>a = np.array([4, 3, 8, 0, 5])
m = np.ma.masked_equal(a, 0) # mask = [0, 0, 0, 1, 0]
</code>```

now you can call m.min() and the value is the second smallest value in the column.

```<code>m.min() # 3
</code>```

Body:
I have a dataset in the following format:

[[ 226      600   3.33    915.     92.6    98.6 ]
  [ 217      700   3.34    640.    93.7    98.5 ]
  [ 213      900   3.35    662.    88.8    96.  ]
  ...
  [ 108      600    2.31   291.     64.     70.4 ]
  [ 125      800    3.36   1094.    65.5    84.1 ]
  [ 109      400    2.44   941.     52.3    68.7 ]]

Each column is a separate criteria that has its own value range. How can I impute values that are 0 to a value that is more than zero based on its column range? In other words the worst minimal value other than 0.

I have written the following code but it can only either change the 0 to the minimal value in the column (which is of course 0) or max. The max varies by column. Thanks for your help!

# Impute 0 values -- give them the worst value for that column

I, J = np.nonzero(scores == 0)
scores[I,J] = scores.min(axis=0)[J] # can only do min or max

Body:
I think the numpy.ma.masked_equal function is what you need.

consider an array:

a = np.array([4, 3, 8, 0, 5])
m = np.ma.masked_equal(a, 0) # mask = [0, 0, 0, 1, 0]

now you can call m.min() and the value is the second smallest value in the column.

m.min() # 3


问:
How to run “echo” command through Java?
I want to change a value inside of a file named scaling_max_freq located in /sys/devices/system/cpu/cpu0/cpufreq/ on an Android device.

On an another post I've read that I'm able to do this through an echo command like:

echo 255 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq
```

Where "255" is the value I want to put in the file.
How can I succeed it through java?

答:
You can do system call, Runtime.exec(). Or if you want to do it in pure Java you can reproduce the behavior of the command line. "echo" is just writing on the standard output, and the '>' operator is redirecting the standard output to a file (but do not append).

So in Java..

```<code>FileWriter writer = new FileWriter(file);
writer.write("255");
</code>```

Title: How to run “echo” command through Java?

Body:
I want to change a value inside of a file named scaling_max_freq located in /sys/devices/system/cpu/cpu0/cpufreq/ on an Android device.

On an another post I've read that I'm able to do this through an echo command like:

echo 255 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq

Where "255" is the value I want to put in the file.
How can I succeed it through java?

Body:
You can do system call, Runtime.exec(). Or if you want to do it in pure Java you can reproduce the behavior of the command line. "echo" is just writing on the standard output, and the '>' operator is redirecting the standard output to a file (but do not append).

So in Java..

FileWriter writer = new FileWriter(file);
writer.write("255");