问:
if/then replace values looping over rows conditional on column value(s) in R
I am trying to do an if/then replacement (recoding) of values row by row (looping over rows), based on one the values of or more columns in those rows. I've looked at a lot of prior examples here and elsewhere (R help) but haven't been able to get very far.

Here is an example data set:

```<code>> set.seed(1234)
> let<-c("AB","AA","BB")
> df <- data.frame(rbind(x1=c(12,"DF1",sample(let,6,TRUE)),x2=c(12,"HA.1",sample(let,6,TRUE)),x3=c(21,"DF1",sample(let,6,TRUE)),x4=c(12,"AS.2",sample(let,6,TRUE))
+ ))
> df
   X1   X2 X3 X4 X5 X6 X7 X8
x1 12  DF1 AB AA AA AA BB AA
x2 12 HA.1 AB AB AA AA BB AA
x3 21  DF1 AB BB AB BB AB AB
x4 12 AS.2 AB AB AB AB AB AB
</code>```

I would like to conditionally change the coding (replace) values in columns 3:8 (from X3 through X8) based on values in X1 and X2 using if/then. 'AB' becomes 1 if X1=12 AND X2=DF1, 'AA' becomes 2 if X1=12 AND X2=DF1, 'BB' becomes 3 if X1=12 and X2=DF1 etc. There will be many other (nested?) if statements to add to complete this specific case, but I am not sure how to approach even the most basic aspect of this script: how to condition the replacement of values in columns 3:8 based on the column 1 value (and also column 2 or more columns) at a given row.

So, looping over each row, I would test if the value in X2 = DF1 and X1=12 (for example), and if so in both cases, change values of AB to 1, AA to 2, and BB to 3...

```<code>for(i in 1:nrow(df)){
      if((df$X2[i]=="DF1") & (df$X1[i]=12)) {
          ifelse(df[i,3:8] == "AB", 1, ifelse(df[i,3:8]=="AA", 2,ifelse(df[i,3:8]=="BB",3,"NA")))}
             else{}
      }
</code>```

Now...this appears to do nothing - no changes to dfand no warnings. But the ifelse statements  work when I specify the row (4):

```<code>> ifelse(df[4,3:8] == "AB", 1, ifelse(df[4,3:8]=="AA", 2,ifelse(df[4,3:8]=="BB",3,"NA")))
   X3  X4  X5  X6  X7  X8
x4 "1" "3" "1" "1" "1" "2"
> df[4,3:8]
   X3 X4 X5 X6 X7 X8
x4 AB BB AB AB AB AA
</code>```

So it must be something in the initial if &  ? Do I need to have something in my else clause?

And of course, my 'real' world use case is more complicated as each different value in X1 or X2 will require different if/then statements to recode the values in colum 3:8

Anyway - am I even approaching this correctly? Would a look up table work better? I would be setting up additional nested if/& statements for each combination of values for X1 and X2. It will be ugly, but if I can get the nested if statements to work, then at least I can get there.

Thanks for any suggestions!

答:
We can get the data in long format and then use separate case_when with conditions to recode values and finally get the data back in original format.

```<code>library(dplyr)
library(tidyr)

df %>%
  pivot_longer(cols = -c(X1, X2)) %>%
  mutate(value = case_when(X1 == 12 & X2 == 'DF1' & value == 'AB' ~ 1,
                           X1 == 12 & X2 == 'DF1' & value == 'AA' ~ 2,
                           X1 == 12 & X2 == 'DF1' & value == 'BB' ~ 3,
                           #Add more conditions as per requirements
                           #....
                           #If none of the above condition satisfy
                           #return a default value
                           TRUE ~ 0)) %>%
  pivot_wider()
</code>```

case_when is an alternative to nested ifelse statements since it makes to easy to write for various conditions in simple steps.

Body:
I am trying to do an if/then replacement (recoding) of values row by row (looping over rows), based on one the values of or more columns in those rows. I've looked at a lot of prior examples here and elsewhere (R help) but haven't been able to get very far.

Here is an example data set:

> set.seed(1234)
> let<-c("AB","AA","BB")
> df <- data.frame(rbind(x1=c(12,"DF1",sample(let,6,TRUE)),x2=c(12,"HA.1",sample(let,6,TRUE)),x3=c(21,"DF1",sample(let,6,TRUE)),x4=c(12,"AS.2",sample(let,6,TRUE))
+ ))
> df
   X1   X2 X3 X4 X5 X6 X7 X8
x1 12  DF1 AB AA AA AA BB AA
x2 12 HA.1 AB AB AA AA BB AA
x3 21  DF1 AB BB AB BB AB AB
x4 12 AS.2 AB AB AB AB AB AB

I would like to conditionally change the coding (replace) values in columns 3:8 (from X3 through X8) based on values in X1 and X2 using if/then. 'AB' becomes 1 if X1=12 AND X2=DF1, 'AA' becomes 2 if X1=12 AND X2=DF1, 'BB' becomes 3 if X1=12 and X2=DF1 etc. There will be many other (nested?) if statements to add to complete this specific case, but I am not sure how to approach even the most basic aspect of this script: how to condition the replacement of values in columns 3:8 based on the column 1 value (and also column 2 or more columns) at a given row.

So, looping over each row, I would test if the value in X2 = DF1 and X1=12 (for example), and if so in both cases, change values of AB to 1, AA to 2, and BB to 3...

for(i in 1:nrow(df)){
      if((df$X2[i]=="DF1") & (df$X1[i]=12)) {
          ifelse(df[i,3:8] == "AB", 1, ifelse(df[i,3:8]=="AA", 2,ifelse(df[i,3:8]=="BB",3,"NA")))}
             else{}
      }

Now...this appears to do nothing - no changes to dfand no warnings. But the ifelse statements  work when I specify the row (4):

> ifelse(df[4,3:8] == "AB", 1, ifelse(df[4,3:8]=="AA", 2,ifelse(df[4,3:8]=="BB",3,"NA")))
   X3  X4  X5  X6  X7  X8
x4 "1" "3" "1" "1" "1" "2"
> df[4,3:8]
   X3 X4 X5 X6 X7 X8
x4 AB BB AB AB AB AA

So it must be something in the initial if &  ? Do I need to have something in my else clause?

And of course, my 'real' world use case is more complicated as each different value in X1 or X2 will require different if/then statements to recode the values in colum 3:8

Anyway - am I even approaching this correctly? Would a look up table work better? I would be setting up additional nested if/& statements for each combination of values for X1 and X2. It will be ugly, but if I can get the nested if statements to work, then at least I can get there.

Thanks for any suggestions!

Body:
We can get the data in long format and then use separate case_when with conditions to recode values and finally get the data back in original format.

library(dplyr)
library(tidyr)

df %>%
  pivot_longer(cols = -c(X1, X2)) %>%
  mutate(value = case_when(X1 == 12 & X2 == 'DF1' & value == 'AB' ~ 1,
                           X1 == 12 & X2 == 'DF1' & value == 'AA' ~ 2,
                           X1 == 12 & X2 == 'DF1' & value == 'BB' ~ 3,
                           #Add more conditions as per requirements
                           #....
                           #If none of the above condition satisfy
                           #return a default value
                           TRUE ~ 0)) %>%
  pivot_wider()

case_when is an alternative to nested ifelse statements since it makes to easy to write for various conditions in simple steps.


来源: stackexchange

问:
Is there a way to version ~/.bashrc in-place by git, without copying to a different repo?
I'd like to version ~/.bashrc and ~/.bash_profile using git, best if in-place (at the actual location), rather than creating a new repo and copy the file over and do the versioning there.

Is there a way to do that? I think the difficulty is, if I create a repo at ~, it includes every folder in my home directory and is not desirable.

Is there some way to tell git: version only these files or folder, and disregard everything else and don't consider them to be submodules? If it can be like that, it might be a solution, except it seem like a super big repo to be at the home directory but at the same time ignoring almost everything.

答:
Check out Simple Revision Control SRC, a simple modern version control system for managing individual files (not collections of files changed in lockstep). Or look for the granddaddy of them all, Revision Control System RCS (probably even available as an official package for your favorite Linux distribution).

Fluff trivia of the day, not too long ago IBM's AIX code was managed with RCS (perhaps still as of today, that came out in the SCO vs IBM lawsuit).

ContentLicense: CC BY-SA 4.0


问:
No AWS RDS Simple Monthly Calculator for Postgres engine
I have noticed that the AWS SIMPLE MONTHLY CALCULATOR does not have an option to calculate expense for Postgres engine. It offers 'MySQL compatible' as the only option. Am I missing something?

screenshot of monthly calculator

答: It looks like you've selected Aurora pricing. Aurora pricing is the same for MySQL and PostgreSQL compatibility. The only difference is that there are some options that are only available in MySQL.</p>


问:
Typescript is it possible to declare a generic type for an array of 1-N strings
A bit hard to explain it in the title but basically, I'd like to be able to declare a type  array of fixed length strings from 1 to N:

```<code>interface Command {
  [key: string]: (args: [string, ...string[]]) => boolean;
}

const cmd: Command = {
  TEST: (args: [string, string]) => args[0] === args[1],
  TEST2: (args: [string]) => args[0] === 'hello'
}
</code>```

so this doesn't work as [string, string] is different from string[]:

Type '(args: [string]) => boolean' is not assignable to type '(args: [string, ...string[]]) => boolean'.

A solution could be to define like all kind of arguments:

```<code>interface Command {
  [key: string]: (args: [string] | [string, string] | [string, string, string]) => boolean;
}
</code>```

But a bit too verbose for something simple (agreed it can be encapsulated in an interface), anyway is there another elegant solution to this that I'm not seeing?

Thanks,

答:
I suspect that you actually need Command to be generic, so that its properties can actually be used.  If you have a function type like (arg: [string] | [string, string]) => boolean, then you cannot implement it with a (arg: [string]) => boolean or with a (arg: [string, string]) => boolean.  Function types vary contravariantly in their arguments' types.  You can widen, but not narrow, the type of a function argument.  Unless you want to require that all methods of type Command must accept every possible string array of length one or more, you have to do something with generics.

Here's a possible type for Command, along with a helper function asCommand() which lets the compiler infer the proper value of T given a value of type Command<T> without forcing you to write it out yourself:

