问:
Variables within app.config/web.config
Is it is possible to do something like the following in the app.config or web.config files?

```<code><appSettings>
 <add key="MyBaseDir" value="C:\MyBase" />
 <add key="Dir1" value="[MyBaseDir]\Dir1"/>
 <add key="Dir2" value="[MyBaseDir]\Dir2"/>
</appSettings>
</code>```

I then want to access Dir2 in my code by simply saying:

```<code> ConfigurationManager.AppSettings["Dir2"]
</code>```

This will help me when I install my application in different servers and locations wherein I will only have to change ONE entry in my entire app.config.
(I know I can manage all the concatenation in code, but I prefer it this way).

答:
You have a couple of options. You could do this with a build / deploy step which would process your configuration file replacing your variables with the correct value.

Another option would be to define your own Configuration section which supported this. For example imagine this xml:

```<code><variableAppSettings>
 <variables>
    <add key="@BaseDir" value="c:\Programs\Widget"/>
 </variables>
 <appSettings>
    <add key="PathToDir" value="@BaseDir\Dir1"/>
 </appSettings>
</variableAppSettings>
</code>```

Now you would implement this using custom configuration objects which would handle replacing the variables for you at runtime.

OwnerDisplayName: DeeStackOverflow

ContentLicense: CC BY-SA 2.5

Title: Variables within app.config/web.config

Body:
Is it is possible to do something like the following in the app.config or web.config files?

<appSettings>
 <add key="MyBaseDir" value="C:\MyBase" />
 <add key="Dir1" value="[MyBaseDir]\Dir1"/>
 <add key="Dir2" value="[MyBaseDir]\Dir2"/>
</appSettings>

I then want to access Dir2 in my code by simply saying:

 ConfigurationManager.AppSettings["Dir2"]

This will help me when I install my application in different servers and locations wherein I will only have to change ONE entry in my entire app.config.
(I know I can manage all the concatenation in code, but I prefer it this way).

LastEditorDisplayName: LFSR Consulting

Body:
You have a couple of options. You could do this with a build / deploy step which would process your configuration file replacing your variables with the correct value.

Another option would be to define your own Configuration section which supported this. For example imagine this xml:

<variableAppSettings>
 <variables>
    <add key="@BaseDir" value="c:\Programs\Widget"/>
 </variables>
 <appSettings>
    <add key="PathToDir" value="@BaseDir\Dir1"/>
 </appSettings>
</variableAppSettings>

Now you would implement this using custom configuration objects which would handle replacing the variables for you at runtime.

OwnerDisplayName: Josh


来源: stackexchange

问:
Getting errors with os.listdir within flask and heroku
I have an application that, takes the url and returns a files corresponding to it. I wanted to push it on heroku but i get this error :
 **File "/app/server.py", line 1525, in upload1

```<code>music = os.listdir(foldername)
</code>```

FileNotFoundError: [Errno 2] No such file or directory: 'favicon.ico'**

Then i tried to add favicon.ico in all of the folders and i am getting

**File "/app/server.py", line 1525, in upload1

```<code>music = os.listdir(foldername)
</code>```

NotADirectoryError: [Errno 20] Not a directory: 'favicon.ico'**

The part where it looks to struggle is

    @app.route('/<path:foldername>')
    def upload1(foldername):
        music = os.listdir(foldername)
        print(music)
        path_to_file = music[0]

        return send_file(
        foldername+"/"+path_to_file,
        mimetype="audio/mp3",
        as_attachment=True,
        attachment_filename=path_to_file )

```

答:
```<code>@app.route('/<path:foldername>')
    def upload1(foldername):
        abs_path = os.path.abspath(foldername)
        music = os.listdir(abs_path)
        path_to_file = os.path.join(abs_path, music[0])

        return send_file(
        foldername+"/"+path_to_file,
        mimetype="audio/mp3",
        as_attachment=True,
        attachment_filename=path_to_file )
</code>```

it will first take the foldername from param and then convert into abspath.
then listdir would list all the files, then it will take first file from list and join path.

ContentLicense: CC BY-SA 4.0

Body:
I have an application that, takes the url and returns a files corresponding to it. I wanted to push it on heroku but i get this error :
 **File "/app/server.py", line 1525, in upload1

music = os.listdir(foldername)

FileNotFoundError: [Errno 2] No such file or directory: 'favicon.ico'**

Then i tried to add favicon.ico in all of the folders and i am getting

**File "/app/server.py", line 1525, in upload1

music = os.listdir(foldername)

NotADirectoryError: [Errno 20] Not a directory: 'favicon.ico'**

The part where it looks to struggle is

    @app.route('/<path:foldername>')
    def upload1(foldername):
        music = os.listdir(foldername)
        print(music)
        path_to_file = music[0]

        return send_file(
        foldername+"/"+path_to_file,
        mimetype="audio/mp3",
        as_attachment=True,
        attachment_filename=path_to_file )

Body:
@app.route('/<path:foldername>')
    def upload1(foldername):
        abs_path = os.path.abspath(foldername)
        music = os.listdir(abs_path)
        path_to_file = os.path.join(abs_path, music[0])

        return send_file(
        foldername+"/"+path_to_file,
        mimetype="audio/mp3",
        as_attachment=True,
        attachment_filename=path_to_file )

it will first take the foldername from param and then convert into abspath.
then listdir would list all the files, then it will take first file from list and join path.


问:
Storage/File delete methods don't delete the file from storage
I am uploading images to storage/uploads and have a queue job that uploads those images to AWS. Here is the code of the job:

```<code>$path = storage_path() . '/uploads/' . $this->fileId;
$fileName = $this->fileId . '.png';

if (Storage::disk('s3images')->put('profile/' . $fileName, fopen($path, 'r+'))) {
   File::delete($path);
}
</code>```

Once the image has been uploaded to AWS the job is supposed to delete the image from storage/uploads but it's not doing that. The images are successfully uploaded to AWS. I tried to delete specific files directly without the if-statement but nothing seems to work. I even tried with Storage::delete but that didn't work either. Could someone point me in the right direction please?

答:
If your specifying the full directory path of the file you can use unlink a native way to delete files from the server.

```<code>$path = storage_path() . '/uploads/' . $this->fileId;
$fileName = $this->fileId . '.png';
$isUploaded = Storage::disk('s3images')->put('profile/' . $fileName, fopen($path, 'r+'));

if ($isUploaded) {
  unlink($path);
}
</code>```

Documentation: unlink php

Body:
I am uploading images to storage/uploads and have a queue job that uploads those images to AWS. Here is the code of the job:

$path = storage_path() . '/uploads/' . $this->fileId;
$fileName = $this->fileId . '.png';

if (Storage::disk('s3images')->put('profile/' . $fileName, fopen($path, 'r+'))) {
   File::delete($path);
}

Once the image has been uploaded to AWS the job is supposed to delete the image from storage/uploads but it's not doing that. The images are successfully uploaded to AWS. I tried to delete specific files directly without the if-statement but nothing seems to work. I even tried with Storage::delete but that didn't work either. Could someone point me in the right direction please?

Body:
If your specifying the full directory path of the file you can use unlink a native way to delete files from the server.

$path = storage_path() . '/uploads/' . $this->fileId;
$fileName = $this->fileId . '.png';
$isUploaded = Storage::disk('s3images')->put('profile/' . $fileName, fopen($path, 'r+'));

if ($isUploaded) {
  unlink($path);
}

Documentation: unlink php


问:
How to keyword search only tweets from 'People you Follow' in Tweepy
Is it possible to use the API search in Tweepy to restrict a keyword search to only people you follow? For example, on the web, the URL would be: https://twitter.com/search?q=keyword&f=live&pf=on

I tried using the pf= paramater, since that is what shows up in the web URL. For example: pf='on' or pf=true. But it is still returning unfiltered tweets.

What I have currently:

```<code>for tweet in tweepy.Cursor(api.search,
                           q='keyword',
                           result_type='recent',
                           pf='on').items(20)
</code>```

I don't see any reference to this in the API docs. Is there some other it would have to be done?

答: There's nothing available in the search API that would let you do this using an operator directly. One (clunky) way you could achieve this would be to put all the the people you are following onto a Twitter list, and then use the list:username/listname operator inside the q parameter to limit the search to the accounts in that list.

Body:
Is it possible to use the API search in Tweepy to restrict a keyword search to only people you follow? For example, on the web, the URL would be: https://twitter.com/search?q=keyword&f=live&pf=on

I tried using the pf= paramater, since that is what shows up in the web URL. For example: pf='on' or pf=true. But it is still returning unfiltered tweets.

What I have currently:

for tweet in tweepy.Cursor(api.search,
                           q='keyword',
                           result_type='recent',
                           pf='on').items(20)

I don't see any reference to this in the API docs. Is there some other it would have to be done?


问:
Updating a List of Object from another list of object using java stream
I have a list of Object A

```<code>A{
name
age
dob
}
</code>```

and list of Object B

```<code>B{
name
dob
}
</code>```

.

I always get the List of A with A.dob as null. and List of B with B.dob having value.
I need to loop thru List of A and List of B find the common objects using the name field in each A and B object and  update A.dob using B.dob

Can this be done using streams?

答:
I'd suggest modifying the list of A objects in a forEach loop:</p>

```<code>// define: List<A> aList =

// define: List<B> bList =

aList.forEach(aListElement -> {
            // find the first B object with matching name:
            Optional<B> matchingBElem = bList.stream()
                    .filter(bElem -> Objects.equals(aListElement.getName(), bElem.getName()))
                    .findFirst();

            // and use it to set the dob value in this A list element:
            if (matchingBElem.isPresent()) {
                aListElement.setDob(matchingBElem.get().getDob());
            }

        }
);
</code>```

Body:
I have a list of Object A

A{
name
age
dob
}

and list of Object B

B{
name
dob
}

.

I always get the List of A with A.dob as null. and List of B with B.dob having value.
I need to loop thru List of A and List of B find the common objects using the name field in each A and B object and  update A.dob using B.dob

Can this be done using streams?

Body:
I'd suggest modifying the list of A objects in a forEach loop:

// define: List<A> aList =

// define: List<B> bList =

aList.forEach(aListElement -> {
            // find the first B object with matching name:
            Optional<B> matchingBElem = bList.stream()
                    .filter(bElem -> Objects.equals(aListElement.getName(), bElem.getName()))
                    .findFirst();

            // and use it to set the dob value in this A list element:
            if (matchingBElem.isPresent()) {
                aListElement.setDob(matchingBElem.get().getDob());
            }

        }
);


问:
SQL Logic for generating new column based Matching field values
```<code>Input:
CUST TAX_TYPE
a      TIN
a      TIN
a      SSN
b      TIN
b      TIN
b      TIN
c      SSN
c      SSN
c      null
</code>```

```<code>Output:
CUST TAX_TYPE VALID
a      TIN     n
a      TIN     n
a      SSN     n
b      TIN     y
b      TIN     y
b      TIN     y
c      SSN     n
c      SSN     n
c      null    n
</code>```

If same CUST has more than one TAX_TYPE, I should mark it as 'n' else if the same CUST has the same tax_type I should mark as 'y' in the VALID column. Can any one suggest the optimized spark-sql or standard sql (so that I can convert to spark sql query) logic query for this scenario

答:
Use case and window functions:

```<code>select t.*,
       (case when min(TAX_TYPE) over (partition by cust) = max(tax_type) over (partition by cust) and
                  count(*) over (partition by cust) = count(tax_type) over (partition by cust)
             then 'y' else 'n'
        end) as valid