```<code>type Command<T> = { [K in keyof T]: (args: T[K]) => boolean }

const asCommand = <T extends Record<keyof T, [string, ...string[]]>>(
    cmd: Command<T>
) => cmd;
</code>```

Then, your cmd constant can be declared like this with no errors:

```<code>const cmd = asCommand({
    TEST: (args: [string, string]) => args[0] === args[1],
    TEST2: (args: [string]) => args[0] === 'hello'
});
</code>```

and the compiler remembers that cmd.TEST takes a pair and cmd.TEST2 takes a one-tuple:

```<code>cmd.TEST(["", ""]); // okay
cmd.TEST([]); // error
cmd.TEST([""]); // error
cmd.TEST(["", "", ""]); // error

cmd.TEST2([""]); // okay
cmd.TEST2([]); // error
cmd.TEST2(["", ""]); // error
cmd.TEST2(["", "", ""]); // error
</code>```

And you're not allowed to give a property that accepts only zero-length tuples:

```<code>const badCmd = asCommand({
    OOPS: (args: []) => false, // error!
})
</code>```

I hope that gives you some direction; good luck!

Playground link to code

Body:
A bit hard to explain it in the title but basically, I'd like to be able to declare a type  array of fixed length strings from 1 to N:

interface Command {
  [key: string]: (args: [string, ...string[]]) => boolean;
}

const cmd: Command = {
  TEST: (args: [string, string]) => args[0] === args[1],
  TEST2: (args: [string]) => args[0] === 'hello'
}

so this doesn't work as [string, string] is different from string[]:

Type '(args: [string]) => boolean' is not assignable to type '(args: [string, ...string[]]) => boolean'.

A solution could be to define like all kind of arguments:

interface Command {
  [key: string]: (args: [string] | [string, string] | [string, string, string]) => boolean;
}

But a bit too verbose for something simple (agreed it can be encapsulated in an interface), anyway is there another elegant solution to this that I'm not seeing?

Thanks,

Body:
I suspect that you actually need Command to be generic, so that its properties can actually be used.  If you have a function type like (arg: [string] | [string, string]) => boolean, then you cannot implement it with a (arg: [string]) => boolean or with a (arg: [string, string]) => boolean.  Function types vary contravariantly in their arguments' types.  You can widen, but not narrow, the type of a function argument.  Unless you want to require that all methods of type Command must accept every possible string array of length one or more, you have to do something with generics.

Here's a possible type for Command, along with a helper function asCommand() which lets the compiler infer the proper value of T given a value of type Command<T> without forcing you to write it out yourself:

type Command<T> = { [K in keyof T]: (args: T[K]) => boolean }

const asCommand = <T extends Record<keyof T, [string, ...string[]]>>(
    cmd: Command<T>
) => cmd;

Then, your cmd constant can be declared like this with no errors:

const cmd = asCommand({
    TEST: (args: [string, string]) => args[0] === args[1],
    TEST2: (args: [string]) => args[0] === 'hello'
});

and the compiler remembers that cmd.TEST takes a pair and cmd.TEST2 takes a one-tuple:

cmd.TEST(["", ""]); // okay
cmd.TEST([]); // error
cmd.TEST([""]); // error
cmd.TEST(["", "", ""]); // error

cmd.TEST2([""]); // okay
cmd.TEST2([]); // error
cmd.TEST2(["", ""]); // error
cmd.TEST2(["", "", ""]); // error

And you're not allowed to give a property that accepts only zero-length tuples:

const badCmd = asCommand({
    OOPS: (args: []) => false, // error!
})

I hope that gives you some direction; good luck!

<a href="https://www.typescriptlang.org/play/#code/C4TwDgpgBAwg9gWwQQwHYBMA8AVAfFAXigG8oBtAaSgEtUoBrCEOAMymwF0AuKACmQBOAcwDOPbJQ4BKQvgBGcOABsIaKAF8AUJoDGcVCOBRkI+EjTpCUHFAgAPYBAwioAJQh6BWRszbYANOSGArRCgQB0kcGhZBwcuLi8mlApUDoI6DxmKBg4uJoyBPjp6ADc2noGRiVWJtkWvMTJqdgAogDK2Dz8wmJBwCGoYVDRQ9Kyxr1kAAwchAREgqJkAIwc-s0pbZ0ATN1LfWSjQuNFk8uz80QA5AAWEEpKcNea6lLluhnh29i8ZABE-0CgOkpSgAHpwVA4PRkCBPuhvh1frF3hCoRABAI4AIEUjOn8QWjIbYsTi8T9CUCoIDgf9QejSdiBFAKl8fjsqQySTC4RTkZzUWCSZjmfzdlS6dyMWTcSV8dhBbSadSicKZWLdPpDFA5Mh0DAMrVTIgcuhGpsoAB5K0ABXa+16PFRExYyCUIgggRFsoAhK8pJogA" rel="nofollow noreferrer">Playground link to code


问:
R: How to use multiple GPUs with XGBoost?
I'm using xgboost to train my model. I expirienced that training with xgboost on GPU is much faster. Since I have 2 GPUs avaiable, I'd like to use both. Actually I have three questions about this topic.

How can I use multiple GPUs at the same time?

When running this example only the first GPU would work. I tried to set gpu_id = 1. That worked well, i.e. the other GPU did the job. Then I read that gpu_id = -1 would provide the solution. Apparently this argument doesn't work with CUDA 10. I also tried n_gpus but that seems to be deprecated.

How can I clear the cache of GPU memory when finished?

This becomes important when I get to tune the parameters in some kind of a loop. A single model fits well into memory, but not hundreds.

R would crash, when I change the gpu_id for the next model. Is there a way to prevent this?

My setup:

R version 3.4.4

Ubuntu 18.04.3

xgboost_1.0.0.1

CUDA 10.2

答:
```<code>tree_method = 'gpu_hist',
n_gpus = -1
</code>```

works for me with CUDA 10.2 and xgboost 0.90 in python.

Body:
tree_method = 'gpu_hist',
n_gpus = -1

works for me with CUDA 10.2 and xgboost 0.90 in python.


问:
benchmark for using base64 string instead of image reducing http requests
I am looking at replacing source of my images currently set to a image file in my css to a base64 string.  Instead of the browser needing to make several calls, one for the CSS file and then one for each image, base64 embedding means that all of the images are embedded within the CSS file itself.

So I am currently investigating introducing this. However I have an issue I would like some advice on, a known problem with this approach. That is in my tests a base64 encoded string image is somewhere around 150% the size of a regular image. This means it’s unusable for large images. While I am not too concerned regarding larger images, I am not sure when I should and shouldn't use it.

Is there a benchmark I should use, as in if the base64 more than 150% larger I should not use it etc?

What are others views on this and what from your own experiences may help with the decision of when to and not to use it?

答:
This works in only handful of browsers. I would not recommend it. Especially for mobile browsers.

Images get cached on browser if you configure webserver properly. So, images don't get downloaded over and over again. They come from cache and thus super fast. There are various easy performance configuration you can do on your webserver to make this work over the base64 encoding of images embedded in CSS.

Take a look at this for some easy ways to boost website performance:
http://omaralzabir.com/making_best_use_of_cache_for_high_performance_website/

ContentLicense: CC BY-SA 3.0


问:
How to get an array that summarizes sometimes repeated negative or positive values, also writing the number of repetitions in a separate column?
I got a list with "Move" (Column C) values.

How to create "Sorted" list (Column E,F) , which repeat number in Column F and write action in Column E as 1, if next value go opposite way from zero;

And summarize 2 or more numbers in Column F, and write action in Column E as 2 or more, if they going together same way from zero;

?

Screenshot shows correct result:

Google Sheets example link:
  https://docs.google.com/spreadsheets/d/13WL9pD7glAZxOIhsXq6k-ZG0Z8bbGAmMOhtGrW3mRTA/edit?usp=sharing

答:
Here's what I came up with in cell E1 on the mk.idea tab

=ARRAYFORMULA(array_constrain(query({C2:C\LOOKUP(A2:A;filter({A2:A;1}; sign({C2:C;0})<>sign(n(C:C))))};"select Count(Col2),sum(Col1),Col2 where Col2>1 group by Col2 label Count(Col2)'Sorted',Sum(Col1)''";0);9^9;2))

Does that give you what you're after?


问:
Regular expression to retrieve a string from a multiline file text
I am searching for a way to extract the peer IP by looking for the secret of that peer.

Example:

```<code>peer 1.2.3.10 {
    authentication {
        mode pre-shared-secret
        pre-shared-secret SecretPasswordA
    }
    connection-type initiate
    ike-group IKE_1.2.3.4
    local-address 6.7.8.9
    vti {
        bind vti64
        esp-group ESP_1.2.3.4
    }
}
peer 1.2.3.20 {
    authentication {
        mode pre-shared-secret
        pre-shared-secret SecretPasswordB
    }
    connection-type initiate
    ike-group IKE_1.2.3.4
    local-address 6.7.8.9
    vti {
        bind vti64
        esp-group ESP_1.2.3.4
    }
}
peer 1.2.3.30 {
    authentication {
        mode pre-shared-secret
        pre-shared-secret SecretPasswordC
    }
    connection-type initiate
    ike-group IKE_1.2.3.4
    local-address 6.7.8.9
    vti {
        bind vti64
        esp-group ESP_1.2.3.4
    }
}
</code>```

Provided I know SecrePasswordB, I would need to retrieve the peer IP which is 1.2.3.20, of empty if not found (or anything else easy to identify.

The text comes from a shell command into a variable (ie. TEXT=$(command_string)).

As I only have a basic shell and few tool available on the system that would need to be done with very basic linux tools. And here I am stuck not finding a solution...

答:
If the data is formatted into separate lines as shown in the question then a simple shell script suffices. Simply split input into a leading word followed by the rest. Save the IP whenever a "peer" line is read. Print the most recent IP if the secret is read.

getPeerIP:

```<code>#!/bin/sh

secret="$1"

while read -r arg1 rest; do
    case "$arg1" in
        peer)
            ip="${rest% *}" # prune everything after first space
            ;;
        pre-shared-secret)
            if [ "$rest" = "$secret" ]; then
                echo "$ip"
                exit # don't bother reading rest of file
            fi
            ;;
    esac
done
</code>```

Usage:

```<code>command_string | getPeerIP 'Secret Password'
</code>```

Body:
I am searching for a way to extract the peer IP by looking for the secret of that peer.

Example:

peer 1.2.3.10 {
    authentication {
        mode pre-shared-secret
        pre-shared-secret SecretPasswordA
    }
    connection-type initiate
    ike-group IKE_1.2.3.4
    local-address 6.7.8.9
    vti {
        bind vti64
        esp-group ESP_1.2.3.4
    }
}
peer 1.2.3.20 {
    authentication {
        mode pre-shared-secret
        pre-shared-secret SecretPasswordB
    }
    connection-type initiate
    ike-group IKE_1.2.3.4
    local-address 6.7.8.9
    vti {
        bind vti64
        esp-group ESP_1.2.3.4
    }
}
peer 1.2.3.30 {
    authentication {
        mode pre-shared-secret
        pre-shared-secret SecretPasswordC
    }
    connection-type initiate
    ike-group IKE_1.2.3.4
    local-address 6.7.8.9
    vti {
        bind vti64
        esp-group ESP_1.2.3.4
    }
}

Provided I know SecrePasswordB, I would need to retrieve the peer IP which is 1.2.3.20, of empty if not found (or anything else easy to identify.

The text comes from a shell command into a variable (ie. TEXT=$(command_string)).

As I only have a basic shell and few tool available on the system that would need to be done with very basic linux tools. And here I am stuck not finding a solution...

Body:
If the data is formatted into separate lines as shown in the question then a simple shell script suffices. Simply split input into a leading word followed by the rest. Save the IP whenever a "peer" line is read. Print the most recent IP if the secret is read.

getPeerIP:

#!/bin/sh

secret="$1"

while read -r arg1 rest; do
    case "$arg1" in
        peer)
            ip="${rest% *}" # prune everything after first space
            ;;
        pre-shared-secret)
            if [ "$rest" = "$secret" ]; then
                echo "$ip"
                exit # don't bother reading rest of file
            fi
            ;;
    esac
done

Usage:

command_string | getPeerIP 'Secret Password'


问:
PutParcelable cannot be applied to Place.Type error?
I am trying to pass map data from the map fragment on an activity to a separate fragment on the same activity.

When the user clicks on a maps POI, I make a call to google and grab a bunch of data including Place.Type which I want to pass on to the new fragment, unfortunately Place.Type is returning an error saying is wrong type.. unparcelable.
Android studio offered me an option of casting to parcelable which I tried and crashed with.

Looking in the reference, google says that Place.Types implements parcelable so am a little confused about why this is failing

I am sure there is a way to loop thought and recast or something but my lack of knowledge holds me back can someone please help here?

```<code>public class ZombieMapActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMyLocationButtonClickListener, GoogleMap.OnMyLocationClickListener, GoogleMap.OnPoiClickListener {

    private GoogleMap mMap;
    private final int PERM_REQUEST_LOCATION_INT = 1;
    private FusedLocationProviderClient FusedLocationClient;
    private String apiKey;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zombie_map);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        //location
        FusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

        //places API stuff
        apiKey  = getResources().getString(R.string.google_maps_key);
        Places.initialize(getApplicationContext(), apiKey);

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
    //perm check
        ...{
         mapSetup();
        }
    }

    private void requestPerms() { ... }

//catch request reply
    @Override
    public void onRequestPermissionsResult(
            int requestCode,
            String permissions[],
            int[] grantResults)    { ... }
    }

    private void mapSetup() {...}

    @Override
    public boolean onMyLocationButtonClick() {...}

    @Override
    public void onMyLocationClick(@NonNull Location location) {
        makeToast("This is you");
    }

    @Override
    public void onPoiClick(final PointOfInterest poi) {
        //distance check and throw out if to far

        //great place to think about a caching system for types.. to cut down on requests

        //placeId to place type method
        PlacesClient placesClient = Places.createClient(this);
        String placeId = poi.placeId;
        List<Place.Field> placeFields = Arrays.asList(Place.Field.ID, Place.Field.TYPES);
        FetchPlaceRequest request = FetchPlaceRequest.newInstance(placeId, placeFields);

        placesClient.fetchPlace(request).addOnSuccessListener(new OnSuccessListener<FetchPlaceResponse>() {
            @Override
            public void onSuccess(FetchPlaceResponse fetchPlaceResponse) {
                Place place = fetchPlaceResponse.getPlace();
                List<Place.Type> types = place.getTypes();
                String placeName = poi.name;
                makeLootFragment(types,placeName);

                makeToast(placeName);
            }
        });
    }

    private void makeLootFragment(List<Place.Type> _types,String name){

        //pack it for sending
        Bundle lootBundle = new Bundle();

        lootBundle.putParcelable("bLootTypes" , (Parcelable) _types);//not working
        lootBundle.putString("bName",name);

        FragmentManager lootFragMan = getSupportFragmentManager();
        FragmentTransaction LootTrans = lootFragMan.beginTransaction();
        LootFragment lootFragment = new LootFragment();
        lootFragment.setArguments(lootBundle);
        LootTrans.add(R.id.lootContainer,lootFragment);
        LootTrans.addToBackStack("LootStack");
        LootTrans.commit();

    }

    private void makeToast(String words) {
        Toast.makeText(this, words, Toast.LENGTH_SHORT).show();
    }
}
</code>```

Any other advice based on the terrible coding displayed here would also be very appreciated :D

答:
The Class of the Object you want to send should implement Parcelable interface as follow -

```<code>public class Student implements Parcelable {

    private Integer rollno;
    private String name;
    private Integer age;

    protected Student(Parcel in) {

        age = in.readInt();
        name  = in.readString();
        rollno = in.readInt();

    }

    public Student(Integer age, String name, Integer rollno) {
        this.age = age;
        this.name = name;
        this.rollno = rollno;
    }

    public static final Creator<Student> CREATOR = new Creator<Student>() {
        @Override
        public Student createFromParcel(Parcel in) {
            return new Student(in);
        }

        @Override
        public Student[] newArray(int size) {
            return new Student[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    public Integer getRollno() {
        return rollno;
    }

    public void setRollno(Integer rollno) {
        this.rollno = rollno;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public static Creator<Student> getCREATOR() {
        return CREATOR;
    }

  @Override
    public void writeToParcel(Parcel parcel, int i) {

        parcel.writeInt(age);
        parcel.writeString(name);
        parcel.writeInt(rollno);

    }
}
</code>```

So what you should do is make a class and implement Parcelable and write the Place.Type content into its members and then pass it to other Fragment

Body:
I am trying to pass map data from the map fragment on an activity to a separate fragment on the same activity.

When the user clicks on a maps POI, I make a call to google and grab a bunch of data including Place.Type which I want to pass on to the new fragment, unfortunately Place.Type is returning an error saying is wrong type.. unparcelable.
Android studio offered me an option of casting to parcelable which I tried and crashed with.

Looking in the reference, google says that Place.Types implements parcelable so am a little confused about why this is failing

I am sure there is a way to loop thought and recast or something but my lack of knowledge holds me back can someone please help here?

public class ZombieMapActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMyLocationButtonClickListener, GoogleMap.OnMyLocationClickListener, GoogleMap.OnPoiClickListener {

    private GoogleMap mMap;
    private final int PERM_REQUEST_LOCATION_INT = 1;
    private FusedLocationProviderClient FusedLocationClient;
    private String apiKey;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zombie_map);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        //location
        FusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

        //places API stuff
        apiKey  = getResources().getString(R.string.google_maps_key);
        Places.initialize(getApplicationContext(), apiKey);

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
    //perm check
        ...{
         mapSetup();
        }
    }

    private void requestPerms() { ... }

//catch request reply
    @Override
    public void onRequestPermissionsResult(
            int requestCode,
            String permissions[],
            int[] grantResults)    { ... }
    }

    private void mapSetup() {...}

    @Override
    public boolean onMyLocationButtonClick() {...}

    @Override
    public void onMyLocationClick(@NonNull Location location) {
        makeToast("This is you");
    }

    @Override
    public void onPoiClick(final PointOfInterest poi) {
        //distance check and throw out if to far

        //great place to think about a caching system for types.. to cut down on requests

        //placeId to place type method
        PlacesClient placesClient = Places.createClient(this);
        String placeId = poi.placeId;
        List<Place.Field> placeFields = Arrays.asList(Place.Field.ID, Place.Field.TYPES);
        FetchPlaceRequest request = FetchPlaceRequest.newInstance(placeId, placeFields);

        placesClient.fetchPlace(request).addOnSuccessListener(new OnSuccessListener<FetchPlaceResponse>() {
            @Override
            public void onSuccess(FetchPlaceResponse fetchPlaceResponse) {
                Place place = fetchPlaceResponse.getPlace();
                List<Place.Type> types = place.getTypes();
                String placeName = poi.name;
                makeLootFragment(types,placeName);

                makeToast(placeName);
            }
        });
    }

    private void makeLootFragment(List<Place.Type> _types,String name){

        //pack it for sending
        Bundle lootBundle = new Bundle();

        lootBundle.putParcelable("bLootTypes" , (Parcelable) _types);//not working
        lootBundle.putString("bName",name);

        FragmentManager lootFragMan = getSupportFragmentManager();
        FragmentTransaction LootTrans = lootFragMan.beginTransaction();
        LootFragment lootFragment = new LootFragment();
        lootFragment.setArguments(lootBundle);
        LootTrans.add(R.id.lootContainer,lootFragment);
        LootTrans.addToBackStack("LootStack");
        LootTrans.commit();

    }

    private void makeToast(String words) {
        Toast.makeText(this, words, Toast.LENGTH_SHORT).show();
    }
}

Any other advice based on the terrible coding displayed here would also be very appreciated :D

Body:
The Class of the Object you want to send should implement Parcelable interface as follow -

public class Student implements Parcelable {

    private Integer rollno;
    private String name;
    private Integer age;

    protected Student(Parcel in) {

        age = in.readInt();
        name  = in.readString();
        rollno = in.readInt();

    }

    public Student(Integer age, String name, Integer rollno) {
        this.age = age;
        this.name = name;
        this.rollno = rollno;
    }