from t;
</code>```

The second condition is validating that there are no NULL values.

Body:
Input:
CUST TAX_TYPE
a      TIN
a      TIN
a      SSN
b      TIN
b      TIN
b      TIN
c      SSN
c      SSN
c      null

Output:
CUST TAX_TYPE VALID
a      TIN     n
a      TIN     n
a      SSN     n
b      TIN     y
b      TIN     y
b      TIN     y
c      SSN     n
c      SSN     n
c      null    n

If same CUST has more than one TAX_TYPE, I should mark it as 'n' else if the same CUST has the same tax_type I should mark as 'y' in the VALID column. Can any one suggest the optimized spark-sql or standard sql (so that I can convert to spark sql query) logic query for this scenario

Body:
Use case and window functions:

select t.*,
       (case when min(TAX_TYPE) over (partition by cust) = max(tax_type) over (partition by cust) and
                  count(*) over (partition by cust) = count(tax_type) over (partition by cust)
             then 'y' else 'n'
        end) as valid
from t;

The second condition is validating that there are no NULL values.


问:
Google Cloud Search API - Search Example PHP
I discovered the new (Google API Cloud Search API : https://developers.google.com/cloud-search/docs/reference/rest) and I would like to use the (Suggest : https://developers.google.com/cloud-search/docs/reference/rest/v1/query/suggest) method. I looked all over the internet for a PHP example to use this API, but I couldn't find anything. Can you help me ?

Thank you

Julia

答:
You need to use Google APIs Client Library for PHP since some APIs like Cloud Search doesn't have a client library.

With APIs Client Library you can use the endpoints that are in the documentation that you found

In this link is explained how to make requests to the APIs using HTTP calls.


问:
Multi-isotope filtering with ramda
I am enhancing an isotope application - and I am now in the process of trying to combine the values of a multi-filter to the application.

I've noticed 2 problems.

1st - is when I set a filter - it updates the state - but its almost like my state tree is one behind - it doesn't appear to have registered the setState directly after I look at the state. So the filtering isn't accurate.

2nd - the actual combination of multi-filters. So I know I could have 2 filters - and each may have a set of values

```<code>let availableFilters = ['statuspromo', 'regionspromo'];
//statuspromo
//regionspromo
let comboValues = [];
availableFilters.map(filter => {
    if(this.state['filteredOption_'+filter]){
        comboValues.push(this.state['filteredOption_'+filter]);
    }
});
</code>```

this gives me a comboValues array -- that contains the 2 filters -- but now I need to combine them.

at this level comboValues - looks like [['LIVE', 'IN_PROGRESS'], ['SIEE']]

I first used ramda to flatten the array - flatten(comboValues) - but this will give me an OR situation.

I need to merge the two array sets or more ---- to be something like "opts = '.LIVE.SIEE, .IN_PROGRESS.SIEE'" - push this into the isotope filter arrange(opts) so that the 2 filters are in AND mode

what's the best way of doing this. Want to do this cleanly -- even the way I map over the combovalues with the old method I am adding a class variant and a join to get picked up on

```<code>let opts = comboValues.map(val => '.' + val).join(',');
let options = { filter: opts };
this.state.iso.arrange(options);
</code>```

```<code>        let layer1 = [];
        let layer2 = [];

        let merged = [];

        if(comboValues[0]){
            layer1 = comboValues[0].map(val => '.' + val);//.join(',');
        }
        if(comboValues[1]){
            layer2 = comboValues[1].map(val => '.' + val);//.join(',');

            layer1.map(val1 => {
                layer2.map(val2 => {
                    merged.push(val1+''+val2);
                });
            });
        }

//let layer1 = [".EXPIRED", ".SONY_FINALIZING"]
//let layer2 = [".SIEJA-ASIA"]
//let merged = [".EXPIRED.SIEJA-ASIA", ".SONY_FINALIZING.SIEJA-ASIA"]

        console.log("layer1", layer1);
        console.log("layer2", layer2);

        console.log("merged", merged);

        let opts = merged.join(',');
        console.log("opts", opts);
        let options = { filter: opts };
        this.state.iso.arrange(options);
</code>```

final current code

```<code>multiFilterIsotope = () => {
    console.log("this.state!!!!!!!!!!!", this.state);

    let availableFilters = ['statuspromo', 'regionspromo'];
    //statuspromo
    //regionspromo
    let comboValues = [];
    availableFilters.map(filter => {
        if(this.state['filteredOption_'+filter]){
            comboValues.push(this.state['filteredOption_'+filter]);
        }
    });

    //comboValues = flatten(comboValues);
    //console.log("comboValues", comboValues);

    let layer1 = [];
    let layer2 = [];

    let merged = [];

    if(comboValues[0] && comboValues[0].length > 0){
        layer1 = comboValues[0].map(val => '.' + val);//.join(',');

        //merged = layer1;
    }
    if(comboValues[1] && comboValues[1].length > 0){
        layer2 = comboValues[1].map(val => '.' + val);//.join(',');

        layer1.map(val1 => {
            layer2.map(val2 => {
                merged.push(val1+''+val2);
            });
        });
    } else {
        merged = layer1;
    }

    console.log("layer1", layer1);
    console.log("layer2", layer2);

    console.log("merged", merged);

    let opts = merged.join(',');
    console.log("opts", opts);
    let options = { filter: opts };
    this.state.iso.arrange(options);

    //comboValues = ["SONY_FINALIZING.SIEJA-ASIA", "EXPIRED.SIEJA-ASIA"];

    //let opts = comboValues.map(val => '.' + val).join(',');
    //let options = { filter: opts };
    //this.state.iso.arrange(options);
}
</code>```

答:
I've come up with this -- but will this work with more filter options - like 3 filters?</p>

```<code>    function mash(layer, m){
        let merge = [];

        console.log("layer", layer);

        m.map(val1 => {
            layer.map(val2 => {
                merge.push(val1 + '' + val2);
            });
        });
        if(m.length === 0){
            merge = layer;
        }
        return merge;
    }

    let merged = [];
    comboValues.map(layer => {
        let l = layer.map(val => '.' + val);
        //console.log('l', l);
        if(l.length > 0) {
            merged = mash(l, merged);
        }
    });
</code>```

Title: Multi-isotope filtering with ramda

Body:
I am enhancing an isotope application - and I am now in the process of trying to combine the values of a multi-filter to the application.

I've noticed 2 problems.

1st - is when I set a filter - it updates the state - but its almost like my state tree is one behind - it doesn't appear to have registered the setState directly after I look at the state. So the filtering isn't accurate.

2nd - the actual combination of multi-filters. So I know I could have 2 filters - and each may have a set of values

let availableFilters = ['statuspromo', 'regionspromo'];
//statuspromo
//regionspromo
let comboValues = [];
availableFilters.map(filter => {
    if(this.state['filteredOption_'+filter]){
        comboValues.push(this.state['filteredOption_'+filter]);
    }
});

this gives me a comboValues array -- that contains the 2 filters -- but now I need to combine them.

at this level comboValues - looks like [['LIVE', 'IN_PROGRESS'], ['SIEE']]

I first used ramda to flatten the array - flatten(comboValues) - but this will give me an OR situation.

I need to merge the two array sets or more ---- to be something like "opts = '.LIVE.SIEE, .IN_PROGRESS.SIEE'" - push this into the isotope filter arrange(opts) so that the 2 filters are in AND mode

what's the best way of doing this. Want to do this cleanly -- even the way I map over the combovalues with the old method I am adding a class variant and a join to get picked up on

let opts = comboValues.map(val => '.' + val).join(',');
let options = { filter: opts };
this.state.iso.arrange(options);

        let layer1 = [];
        let layer2 = [];

        let merged = [];

        if(comboValues[0]){
            layer1 = comboValues[0].map(val => '.' + val);//.join(',');
        }
        if(comboValues[1]){
            layer2 = comboValues[1].map(val => '.' + val);//.join(',');

            layer1.map(val1 => {
                layer2.map(val2 => {
                    merged.push(val1+''+val2);
                });
            });
        }

//let layer1 = [".EXPIRED", ".SONY_FINALIZING"]
//let layer2 = [".SIEJA-ASIA"]
//let merged = [".EXPIRED.SIEJA-ASIA", ".SONY_FINALIZING.SIEJA-ASIA"]

        console.log("layer1", layer1);
        console.log("layer2", layer2);

        console.log("merged", merged);

        let opts = merged.join(',');
        console.log("opts", opts);
        let options = { filter: opts };
        this.state.iso.arrange(options);

final current code

multiFilterIsotope = () => {
    console.log("this.state!!!!!!!!!!!", this.state);

    let availableFilters = ['statuspromo', 'regionspromo'];
    //statuspromo
    //regionspromo
    let comboValues = [];
    availableFilters.map(filter => {
        if(this.state['filteredOption_'+filter]){
            comboValues.push(this.state['filteredOption_'+filter]);
        }
    });

    //comboValues = flatten(comboValues);
    //console.log("comboValues", comboValues);

    let layer1 = [];
    let layer2 = [];

    let merged = [];

    if(comboValues[0] && comboValues[0].length > 0){
        layer1 = comboValues[0].map(val => '.' + val);//.join(',');

        //merged = layer1;
    }
    if(comboValues[1] && comboValues[1].length > 0){
        layer2 = comboValues[1].map(val => '.' + val);//.join(',');

        layer1.map(val1 => {
            layer2.map(val2 => {
                merged.push(val1+''+val2);
            });
        });
    } else {
        merged = layer1;
    }

    console.log("layer1", layer1);
    console.log("layer2", layer2);

    console.log("merged", merged);

    let opts = merged.join(',');
    console.log("opts", opts);
    let options = { filter: opts };
    this.state.iso.arrange(options);

    //comboValues = ["SONY_FINALIZING.SIEJA-ASIA", "EXPIRED.SIEJA-ASIA"];

    //let opts = comboValues.map(val => '.' + val).join(',');
    //let options = { filter: opts };
    //this.state.iso.arrange(options);
}

Body:
I've come up with this -- but will this work with more filter options - like 3 filters?

    function mash(layer, m){
        let merge = [];

        console.log("layer", layer);

        m.map(val1 => {
            layer.map(val2 => {
                merge.push(val1 + '' + val2);
            });
        });
        if(m.length === 0){
            merge = layer;
        }
        return merge;
    }

    let merged = [];
    comboValues.map(layer => {
        let l = layer.map(val => '.' + val);
        //console.log('l', l);
        if(l.length > 0) {
            merged = mash(l, merged);
        }
    });


问:
How to use optional command line arguments in a python function?
I want a more compact and scalable way to use command line args to feed a python function, here is what i have:

```<code>def getRelevant (number = 5, sortBy = "Change"):
    number, sortBy = int(number), sortBy
    relevant = ...
    return relevant