    public static final Creator<Student> CREATOR = new Creator<Student>() {
        @Override
        public Student createFromParcel(Parcel in) {
            return new Student(in);
        }

        @Override
        public Student[] newArray(int size) {
            return new Student[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    public Integer getRollno() {
        return rollno;
    }

    public void setRollno(Integer rollno) {
        this.rollno = rollno;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public static Creator<Student> getCREATOR() {
        return CREATOR;
    }

  @Override
    public void writeToParcel(Parcel parcel, int i) {

        parcel.writeInt(age);
        parcel.writeString(name);
        parcel.writeInt(rollno);

    }
}

So what you should do is make a class and implement Parcelable and write the Place.Type content into its members and then pass it to other Fragment


问:
useState on React Hooks not updating Array
I have tried many things and can't seem to understand why setTypes won't update the 'types' array??

```<code>import { useState, useEffect } from 'react';
import { PostList } from './post-list';
import * as api from '../utils/api';

export const PostSelector = (props) => {
  const [posts, setPosts]     = useState([]);
  const [loading, setLoading] = useState(false);
  const [type, setType]       = useState('post');
  const [types, setTypes]     = useState([]);

  const fetchTypes = async () => {
    setLoading(true);
    const response = await api.getPostTypes();
    delete response.data.attachment;
    delete response.data.wp_block;
    const postTypes = response.data;
    console.log(response.data); // {post: {…}, page: {…}, case: {…}}
    setTypes(postTypes);
    console.log(types); // []

    // Why types remain empty??
  }

const loadPosts = async (args = {}) => {
  const defaultArgs = { per_page: 10, type };
  const requestArgs = { ...defaultArgs, ...args };

  requestArgs.restBase = types[requestArgs.type].rest_base; // Cannot read property 'rest_base' of undefined

  const response = await api.getPosts(requestArgs);
  console.log(response.data);
}

useEffect(() => {
  fetchTypes();
  loadPosts();
}, []);

  return (
    <div className="filter">
      <label htmlFor="options">Post Type: </label>
      <select name="options" id="options">
        { types.length < 1 ? (<option value="">loading</option>) : Object.keys(types).map((key, index) => <option key={ index } value={ key }>{ types[key].name }</option> ) }
      </select>
    </div>
  );
}
</code>```

Please, take a look at the console.log and notice the different responses.

What I am trying to do is to load list of types, in this case 'post', 'page' and 'case' and then render a list of posts based on the current 'type'. The default type is 'post'.

If I add [types] to useEffect. I finally get the values but the component renders nonstop.

Thanks to everyone for your comments. Multiple people have pointed out the problem, being that, the fact that we set the state doesn't mean it will set right away because it it asynchronous.

How do we solve this problem then? Regardless of the reasons, how do we get it done? How do we work with our state at any point in time and perform calculations based on our state if we don't know when it will become available? How do we make sure we wait whatever we need to and then use the values we expect?

答:
It seems like useState is asynchronous and does not update the value instantly after calling it.

Review this same case here

Body:
I have tried many things and can't seem to understand why setTypes won't update the 'types' array??

import { useState, useEffect } from 'react';
import { PostList } from './post-list';
import * as api from '../utils/api';

export const PostSelector = (props) => {
  const [posts, setPosts]     = useState([]);
  const [loading, setLoading] = useState(false);
  const [type, setType]       = useState('post');
  const [types, setTypes]     = useState([]);

  const fetchTypes = async () => {
    setLoading(true);
    const response = await api.getPostTypes();
    delete response.data.attachment;
    delete response.data.wp_block;
    const postTypes = response.data;
    console.log(response.data); // {post: {…}, page: {…}, case: {…}}
    setTypes(postTypes);
    console.log(types); // []

    // Why types remain empty??
  }

const loadPosts = async (args = {}) => {
  const defaultArgs = { per_page: 10, type };
  const requestArgs = { ...defaultArgs, ...args };

  requestArgs.restBase = types[requestArgs.type].rest_base; // Cannot read property 'rest_base' of undefined

  const response = await api.getPosts(requestArgs);
  console.log(response.data);
}

useEffect(() => {
  fetchTypes();
  loadPosts();
}, []);

  return (

      Post Type:
      <select name="options" id="options">
        { types.length < 1 ? (<option value="">loading</option>) : Object.keys(types).map((key, index) => <option key={ index } value={ key }>{ types[key].name }</option> ) }
      </select>

  );
}

Please, take a look at the console.log and notice the different responses.

What I am trying to do is to load list of types, in this case 'post', 'page' and 'case' and then render a list of posts based on the current 'type'. The default type is 'post'.

If I add [types] to useEffect. I finally get the values but the component renders nonstop.

Thanks to everyone for your comments. Multiple people have pointed out the problem, being that, the fact that we set the state doesn't mean it will set right away because it it asynchronous.

How do we solve this problem then? Regardless of the reasons, how do we get it done? How do we work with our state at any point in time and perform calculations based on our state if we don't know when it will become available? How do we make sure we wait whatever we need to and then use the values we expect?


问:
Automatically no-overwrite in ssh-keygen
If I run

ssh-keygen -t rsa -N "" -f id_rsa

and the file id_rsa already exists, it will prompt me whether I want to overwrite:

```<code>id_rsa already exists.
Overwrite (y/n)?
</code>```

How do I automatically answer no in a bash script? I checked man ssh-keygen but couldn't find any such option.

答:
you could simply do like this:
echo "n"|ssh-keygen -t rsa -N "" -f id_rsa</p>

Body:
If I run

ssh-keygen -t rsa -N "" -f id_rsa

and the file id_rsa already exists, it will prompt me whether I want to overwrite:

id_rsa already exists.
Overwrite (y/n)?

How do I automatically answer no in a bash script? I checked man ssh-keygen but couldn't find any such option.


问:
JDBC unclosed connections
If we forget to close Java JDBC connection (say oracle) in the code , would like to know will the connection stays at DB end forever (oracle) or the Oracle has any implementation at its end to auto release DB connections after some time?

```<code>try{
       ds.getConnection();
       //do some business logic

   }catch(Exception e){
       //handle exceptions

   }  finally{
           //let's say DB connection is NOT cosed..
      }
</code>```

What happens to the open connection in the code above? Does the connection gets auto released at database side once the java program exits?
I understand it is highly not recommended and bad practice to not close DB connections. I just want to know the implications and understand how oracle handles unclosed connections.

答:
Once the VM is terminated, whether more or less normally (all non-daemon threads end, System.exit is invoked, or a kill signal is received, such as hitting CTRL+C in the terminal), or abnormally (you trip over a powercord, or a terminate signal causes the kernel to just hard-exit your VM), all TCP/IP connections go away automatically, and with that, the connection is cleaned up.

But, until the VM exits, you get no guarantees. The behaviour is intentionally unspecified (as in, you must close them yourself. If you do not, no guarantees are provided), and what actually happens depends on the state of your computer (as it depends on gc runs and when those go depends on everything from which song is playing in your music player to the phase of the moon), and the JDBC driver being used.

You can use lint tools and IDE plugins to recognize that you aren't closing your connections. Also, your snippet is over 10 years out of date. The recommended and much simpler way to ensure your connection does not die on you is to use:

```<code>try (Connection con = ds.getConnection()) {
    // use 'con' here
} // no need for a catch or finally.
</code>```

Or, use connection poolers (like HikariCP), along with an abstraction to make JDBC less annoying, such as JDBI or JOOQ.

Title: JDBC unclosed connections

Body:
If we forget to close Java JDBC connection (say oracle) in the code , would like to know will the connection stays at DB end forever (oracle) or the Oracle has any implementation at its end to auto release DB connections after some time?

try{
       ds.getConnection();
       //do some business logic

   }catch(Exception e){
       //handle exceptions

   }  finally{
           //let's say DB connection is NOT cosed..
      }

What happens to the open connection in the code above? Does the connection gets auto released at database side once the java program exits?
I understand it is highly not recommended and bad practice to not close DB connections. I just want to know the implications and understand how oracle handles unclosed connections.

Body:
Once the VM is terminated, whether more or less normally (all non-daemon threads end, System.exit is invoked, or a kill signal is received, such as hitting CTRL+C in the terminal), or abnormally (you trip over a powercord, or a terminate signal causes the kernel to just hard-exit your VM), all TCP/IP connections go away automatically, and with that, the connection is cleaned up.

But, until the VM exits, you get no guarantees. The behaviour is intentionally unspecified (as in, you must close them yourself. If you do not, no guarantees are provided), and what actually happens depends on the state of your computer (as it depends on gc runs and when those go depends on everything from which song is playing in your music player to the phase of the moon), and the JDBC driver being used.

You can use lint tools and IDE plugins to recognize that you aren't closing your connections. Also, your snippet is over 10 years out of date. The recommended and much simpler way to ensure your connection does not die on you is to use:

try (Connection con = ds.getConnection()) {
    // use 'con' here
} // no need for a catch or finally.

Or, use connection poolers (like HikariCP), along with an abstraction to make JDBC less annoying, such as JDBI or JOOQ.


问:
How do I sum 2 specific column rows in a DataFrame if some of the values are NaN?
I'd like to create a new column, Inches_z. If there are values in both Inches_x and Inches_y, I want to sum the values in those 2 specific columns and return it as the result for Inches_z in the same row. If one NaN value exists, I'd like to return the row value that's not the NaN value. If both values are NaN, I'd like the resulting value to also be NaN. How do I do this?

I have:

```<code>Name    | Inches_x | Feet | Inches_y
------------------------------------
'Silvers'|    7    |   1   |     2
'Jones'  |    7    |   2   |     7
'Jackson'|    4    |  NaN  |    NaN
'Merole' |   NaN   |   2   |     8
'Kanoff' |   NaN   |   5   |    NaN
'Walker' |   NaN   |   8   |     0
'Smith'  |    8    |   0   |     3
</code>```

I want:

```<code>Name    | Inches_x | Feet | Inches_y | Inches_z
-----------------------------------------------
'Silvers'|    7    |   1   |     2   |    9
'Jones'  |    7    |   2   |     7   |    14
'Jackson'|    4    |  NaN  |    NaN  |    4
'Merole' |   NaN   |   2   |     8   |    8
'Kanoff' |   NaN   |   5   |    NaN  |   NaN
'Walker' |   NaN   |   8   |     0   |    0
'Smith'  |    8    |   0   |     3   |    11
</code>```

答:
Use an explicit call to add(), in which case you can set a fill_value for when one of the values (but not both) is NaN:

```<code>df['Inches_z'] = df['Inches_x'].add(df['Inches_y'], fill_value=0.0)
</code>```

Resulting DataFrame matches your stated expectation:

```<code>      Name  Inches_x  Feet  Inches_y  Inches_z
0  Silvers       7.0   1.0       2.0       9.0
1  Jones         7.0   2.0       7.0      14.0
2  Jackson       4.0   NaN       NaN       4.0
3  Merole        NaN   2.0       8.0       8.0
4  Kanoff        NaN   5.0       NaN       NaN
5  Walker        NaN   8.0       0.0       0.0
6  Smith         8.0   0.0       3.0      11.0
</code>```

Body:
I'd like to create a new column, Inches_z. If there are values in both Inches_x and Inches_y, I want to sum the values in those 2 specific columns and return it as the result for Inches_z in the same row. If one NaN value exists, I'd like to return the row value that's not the NaN value. If both values are NaN, I'd like the resulting value to also be NaN. How do I do this?

I have:

Name    | Inches_x | Feet | Inches_y
------------------------------------
'Silvers'|    7    |   1   |     2
'Jones'  |    7    |   2   |     7
'Jackson'|    4    |  NaN  |    NaN
'Merole' |   NaN   |   2   |     8
'Kanoff' |   NaN   |   5   |    NaN
'Walker' |   NaN   |   8   |     0
'Smith'  |    8    |   0   |     3

I want:

Name    | Inches_x | Feet | Inches_y | Inches_z
-----------------------------------------------
'Silvers'|    7    |   1   |     2   |    9
'Jones'  |    7    |   2   |     7   |    14
'Jackson'|    4    |  NaN  |    NaN  |    4
'Merole' |   NaN   |   2   |     8   |    8
'Kanoff' |   NaN   |   5   |    NaN  |   NaN
'Walker' |   NaN   |   8   |     0   |    0
'Smith'  |    8    |   0   |     3   |    11

Body:
Use an explicit call to add(), in which case you can set a fill_value for when one of the values (but not both) is NaN:

df['Inches_z'] = df['Inches_x'].add(df['Inches_y'], fill_value=0.0)

Resulting DataFrame matches your stated expectation:

      Name  Inches_x  Feet  Inches_y  Inches_z
0  Silvers       7.0   1.0       2.0       9.0
1  Jones         7.0   2.0       7.0      14.0
2  Jackson       4.0   NaN       NaN       4.0
3  Merole        NaN   2.0       8.0       8.0
4  Kanoff        NaN   5.0       NaN       NaN
5  Walker        NaN   8.0       0.0       0.0
6  Smith         8.0   0.0       3.0      11.0


问:
How to write nested if in makefile?
How do I use multiple nested if-then blocks in a Makefile?

E.g.

```<code>$(NAMING_SCHEME).$(COMPRESS_TYPE):
ifeq ($(COMPRESS_TYPE),lz4)
    if [ ${LOG_LEVEL} -gt 0 ] ; then \
        @echo hi \
        if [ ${LOG_LEVEL} -gt 1 ] ; then \
            @echo hi again \
            if [ ${LOG_LEVEL} -gt 2 ] ; then \
                @echo hi for the last time!!! \
            fi; \
        fi; \
    fi;
endif
</code>```

This results in

```<code>bin/sh: -c: line 2: syntax error near unexpected token 'then'
/bin/sh: -c: line 0: 'ifeq (1, 1)'
make: *** [Makefile:22: program_name.1.2.3.lz4] Error 1
</code>```

What am I doing incorrectly?

答: make ships off each line to the shell on it's own, thus mutilating your command. To continue a line, end it with a backslash (\).

Title: How to write nested if in makefile?

Body:
How do I use multiple nested if-then blocks in a Makefile?

E.g.

$(NAMING_SCHEME).$(COMPRESS_TYPE):
ifeq ($(COMPRESS_TYPE),lz4)
    if [ ${LOG_LEVEL} -gt 0 ] ; then \
        @echo hi \
        if [ ${LOG_LEVEL} -gt 1 ] ; then \
            @echo hi again \
            if [ ${LOG_LEVEL} -gt 2 ] ; then \
                @echo hi for the last time!!! \
            fi; \
        fi; \
    fi;
endif

This results in

bin/sh: -c: line 2: syntax error near unexpected token 'then'
/bin/sh: -c: line 0: 'ifeq (1, 1)'
make: *** [Makefile:22: program_name.1.2.3.lz4] Error 1

What am I doing incorrectly?


问:
UIScrollview subviews outside of clipping bounds not receiving touches
I have a UIScrollView which I have set up to swipe one column at a time (two columns per page)  - by setting the frame to half of the views actual width, setting clipToBounds to NO and use hitTest to declare the area outside of the frame as belonging to the UIScrollView (see example below).

This works great, but my problem now is that the subviews of the UIScrollView don't get any touch events - only the main UIScrollView does.

In the following example, if the hitTest code is included, then the scrollview scrolls correctly, paging one column at a time and all its content may be seen - but the inner scrollviews do not receive touch events.

If I remove the hitTest code, then only the first child scrollview receives touches, and all its content may be seen - but the main scrollview wont get touches in the non-clipped area.

How can I solve this?

Example:

```<code>//=========================================
// UIScrollViewEx
// Just in order to log touches...
//=========================================

@interface UIScrollViewEx : UIScrollView {}
@end

@implementation UIScrollViewEx
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    NSLog(@"Touches Began (0x%08X)", (unsigned int)self);
}
@end

//=========================================
// UIViewEx
// Dummy class - sets subview as hit target
// just to demonstrate usage of non-clipped
// content
//=========================================

@interface UIViewEx : UIView {}
@end

@implementation UIViewEx
- (UIView *) hitTest:(CGPoint) point withEvent:(UIEvent *)event {
    if ([self pointInside:point withEvent:event]) {
        return [self.subviews objectAtIndex:0];
    }
    return nil;
}
@end

//=========================================
// MainClass
// Any UIViewEx based class which returns
// the UIScrollView child on hittest
//=========================================

@implementation MyClass

- (UIColor*) randomColor
{
    int r = arc4random() % 100;
    int g = arc4random() % 100;
    int b = arc4random() % 100;
    return [UIColor colorWithRed:(0.01 * r) green:(0.01 * g) blue:(0.01 * b) alpha:1.0];
}

- (void) loadScrollviews
{
    // Set frame to half of actual width so that paging will swipe half a page only
    CGRect frame = CGRectMake(0, 0, self.bounds.size.width / 2, 400);

    // Main scrollview
    UIScrollView *scrollview = [[UIScrollView alloc] initWithFrame:frame];
    [scrollview setBackgroundColor:[UIColor greenColor]];
    [scrollview setPagingEnabled:YES];
    [scrollview setClipsToBounds:NO];

    // Create smaller scrollviews inside it - each one half a screen wide
    const int numItems = 5;
    for(int i = 0; i < numItems; ++i) {
        frame.origin.x = frame.size.width * i;
        UIScrollView *innerScrollview = [[UIScrollViewEx alloc] initWithFrame:frame];
        [innerScrollview setContentSize:CGSizeMake(frame.size.width, 1000)];
        [innerScrollview setBackgroundColor:[self randomColor]];
        [scrollview addSubview:innerScrollview];
        [innerScrollview release];
    }

    [scrollview setContentSize:CGSizeMake(numItems * frame.size.width, frame.size.height)];

    [self addSubview:scrollview];
}

@end
</code>```

Update

I get the touches forwarded to the inner view by doing the following, but surely there must be a better way?

```<code>- (UIView *) hitTest: (CGPoint) pt withEvent: (UIEvent *) event
{
    if(CGRectContainsPoint(self.bounds, pt))
    {
        UIScrollView *scrollview = [self.subviews objectAtIndex:0];
        CGPoint scrollViewpoint = [scrollview convertPoint:pt fromView:self];

        for(UIView *view in scrollview.subviews) {
            if(CGRectContainsPoint(view.frame, scrollViewpoint)) {
                return view;
            }
        }
        return scrollview;
    }
    else {
        return [super hitTest:pt withEvent:event];
    }
}
</code>```

答:
This may work:

```<code>- (UIView*)hitTest:(CGPoint)point withEvent:(UIEvent*)event {
    UIView* child = nil;
    if ((child = [super hitTest:point withEvent:event]) == self)
        return self.scrollView;
    return child;
}
</code>```

But if subview is out of scrollview bounds events were not fired and this function returns self.scrollView.

ContentLicense: CC BY-SA 2.5

Body:
I have a UIScrollView which I have set up to swipe one column at a time (two columns per page)  - by setting the frame to half of the views actual width, setting clipToBounds to NO and use hitTest to declare the area outside of the frame as belonging to the UIScrollView (see example below).

This works great, but my problem now is that the subviews of the UIScrollView don't get any touch events - only the main UIScrollView does.

In the following example, if the hitTest code is included, then the scrollview scrolls correctly, paging one column at a time and all its content may be seen - but the inner scrollviews do not receive touch events.

If I remove the hitTest code, then only the first child scrollview receives touches, and all its content may be seen - but the main scrollview wont get touches in the non-clipped area.

How can I solve this?

Example:

//=========================================
// UIScrollViewEx
// Just in order to log touches...
//=========================================

@interface UIScrollViewEx : UIScrollView {}
@end

@implementation UIScrollViewEx
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    NSLog(@"Touches Began (0x%08X)", (unsigned int)self);
}
@end

//=========================================
// UIViewEx
// Dummy class - sets subview as hit target
// just to demonstrate usage of non-clipped
// content
//=========================================

@interface UIViewEx : UIView {}
@end

@implementation UIViewEx
- (UIView *) hitTest:(CGPoint) point withEvent:(UIEvent *)event {
    if ([self pointInside:point withEvent:event]) {
        return [self.subviews objectAtIndex:0];
    }
    return nil;
}
@end

//=========================================
// MainClass
// Any UIViewEx based class which returns
// the UIScrollView child on hittest
//=========================================

@implementation MyClass

- (UIColor*) randomColor
{
    int r = arc4random() % 100;
    int g = arc4random() % 100;
    int b = arc4random() % 100;
    return [UIColor colorWithRed:(0.01 * r) green:(0.01 * g) blue:(0.01 * b) alpha:1.0];
}

- (void) loadScrollviews
{
    // Set frame to half of actual width so that paging will swipe half a page only
    CGRect frame = CGRectMake(0, 0, self.bounds.size.width / 2, 400);

    // Main scrollview
    UIScrollView *scrollview = [[UIScrollView alloc] initWithFrame:frame];
    [scrollview setBackgroundColor:[UIColor greenColor]];
    [scrollview setPagingEnabled:YES];
    [scrollview setClipsToBounds:NO];

    // Create smaller scrollviews inside it - each one half a screen wide
    const int numItems = 5;
    for(int i = 0; i < numItems; ++i) {
        frame.origin.x = frame.size.width * i;
        UIScrollView *innerScrollview = [[UIScrollViewEx alloc] initWithFrame:frame];
        [innerScrollview setContentSize:CGSizeMake(frame.size.width, 1000)];
        [innerScrollview setBackgroundColor:[self randomColor]];
        [scrollview addSubview:innerScrollview];
        [innerScrollview release];
    }

    [scrollview setContentSize:CGSizeMake(numItems * frame.size.width, frame.size.height)];

    [self addSubview:scrollview];
}

@end

Update

I get the touches forwarded to the inner view by doing the following, but surely there must be a better way?

- (UIView *) hitTest: (CGPoint) pt withEvent: (UIEvent *) event
{
    if(CGRectContainsPoint(self.bounds, pt))
    {
        UIScrollView *scrollview = [self.subviews objectAtIndex:0];
        CGPoint scrollViewpoint = [scrollview convertPoint:pt fromView:self];

        for(UIView *view in scrollview.subviews) {
            if(CGRectContainsPoint(view.frame, scrollViewpoint)) {
                return view;
            }
        }
        return scrollview;
    }
    else {
        return [super hitTest:pt withEvent:event];
    }
}

Body:
This may work:

- (UIView*)hitTest:(CGPoint)point withEvent:(UIEvent*)event {
    UIView* child = nil;
    if ((child = [super hitTest:point withEvent:event]) == self)
        return self.scrollView;
    return child;
}

But if subview is out of scrollview bounds events were not fired and this function returns self.scrollView.


问:
Unable to align edge of view to another center aligned view
I have a pretty simple RelativeLayout with following views:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/main_menu_selector"
    android:minHeight="48dp">

    <ImageView
        android:id="@+id/menuItemAvatar"
        android:layout_width="38dp"
        android:layout_height="38dp"
        android:layout_centerVertical="true"
        android:layout_marginStart="10dp"
        android:layout_marginEnd="6dp"
        android:background="@color/IconOff" />

    <ImageView
        android:id="@+id/iv_status"
        android:layout_width="14dp"
        android:layout_height="14dp"
        android:layout_alignEnd="@id/menuItemAvatar"
        android:layout_alignBottom="@id/menuItemAvatar"
        android:scaleType="fitCenter" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toEndOf="@+id/menuItemAvatar"
        android:gravity="start"
        android:orientation="vertical"
        android:padding="4dp">

        <TextView
            android:id="@+id/menuItemTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:textColor="@color/TextBlackColor"
            android:textSize="@dimen/main_menu_text_size" />

    </LinearLayout>

</RelativeLayout>
</code>```

I want the iv_status(the small green square) to be in the right bottom corner of menuItemAvatar, but what I get looks like this:

As you can see the bottom edges are not aligned properly. The funny thing is - if I remove the line android:layout_centerVertical="true" from menuItemAvatar it aligns as it should:

But then the image is not centered and everything looks shifted in relation to the text.

答:
I converted your layout to a ConstraintLayout with the right constraints and it seems to be working fine for me. Have a go with this:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/main_menu_selector"
    android:minHeight="48dp">

    <ImageView
        android:id="@+id/menuItemAvatar"
        android:layout_width="38dp"
        android:layout_height="38dp"
        android:layout_marginStart="10dp"
        android:layout_marginEnd="6dp"
        android:background="@color/IconOff"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <ImageView
        android:id="@+id/iv_status"
        android:layout_width="14dp"
        android:layout_height="14dp"
        android:layout_alignEnd="@id/menuItemAvatar"
        android:layout_alignBottom="@id/menuItemAvatar"
        app:layout_constraintEnd_toEndOf="@id/menuItemAvatar"
        app:layout_constraintBottom_toBottomOf="@id/menuItemAvatar"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toEndOf="@+id/menuItemAvatar"
        android:orientation="vertical"
        android:padding="4dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="@+id/menuItemAvatar">

        <TextView
            android:id="@+id/menuItemTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:textColor="@color/TextBlackColor"
            android:textSize="@dimen/main_menu_text_size" />

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Body:
I have a pretty simple RelativeLayout with following views:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/main_menu_selector"
    android:minHeight="48dp">

    <ImageView
        android:id="@+id/menuItemAvatar"
        android:layout_width="38dp"
        android:layout_height="38dp"
        android:layout_centerVertical="true"
        android:layout_marginStart="10dp"
        android:layout_marginEnd="6dp"
        android:background="@color/IconOff" />

    <ImageView
        android:id="@+id/iv_status"
        android:layout_width="14dp"
        android:layout_height="14dp"
        android:layout_alignEnd="@id/menuItemAvatar"
        android:layout_alignBottom="@id/menuItemAvatar"
        android:scaleType="fitCenter" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toEndOf="@+id/menuItemAvatar"
        android:gravity="start"
        android:orientation="vertical"
        android:padding="4dp">

        <TextView
            android:id="@+id/menuItemTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:textColor="@color/TextBlackColor"
            android:textSize="@dimen/main_menu_text_size" />

    </LinearLayout>

</RelativeLayout>

I want the iv_status(the small green square) to be in the right bottom corner of menuItemAvatar, but what I get looks like this:

As you can see the bottom edges are not aligned properly. The funny thing is - if I remove the line android:layout_centerVertical="true" from menuItemAvatar it aligns as it should:

But then the image is not centered and everything looks shifted in relation to the text.

Body:
I converted your layout to a ConstraintLayout with the right constraints and it seems to be working fine for me. Have a go with this:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/main_menu_selector"
    android:minHeight="48dp">

    <ImageView
        android:id="@+id/menuItemAvatar"
        android:layout_width="38dp"
        android:layout_height="38dp"
        android:layout_marginStart="10dp"
        android:layout_marginEnd="6dp"
        android:background="@color/IconOff"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <ImageView
        android:id="@+id/iv_status"
        android:layout_width="14dp"
        android:layout_height="14dp"
        android:layout_alignEnd="@id/menuItemAvatar"
        android:layout_alignBottom="@id/menuItemAvatar"
        app:layout_constraintEnd_toEndOf="@id/menuItemAvatar"
        app:layout_constraintBottom_toBottomOf="@id/menuItemAvatar"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toEndOf="@+id/menuItemAvatar"
        android:orientation="vertical"
        android:padding="4dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="@+id/menuItemAvatar">

        <TextView
            android:id="@+id/menuItemTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:textColor="@color/TextBlackColor"
            android:textSize="@dimen/main_menu_text_size" />

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>


问:
Cursor weird behavior: resets to default
On a mouse move on an NSView, I change the cursor to a hand [[NSCursor pointingHandCursor] set]. I do NOT reset anywhere in the code the cursor to arrow.

This works pretty well, however if I move the mouse slowly I can see at times it reverts to the arrow. This is unwanted. Is that a bug in Cocoa or is there a work around?

```<code>-(void) mouseMoved:(NSEvent*) event {
  [[NSCursor pointingHandCursor] set];
}
</code>```

Again, I do not play with the cursor anywhere else in the code. I do not have other views overlaying on my NSView. Thanks in advance!

答:
Answering my own question based on @seth's suggestion. This is what I used to set or unset a cursor. It does not have the issue I described above. I did not use mouseEntered or mouseExit.</p>

```<code>-(void)setCursor:(NSCursor *)cursor {  // nil to reset to the arrow
    if (cursor == _cursor)
        return;
    _cursor = cursor;
    [self discardCursorRects];
    [self.window invalidateCursorRectsForView:self];  // this is needed in Catalina
    [self resetCursorRects];
}

-(void)resetCursorRects {
    if (_cursor != nil) {
        [self addCursorRect:self.bounds cursor:_cursor];
    }
    [super resetCursorRects];
}
</code>```

Body:
On a mouse move on an NSView, I change the cursor to a hand [[NSCursor pointingHandCursor] set]. I do NOT reset anywhere in the code the cursor to arrow.

This works pretty well, however if I move the mouse slowly I can see at times it reverts to the arrow. This is unwanted. Is that a bug in Cocoa or is there a work around?

-(void) mouseMoved:(NSEvent*) event {
  [[NSCursor pointingHandCursor] set];
}

Again, I do not play with the cursor anywhere else in the code. I do not have other views overlaying on my NSView. Thanks in advance!

Body:
Answering my own question based on @seth's suggestion. This is what I used to set or unset a cursor. It does not have the issue I described above. I did not use mouseEntered or mouseExit.

-(void)setCursor:(NSCursor *)cursor {  // nil to reset to the arrow
    if (cursor == _cursor)
        return;
    _cursor = cursor;
    [self discardCursorRects];
    [self.window invalidateCursorRectsForView:self];  // this is needed in Catalina
    [self resetCursorRects];
}

-(void)resetCursorRects {
    if (_cursor != nil) {
        [self addCursorRect:self.bounds cursor:_cursor];
    }
    [super resetCursorRects];
}


问:
C++ omp no significant improvement
I am on MSVC 2019 with the default compiler. The code I am working on is a Mandelbrot image. Relevant bits of my code looks like:

```<code>#pragma omp parallel for
for (int y = 0; y < HEIGHT; y++)
    {
       for (int x = 0; x < WIDTH; x++)
           {
               unsigned int retVal = mandel(x_val + x_incr * x, y_val + y_incr * y);
               mtest.setPixels(x, y,
                        static_cast<unsigned char>(retVal / 6),
                        static_cast<unsigned char>(retVal / 5),
                        static_cast<unsigned char>(retVal / 4));

           }
     }
</code>```

All of the variables outside of the loop are constexpr, eliminating any dependencies. The mandel function does about 1000 iterations with each call. I would expect the outer loop to run on several threads but my msvc records each run at about 5-6 seconds with or without the omp directive.

Edit (The mandel function):

```<code>unsigned int mandel(long double x, long double y)
{
    long double z_x = 0;
    long double z_y = 0;

    for (int i = 0; i < ITER; i++)
    {
        long double temp = z_x;
        z_x = (z_x * z_x) - (z_y * z_y) + x;
        z_y = 2 * temp * z_y + y;

        if ((z_x * z_x + z_y * z_y) > 4)
            return i;
    }
    return ITER; //ITER is a #define macro
}
</code>```

答:
Your mandel function has a vastly differing runtime cost depending on whether the if condition within the loop has been met. As a result, each iteration of your loop will run in a different time. By default omp uses static scheduling (i.e. break loop into N partitions). This is kinda bad, because you don't have a workload that fits static scheduling. See what happens when you use dynamic scheduling.

#pragma omp parallel for schedule(dynamic, 1)
for (int y = 0; y < HEIGHT; y++)
    {
       for (int x = 0; x < WIDTH; x++)
           {
               unsigned int retVal = mandel(x_val + x_incr * x, y_val + y_incr * y);
               mtest.setPixels(x, y,
                        static_cast<unsigned char>(retVal / 6),
                        static_cast<unsigned char>(retVal / 5),
                        static_cast<unsigned char>(retVal / 4));

           }
     }
```

Also time to rule out the really dumb stuff.....

Have you included omp.h at least once in your program?

Have you enabled omp in the project settings?

IIRC, if you haven't done those two things, omp will be disabled under MSVC.

Title: C++ omp no significant improvement

Body:
I am on MSVC 2019 with the default compiler. The code I am working on is a Mandelbrot image. Relevant bits of my code looks like:

#pragma omp parallel for
for (int y = 0; y < HEIGHT; y++)
    {
       for (int x = 0; x < WIDTH; x++)
           {
               unsigned int retVal = mandel(x_val + x_incr * x, y_val + y_incr * y);
               mtest.setPixels(x, y,
                        static_cast<unsigned char>(retVal / 6),
                        static_cast<unsigned char>(retVal / 5),
                        static_cast<unsigned char>(retVal / 4));

           }
     }

All of the variables outside of the loop are constexpr, eliminating any dependencies. The mandel function does about 1000 iterations with each call. I would expect the outer loop to run on several threads but my msvc records each run at about 5-6 seconds with or without the omp directive.

Edit (The mandel function):

unsigned int mandel(long double x, long double y)
{
    long double z_x = 0;
    long double z_y = 0;

    for (int i = 0; i < ITER; i++)
    {
        long double temp = z_x;
        z_x = (z_x * z_x) - (z_y * z_y) + x;
        z_y = 2 * temp * z_y + y;

        if ((z_x * z_x + z_y * z_y) > 4)
            return i;
    }
    return ITER; //ITER is a #define macro
}

Body:
Your mandel function has a vastly differing runtime cost depending on whether the if condition within the loop has been met. As a result, each iteration of your loop will run in a different time. By default omp uses static scheduling (i.e. break loop into N partitions). This is kinda bad, because you don't have a workload that fits static scheduling. See what happens when you use dynamic scheduling.

#pragma omp parallel for schedule(dynamic, 1)
for (int y = 0; y < HEIGHT; y++)
    {
       for (int x = 0; x < WIDTH; x++)
           {
               unsigned int retVal = mandel(x_val + x_incr * x, y_val + y_incr * y);
               mtest.setPixels(x, y,
                        static_cast<unsigned char>(retVal / 6),
                        static_cast<unsigned char>(retVal / 5),
                        static_cast<unsigned char>(retVal / 4));

           }
     }

Also time to rule out the really dumb stuff.....

Have you included omp.h at least once in your program?

Have you enabled omp in the project settings?

IIRC, if you haven't done those two things, omp will be disabled under MSVC.


问:
Android: how to open a Google Map?
I have an activity which extends MapActivity. After running the activity, the Google Map should be shown on the emulator.
How can I do that?</p>

答:
You can refer this link, http://developer.android.com/resources/tutorials/views/hello-mapview.html

Check if you have provided your Map API key properly. This link has helped me to display the map with my present location.

Title: Android: how to open a Google Map?


问:
How to disable function signature suggestion popups in vscode?
I disabled all the suggestions options I could find in settings, but this one still pops up.

How could I disable it?

答:
Te VS Code term for this is signature-help/parameter-hints. To disable them, just set:

```<code>"editor.parameterHints.enabled:: false
</code>```

After disabling, you can manually show the parameter hints at the current location using the Trigger parameter hints command

Body:
Te VS Code term for this is signature-help/parameter-hints. To disable them, just set:

"editor.parameterHints.enabled:: false

After disabling, you can manually show the parameter hints at the current location using the Trigger parameter hints command


问:
AM4Charts Invalidate Property Fields
I'm trying to create a column chart where the column shows the percentage completed of some task. The data is updated every thirty seconds. I want to make it so that when the job is between 0-50% complete, otherwise, the column is green.

```<code>series.columns.template.adapter.add('stroke', (stroke, target) =>
{
    let returnValue;
    if (target.dummyData.level < 50)
        returnValue = "#f26969";
    else
        returnValue = '#9d4062';
    return am4core.color(returnValue);
})
</code>```

Where level is part of a variable called breakdown assigned to property fields via:

```<code>                seriesCanisterLevels.tooltip.propertyFields.dummyData = "breakdown";
</code>```

This code works fine the first time that it is run (ie when the graph is first rendered). If I set the initial value > or < 50, I get the behaviour I expect. However, after that, as the data is dynamically changed every 30 seconds, it does not change the color (though the length of the columns change).

Upon some investigation, it turns out, that a change in a propertyField, and a subsequent chart.invalidateRawData(), does not cause the adapters to fire again. Is there a workaround for this (I do not want to call chart.invalidateData as I don't want to rerender the whole graph, though this does work)

答:
Adapters won't retrigger unless you invalidate the chart and/or associated elements directly (like you noticed) or if the properties assocated with the adapter have been changed. You can mimic the latter by looping through the series columns and assign the stroke to itself after you update the data:

```<code>  series.columns.each(function(column) {
    column.stroke = column.stroke;
  })
</code>```

Demo below:

// Themes begin
am4core.useTheme(am4themes_animated);
// Themes end

// Create chart instance
var chart = am4core.create("chartdiv", am4charts.XYChart);

// Add data
chart.data = [{
  "category": "0",
  "value": 50,
  "breakdown": {
    "level": 50
  }
}];

// Create axes
var categoryAxis = chart.yAxes.push(new am4charts.CategoryAxis());
categoryAxis.dataFields.category = "category";
categoryAxis.renderer.labels.template.disabled = true;
categoryAxis.renderer.grid.template.disabled = true;

var valueAxis = chart.xAxes.push(new am4charts.ValueAxis());
valueAxis.renderer.opposite = true;
valueAxis.renderer.grid.template.disabled = true;
valueAxis.min = 0;
valueAxis.max = 100;
valueAxis.strictMinMax = 0;

var series = chart.series.push(new am4charts.ColumnSeries());
series.dataFields.valueX = "value";
series.dataFields.categoryY = "category";
series.columns.template.tooltipText = "Text: [bold]{dummyData.level}[/]";
series.columns.template.height = am4core.percent(100);
series.columns.template.strokeWidth = 10;
series.sequencedInterpolation = true;
series.columns.template.propertyFields.dummyData = "breakdown";
series.tooltip.propertyFields.dummyData = "breakdown";
series.columns.template.adapter.add('stroke', (stroke, target) => {
  let returnValue;
  if (target.dummyData.level < 50) {
    returnValue = "#f26969";
  } else {
    returnValue = '#9d4062';
  }
  return am4core.color(returnValue);
});

setInterval(function() {
  var value = Math.floor(Math.random() * 100);
  chart.data[0].value = value;
  chart.data[0].breakdown.level = value;
  chart.invalidateRawData();
  series.columns.each(function(column) {
    column.stroke = column.stroke;
  })
}, 2000)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#chartdiv {
  width: 100%;
  height: 200px;
}</code>```

```

Title: AM4Charts Invalidate Property Fields

Body:
I'm trying to create a column chart where the column shows the percentage completed of some task. The data is updated every thirty seconds. I want to make it so that when the job is between 0-50% complete, otherwise, the column is green.

series.columns.template.adapter.add('stroke', (stroke, target) =>
{
    let returnValue;
    if (target.dummyData.level < 50)
        returnValue = "#f26969";
    else
        returnValue = '#9d4062';
    return am4core.color(returnValue);
})

Where level is part of a variable called breakdown assigned to property fields via:

                seriesCanisterLevels.tooltip.propertyFields.dummyData = "breakdown";

This code works fine the first time that it is run (ie when the graph is first rendered). If I set the initial value > or < 50, I get the behaviour I expect. However, after that, as the data is dynamically changed every 30 seconds, it does not change the color (though the length of the columns change).

Upon some investigation, it turns out, that a change in a propertyField, and a subsequent chart.invalidateRawData(), does not cause the adapters to fire again. Is there a workaround for this (I do not want to call chart.invalidateData as I don't want to rerender the whole graph, though this does work)

Body:
Adapters won't retrigger unless you invalidate the chart and/or associated elements directly (like you noticed) or if the properties assocated with the adapter have been changed. You can mimic the latter by looping through the series columns and assign the stroke to itself after you update the data:

  series.columns.each(function(column) {
    column.stroke = column.stroke;
  })

Demo below:

// Themes begin
am4core.useTheme(am4themes_animated);
// Themes end

// Create chart instance
var chart = am4core.create("chartdiv", am4charts.XYChart);

// Add data
chart.data = [{
  "category": "0",
  "value": 50,
  "breakdown": {
    "level": 50
  }
}];

// Create axes
var categoryAxis = chart.yAxes.push(new am4charts.CategoryAxis());
categoryAxis.dataFields.category = "category";
categoryAxis.renderer.labels.template.disabled = true;
categoryAxis.renderer.grid.template.disabled = true;

var valueAxis = chart.xAxes.push(new am4charts.ValueAxis());
valueAxis.renderer.opposite = true;
valueAxis.renderer.grid.template.disabled = true;
valueAxis.min = 0;
valueAxis.max = 100;
valueAxis.strictMinMax = 0;

var series = chart.series.push(new am4charts.ColumnSeries());
series.dataFields.valueX = "value";
series.dataFields.categoryY = "category";
series.columns.template.tooltipText = "Text: [bold]{dummyData.level}[/]";
series.columns.template.height = am4core.percent(100);
series.columns.template.strokeWidth = 10;
series.sequencedInterpolation = true;
series.columns.template.propertyFields.dummyData = "breakdown";
series.tooltip.propertyFields.dummyData = "breakdown";
series.columns.template.adapter.add('stroke', (stroke, target) => {
  let returnValue;
  if (target.dummyData.level < 50) {
    returnValue = "#f26969";
  } else {
    returnValue = '#9d4062';
  }
  return am4core.color(returnValue);
});

setInterval(function() {
  var value = Math.floor(Math.random() * 100);
  chart.data[0].value = value;
  chart.data[0].breakdown.level = value;
  chart.invalidateRawData();
  series.columns.each(function(column) {
    column.stroke = column.stroke;
  })
}, 2000)

#chartdiv {
  width: 100%;
  height: 200px;
}

<script src="https://www.amcharts.com/lib/4/core.js"></script>
<script src="https://www.amcharts.com/lib/4/charts.js"></script>
<script src="https://www.amcharts.com/lib/4/themes/animated.js"></script>
<div id="chartdiv"></div>


问:
AWS S3 Replication - One source bucket to multiple destination bucket
I have a requirement of copying objects from one s3 bucket to multiple destination bucket.

From bucket A, copy all object to Bucket B (different region)

From bucket A, copy objects with only few prefixes to Bucket C (same region)

I saw that multiple S3 replication rules can be applied to only one destination bucket. Any thoughts on how to achieve this?

答: Updated December 2020: S3 Replication now supports replicating objects from one bucket to multiple destination buckets. See: New – Amazon S3 Replication Adds Support for Multiple Destination Buckets | AWS News Blog


问:
Testing Imported Function with Parameter using Jest Mock Function / Jest spyOn
I'm trying to write a unit test for a Node.js project's logic using Jest.
However, most documentations only provide a case for importing a module or class, however, in my case, my module only contains functions.

So far I know that there are mainly three ways to test a function in Jest:

1) jest.fn()

2) jest.spyOn

3) jest.mock('path')