if __name__ == "__main__":
    if len(sys.argv) == 3:
        print(getRelevant(sys.argv[1], sys.argv[2]))
    elif len(sys.argv) == 2:
        print(getRelevant(sys.argv[1]))
    else:
        print(getRelevant())
</code>```

It works. But I'm not happy with this conditionals, is there a way to make it simpler?

答:
argparse is of course the tool you want to learn for commandline options and arguments - it's part of the tools alls devs should know about (with logging and pdb).

This being said, for this exact case, you could also solve the issue very simply without argparse:

```<code>if __name__ == "__main__":
    args = sys.argv[1:]
    print(getRelevant(*args))
</code>```

Body:
I want a more compact and scalable way to use command line args to feed a python function, here is what i have:

def getRelevant (number = 5, sortBy = "Change"):
    number, sortBy = int(number), sortBy
    relevant = ...
    return relevant

if __name__ == "__main__":
    if len(sys.argv) == 3:
        print(getRelevant(sys.argv[1], sys.argv[2]))
    elif len(sys.argv) == 2:
        print(getRelevant(sys.argv[1]))
    else:
        print(getRelevant())

It works. But I'm not happy with this conditionals, is there a way to make it simpler?

Body:
argparse is of course the tool you want to learn for commandline options and arguments - it's part of the tools alls devs should know about (with logging and pdb).

This being said, for this exact case, you could also solve the issue very simply without argparse:

if __name__ == "__main__":
    args = sys.argv[1:]
    print(getRelevant(*args))


问:
how to fetch data from existing remote oracle database on ruby on rails
I have already installed the required oci8 gem as well as instant client connection was successful
however i still can't retrieve the data from the existing table from the database such as there is a userlists table

I have tried to use scaffold without a migration to create the application but oracle has given me the error saying

```<code>OCIError: ORA-00942: table or view does not exist
</code>```

Below is my database.yml setup

default: &default
  adapter: oracle_enhanced
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  host: link to server
  database: dbname
  username: dbuser
  password: dbpass
  port: portnum

development:
  adapter: oracle_enhanced
  username: dbuser
  password: dbpass
  database: serverlink/dbname
```

答:
Most probably the error is about schema_migrations table (contains one varchar column version), which rails uses to store info about which migrations have been applied to the database.

If you can change the database - the simplest way is to create that table, as you might need that later.

Also you can try setting config.active_record.migration_error = false

Body:
I have already installed the required oci8 gem as well as instant client connection was successful
however i still can't retrieve the data from the existing table from the database such as there is a userlists table

I have tried to use scaffold without a migration to create the application but oracle has given me the error saying

OCIError: ORA-00942: table or view does not exist

Below is my database.yml setup

default: &default
  adapter: oracle_enhanced
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  host: link to server
  database: dbname
  username: dbuser
  password: dbpass
  port: portnum

development:
  adapter: oracle_enhanced
  username: dbuser
  password: dbpass
  database: serverlink/dbname


问:
Show an image inside an Ext.window.Window?
This sounds incredibly simple, but I'm having issues displaying an image from a relative path in a popup window triggered by an onclick event from another component. Here's an example snippet:

```<code>var dialog = Ext.create(Ext.window.Window, {
    layout: 'vbox',
    maximizable: true,
    scrollable: true,
    id: 'dialog',
    title: 'Help',
    items: [
        {
            xtype: 'image',
            src: 'path/to/image/image1.png',
            margin: '10 10 10 10'
        },
        {
            xtype: 'image',
            src: 'path/to/image/image2.png',
            margin: '10 10 10 10'
        }
    ]
});
dialog.show();
</code>```

So, my problem is that when I create and show the window for the first time, the images don't appear. Then, if I close it and reopen it, the images appear. I know that this is due to the browser requesting the images and showing them too fast. I've been tinkering and tinkering and can't find a good solution to show the images the right way the first time. Any advice is appreciated.

答:
You need to set width and height parameters.

```<code> var dialog = Ext.create(Ext.window.Window, {
            layout: 'vbox',
            maximizable: true,
            scrollable: true,
            id: 'dialog',
            width: 500,
            height: 600,
            title: 'Help',
            items: [{
                width: 300,
                height: 200,
                xtype: 'image',
                src: 'https://fiddle.sencha.com/classic/resources/images/sencha-logo.png',
                margin: '10 10 10 10'
            }, {
                width: 300,
                height: 200,
                xtype: 'image',
                src: 'https://fiddle.sencha.com/classic/resources/images/sencha-logo.png',
                margin: '10 10 10 10'
            }]
        });
        dialog.show();
</code>```

Check example on https://fiddle.sencha.com/#view/editor&fiddle/33q1

Body:
This sounds incredibly simple, but I'm having issues displaying an image from a relative path in a popup window triggered by an onclick event from another component. Here's an example snippet:

var dialog = Ext.create(Ext.window.Window, {
    layout: 'vbox',
    maximizable: true,
    scrollable: true,
    id: 'dialog',
    title: 'Help',
    items: [
        {
            xtype: 'image',
            src: 'path/to/image/image1.png',
            margin: '10 10 10 10'
        },
        {
            xtype: 'image',
            src: 'path/to/image/image2.png',
            margin: '10 10 10 10'
        }
    ]
});
dialog.show();

So, my problem is that when I create and show the window for the first time, the images don't appear. Then, if I close it and reopen it, the images appear. I know that this is due to the browser requesting the images and showing them too fast. I've been tinkering and tinkering and can't find a good solution to show the images the right way the first time. Any advice is appreciated.

Body:
You need to set width and height parameters.

 var dialog = Ext.create(Ext.window.Window, {
            layout: 'vbox',
            maximizable: true,
            scrollable: true,
            id: 'dialog',
            width: 500,
            height: 600,
            title: 'Help',
            items: [{
                width: 300,
                height: 200,
                xtype: 'image',
                src: 'https://fiddle.sencha.com/classic/resources/images/sencha-logo.png',
                margin: '10 10 10 10'
            }, {
                width: 300,
                height: 200,
                xtype: 'image',
                src: 'https://fiddle.sencha.com/classic/resources/images/sencha-logo.png',
                margin: '10 10 10 10'
            }]
        });
        dialog.show();

Check example on https://fiddle.sencha.com/#view/editor&fiddle/33q1


问:
Regex for plain and accentuated chars, with spaces and dashes only inside the string
I'm trying to come up with a regex to use inside a JSON schema.
The constraints:

from 0 to 100 chars string

accepts letters, accentuated letters (no greek chars, but also include œ)

accepts space, ' and - ONLY inside the string

I have a brute force approach:

```<code>"^((?![Ð×Þß÷þø])[a-zA-ZÀ-ÿŒœ]{1})((?![Ð×Þß÷þø])[-'a-zA-ZÀ-ÿŒœ ]{0,98})((?![Ð×Þß÷þø])[a-zA-ZÀ-ÿŒœ]{1})$"
</code>```

This works.. almost: the character selection matches what I want. But it won't accept strings below 2 chars.
So, instead of creating three groups, is there a way to reject space, - and ' at the beginning and end of a group?

Bonus question: writing this I realize that contiguous spaces or dashes are not desirable either...

答:
You can do it with negative look-arounds, i.e. a look-ahead in front of it and a look-behind after it. And we also exclude the unwanted character group everywhere:

```<code>^((?!.*[Ð×Þß÷þø])(?![ '-])[-'a-zA-ZÀ-ÿŒœ ]{0,100})(?<![ '-])$
</code>```

Demo

Body:
I'm trying to come up with a regex to use inside a JSON schema.
The constraints:

from 0 to 100 chars string

accepts letters, accentuated letters (no greek chars, but also include œ)

accepts space, ' and - ONLY inside the string

I have a brute force approach:

"^((?![Ð×Þß÷þø])[a-zA-ZÀ-ÿŒœ]{1})((?![Ð×Þß÷þø])[-'a-zA-ZÀ-ÿŒœ ]{0,98})((?![Ð×Þß÷þø])[a-zA-ZÀ-ÿŒœ]{1})$"

This works.. almost: the character selection matches what I want. But it won't accept strings below 2 chars.
So, instead of creating three groups, is there a way to reject space, - and ' at the beginning and end of a group?

Bonus question: writing this I realize that contiguous spaces or dashes are not desirable either...

Body:
You can do it with negative look-arounds, i.e. a look-ahead in front of it and a look-behind after it. And we also exclude the unwanted character group everywhere:

^((?!.*[Ð×Þß÷þø])(?![ '-])[-'a-zA-ZÀ-ÿŒœ ]{0,100})(?<![ '-])$

Demo


问:
Adb reverse tcp not working on android connected remotely
I am trying to execute reverse tcp command on a android device connected remotely(using adb connect <ip-address>). But I am getting following error while executing:

```<code>adb -s 192.168.0.101 reverse tcp:8081 tcp:8081
error: more than one device/emulator
</code>```

but I have only one device connected.

```<code>adb devices
List of devices attached
192.168.0.101:5555      device
</code>```

same command works fine if I connect my device using usb. Any Ideas ?

答:
I just came across this, and while none of the answers worked I eventually got it working repeatably.  Following these steps should get you wirelessly debugging your React Native app on your real Android device.

I ran adb kill-server && adb start-server first.  I'm not sure if that's strictly necessary.

Connect your phone and computer to the same network

Connect your phone to your computer via USB

adb tcpip 5555

adb reverse tcp:8081 tcp:5555

adb connect YOUR.PHONE.IP.ADDRESS:5555

You can find your phone's wifi IP address from Network Settings -> Wifi -> Wifi Preferences -> IP Address.

Disconnect the USB wire.

If the app isn't yet installed, install the app on your phone the way you usually do over USB, react-native run android for most cases.

Open the app, and you get an “Unable to load Script” error. Pressing ‘Reload’ gives an error “Could not connect to development server.”  Overcome your despair and push onwards.

Open the developer menu (shake the phone with your React Native app open) and select “Dev Settings”. Select “Debug server host & port for device” from the menu.
Find your computer’s ip address. Enter that in the window on your phone, followed by the port number 8081: YOUR.COMPUTER.IP.ADDRESS:8081

Now shake and reload.  Sometimes this doesn’t do anything, so closing the app and reopening does the trick.

At this point, you should see the bundler loading up with the familiar green bar.

shake and hit “debug js remotely”.

From here you should have your normal debugging experience, minus the wire.

Body:
I am trying to execute reverse tcp command on a android device connected remotely(using adb connect <ip-address>). But I am getting following error while executing:

adb -s 192.168.0.101 reverse tcp:8081 tcp:8081
error: more than one device/emulator

but I have only one device connected.

adb devices
List of devices attached
192.168.0.101:5555      device

same command works fine if I connect my device using usb. Any Ideas ?


问:
pick first and last int value from and list and continue the sequence till the end of list
Input:

```<code>l1 = [1,2,3,5,7,9,10,11,12,15]
</code>```

Expected output:

```<code>l2 = [[1,3],[5],[7],[9,12],[15]]
</code>```

In l2, the first nested list is the sequence from 1 to 3, so the first and last values are picked. 5 doesn't have any adjacent values (+/- 1), so 5 is in the second sublist, this follows until the sequence is exhausted.

Below is the code I have tried:

```<code>a = [1,2,3,5,7,9,10,11,12,15]
l=[]
l2 = []

def nested_list(n):
    for i in n:
        if i not in l:
            l.append(i)
            if i+1 not in a:
                break

l2.append(l)
nested_list(a)
print(l2)
</code>```

It's not iterating through all the elements of l1.
Any ideas?

Body:
Input:

l1 = [1,2,3,5,7,9,10,11,12,15]

Expected output:

l2 = [[1,3],[5],[7],[9,12],[15]]

In l2, the first nested list is the sequence from 1 to 3, so the first and last values are picked. 5 doesn't have any adjacent values (+/- 1), so 5 is in the second sublist, this follows until the sequence is exhausted.

Below is the code I have tried:

a = [1,2,3,5,7,9,10,11,12,15]
l=[]
l2 = []

def nested_list(n):
    for i in n:
        if i not in l:
            l.append(i)
            if i+1 not in a:
                break

l2.append(l)
nested_list(a)
print(l2)

It's not iterating through all the elements of l1.
Any ideas?

Body:
year = [[2002,2004,2005],[2003],[2004,2006,2008]]
M=[]
for i in year:
    for tpl in intspan(i).ranges():
        M.append(tpl)

Results:
[(2002, 2002),
 (2004, 2005),
 (2003, 2003),
 (2004, 2004),
 (2006, 2006),
 (2008, 2008)]

Iam not getting the right result. Iam trying to get the year span.


问:
How does doctrine handles unchanged field when updating an already existing entity
Supposing I have an entity mapped to a MariaDB database table with the following fields: ID, firstName and lastName.

This entity has been loaded from the database in the PHP object and I execute the following code

/**
 * $myEntity is the entity and $em is the entity manager
 * $myEntity->getFirstName(); Would be John
 * $myEntity->getLastName(); Would be Doe
 */

$myEntity->setFirstName("Bob");

$em->persist($myEntity);
$em->flush();
```

<p>Will this result in the following query:</p>

```UPDATE `table`SET `firstName` = 'Bob' WHERE `ID`= "x"
```

<p>Or the following query:</p>

```UPDATE `table` SET `firstName` = 'Bob', SET `lastName` = 'Doe' WHERE `ID` = 'x'
```

More generally: How does Doctrine handles unchanged fields, and what is consired as "unchhanged" ? Same value, no variable assignation, something else?

I have searched in the Doctrine documentation and on Google but I have found nothing about this question.

I am asking because I have an entity which is, obviously, bigger than the one in the example (35 columns, including 2 TEXT columns) and often only one or two columns are updated at a time.

答: Doctrine only updates what actually changed, so your first scenario will happen.</p>

Body:
Supposing I have an entity mapped to a MariaDB database table with the following fields: ID, firstName and lastName.

This entity has been loaded from the database in the PHP object and I execute the following code

/**
 * $myEntity is the entity and $em is the entity manager
 * $myEntity->getFirstName(); Would be John
 * $myEntity->getLastName(); Would be Doe
 */

$myEntity->setFirstName("Bob");

$em->persist($myEntity);
$em->flush();

Will this result in the following query:

UPDATE `table`SET `firstName` = 'Bob' WHERE `ID`= "x"

Or the following query:

UPDATE `table` SET `firstName` = 'Bob', SET `lastName` = 'Doe' WHERE `ID` = 'x'

More generally: How does Doctrine handles unchanged fields, and what is consired as "unchhanged" ? Same value, no variable assignation, something else?

I have searched in the Doctrine documentation and on Google but I have found nothing about this question.

I am asking because I have an entity which is, obviously, bigger than the one in the example (35 columns, including 2 TEXT columns) and often only one or two columns are updated at a time.


问:
optparse NA default not being overwritten by command-line argument
Consider the following script:

```<code>library(optparse)

option_list <- list(
    make_option(c('--sample_p'), default=NA, dest='sample_p', help='Sample probability of inclusion if randomly sampling records')
)

args <- parse_args(OptionParser(option_list=option_list))
print(args)

if(!is.na(args$sample_p)){
    print('Chose to sample')
}else{
    print('Did not choose to sample')
}
</code>```

I want to pass a floating-point value to the script, to be stored in args$sample_p. I've tried the following, but neither approach leaves me with 0.05 being stored:

$ Rscript test.R --sample_p 0.05
$sample_p
[1] NA

$help
[1] FALSE

[1] "Did not choose to sample"
$ Rscript test.R --sample_p=0.05
Warning message:
In getopt(spec = spec, opt = args) :
  long flag sample_p given a bad argument
$sample_p
[1] NA

$help
[1] FALSE

[1] "Did not choose to sample"
```

<p>However, if I change the default value of <code>sample_p</code> to a number, instead of <code>NA</code>, it works:</p>

```library(optparse)

option_list <- list(
    make_option(c('--sample_p'), default=0, dest='sample_p', help='Sample probability of inclusion if randomly sampling records')
)

args <- parse_args(OptionParser(option_list=option_list))
print(args)

if(!is.na(args$sample_p)){
    print('Chose to sample')
}else{
    print('Did not choose to sample')
}
```

<pre class="lang-sh prettyprint-override"><code>$ Rscript test.R --sample_p 0.05
$sample_p
[1] 0.05

$help
[1] FALSE

[1] "Chose to sample"
</code>```

Why does the NA as a default value cause problems?

答:
Looks like you need to use NA_real_ to specify the kind of NA to use in this context (https://stat.ethz.ch/R-manual/R-devel/library/base/html/NA.html).

```<code>option_list <- list(
    make_option(c('--sample_p'), default=NA_real_, dest='sample_p', help='Sample probability of inclusion if randomly sampling records')
)
</code>```

This is basically because of how type is handled in make_option().

Body:
Consider the following script:

library(optparse)

option_list <- list(
    make_option(c('--sample_p'), default=NA, dest='sample_p', help='Sample probability of inclusion if randomly sampling records')
)

args <- parse_args(OptionParser(option_list=option_list))
print(args)

if(!is.na(args$sample_p)){
    print('Chose to sample')
}else{
    print('Did not choose to sample')
}

I want to pass a floating-point value to the script, to be stored in args$sample_p. I've tried the following, but neither approach leaves me with 0.05 being stored:

$ Rscript test.R --sample_p 0.05
$sample_p
[1] NA

$help
[1] FALSE

[1] "Did not choose to sample"
$ Rscript test.R --sample_p=0.05
Warning message:
In getopt(spec = spec, opt = args) :
  long flag sample_p given a bad argument
$sample_p
[1] NA

$help
[1] FALSE

[1] "Did not choose to sample"

However, if I change the default value of sample_p to a number, instead of NA, it works:

library(optparse)

option_list <- list(
    make_option(c('--sample_p'), default=0, dest='sample_p', help='Sample probability of inclusion if randomly sampling records')
)

args <- parse_args(OptionParser(option_list=option_list))
print(args)

if(!is.na(args$sample_p)){
    print('Chose to sample')
}else{
    print('Did not choose to sample')
}

$ Rscript test.R --sample_p 0.05
$sample_p
[1] 0.05

$help
[1] FALSE

[1] "Chose to sample"

Why does the NA as a default value cause problems?

Body:
Looks like you need to use NA_real_ to specify the kind of NA to use in this context (https://stat.ethz.ch/R-manual/R-devel/library/base/html/NA.html).

option_list <- list(
    make_option(c('--sample_p'), default=NA_real_, dest='sample_p', help='Sample probability of inclusion if randomly sampling records')
)

This is basically because of how type is handled in make_option().


问:
Powershell Rest API problems to deliver Parameter
I am trying to translate a working CURL WebRequest into using pure powershell. Unfortunately I don't know what the parameter in Powershell is that replaces the CURL parameter --data.

The authentication (and simpler post requests I've already done with Powershell and REST) but for the specific CURL request I can't get the translation to Powershell right.

This is the working CURL Request:

```<code>curl -k https://RestAPI-URL -X GET -H "auth: Basic <Token>" -H "Content-Type: application/json" --data "{\"net_cidr\":\"10.0.0.0/8\"}"
</code>```

And this is the Powershell-Translation (Using PS-Version 5.1):

```<code>$json = ConvertTo-Json (@{"username"="Test";"password"="Test";})
$token = (Invoke-WebRequest -Uri "https://RestAPI-URL"  -Body $json -ContentType "application/json" -Method POST).content | Out-String | ConvertFrom-Json

$token = $token.access_token
$header = @{auth="Basic $token"}

$Parameters = @{
  net_cidr = '10.0.0.0/8'
}

Invoke-RestMethod -Uri "https://RestAPI-URL" -Headers $header -body $Parameters -Method GET -ContentType "application/json"
</code>```

Error-Ouput from Webrequest trough Powershell:

FAILED: Please provide all parameters: net_id

答:
I had a similar issue with another API. I used the method below to troubleshoot it. Run this code and report what you see. You may have to include this net_id param. In my case I was missing a mandatory param that was not in the REST documentation for the app I was working with.

Below I put your code into function REST-CALL, then I included a function to help us understand the error (Get-ErrorFromResponseBody). We try the invoke-restmethod cmdlet, and on error it is caught and handled by Get-ErrorFromResponseBody. While this isn't quite your answer, it is a step towards it. I will update this after you report back what the response is.

```<code>function REST-CALL(){
    $json = ConvertTo-Json (@{"username"="Test";"password"="Test"})
    $token = (Invoke-WebRequest -Uri "https://RestAPI-URL"  -Body $json -ContentType "application/json" -Method POST).content | Out-String | ConvertFrom-Json

    $token = $token.access_token
    $header = @{auth="Basic $token"}

$Parameters = @{
  net_cidr = '10.0.0.0/8'
}

        try{
            $global:site = Invoke-RestMethod -Uri "https://RestAPI-URL" -Headers $header -body $Parameters -Method POST -ContentType "application/json"

        }
        catch{
            write-host "An exception occurred: The request did not complete."
            Get-ErrorFromResponseBody($_)
        }
}

Function Get-ErrorFromResponseBody($ErrorMessage) {
    #Determine if we are using PowerShell v5.1 and lower exception handling
    if ($PSVersionTable.PSVersion.Major -lt 6) {
        if ($Error.Exception.Response) {
            $Reader = New-Object System.IO.StreamReader($ErrorMessage.Exception.Response.GetResponseStream())
            $Reader.BaseStream.Position = 0
            $Reader.DiscardBufferedData()
            $ResponseBody = $Reader.ReadToEnd()
            if ($ResponseBody.StartsWith('{')) {
                $ResponseBody = $ResponseBody | ConvertFrom-Json
            }
            return $ResponseBody
        }
    }
    else {
        return $ErrorMessage.ErrorDetails.Message
    }
}

REST-CALL
</code>```

"The --data flag should be for defining POST data." So I feel strongly you should try a POST method.

Body:
I am trying to translate a working CURL WebRequest into using pure powershell. Unfortunately I don't know what the parameter in Powershell is that replaces the CURL parameter --data.

The authentication (and simpler post requests I've already done with Powershell and REST) but for the specific CURL request I can't get the translation to Powershell right.

This is the working CURL Request:

curl -k https://RestAPI-URL -X GET -H "auth: Basic <Token>" -H "Content-Type: application/json" --data "{\"net_cidr\":\"10.0.0.0/8\"}"

And this is the Powershell-Translation (Using PS-Version 5.1):

$json = ConvertTo-Json (@{"username"="Test";"password"="Test";})
$token = (Invoke-WebRequest -Uri "https://RestAPI-URL"  -Body $json -ContentType "application/json" -Method POST).content | Out-String | ConvertFrom-Json

$token = $token.access_token
$header = @{auth="Basic $token"}

$Parameters = @{
  net_cidr = '10.0.0.0/8'
}

Invoke-RestMethod -Uri "https://RestAPI-URL" -Headers $header -body $Parameters -Method GET -ContentType "application/json"

Error-Ouput from Webrequest trough Powershell:

FAILED: Please provide all parameters: net_id

Body:
I had a similar issue with another API. I used the method below to troubleshoot it. Run this code and report what you see. You may have to include this net_id param. In my case I was missing a mandatory param that was not in the REST documentation for the app I was working with.

Below I put your code into function REST-CALL, then I included a function to help us understand the error (Get-ErrorFromResponseBody). We try the invoke-restmethod cmdlet, and on error it is caught and handled by Get-ErrorFromResponseBody. While this isn't quite your answer, it is a step towards it. I will update this after you report back what the response is.

function REST-CALL(){
    $json = ConvertTo-Json (@{"username"="Test";"password"="Test"})
    $token = (Invoke-WebRequest -Uri "https://RestAPI-URL"  -Body $json -ContentType "application/json" -Method POST).content | Out-String | ConvertFrom-Json

    $token = $token.access_token
    $header = @{auth="Basic $token"}

$Parameters = @{
  net_cidr = '10.0.0.0/8'
}

        try{
            $global:site = Invoke-RestMethod -Uri "https://RestAPI-URL" -Headers $header -body $Parameters -Method POST -ContentType "application/json"

        }
        catch{
            write-host "An exception occurred: The request did not complete."
            Get-ErrorFromResponseBody($_)
        }
}

Function Get-ErrorFromResponseBody($ErrorMessage) {
    #Determine if we are using PowerShell v5.1 and lower exception handling
    if ($PSVersionTable.PSVersion.Major -lt 6) {
        if ($Error.Exception.Response) {
            $Reader = New-Object System.IO.StreamReader($ErrorMessage.Exception.Response.GetResponseStream())
            $Reader.BaseStream.Position = 0
            $Reader.DiscardBufferedData()
            $ResponseBody = $Reader.ReadToEnd()
            if ($ResponseBody.StartsWith('{')) {
                $ResponseBody = $ResponseBody | ConvertFrom-Json
            }
            return $ResponseBody
        }
    }
    else {
        return $ErrorMessage.ErrorDetails.Message
    }
}

REST-CALL

"The --data flag should be for defining POST data." So I feel strongly you should try a POST method.


问:
Reading a config.json from a nodejs discord bot
i'm wondering if there is a other way to read my code from the config.json file ?

for example this is in my config.json

```<code>{
            "prefix": "!",
            "Settings":
            [
            {"bot_secret_token": "11111111111111"},
            {"PushToken": "11111111111111"},
            {"PushREF": "11111111111111"},
            {"Push_EventID": "11111111111111"},
            {"Home_IP": "11111111111111"},
            {"Home_port": "11111111111111"},
            {"Homes2_Port": "11111111111111"},
            {"GROUPNAME":"Settings"},
            {"OwnerID":"11111111111111"},
            {"StatusCHannelID":"11111111111111"},
            {"Channel2Way":"11111111111111"},
            {"PushAccount1":"11111111111111"},
            {"PushAccount2":"11111111111111"},
            {"GuildID":"11111111111111"},
            {"HumGroup":"11111111111111"},
]
}
</code>```

when i want to read out for example Ownerid i need to use this code
so i always need to count the number[8]

```<code>let owner =  client.users.get(config.Settings[8].OwnerID);
</code>```

is there a way to get rid of it and just do it in a better way?

regards

答:
You can do</p>

```<code>const config = require('./config');

const found = config.Settings.find((elem) => Object.keys(elem).some((key) => key == 'OwnerID'));

// found is equal to { OwnerID: '11111111111111' }
let owner = client.users.get(found.OwnerID);
</code>```

Body:
i'm wondering if there is a other way to read my code from the config.json file ?

for example this is in my config.json

{
            "prefix": "!",
            "Settings":
            [
            {"bot_secret_token": "11111111111111"},
            {"PushToken": "11111111111111"},
            {"PushREF": "11111111111111"},
            {"Push_EventID": "11111111111111"},
            {"Home_IP": "11111111111111"},
            {"Home_port": "11111111111111"},
            {"Homes2_Port": "11111111111111"},
            {"GROUPNAME":"Settings"},
            {"OwnerID":"11111111111111"},
            {"StatusCHannelID":"11111111111111"},
            {"Channel2Way":"11111111111111"},
            {"PushAccount1":"11111111111111"},
            {"PushAccount2":"11111111111111"},
            {"GuildID":"11111111111111"},
            {"HumGroup":"11111111111111"},
]
}

when i want to read out for example Ownerid i need to use this code
so i always need to count the number[8]

let owner =  client.users.get(config.Settings[8].OwnerID);

is there a way to get rid of it and just do it in a better way?

regards

Body:
You can do

const config = require('./config');

const found = config.Settings.find((elem) => Object.keys(elem).some((key) => key == 'OwnerID'));

// found is equal to { OwnerID: '11111111111111' }
let owner = client.users.get(found.OwnerID);


问:
How to dynamically set drawableTop for Button (android)
I have a Button:

```<code>    <Button
        android:id="@+id/btnCap2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:drawableTop="@drawable/btn_s9cap2"
        android:background="@null"
        android:layout_gravity="center_horizontal"
        android:drawablePadding="10dp"
        android:padding="20dp"
        android:text="@string/menu_btn_s9cap2"
        android:textColor="@color/black"
        android:textStyle="bold" />
</code>```

I need to adjust drawableTop dynamically . How can I do this ?
I know how to adjust background but this does not solve my problem.

```<code>btnCap2 = (Button) findViewById(R.id.btnCap2);
drawable = getResources().getDrawable(R.drawable.btn_s9cap2);
btnCap2.setBackground(drawable);
btnCap2.setOnClickListener(this);
</code>```

答:
Use </p>

```<code> btnCap2.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);
</code>```

Body:
I have a Button:

    <Button
        android:id="@+id/btnCap2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:drawableTop="@drawable/btn_s9cap2"
        android:background="@null"
        android:layout_gravity="center_horizontal"
        android:drawablePadding="10dp"
        android:padding="20dp"
        android:text="@string/menu_btn_s9cap2"
        android:textColor="@color/black"
        android:textStyle="bold" />

I need to adjust drawableTop dynamically . How can I do this ?
I know how to adjust background but this does not solve my problem.

btnCap2 = (Button) findViewById(R.id.btnCap2);
drawable = getResources().getDrawable(R.drawable.btn_s9cap2);
btnCap2.setBackground(drawable);
btnCap2.setOnClickListener(this);

Body:
Use

 btnCap2.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);


问:
Echarts. How update two series in realtimie chart?
I have realtime chart https://codepen.io/xnkka/pen/qBdNpmo, which has two series, updating with setOption work only to one of the series. How fix this?</p>

```<code>myChart.setOption({
    xAxis: {
      data: startDataCat,
    },
    series: [{
      data: startDataVal
    },
    {
      data: startDataVal2
    },
    ]
  });
</code>```

答:
Just checked your code, seems like you have missed to remove the value from second dataset. You forgot to add the below statement where you remove the data from front of second dataset.

startDataVal2.shift();

I have updated your code and made the following post.

var myChart = echarts.init(document.getElementById('main'));
    var dataCount = 500;
    var data = generateData(dataCount);
    var data2 = generateData(dataCount);
    var startDataCat = data.categoryData.slice(0, 250);
    var endDataCat = data.categoryData.slice(250);
    var startDataVal = data.valueData.slice(0, 250);
    var startDataVal2 = data2.valueData.slice(0, 250);
    var endDataVal = data.valueData.slice(250);
    var endDataVal2 = data2.valueData.slice(250);

    var option = {
      title: {
        text: "live chart",//
        left: 10
      },
      toolbox: {
        feature: {
          dataZoom: {
            yAxisIndex: false
          },
          saveAsImage: {
            pixelRatio: 2
          }
        }
      },
      legend: {
        data: ['first', 'second'],

    },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        bottom: 90
      },
      dataZoom: [{
        type: 'inside'
      }, {
        type: 'slider'
      }],
      xAxis: {
        data: startDataCat,
        silent: false,
        splitLine: {
          show: false
        },
        splitArea: {
          show: false
        }
      },
      yAxis: {
        splitArea: {
          show: false
        }
      },
      series: [{
        name: 'first',
        type: 'line',
        data: startDataVal,
        // Set `large` for large data amount
        large: true
      },
      {
        name: 'second',
        type: 'line',
        data: startDataVal2,
        // Set `large` for large data amount
        large: true
      }
      ]
    };
    setInterval(function () {
      startDataCat.shift();
      startDataCat.push(endDataCat.shift())
      startDataVal.shift();
      startDataVal2.shift();
      startDataVal.push(endDataVal.shift())
      startDataVal2.push(endDataVal2.shift())
      myChart.setOption({
        xAxis: {
          data: startDataCat,
        },
        series: [{
          data: startDataVal
        },
        {
          data: startDataVal2
        },
        ]
      });
    }, 1000);
    function generateData(count) {
      var baseValue = Math.random() * 1000;
      var time = +new Date(2020, 1, 1);
      var smallBaseValue;

      function next(idx) {
        smallBaseValue = idx % 30 === 0
          ? Math.random() * 700
          : (smallBaseValue + Math.random() * 500 - 250);
        baseValue += Math.random() * 20 - 10;
        return Math.max(
          0,
          Math.round(baseValue + smallBaseValue) + 3000
        );
      }

      var categoryData = [];
      var valueData = [];

      for (var i = 0; i < count; i++) {
        categoryData.push(echarts.format.formatTime('yyyy-MM-dd\nhh:mm:ss', time));
        valueData.push(next(i).toFixed(2));
        time += 1000;
      }

      return {
        categoryData: categoryData,
        valueData: valueData
      };
    }
    myChart.setOption(option)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="main" style="width:1000px; height:400px;"></div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/4.6.0/echarts.min.js"></script>
</body>

</html></code>```

Body:
I have realtime chart https://codepen.io/xnkka/pen/qBdNpmo, which has two series, updating with setOption work only to one of the series. How fix this?

myChart.setOption({
    xAxis: {
      data: startDataCat,
    },
    series: [{
      data: startDataVal
    },
    {
      data: startDataVal2
    },
    ]
  });

Body:
Just checked your code, seems like you have missed to remove the value from second dataset. You forgot to add the below statement where you remove the data from front of second dataset.

startDataVal2.shift();

I have updated your code and made the following post.

var myChart = echarts.init(document.getElementById('main'));
    var dataCount = 500;
    var data = generateData(dataCount);
    var data2 = generateData(dataCount);
    var startDataCat = data.categoryData.slice(0, 250);
    var endDataCat = data.categoryData.slice(250);
    var startDataVal = data.valueData.slice(0, 250);
    var startDataVal2 = data2.valueData.slice(0, 250);
    var endDataVal = data.valueData.slice(250);
    var endDataVal2 = data2.valueData.slice(250);

    var option = {
      title: {
        text: "live chart",//
        left: 10
      },
      toolbox: {
        feature: {
          dataZoom: {
            yAxisIndex: false
          },
          saveAsImage: {
            pixelRatio: 2
          }
        }
      },
      legend: {
        data: ['first', 'second'],

    },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        bottom: 90
      },
      dataZoom: [{
        type: 'inside'
      }, {
        type: 'slider'
      }],
      xAxis: {
        data: startDataCat,
        silent: false,
        splitLine: {
          show: false
        },
        splitArea: {
          show: false
        }
      },
      yAxis: {
        splitArea: {
          show: false
        }
      },
      series: [{
        name: 'first',
        type: 'line',
        data: startDataVal,
        // Set `large` for large data amount
        large: true
      },
      {
        name: 'second',
        type: 'line',
        data: startDataVal2,
        // Set `large` for large data amount
        large: true
      }
      ]
    };
    setInterval(function () {
      startDataCat.shift();
      startDataCat.push(endDataCat.shift())
      startDataVal.shift();
      startDataVal2.shift();
      startDataVal.push(endDataVal.shift())
      startDataVal2.push(endDataVal2.shift())
      myChart.setOption({
        xAxis: {
          data: startDataCat,
        },
        series: [{
          data: startDataVal
        },
        {
          data: startDataVal2
        },
        ]
      });
    }, 1000);
    function generateData(count) {
      var baseValue = Math.random() * 1000;
      var time = +new Date(2020, 1, 1);
      var smallBaseValue;

      function next(idx) {
        smallBaseValue = idx % 30 === 0
          ? Math.random() * 700
          : (smallBaseValue + Math.random() * 500 - 250);
        baseValue += Math.random() * 20 - 10;
        return Math.max(
          0,
          Math.round(baseValue + smallBaseValue) + 3000
        );
      }

      var categoryData = [];
      var valueData = [];

      for (var i = 0; i < count; i++) {
        categoryData.push(echarts.format.formatTime('yyyy-MM-dd\nhh:mm:ss', time));
        valueData.push(next(i).toFixed(2));
        time += 1000;
      }

      return {
        categoryData: categoryData,
        valueData: valueData
      };
    }
    myChart.setOption(option)

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="main" style="width:1000px; height:400px;"></div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/4.6.0/echarts.min.js"></script>
</body>

</html>


问:
Custom meta tag name color in VS Code
I'm new in developement. I'm using VSCode with One Dark+ theme. I would like to change a meta tag name color from "#E06C75" to "#1b1ff0". I tried modified the settings.json but it didn't work. Please help me to resolve this issue.

To make it clear what is "meta tag name" (maybe I use wrong words), it means something like <xs:complexType> </xs:complexType> in XML file or html tag like
,
 etc...

Here is my settings.json file.
Hope it helps.

Thank you.

```<code>    {
    "php.validate.executablePath": "C:/xampp/php/php.exe",
    "workbench.sideBar.location": "right",
    "workbench.iconTheme": "vscode-icons",
    "workbench.colorTheme": "One Dark Pro",
    "workbench.colorCustomizations":{
        "tokenColors": [
           {
            "scope": "entity.name.tag",
            "settings": {
                "foreground": "#1b1ff0"
            }
           },
           {
            "scope": "text.html.laravel-blade source.php.embedded.line.html entity.name.tag.laravel-blade",
            "settings": {
                "foreground": "#1b1ff0"
            }
        }
        ]
    }
}
</code>```

答: You can try the Highlight extension to configure the tokens colors. Althought I don't know if this plugin provides a way to says "any token", but since is using Regex I think there is and you should figure it out (maybe something like <*>*<*>, not actual Regex code btw but you get the idea)

Title: Custom meta tag name color in VS Code

Body:
I'm new in developement. I'm using VSCode with One Dark+ theme. I would like to change a meta tag name color from "#E06C75" to "#1b1ff0". I tried modified the settings.json but it didn't work. Please help me to resolve this issue.

To make it clear what is "meta tag name" (maybe I use wrong words), it means something like <xs:complexType> </xs:complexType> in XML file or html tag like
,
 etc...

Here is my settings.json file.
Hope it helps.

Thank you.

    {
    "php.validate.executablePath": "C:/xampp/php/php.exe",
    "workbench.sideBar.location": "right",
    "workbench.iconTheme": "vscode-icons",
    "workbench.colorTheme": "One Dark Pro",
    "workbench.colorCustomizations":{
        "tokenColors": [
           {
            "scope": "entity.name.tag",
            "settings": {
                "foreground": "#1b1ff0"
            }
           },
           {
            "scope": "text.html.laravel-blade source.php.embedded.line.html entity.name.tag.laravel-blade",
            "settings": {
                "foreground": "#1b1ff0"
            }
        }
        ]
    }
}


问:
Wordpress Archive Page - Get related taxonomies
Im currently building filters for my archive pages. Since I'm working on an ecommerce project (woocommerce) I using some additional custom terms like brands. Considering a user is on the product category archive T-Shirts, I now want to display all brands in the archive page which are related to T-Shirts.

With get_terms I can only display all brands, but not "cross-filtered" by T-Shirts. Any help is well appreciated. I also might be totally wrong with my approach.

My approach until now: (This cant be a common way)

```<code>$product_ids = get_posts(array(
    'numberposts'   => -1, // get all posts.
    'post_type'     => 'product',
    'post_status'   => 'publish',
    'tax_query'     => array(
        array(
            'taxonomy'  => 'product_cat',
            'field'     => 'term_id',
            'terms'     => $term_id,
        ),
    ),
    'fields'        => 'ids', // Only get post IDs
));

foreach ($product_ids as $test_id) {
    $aaa = wp_get_post_terms($test_id, 'manufacturer', array('fields' => 'ids'));
    $brands[] = $aaa[0];
}

$brands = array_unique($brands);
</code>```

答:
I'm having trouble figuring out what "brands" is. Your wp_get_post_terms statement is going to get all the posts for each category in taxonomy "manufacturer." If manufacturer = brands, you can add this loop to cycle through them:

```<code>foreach ($product_ids as $test_id) {
$post = get_post($test_id);
echo '>> ' . $post->post_name . '</br>';
$aaa = wp_get_post_terms($test_id, 'manufacturer',
    array('fields' => 'id=>slug'));

foreach( $aaa as $a) {
    echo $a . '</br>';
    }
</code>```

}