I have tried all three but none work.

I wanted to test if the function returns a correct value(string) when called.
I tried many different

Here's my code: (I will show short snippets of my code in the later parts)

getDefApCode.ts

export function getDefApCode(code: string) {
  switch (code) {
    case 'BKK':
      return 'NRT'
    case 'CTX':
      return 'ICN'
    case 'SIN':
      return 'TPE'
    default:
      return code
  }
}

export function getDefaultDepartureCode(code: string) {
  return code ? getDefaultLocationCode(code) : 'LHR'
}

export function getDefaultDestinationCode(code: string) {
  return code ? getDefaultLocationCode(code) : 'ZRH'
}```
</div>
</div>
</p>

<p><strong>getDefAPCode.spec.ts</strong> >> Pattern 1 (using required + jest.fn)</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>import { Connection, getConnection, getConnectionOptions } from "typeorm";
import { bootstrap, dbConnection } from "../../../src/app";
import { TourSearchParamsFactory } from "../../helpers/typeOrmFactory";
import * as getDefAPCode from "../../../src/controllers/logic/getDefAPCode";

describe("Logic Test", () => {
  beforeAll(async () => {
    await dbConnection(15, 3000);
  });

  afterAll(async () => {
    const conn = getConnection();
    await conn.close();
  });

  it("should get a default location code", async () => {
   const getLocation = require('../../../src/controllers/logic/getDefAPCode');
   const code = jest.fn(code => 'BKK');
   const getCode = getLocation(code);
   expect(getCode).toHaveBeenCalled();

   });
 });</code>```