You can then add 'if' statements to make your comparisons.

Body:
Im currently building filters for my archive pages. Since I'm working on an ecommerce project (woocommerce) I using some additional custom terms like brands. Considering a user is on the product category archive T-Shirts, I now want to display all brands in the archive page which are related to T-Shirts.

With get_terms I can only display all brands, but not "cross-filtered" by T-Shirts. Any help is well appreciated. I also might be totally wrong with my approach.

My approach until now: (This cant be a common way)

$product_ids = get_posts(array(
    'numberposts'   => -1, // get all posts.
    'post_type'     => 'product',
    'post_status'   => 'publish',
    'tax_query'     => array(
        array(
            'taxonomy'  => 'product_cat',
            'field'     => 'term_id',
            'terms'     => $term_id,
        ),
    ),
    'fields'        => 'ids', // Only get post IDs
));

foreach ($product_ids as $test_id) {
    $aaa = wp_get_post_terms($test_id, 'manufacturer', array('fields' => 'ids'));
    $brands[] = $aaa[0];
}

$brands = array_unique($brands);

Body:
I'm having trouble figuring out what "brands" is. Your wp_get_post_terms statement is going to get all the posts for each category in taxonomy "manufacturer." If manufacturer = brands, you can add this loop to cycle through them:

foreach ($product_ids as $test_id) {
$post = get_post($test_id);
echo '>> ' . $post->post_name . '</br>';
$aaa = wp_get_post_terms($test_id, 'manufacturer',
    array('fields' => 'id=>slug'));

foreach( $aaa as $a) {
    echo $a . '</br>';
    }

}

You can then add 'if' statements to make your comparisons.


问:
Pandas df conditionals: changing value name if pd.value_counts is less than something
I have this table with models df['model'] and

pd.value_counts(df2['model'].values, sort=True)

returns this:

```<code>'''
MONSTER        331
MULTISTRADA    134
HYPERMOTARD     69
SCRAMBLER       63
SUPERSPORT      31
              ...
900              1
T-MAX            1
FC               1
GTS              1
SCOUT            1
Length: 75, dtype: int64
'''
</code>```

I want to rename all the values in df2['model'] that have count <5 into 'OTHER'.
Please can anyone help me, how to go about this?

答:
You first can get a list of the categories you want to change to other with the first line of code. It takes your functiona and selects the rows which meet the condicion you want (in this case less than 5 occurences).

Then you select the dataframe and just select the rows whose model cell is in the list of categories you want to substitute and change te value to 'OTHER'.

```<code>other_classes = data['model'].value_counts()[data['model'].value_counts() < 5].index

data['model'][data['model'].isin(other_classes)] = 'OTHER'
</code>```

Hope it helps

Body:
I have this table with models df['model'] and

pd.value_counts(df2['model'].values, sort=True)

returns this:

'''
MONSTER        331
MULTISTRADA    134
HYPERMOTARD     69
SCRAMBLER       63
SUPERSPORT      31
              ...
900              1
T-MAX            1
FC               1
GTS              1
SCOUT            1
Length: 75, dtype: int64
'''

I want to rename all the values in df2['model'] that have count <5 into 'OTHER'.
Please can anyone help me, how to go about this?

Body:
You first can get a list of the categories you want to change to other with the first line of code. It takes your functiona and selects the rows which meet the condicion you want (in this case less than 5 occurences).

Then you select the dataframe and just select the rows whose model cell is in the list of categories you want to substitute and change te value to 'OTHER'.

other_classes = data['model'].value_counts()[data['model'].value_counts() < 5].index

data['model'][data['model'].isin(other_classes)] = 'OTHER'

Hope it helps


问:
Pastes gibberish when copied text from a PDF generated from jsPDF
Well I needed to use a font which supports unicode characters to generate PDFs from jsPDF in order to serve my purpose. For example the '€' sign since it was generating a gibber when jsPDF inbuild fonts were used as it does not support unicode chars.

However good news is you can use custom true type fonts(ttf) and a lot ttf support unicode chars and my issue above is solved.

Now bad news or the next side effect is after generating the pdf if someone tries to copy the exact text from the pdf and wants to paste it somewhere else like text file, word document etc., generates this:

"ࣆࣆGROODUGROODUORWRIGROODUࣆࣆKDKDLDPULFK"

instead of:

"€€ euro euro lot of euro €€ - haha i am rich ..."