Error Message:

```<code>TypeError: getLocation is not a function
</code>```

getDefAPCode.spec.ts >> Pattern 2 (using spyON)

import { Connection, getConnection, getConnectionOptions } from "typeorm";
import { bootstrap, dbConnection } from "../../../src/app";
import { TourSearchParamsFactory } from "../../helpers/typeOrmFactory";
import * as getDefaultLocationCode from "../../../src/controllers/logic/getDefaultLocationCode";

describe("Logic Test", () => {
  beforeAll(async () => {
    await dbConnection(15, 3000);
  });

  afterAll(async () => {
    const conn = getConnection();
    await conn.close();
  });

  const { getDefaultLocationCode, getDefaultDepartureCode, getDefaultDestinationCode } = require('../../../src/controllers/logic/getDefaultLocationCode');

  it("should get a default location code", async () => {
   const spy = jest.spyOn(getDefaultLocationCode, 'getDefaultLocationCode');
   getDefaultLocationCode.getDefaultLocationCode('AKJ');
   expect(spy).toHaveBeenCalled();
  });
 });```
</div>
</div>
</p>

<p>These are some error messages appear when I tried a different pattern (I didn't keep track of all of the test code pattern, will add the test code pattern once I fixed docker)</p>

<p>Error Message: </p>

```Cannot spy the getDefaultLocationCode property because it is not a function; undefined given instead
```

<blockquote>
  <p>31 |      const spy = jest.spyOn(getDefaultLocationCode, 'getDefaultLocationCode');</p>
</blockquote>

<p>Past Error Messages</p>

```error TS2349: This expression is not callable.
      Type 'typeof import("/app/src/controllers/logic/getDefAPCode")' has no call signatures.