we tried all sorts of workaround with the acrobat pdf settings. Nothing works in particular. Downloaded and tried a lot of different fonts but no solution.

jspdf version is 1.4.1.

Any idea why this is happenening or any solution for this ?

Any help will be so grateful.

Thanks.

答:
Well, the issue was with jspdf version. This problem was solved in 1.5.0 and the version that i was using was 1.4.1

See release notes:
https://github.com/MrRio/jsPDF/releases

Move to:
commit "c53beb6": Font Dictionary now has toUnicode entry to be able to copy paste out from pdf viewer.


问:
Jenkins Pipeline script error - MultipleCompilationErrorsException
I am trying to fetch Jenkins job result using the following code:

```<code>pipeline {
   agent { label 'Agent_Name' }

   stages {
      stage('Build') {
         steps {
            def res=build job: 'App_Build', parameters: [string(name: 'App', value: 'WindowsApp')]
         }
      }
   }
}
</code>```

However, it looks like if I add "def res=" then the job fails with the following error:

org.codehaus.groovy.control.MultipleCompilationErrorsException:
  startup failed:

If I remove def res=, then it works fine. Also, if I keep only def res=buid..... line in pipeline script, then it works fine too.

How can I fix this error? I need to get the result from the App_Build job and run the pipeline in stages.

答:
If you want to capture the result of the build step, you need to put it into script block, e.g.

pipeline {
   agent { label 'Agent_Name' }

   stages {
      stage('Build') {
         steps {
            script {
                def res=build job: 'App_Build', parameters: [string(name: 'App', value: 'WindowsApp')]
                // do something with the result...
            }
         }
      }
   }
}
```

Body:
I am trying to fetch Jenkins job result using the following code:

pipeline {
   agent { label 'Agent_Name' }

   stages {
      stage('Build') {
         steps {
            def res=build job: 'App_Build', parameters: [string(name: 'App', value: 'WindowsApp')]
         }
      }
   }
}

However, it looks like if I add "def res=" then the job fails with the following error:

org.codehaus.groovy.control.MultipleCompilationErrorsException:
  startup failed:

If I remove def res=, then it works fine. Also, if I keep only def res=buid..... line in pipeline script, then it works fine too.

How can I fix this error? I need to get the result from the App_Build job and run the pipeline in stages.


问:
Firebase InstanceId: binding to the service failed: Kotlin
App successfully lanches but get this error message in debugging. FirebaseInstanceId: binding to the service failed

App Build Gradle:

```<code>android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
    applicationId ""
    minSdkVersion 16
    targetSdkVersion 29
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    multiDexEnabled true // enable mun

}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}
</code>```

Android manifest:

```<code> <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    tools:ignore="GoogleAppIndexingWarning">
    <activity android:name=".FilterPage"></activity>
    <activity android:name=".filterdashboard" />
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</code>```

答:
I downloaded the newest version of google-service.json (can be done via Firebase Settings). In my case there was a new entry added to oauth_client. After syncing with the file system and rebuilding my app the warning does not seem to appear anymore.

EDIT 20-02-2020: After testing this a bit more it unfortunately doesn't seem to help in the end. In my case the error message only for sure occur when starting the app the first time after an uninstall of the app - in most other cases it does not happen.

Body:
App successfully lanches but get this error message in debugging. FirebaseInstanceId: binding to the service failed

App Build Gradle:

android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
    applicationId ""
    minSdkVersion 16
    targetSdkVersion 29
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    multiDexEnabled true // enable mun

}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}

Android manifest:

 <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    tools:ignore="GoogleAppIndexingWarning">
    <activity android:name=".FilterPage"></activity>
    <activity android:name=".filterdashboard" />
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>


问:
Send a mail using Javascript without going through Outlook
Is it possible to Send a mail using Javascript without going through Outlook</p>

答:
You cannot purely use javascript to send e-mail without outlook, your javascript will need to interact with a server side language e.g. asp.net / php etc.

Or there are numerous free services which allow you to send your e-mail via their server-side, such as http://allforms.mailjol.net/

ContentLicense: CC BY-SA 3.0


问:
Get path for data storage
I need to create file in storage card from my Android program. I know I can create this file only in particular location like  \Card\Android\data\my.application.package\. How to get this directory exact location? Code below brings path /data/my.application.package/Log and mkdirs() does not creates directories.

```<code>        String path = "Log";

        File root = new File(Environment.getDataDirectory().getAbsolutePath(),
                "my.application.package" + File.separator + path);

        boolean dirExists = true;

        if (!root.exists()) {
            dirExists = root.mkdirs();
        }
</code>```

How to get the same application path on internal storage?

答:
You should use getFilesDir() for getting app specific internal File path and getExternalFilesDir() for getting app specific external File path.

Note that on Android 4.3 (API level 18) or lower, your app need to request storage-related permissions to access app-specific directories within external storage.

For more information see https://developer.android.com/training/data-storage/app-specific

Title: Get path for data storage

Body:
I need to create file in storage card from my Android program. I know I can create this file only in particular location like  \Card\Android\data\my.application.package\. How to get this directory exact location? Code below brings path /data/my.application.package/Log and mkdirs() does not creates directories.

        String path = "Log";

        File root = new File(Environment.getDataDirectory().getAbsolutePath(),
                "my.application.package" + File.separator + path);

        boolean dirExists = true;

        if (!root.exists()) {
            dirExists = root.mkdirs();
        }

How to get the same application path on internal storage?


问:
Look up service implementations dynamically
Our Angular application has a service which can have different implementations, aka. “strategies”. For simplicity, let’s assume it’s an “event reporting” service. The event reporting service has a function for reporting information. Depending on a runtime preference, the reporting can either turned off, go to the console, or be sent to a REST API, or go somewhere else.

Using pure TS, this would look like:

interface IReporter {
  report (message: string): void;
}

class NoReporter implements IReporter {
  report (message: string): void {
    // no op.
  }
}

class ConsoleReporter implements IReporter {
  report (message: string): void {
    console.log(message);
  }
}

// etc.
```

<p>In a consumer, I’d put some factory which delivers the desired reporter, e.g. based on a user-preference setting:</p>

<pre class="lang-js prettyprint-override"><code>getReporter (key: string): IReporter {
  switch (key) {
    // … tedious cases, which need to be mainted. Yikes!
  }
}
</code>```

However, this feels not very “Angular”-like. First step would probably be to make proper Angular services of the individual reporters, but this alone feels like little gained. So: Is there some existing mechanism which would give me above factory functionality to dynamically look up an implementation? Any patterns, example or best practices to follow?

答:
Like mentioned in the comment FactoryProviders perfectly solve this problem.

You have to define your IReporter interface as an class interface because interfaces don't exist at runtime and therefore they are no valid DI tokens:

```<code>export abstract class IReporter {
  report: (message: string) => void;
}

@Injectable()
export class NoReporter implements IReporter{
  report(message:string):void{

  }
}

@Injectable()
export class ConsoleReporter implements IReporter {
  report(message: string): void {
    console.log(message);
  }
}

</code>```

Now you could create your reporterFactory and reporterProvider like shown below:

```<code>const reporterFactory = (key: string) => {
  switch (key) {
    case 'no-report':
      return () => new NoReporter();
    case 'console-report':
      return () => new ConsoleReporter();
    default:
      return () => new ConsoleReporter();
  }
};

export const reporterProvider = (key: string) => {
  return {
    provide: IReporter,
    useFactory: reporterFactory(key)
  }
};
</code>```

And inject a reporter in your component:

```<code>@Component({
  selector: 'test',
  template: `TESTCOMPONENT`,
  providers: [
    reporterProvider('console-report')
  ]
})
export class TestComponent {
  constructor(private reporter: IReporter) {
    reporter.report('it works!!!');
  }

}
</code>```

Body:
Our Angular application has a service which can have different implementations, aka. “strategies”. For simplicity, let’s assume it’s an “event reporting” service. The event reporting service has a function for reporting information. Depending on a runtime preference, the reporting can either turned off, go to the console, or be sent to a REST API, or go somewhere else.

Using pure TS, this would look like:

interface IReporter {
  report (message: string): void;
}

class NoReporter implements IReporter {
  report (message: string): void {
    // no op.
  }
}

class ConsoleReporter implements IReporter {
  report (message: string): void {
    console.log(message);
  }
}

// etc.

In a consumer, I’d put some factory which delivers the desired reporter, e.g. based on a user-preference setting:

getReporter (key: string): IReporter {
  switch (key) {
    // … tedious cases, which need to be mainted. Yikes!
  }
}

However, this feels not very “Angular”-like. First step would probably be to make proper Angular services of the individual reporters, but this alone feels like little gained. So: Is there some existing mechanism which would give me above factory functionality to dynamically look up an implementation? Any patterns, example or best practices to follow?

Body:
Like mentioned in the comment FactoryProviders perfectly solve this problem.

You have to define your IReporter interface as an class interface because interfaces don't exist at runtime and therefore they are no valid DI tokens:

export abstract class IReporter {
  report: (message: string) => void;
}

@Injectable()
export class NoReporter implements IReporter{
  report(message:string):void{

  }
}

@Injectable()
export class ConsoleReporter implements IReporter {
  report(message: string): void {
    console.log(message);
  }
}

Now you could create your reporterFactory and reporterProvider like shown below:

const reporterFactory = (key: string) => {
  switch (key) {
    case 'no-report':
      return () => new NoReporter();
    case 'console-report':
      return () => new ConsoleReporter();
    default:
      return () => new ConsoleReporter();
  }
};

export const reporterProvider = (key: string) => {
  return {
    provide: IReporter,
    useFactory: reporterFactory(key)
  }
};

And inject a reporter in your component:

@Component({
  selector: 'test',
  template: `TESTCOMPONENT`,
  providers: [
    reporterProvider('console-report')
  ]
})
export class TestComponent {
  constructor(private reporter: IReporter) {
    reporter.report('it works!!!');
  }

}


问:
Headless Chrome with Python suspends when trying to download a file
I'm using Python, Jupyter, Selenium webdriver and headless Chrome (with Canary) on Mac.

I wrote a script that scrapes a very old website,
In order to download a file from that website I need to click on several buttons which eventually lead me to a button that once clicked it downloads a CSV file

The problem is that when headless Chrome tries to download the target file it suspends and does nothing (i.e. doesn't download the required file) even though the script finished running (and yes I did close it at the end of the script)

I tried:

Downloading other files (from different websites) and headless Chrome seems to download them without any problems (I enabled the headless chrome option to download files successfully)

Taking snapshots of the websites to make sure it's navigating correctly to the download page (and yeah, its navigating correctly)

Modifying the user agent (it appears to be using the user agent I expect it to)

Running the exact same code without the headless option - it downloads the file successfully with regular chrome

Changing plugins and languages JS script on the driver by using driver.execute_script(js_that_changes_plugins_and_langs) but I'm not quite sure how to check if it's actually executing it or not (and it's still not working)

Problems I'm facing:

I can't find a way to get just the last download URL because it seems to be using some unique IDs generated along the way (it's given when you go to the homepage and when you are navigating between pages in the site) so for every session it's going to change

The navigation URLs seem to be originating from iframes inside the homepage (and also in the following URLs) and I'm not quite sure how to inspect the Javascript it's generating

I don't have any problem providing the website URL but:

You have to go through like ~6 clicks on different pages in order to just get to the last page with the download button. These clicks are not intuitive and it will take a lot in order to explain how to navigate to where I want

This site is not in English which will make it even harder to explain how to navigate

I need it to be headless as opposed to regular Chrome since the machine where we want to run the code is very weak and cannot run the chrome GUI

So my question is: does anyone knows what may the problem? or at least, how can I debug it?

This is more or less the code that I'm using:

```<code>from selenium import webdriver
from selenium.webdriver.chrome.options import Options