```

<p>another one</p>

```expect(received).toHaveBeenCalled()

Matcher error: received value must be a mock or spy function

Received has type:  string
Received has value: "NRT"
```

答:
I figured out that I don't have to use mock function in this case.

I stored argument in a variable and then I use the variable instead using a string directly.

Here's how I edit my test code

```<code>  it("should get a default location code", () => {
    const code = 'BKK';
    expect(code).toHaveBeenCalled();
   });
</code>```

Body:
I'm trying to write a unit test for a Node.js project's logic using Jest.
However, most documentations only provide a case for importing a module or class, however, in my case, my module only contains functions.

So far I know that there are mainly three ways to test a function in Jest:

1) jest.fn()

2) jest.spyOn

3) jest.mock('path')

I have tried all three but none work.

I wanted to test if the function returns a correct value(string) when called.
I tried many different

Here's my code: (I will show short snippets of my code in the later parts)

getDefApCode.ts

export function getDefApCode(code: string) {
  switch (code) {
    case 'BKK':
      return 'NRT'
    case 'CTX':
      return 'ICN'
    case 'SIN':
      return 'TPE'
    default:
      return code
  }
}

export function getDefaultDepartureCode(code: string) {
  return code ? getDefaultLocationCode(code) : 'LHR'
}

export function getDefaultDestinationCode(code: string) {
  return code ? getDefaultLocationCode(code) : 'ZRH'
}

getDefAPCode.spec.ts >> Pattern 1 (using required + jest.fn)

import { Connection, getConnection, getConnectionOptions } from "typeorm";
import { bootstrap, dbConnection } from "../../../src/app";
import { TourSearchParamsFactory } from "../../helpers/typeOrmFactory";
import * as getDefAPCode from "../../../src/controllers/logic/getDefAPCode";

describe("Logic Test", () => {
  beforeAll(async () => {
    await dbConnection(15, 3000);
  });

  afterAll(async () => {
    const conn = getConnection();
    await conn.close();
  });

  it("should get a default location code", async () => {
   const getLocation = require('../../../src/controllers/logic/getDefAPCode');
   const code = jest.fn(code => 'BKK');
   const getCode = getLocation(code);
   expect(getCode).toHaveBeenCalled();

   });
 });

Error Message:

TypeError: getLocation is not a function

getDefAPCode.spec.ts >> Pattern 2 (using spyON)

import { Connection, getConnection, getConnectionOptions } from "typeorm";
import { bootstrap, dbConnection } from "../../../src/app";
import { TourSearchParamsFactory } from "../../helpers/typeOrmFactory";
import * as getDefaultLocationCode from "../../../src/controllers/logic/getDefaultLocationCode";

describe("Logic Test", () => {
  beforeAll(async () => {
    await dbConnection(15, 3000);
  });

  afterAll(async () => {
    const conn = getConnection();
    await conn.close();
  });

  const { getDefaultLocationCode, getDefaultDepartureCode, getDefaultDestinationCode } = require('../../../src/controllers/logic/getDefaultLocationCode');

  it("should get a default location code", async () => {
   const spy = jest.spyOn(getDefaultLocationCode, 'getDefaultLocationCode');
   getDefaultLocationCode.getDefaultLocationCode('AKJ');
   expect(spy).toHaveBeenCalled();
  });
 });

These are some error messages appear when I tried a different pattern (I didn't keep track of all of the test code pattern, will add the test code pattern once I fixed docker)

Error Message:

Cannot spy the getDefaultLocationCode property because it is not a function; undefined given instead

31 |      const spy = jest.spyOn(getDefaultLocationCode, 'getDefaultLocationCode');

Past Error Messages

error TS2349: This expression is not callable.
      Type 'typeof import("/app/src/controllers/logic/getDefAPCode")' has no call signatures.

another one

expect(received).toHaveBeenCalled()

Matcher error: received value must be a mock or spy function

Received has type:  string
Received has value: "NRT"

Body:
I figured out that I don't have to use mock function in this case.

I stored argument in a variable and then I use the variable instead using a string directly.

Here's how I edit my test code

  it("should get a default location code", () => {
    const code = 'BKK';
    expect(code).toHaveBeenCalled();
   });


问:
GIT: Move changes from one branch to other
I have 2 branches A and B.
I made some changes to A and committed them.
I then made more changes to A (by mistake).
I pushed them to B and committed them. </p>

<p>But now  I see changes from A (old) and B (new) being committed. How do I revert this? </p>

答:
```<code>git checkout <branchname>
git reset --hard <commitid>
</code>```

This restores everything to it's original state. If you meant something else, please elaborate.

Regards,
Zenima

Body:
I have 2 branches A and B.
I made some changes to A and committed them.
I then made more changes to A (by mistake).
I pushed them to B and committed them.

But now  I see changes from A (old) and B (new) being committed. How do I revert this?

Body:
git checkout <branchname>
git reset --hard <commitid>

This restores everything to it's original state. If you meant something else, please elaborate.

Regards,
Zenima