def enable_download_in_headless_chrome(driver, download_dir):
        """
        there is currently a "feature" in chrome where
        headless does not allow file download: https://bugs.chromium.org/p/chromium/issues/detail?id=696481
        This method is a hacky work-around until the official chromedriver support for this.
        Requires chrome version 62.0.3196.0 or above.
        """

        # add missing support for chrome "send_command"  to selenium webdriver
        driver.command_executor._commands["send_command"] = ("POST", '/session/' + driver.session_id + '/chromium/send_command')

        params = {'cmd': 'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': download_dir}}
        command_result = driver.execute("send_command", params)
        print("response from browser:")
        for key in command_result:
            print("result:" + key + ":" + str(command_result[key]))

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('headless')
chrome_options.add_argument('no-sandbox')
chrome_options.add_argument('disable-gpu')
chrome_options.add_argument('remote-deubgging-port=9222')
chrome_options.add_argument('disable-popup-blocking')
chrome_options.add_argument('enable-logging')
download_dir = # some path here
driver = webdriver.Chrome(chrome_options=chrome_options)
enable_download_in_headless_chrome(driver, download_dir)
ok_button = driver.find_element_by_id('the-button-name')
ok_button.click()
</code>```

Thanks for the help

答:
try     String downloadFilepath ="\\sd-";

chromePrefs.put("download.default_directory", downloadFilepath);

Body:
I'm using Python, Jupyter, Selenium webdriver and headless Chrome (with Canary) on Mac.

I wrote a script that scrapes a very old website,
In order to download a file from that website I need to click on several buttons which eventually lead me to a button that once clicked it downloads a CSV file

The problem is that when headless Chrome tries to download the target file it suspends and does nothing (i.e. doesn't download the required file) even though the script finished running (and yes I did close it at the end of the script)

I tried:

Downloading other files (from different websites) and headless Chrome seems to download them without any problems (I enabled the headless chrome option to download files successfully)

Taking snapshots of the websites to make sure it's navigating correctly to the download page (and yeah, its navigating correctly)

Modifying the user agent (it appears to be using the user agent I expect it to)

Running the exact same code without the headless option - it downloads the file successfully with regular chrome

Changing plugins and languages JS script on the driver by using driver.execute_script(js_that_changes_plugins_and_langs) but I'm not quite sure how to check if it's actually executing it or not (and it's still not working)

Problems I'm facing:

I can't find a way to get just the last download URL because it seems to be using some unique IDs generated along the way (it's given when you go to the homepage and when you are navigating between pages in the site) so for every session it's going to change

The navigation URLs seem to be originating from iframes inside the homepage (and also in the following URLs) and I'm not quite sure how to inspect the Javascript it's generating

I don't have any problem providing the website URL but:

You have to go through like ~6 clicks on different pages in order to just get to the last page with the download button. These clicks are not intuitive and it will take a lot in order to explain how to navigate to where I want

This site is not in English which will make it even harder to explain how to navigate

I need it to be headless as opposed to regular Chrome since the machine where we want to run the code is very weak and cannot run the chrome GUI

So my question is: does anyone knows what may the problem? or at least, how can I debug it?

This is more or less the code that I'm using:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

def enable_download_in_headless_chrome(driver, download_dir):
        """
        there is currently a "feature" in chrome where
        headless does not allow file download: https://bugs.chromium.org/p/chromium/issues/detail?id=696481
        This method is a hacky work-around until the official chromedriver support for this.
        Requires chrome version 62.0.3196.0 or above.
        """

        # add missing support for chrome "send_command"  to selenium webdriver
        driver.command_executor._commands["send_command"] = ("POST", '/session/' + driver.session_id + '/chromium/send_command')

        params = {'cmd': 'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': download_dir}}
        command_result = driver.execute("send_command", params)
        print("response from browser:")
        for key in command_result:
            print("result:" + key + ":" + str(command_result[key]))

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('headless')
chrome_options.add_argument('no-sandbox')
chrome_options.add_argument('disable-gpu')
chrome_options.add_argument('remote-deubgging-port=9222')
chrome_options.add_argument('disable-popup-blocking')
chrome_options.add_argument('enable-logging')
download_dir = # some path here
driver = webdriver.Chrome(chrome_options=chrome_options)
enable_download_in_headless_chrome(driver, download_dir)
ok_button = driver.find_element_by_id('the-button-name')
ok_button.click()

Thanks for the help


问:
terraform returns 500 error when whitelisting IPs in Mongo Atlas
When I try to whitelist IPs via terraform in Mongo Atlas, I get the below error intermittently;

mongodbatlas_project_ip_whitelist.test[2]:

1 error(s) occurred:

mongodbatlas_project_ip_whitelist.test.2: error creating project IP whitelist:

POST https://cloud.mongodb.com/api/atlas/v1.0/groups/5e4652ed55385542bbfeb88c/whitelist:

```<code> 500 (request "Internal Server Error") Unexpected error.

mongodbatlas_project_ip_whitelist.test[0]: 1 error(s) occurred:

mongodbatlas_project_ip_whitelist.test.0: error creating project IP whitelist
</code>```

POST

https://cloud.mongodb.com/api/atlas/v1.0/groups/5e4652ed55385542bbfeb88c/whitelist

```<code>500 (request "Internal Server Error") Unexpected error.
</code>```

The terraform script I used:

```<code>resource "mongodbatlas_project_ip_whitelist" "mongo_whitelist" {
   project_id = "${var.mongo_projectkey}"
   count = "${length(var.mongo_atlas_inbound_whitelist)}"
   cidr_block = "${var.mongo_atlas_inbound_whitelist[count.index]}"
}
</code>```

Any idea please?

答:
Seems this is a bug in 0.3.1 Terraform MongoDB Atlas Provider when count meta-parameter is used.

It seems fixed in the version 0.4.0 of the MongoDB Atlas Terraform provider, which contains a number of other changes too to the mongodbatlas_project_ip_whitelist resource.

I just upgraded the version from 0.3.1 to 0.4.0:

```<code>terraform init -upgrade=true
</code>```

This sorted out the issue.

Body:
When I try to whitelist IPs via terraform in Mongo Atlas, I get the below error intermittently;

mongodbatlas_project_ip_whitelist.test[2]:

1 error(s) occurred:

mongodbatlas_project_ip_whitelist.test.2: error creating project IP whitelist:

POST https://cloud.mongodb.com/api/atlas/v1.0/groups/5e4652ed55385542bbfeb88c/whitelist:

 500 (request "Internal Server Error") Unexpected error.

mongodbatlas_project_ip_whitelist.test[0]: 1 error(s) occurred:

mongodbatlas_project_ip_whitelist.test.0: error creating project IP whitelist

POST

https://cloud.mongodb.com/api/atlas/v1.0/groups/5e4652ed55385542bbfeb88c/whitelist

500 (request "Internal Server Error") Unexpected error.

The terraform script I used:

resource "mongodbatlas_project_ip_whitelist" "mongo_whitelist" {
   project_id = "${var.mongo_projectkey}"
   count = "${length(var.mongo_atlas_inbound_whitelist)}"
   cidr_block = "${var.mongo_atlas_inbound_whitelist[count.index]}"
}

Any idea please?

Body:
Seems this is a bug in 0.3.1 Terraform MongoDB Atlas Provider when count meta-parameter is used.

It seems fixed in the version 0.4.0 of the MongoDB Atlas Terraform provider, which contains a number of other changes too to the mongodbatlas_project_ip_whitelist resource.

I just upgraded the version from 0.3.1 to 0.4.0:

terraform init -upgrade=true

This sorted out the issue.


问:
Java regex with replace
I need to replace string with a variable inside {} using a regex

For example:

```<code>"Hi, there are {online@US-server} players in the US server" to "Hi, there are 12 players in the US server"
</code>```

Inside the Strings variables inside {} can be more than 1

I need this code to allow users to modify messages. variable inside {} after @ like in the example 'US-server' are put in by users so there aren't list to check for variable. Variables could be as strange as possible ex: '{online@test-UK}' '{online@asdtest}'

```<code>public static String getReplaced(String d) {
    String result = d.split("\\{online@")[0];

    for (int i = 1; i < d.split("\\{online@").length; i++) {
        String dd = d.split("\\{online@")[i];

        Pattern p = Pattern.compile("(.*?)}(.*)");
        Matcher m = p.matcher(dd);

        if (m.lookingAt()) {
            int count = 12;

            result += count + m.group(2);
        } else {
            result += dd;
        }
    }

    return result;
}
</code>```

Title: Java regex with replace

Body:
I need to replace string with a variable inside {} using a regex

For example:

"Hi, there are {online@US-server} players in the US server" to "Hi, there are 12 players in the US server"

Inside the Strings variables inside {} can be more than 1

I need this code to allow users to modify messages. variable inside {} after @ like in the example 'US-server' are put in by users so there aren't list to check for variable. Variables could be as strange as possible ex: '{online@test-UK}' '{online@asdtest}'

public static String getReplaced(String d) {
    String result = d.split("\\{online@")[0];

    for (int i = 1; i < d.split("\\{online@").length; i++) {
        String dd = d.split("\\{online@")[i];

        Pattern p = Pattern.compile("(.*?)}(.*)");
        Matcher m = p.matcher(dd);

        if (m.lookingAt()) {
            int count = 12;

            result += count + m.group(2);
        } else {
            result += dd;
        }
    }

    return result;
}

Body:
([^\s]+)online@[A-Za-z\-]([^\s]+)

seems to work.


问:
Python: Random selection per group
Say that I have a dataframe that looks like:

```<code>Name Group_Id
AAA  1
ABC  1
CCC  2
XYZ  2
DEF  3
YYH  3
</code>```

How could I randomly select one (or more) row for each Group_Id? Say that I want one random draw per Group_Id, I would get:

```<code>Name Group_Id
AAA  1
XYZ  2
DEF  3
</code>```

答:
A very pandas-ish way:</p>

```<code>takesamp = lambda d: d.sample(n)
df = df.groupby('Group_Id').apply(takesamp)
</code>```

Title: Python: Random selection per group

Body:
Say that I have a dataframe that looks like:

Name Group_Id
AAA  1
ABC  1
CCC  2
XYZ  2
DEF  3
YYH  3

How could I randomly select one (or more) row for each Group_Id? Say that I want one random draw per Group_Id, I would get:

Name Group_Id
AAA  1
XYZ  2
DEF  3

Body:
A very pandas-ish way:

takesamp = lambda d: d.sample(n)
df = df.groupby('Group_Id').apply(takesamp)