问:
PHP (Laravel) Dependency Injection Basics
I have recently come across the SOLID design principles and have been looking to find ways to incorporate dependency injection into my work so that I can write better tests and mock out any external calls. I have had a go at some dependency injection in PHP Laravel (Lumen) but something doesn't seem right in the below.

The code to create the dependencies is being created inside a public method in one of the controllers. This doesn't seem like the appropriate place to put it as I now have a lot of quite ugly code instantiating objects inside the controller rather than just receiving the request and packaging up the response. Is there somewhere more appropriate to the do the instantiation? Also for certain items, e.g. the $paying_user object. I am creating an empty Eloquent model, using a method to retrieve the first item in a collection and swapping it with the returned object to inject. This doesn't feel right either. Can anyone point me in what the best and proper way to structure the below should be?

```<code>public function cancel_subscription(Request $request)
{
    $result = false;

    // Create dependencies
    $platform_id = Sanitiser::clean_integer($request->input('platform_id'));
    $paying_user = new PayingUserModel();
    $paying_user = $paying_user->where('platform_id','=',$platform_id)->first();
    $current_subscription_model = $paying_user->non_cancelled_subscriptions->first();
    $refund_model = new RefundModel();
    $stripe = new Stripe();
    $stripe_refund = new Refund();
    $charge = new ChargeModel();
    $stripe::setAPIkey(env('STRIPE_SK'));
    $stripe_subscription = new Subscription();

    // Create services and inject
    $this->cancellation_service = new CancellationService($paying_user,$current_subscription_model,$stripe_subscription);
    $this->refund_service = new RefundService($paying_user,$current_subscription_model,$refund_model,$stripe_refund,$charge);

    // Run services
    $result = $this->cancellation_service->cancel_subscription();
    if($this->cancellation_service->get_refund_required()==true){
        $result = $this->refund_service->handle_refund();
    }
}
</code>```

答:
If I understood well, you are trying to organize your code using dependency injection. I think the easiest way to do it, is by using Laravel's automatic injection.

Looking at your code, the class where cancel_subscription() is defined, depends of CancellationService and RefundService.

At the same time CancellationService depends of PayingUserModel and Subscription. And RefundService depends of PayingUserModel, RefundModel, Refund and ChargeModel.

You can use automatic injection by type hinting the arguments in each class constructor.

E.g. the CancellationService class constructor would look something like:

```<code>class CancellationService
{
    protected $payingUserModel;

    protected $subscription;

    public function __construct(PayingUserModel $payingUserModel, Subscription $subscription)
    {
        $this->payingUserModel = $payingUserModel;

        $this->subscription = $subscription;
    }
}
</code>```

Now, for the PayingUserModel you want to pass a specific instance of the class.

This can be done by binding an instance to the container in the AppServiceProvider class.

```<code>$platform_id = request()->input('platform_id');

$user = PayingUserModel::where('platform_id', '=', $platform_id)->first();

$this->app->instance('PayingUserModel', $user);
</code>```

Alternatively you could register the PayingUserModel instance as a singleton.

```<code>$this->app->singleton('PayingUserModel', function() use($platform_id) {
    return PayingUserModel::where('platform_id', '=', $platform_id)->first();
});
</code>```

I didn't try it myself so I'm not 100% sure if this is the way to go. But according to the Laravel documentation this is how you manage dependency injection and hopefully it will give you an idea on how to proceed.

Body:
I have recently come across the SOLID design principles and have been looking to find ways to incorporate dependency injection into my work so that I can write better tests and mock out any external calls. I have had a go at some dependency injection in PHP Laravel (Lumen) but something doesn't seem right in the below.

The code to create the dependencies is being created inside a public method in one of the controllers. This doesn't seem like the appropriate place to put it as I now have a lot of quite ugly code instantiating objects inside the controller rather than just receiving the request and packaging up the response. Is there somewhere more appropriate to the do the instantiation? Also for certain items, e.g. the $paying_user object. I am creating an empty Eloquent model, using a method to retrieve the first item in a collection and swapping it with the returned object to inject. This doesn't feel right either. Can anyone point me in what the best and proper way to structure the below should be?

public function cancel_subscription(Request $request)
{
    $result = false;

    // Create dependencies
    $platform_id = Sanitiser::clean_integer($request->input('platform_id'));
    $paying_user = new PayingUserModel();
    $paying_user = $paying_user->where('platform_id','=',$platform_id)->first();
    $current_subscription_model = $paying_user->non_cancelled_subscriptions->first();
    $refund_model = new RefundModel();
    $stripe = new Stripe();
    $stripe_refund = new Refund();
    $charge = new ChargeModel();
    $stripe::setAPIkey(env('STRIPE_SK'));
    $stripe_subscription = new Subscription();

    // Create services and inject
    $this->cancellation_service = new CancellationService($paying_user,$current_subscription_model,$stripe_subscription);
    $this->refund_service = new RefundService($paying_user,$current_subscription_model,$refund_model,$stripe_refund,$charge);

    // Run services
    $result = $this->cancellation_service->cancel_subscription();
    if($this->cancellation_service->get_refund_required()==true){
        $result = $this->refund_service->handle_refund();
    }
}

Body:
If I understood well, you are trying to organize your code using dependency injection. I think the easiest way to do it, is by using Laravel's automatic injection.

Looking at your code, the class where cancel_subscription() is defined, depends of CancellationService and RefundService.

At the same time CancellationService depends of PayingUserModel and Subscription. And RefundService depends of PayingUserModel, RefundModel, Refund and ChargeModel.

You can use automatic injection by type hinting the arguments in each class constructor.

E.g. the CancellationService class constructor would look something like:

class CancellationService
{
    protected $payingUserModel;

    protected $subscription;

    public function __construct(PayingUserModel $payingUserModel, Subscription $subscription)
    {
        $this->payingUserModel = $payingUserModel;

        $this->subscription = $subscription;
    }
}

Now, for the PayingUserModel you want to pass a specific instance of the class.

This can be done by binding an instance to the container in the AppServiceProvider class.

$platform_id = request()->input('platform_id');

$user = PayingUserModel::where('platform_id', '=', $platform_id)->first();

$this->app->instance('PayingUserModel', $user);

Alternatively you could register the PayingUserModel instance as a singleton.

$this->app->singleton('PayingUserModel', function() use($platform_id) {
    return PayingUserModel::where('platform_id', '=', $platform_id)->first();
});

I didn't try it myself so I'm not 100% sure if this is the way to go. But according to the Laravel documentation this is how you manage dependency injection and hopefully it will give you an idea on how to proceed.


来源: stackexchange

问:
Sync one local repo with the remote git repository

I have a git repository with many people contributing to it. So every user having their own repository checked out locally in their workspace. I would like to maintain one more local repo as a centralized place to look for the latest code. So I would like to have an exact replica of the remote repository. By which, I mean my centralized repo should be in sync with the remote repository all the time (24/7). So I am looking for something like if someone pushes a new commit to the remote repo, my centralized repo should checkout(git pull) latest code to have the updated code all the time. Please tell me how could I achieve this
</p>

答:
For the local git repo (even you treat it as a centralized place), it can not sync  with remote git repo automatically.

There are two ways to sync local repo if there has new changes in remote repo:

Option 1: schedule to run a script to execute git pull for time to time

The script can be:

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

git fetch -p
for bran in $(git branch -r)
do
{
  if [[ $bran == *"origin/HEAD -> origin/"* ]]; then
  echo "this is not a branch"
  else
  {
    localb=$(echo $bran | cut -d'/' -f 2)
    echo "This is $localb branch"
    git checkout $localb
    git pull origin $localb
  }
  fi
}
done
</code>```

Schedule to run the script, you can refer:

schedule running a bash shell script in windows

Running .sh every 5 minutes

Option 2: use post-receive hook to update the local repo

Use post-receive hook so that when changes are pushed to remote repo, then execute the script automatically.

ContentLicense: CC BY-SA 3.0

Body:
For the local git repo (even you treat it as a centralized place), it can not sync  with remote git repo automatically.

There are two ways to sync local repo if there has new changes in remote repo:

Option 1: schedule to run a script to execute git pull for time to time

The script can be:

#!/bin/sh

git fetch -p
for bran in $(git branch -r)
do
{
  if [[ $bran == *"origin/HEAD -> origin/"* ]]; then
  echo "this is not a branch"
  else
  {
    localb=$(echo $bran | cut -d'/' -f 2)
    echo "This is $localb branch"
    git checkout $localb
    git pull origin $localb
  }
  fi
}
done

Schedule to run the script, you can refer:

schedule running a bash shell script in windows

Running .sh every 5 minutes

Option 2: use post-receive hook to update the local repo

Use post-receive hook so that when changes are pushed to remote repo, then execute the script automatically.


问:
How to eliminate if-else with same condition but different actions inside another if-else?
Suppose I have the code like following:

```<code>int age=(from user input);
int weight=(from user input);

if(age>60){
    if(weight>100){
        function1();
    }else if(weight<40){
        function2();
    }else{
        function3();
    }
}else if(age<20){
    if(weight>100){
        function4();
    }else if(weight<40){
        function5();
    }else{
        function6();
    }
}else{
    if(weight>100){
        function7();
    }else if(weight<40){
        function8();
    }else{
        function9();
    }
}
</code>```

the problem is that the code pattern:

```<code>if(weight>100){
    //do something different
}else if(weight<40){
    //do something different
}else{
    //do something different
}
</code>```

repeats as there are different ranges of age. And I can't enclose the inner if-else into a single function, because the things to do is different even through the condition is the same. Is there any way to modify this code so that the code pattern:

```<code>if(age>60){
    //do something different
}else if(age<20){
    //do something different
}else{
    //do something different
}
</code>```

and

```<code>if(weight>100){
    //do something different
}else if(weight<40){
    //do something different
}else{
    //do something different
}
</code>```

would appear once only?

答:
```<code>public class User {
    int age;
    int weight;
}

@FunctionalInterface
public interface WeightFunction {
    void perform(User user);
}

@FunctionalInterface
public interface AgeFunction {

    WeightFunction getWeightFunction(User user);
}

public class Age60Function implements AgeFunction {
    @Override
    public WeightFunction getWeightFunction(User user) {
        String desc = "Age 60 ";
        if (user.weight > 100) {
            return weightUser -> System.out.println(desc + "Age > 100");
        } else if (user.weight < 40) {
            return weightUser -> System.out.println(desc + "Age < 40");
        }
        return weightUser -> System.out.println(desc + "100 > Age > 40");
    }

}
</code>```

Then you can create outer if and create related AgeFunction and perform the function.

Also another suggestion IF WEIGHT CATEGORY ARE CONSTANT FOR ALL AGE LIMITS, as this example weight category 100+, 40- and 100>age>40 you can follow below implementation.

```<code>public interface AdvanceAgeFunction {
    WeightFunction get100PlusWeightFunction(User user);
    WeightFunction get40MinusWeightFunction(User user);
    WeightFunction getWeightFunction(User user);
}
</code>```

Body:
Suppose I have the code like following:

int age=(from user input);
int weight=(from user input);

if(age>60){
    if(weight>100){
        function1();
    }else if(weight<40){
        function2();
    }else{
        function3();
    }
}else if(age<20){
    if(weight>100){
        function4();
    }else if(weight<40){
        function5();
    }else{
        function6();
    }
}else{
    if(weight>100){
        function7();
    }else if(weight<40){
        function8();
    }else{
        function9();
    }
}

the problem is that the code pattern:

if(weight>100){
    //do something different
}else if(weight<40){
    //do something different
}else{
    //do something different
}

repeats as there are different ranges of age. And I can't enclose the inner if-else into a single function, because the things to do is different even through the condition is the same. Is there any way to modify this code so that the code pattern:

if(age>60){
    //do something different
}else if(age<20){
    //do something different
}else{
    //do something different
}

and

if(weight>100){
    //do something different
}else if(weight<40){
    //do something different
}else{
    //do something different
}

would appear once only?

Body:
public class User {
    int age;
    int weight;
}

@FunctionalInterface
public interface WeightFunction {
    void perform(User user);
}

@FunctionalInterface
public interface AgeFunction {

    WeightFunction getWeightFunction(User user);
}

public class Age60Function implements AgeFunction {
    @Override
    public WeightFunction getWeightFunction(User user) {
        String desc = "Age 60 ";
        if (user.weight > 100) {
            return weightUser -> System.out.println(desc + "Age > 100");
        } else if (user.weight < 40) {
            return weightUser -> System.out.println(desc + "Age < 40");
        }
        return weightUser -> System.out.println(desc + "100 > Age > 40");
    }

}

Then you can create outer if and create related AgeFunction and perform the function.

Also another suggestion IF WEIGHT CATEGORY ARE CONSTANT FOR ALL AGE LIMITS, as this example weight category 100+, 40- and 100>age>40 you can follow below implementation.

public interface AdvanceAgeFunction {
    WeightFunction get100PlusWeightFunction(User user);
    WeightFunction get40MinusWeightFunction(User user);
    WeightFunction getWeightFunction(User user);
}


问:
Mask tensorflow input data
I would like to apply a mask to each input feature in tensorflow. This is very easy to do if the mask is fixed - just define and apply it in the graph. The catch is, I want the mask to be varied during training - it will be slightly different for each training step. In fact, for each step, I have a function that returns a numpy array that represents the mask at every step.

After much trial and error and searching,I have found no way to apply this mask - as far as I am concerned, it is impossible to do, mandated by the properties of tensorflow to fix all the properties of the computation when the graph is built.

However, I am quite new to tensorflow so it is very possible that this is do-able, and even easy. Can anyone help me?

The pseudo-code would be:

```<code>    build graph with mask as placeholder
    Loop over training steps
        numpy_array = my_func(step_number)
        mask_placeholder = something(numpy_array)*
        Session.run([my graph(mask_placeholder)])*
</code>```

The stars are where I don't know what to do.

答:
This seems like it would be so easy with just numpy. In fact, I had a situation where I wanted to do something which to me seemed trivial in numpy yet difficult in tensorflow. Specifically, I wanted to apply a mathematical function to certain elements of a tensor based on the value of those elements. EG:

array_a[array_a > 0] = np.log(array_a + 1)[array_a > 0]

Which translates into something like “A where A is greater than zero equals the log of A plus one where A is greater than zero”.

I didn’t succeed with it in tensorflow until I discovered tf.py_func. According to the description of py_func at https://www.tensorflow.org/api_docs/python/tf/py_func,

“Given a python function func, which takes numpy arrays as its inputs and returns numpy arrays as its outputs, wrap this function as an operation in a TensorFlow graph.”

So, to apply this to your situation, you could do something like

```<code>def tf_mask(the_tensor,the_mask):
    def np_mask(a,b):
        return a[b]
    return tf.py_func(np_mask, [the_tensor,the_mask], tf.float32)
</code>```

or if you want to preserve the shape of the array, do something like

```<code>def tf_mask(the_tensor,the_mask):
    def np_mask(a,b):
        a[b == 0] = 0
        return a
    return tf.py_func(np_mask, [the_tensor,the_mask], tf.float32)
</code>```

In summary, find a way to do it in numpy, and then use py_func. Numpy is pretty powerful and it is great that we can apparently wield that power in Tensorflow.

Title: Mask tensorflow input data

Body:
I would like to apply a mask to each input feature in tensorflow. This is very easy to do if the mask is fixed - just define and apply it in the graph. The catch is, I want the mask to be varied during training - it will be slightly different for each training step. In fact, for each step, I have a function that returns a numpy array that represents the mask at every step.

After much trial and error and searching,I have found no way to apply this mask - as far as I am concerned, it is impossible to do, mandated by the properties of tensorflow to fix all the properties of the computation when the graph is built.

However, I am quite new to tensorflow so it is very possible that this is do-able, and even easy. Can anyone help me?

The pseudo-code would be:

    build graph with mask as placeholder
    Loop over training steps
        numpy_array = my_func(step_number)
        mask_placeholder = something(numpy_array)*
        Session.run([my graph(mask_placeholder)])*

The stars are where I don't know what to do.

Body:
This seems like it would be so easy with just numpy. In fact, I had a situation where I wanted to do something which to me seemed trivial in numpy yet difficult in tensorflow. Specifically, I wanted to apply a mathematical function to certain elements of a tensor based on the value of those elements. EG:

array_a[array_a > 0] = np.log(array_a + 1)[array_a > 0]

Which translates into something like “A where A is greater than zero equals the log of A plus one where A is greater than zero”.

I didn’t succeed with it in tensorflow until I discovered tf.py_func. According to the description of py_func at https://www.tensorflow.org/api_docs/python/tf/py_func,

“Given a python function func, which takes numpy arrays as its inputs and returns numpy arrays as its outputs, wrap this function as an operation in a TensorFlow graph.”

So, to apply this to your situation, you could do something like

def tf_mask(the_tensor,the_mask):
    def np_mask(a,b):
        return a[b]
    return tf.py_func(np_mask, [the_tensor,the_mask], tf.float32)

or if you want to preserve the shape of the array, do something like

def tf_mask(the_tensor,the_mask):
    def np_mask(a,b):
        a[b == 0] = 0
        return a
    return tf.py_func(np_mask, [the_tensor,the_mask], tf.float32)

In summary, find a way to do it in numpy, and then use py_func. Numpy is pretty powerful and it is great that we can apparently wield that power in Tensorflow.


问:
Elasticsearch 5.1.1 log files are not removed automatically
I am using elasticsearch 5.1.1 version. In that, the machine is out of disk space because of elasticsearch logs are occupying 10GB of data. Is there any way to maintain only some 5 days logs.</p>

答:
I don't know if you've looked at this discussion on the Elastic forum regarding someone asking for how to delete logs after a certain period.

elastic forum

One of the suggestions was to look at Curator

Curator

which may or may not do what you're after but certainly worth a read of that thread


问:
How to indent code in pycharm
Here is a python code sample.

```<code>r = request.get(...)
....
....
....
print r.text
</code>```

Now I want to write an function.

```<code>def get_response(url):
r = request.get(...)
....
....
....
print r.text
</code>```

My target is :

```<code>def get_response(url):
    r = request.get(...)
    ....
    ....
    ....
    print r.text
</code>```

Adding tab in each line is very inconvenient. Is there any short cut for this situation? My ide is PyCharm.

答: Highlight the lines you want to indent and hit tab. it'll move them all across.</p>

Title: How to indent code in pycharm

Body:
Here is a python code sample.

r = request.get(...)
....
....
....
print r.text

Now I want to write an function.

def get_response(url):
r = request.get(...)
....
....
....
print r.text

My target is :

def get_response(url):
    r = request.get(...)
    ....
    ....
    ....
    print r.text

Adding tab in each line is very inconvenient. Is there any short cut for this situation? My ide is PyCharm.


问:
Where is a value type object stored in swift?
I declared an object of Array, like:

```<code>let data = ["foo", "bar"]
</code>```

Array type in swift is value type, where is it stored? heap or stack?

I guess it is stored in heap, but how to access it?

And does it follow ARC rule, when will it release?

Can you give me the graphic of the object's memory?

答:
Given the empty array:

```<code>let data = Array<Any>()
</code>```

Array type in swift is value type, where is it stored? heap or stack?

This is a constant, empty array, so it is stored nowhere. Literally nowhere. If it had some elements in it, the boxes for them would be stored on the stack. The contents of those boxes might be stored on the stack or heap depending on the size. If it had more elements, the boxes would also be stored on the heap.

And does it follow ARC rule, when will it release?

Value types are destroyed when their referent goes out of scope, so whenever data leaves scope. ARC is not relevant here. That said, if there are other reference of the backing (heap) storage, then that storage may not be destroyed until later and ARC is totally relevant (but completely internal, so not related to data).

Can you give me the graphic of the object's memory?

In the case given, the graphic of object memory is:

That's it. There is no memory. But if you put things in it, then it would wildly depend on what you put it in it.

I know I'm being incredibly flippant here. That's on purpose. The answer is "it depends, and also, in most cases, you shouldn't care, and in all cases, it's an internal implementation detail that is not promised and can change from release to release."

The time where you do care is when there's a performance concern, and then you care a lot. Unfortunately, Swift gives almost no promises about that. Even so, we do have a lot of specific information from the Swift team. The best resource is Understanding Swift Performance from WWDC 2016 which explains the internal memory layout. It is likely nothing like you're expecting, and it is incredibly dependent on the specifics of the array. Given the array you've asked about, the answer is "nowhere; it's empty."

Body:
I declared an object of Array, like:

let data = ["foo", "bar"]

Array type in swift is value type, where is it stored? heap or stack?

I guess it is stored in heap, but how to access it?

And does it follow ARC rule, when will it release?

Can you give me the graphic of the object's memory?

Body:
Given the empty array:

let data = Array<Any>()

Array type in swift is value type, where is it stored? heap or stack?

This is a constant, empty array, so it is stored nowhere. Literally nowhere. If it had some elements in it, the boxes for them would be stored on the stack. The contents of those boxes might be stored on the stack or heap depending on the size. If it had more elements, the boxes would also be stored on the heap.

And does it follow ARC rule, when will it release?

Value types are destroyed when their referent goes out of scope, so whenever data leaves scope. ARC is not relevant here. That said, if there are other reference of the backing (heap) storage, then that storage may not be destroyed until later and ARC is totally relevant (but completely internal, so not related to data).

Can you give me the graphic of the object's memory?

In the case given, the graphic of object memory is:

That's it. There is no memory. But if you put things in it, then it would wildly depend on what you put it in it.

I know I'm being incredibly flippant here. That's on purpose. The answer is "it depends, and also, in most cases, you shouldn't care, and in all cases, it's an internal implementation detail that is not promised and can change from release to release."

The time where you do care is when there's a performance concern, and then you care a lot. Unfortunately, Swift gives almost no promises about that. Even so, we do have a lot of specific information from the Swift team. The best resource is Understanding Swift Performance from WWDC 2016 which explains the internal memory layout. It is likely nothing like you're expecting, and it is incredibly dependent on the specifics of the array. Given the array you've asked about, the answer is "nowhere; it's empty."


问:
How to link data records in pandas?
I have a csv file which I can read into a pandas data frame. The data is like:

+--------+---------+------+----------------+
|  Name  | Address |  ID  |   Linked_To    |
+--------+---------+------+----------------+
| Name 1 | ABC     | 1233 | 1234;1235      |
| Name 2 | DEF     | 1234 | 1233;1236;1237 |
| Name 3 | GHI     | 1235 | 1234;1233;2589 |
+--------+---------+------+----------------+
```

How do I run analysis on the linkage between ID and the Linked_To columns. For example, should I be turning the Linked_To values into a list and doing a VLOOKUP type analysis on the ID column? I know there must be an obvious way to do this but I am stumped.

Ideally the end result should be a list or dictionary which has the entire attributes of the row, including all of the other records its linked to.

OR is this a problem where I should be transforming the data into an SQL database?

Title: How to link data records in pandas?

Body:
I have a csv file which I can read into a pandas data frame. The data is like:

+--------+---------+------+----------------+
|  Name  | Address |  ID  |   Linked_To    |
+--------+---------+------+----------------+
| Name 1 | ABC     | 1233 | 1234;1235      |
| Name 2 | DEF     | 1234 | 1233;1236;1237 |
| Name 3 | GHI     | 1235 | 1234;1233;2589 |
+--------+---------+------+----------------+

How do I run analysis on the linkage between ID and the Linked_To columns. For example, should I be turning the Linked_To values into a list and doing a VLOOKUP type analysis on the ID column? I know there must be an obvious way to do this but I am stumped.

Ideally the end result should be a list or dictionary which has the entire attributes of the row, including all of the other records its linked to.

OR is this a problem where I should be transforming the data into an SQL database?

Body:
If you working with pandas dataframe , try this

df.set_index('ID').Linked_To.str.split(';').to_dict()
Out[142]:
{1233: ['1234', '1235'],
 1234: ['1233', '1236', '1237'],
 1235: ['1234', '1233', '2589']}


问:
Aggregation on an array of structs in a map inside a Spark dataframe
I apologize for the verbose title, but I really couldn't come up with something better.

Basically, I have data with the following schema:

```<code> |-- id: string (nullable = true)
 |-- mainkey: map (nullable = true)
 |    |-- key: string
 |    |-- value: array (valueContainsNull = true)
 |    |    |-- element: struct (containsNull = true)
 |    |    |    |-- price: double (nullable = true)
 |    |    |    |-- recordtype: string (nullable = true)
</code>```

Let me use the following example data:

```<code>{"id":1, "mainkey":{"key1":[{"price":0.01,"recordtype":"BID"}],"key2":[{"price":4.3,"recordtype":"FIXED"}],"key3":[{"price":2.0,"recordtype":"BID"}]}}
{"id":2, "mainkey":{"key4":[{"price":2.50,"recordtype":"BID"}],"key5":[{"price":2.4,"recordtype":"BID"}],"key6":[{"price":0.19,"recordtype":"BID"}]}}
</code>```

For each of the two records above, I want to calculate mean of all prices when the recordtype is "BID". So, for the first record (with "id":1), we have 2 such bids, with prices 0.01 and 2.0, so the mean rounded to 2 decimal places is 1.01. For the second record (with "id":2), there are 3 bids, with prices 2.5, 2.4 and 0.19, and the mean is 1.70. So I want the following output:

```<code>+---+---------+
| id|meanvalue|
+---+---------+
|  1|     1.01|
|  2|      1.7|
+---+---------+
</code>```

The following code does it:

```<code>val exSchema = (new StructType().add("id", StringType).add("mainkey", MapType(StringType, new ArrayType(new StructType().add("price", DoubleType).add("recordtype", StringType), true))))
val exJsonDf = spark.read.schema(exSchema).json("file:///data/json_example")
var explodeExJson = exJsonDf.select($"id",explode($"mainkey")).explode($"value") {
    case Row(recordValue: Seq[Row] @unchecked ) => recordValue.map{ recordValue =>
    val price = recordValue(0).asInstanceOf[Double]
    val recordtype = recordValue(1).asInstanceOf[String]
    RecordValue(price, recordtype)
    }
    }.cache()

val filteredExJson = explodeExJson.filter($"recordtype"==="BID")

val aggExJson = filteredExJson.groupBy("id").agg(round(mean("price"),2).alias("meanvalue"))
</code>```

The problem is that it uses an "expensive" explode operation and it becomes a problem when I am dealing with lots of data, especially when there can be a lot of keys in the map.

Please let me know if you can think of a simpler solution, using UDFs or otherwise. Please also keep in mind that I am a beginner to Spark, and hence may have missed some stuff that would be obvious to you.

Any help would be really appreciated. Thanks in advance!

答:
If aggregation is limited to a single Row udf will solve this:

```<code>import org.apache.spark.util.StatCounter
import org.apache.spark.sql.functions.udf
import org.apache.spark.sql.Row

val meanPrice =  udf((map: Map[String, Seq[Row]]) => {
  val prices = map.values
    .flatMap(x => x)
    .filter(_.getAs[String]("recordtype") == "BID")
    .map(_.getAs[Double]("price"))
  StatCounter(prices).mean
})

df.select($"id", meanPrice($"mainkey"))
</code>```

Body:
I apologize for the verbose title, but I really couldn't come up with something better.

Basically, I have data with the following schema:

 |-- id: string (nullable = true)
 |-- mainkey: map (nullable = true)
 |    |-- key: string
 |    |-- value: array (valueContainsNull = true)
 |    |    |-- element: struct (containsNull = true)
 |    |    |    |-- price: double (nullable = true)
 |    |    |    |-- recordtype: string (nullable = true)

Let me use the following example data:

{"id":1, "mainkey":{"key1":[{"price":0.01,"recordtype":"BID"}],"key2":[{"price":4.3,"recordtype":"FIXED"}],"key3":[{"price":2.0,"recordtype":"BID"}]}}
{"id":2, "mainkey":{"key4":[{"price":2.50,"recordtype":"BID"}],"key5":[{"price":2.4,"recordtype":"BID"}],"key6":[{"price":0.19,"recordtype":"BID"}]}}

For each of the two records above, I want to calculate mean of all prices when the recordtype is "BID". So, for the first record (with "id":1), we have 2 such bids, with prices 0.01 and 2.0, so the mean rounded to 2 decimal places is 1.01. For the second record (with "id":2), there are 3 bids, with prices 2.5, 2.4 and 0.19, and the mean is 1.70. So I want the following output:

+---+---------+
| id|meanvalue|
+---+---------+
|  1|     1.01|
|  2|      1.7|
+---+---------+

The following code does it:

val exSchema = (new StructType().add("id", StringType).add("mainkey", MapType(StringType, new ArrayType(new StructType().add("price", DoubleType).add("recordtype", StringType), true))))
val exJsonDf = spark.read.schema(exSchema).json("file:///data/json_example")
var explodeExJson = exJsonDf.select($"id",explode($"mainkey")).explode($"value") {
    case Row(recordValue: Seq[Row] @unchecked ) => recordValue.map{ recordValue =>
    val price = recordValue(0).asInstanceOf[Double]
    val recordtype = recordValue(1).asInstanceOf[String]
    RecordValue(price, recordtype)
    }
    }.cache()

val filteredExJson = explodeExJson.filter($"recordtype"==="BID")

val aggExJson = filteredExJson.groupBy("id").agg(round(mean("price"),2).alias("meanvalue"))

The problem is that it uses an "expensive" explode operation and it becomes a problem when I am dealing with lots of data, especially when there can be a lot of keys in the map.

Please let me know if you can think of a simpler solution, using UDFs or otherwise. Please also keep in mind that I am a beginner to Spark, and hence may have missed some stuff that would be obvious to you.

Any help would be really appreciated. Thanks in advance!

Body:
If aggregation is limited to a single Row udf will solve this:

import org.apache.spark.util.StatCounter
import org.apache.spark.sql.functions.udf
import org.apache.spark.sql.Row

val meanPrice =  udf((map: Map[String, Seq[Row]]) => {
  val prices = map.values
    .flatMap(x => x)
    .filter(_.getAs[String]("recordtype") == "BID")
    .map(_.getAs[Double]("price"))
  StatCounter(prices).mean
})

df.select($"id", meanPrice($"mainkey"))


问:
What is the difference between these two ways of mapping functions in scala?
Here in the Scala Koans for Lazy Sequences they have:

```<code>var x = 0
def inc = {x += 1; x}

val strictList = List(inc _, inc _, inc _)
strictList.map(f => f).head should be(_)
</code>```

This last line

```<code>strictList.map(f => f).head
</code>```

returns a function.

Now this last line compiles - but to achieve the goal they want in the koan you have to modify it to:

```<code>strictList.map(f => f()).head should be(1)
</code>```

(ie you add the parens after the second reference to f. )

What would cause that difference? (Assuming it is not a mistake). Has the Scala language changed?

My question is: What is the difference between these two ways of mapping functions in scala?

答:
strictList is a list of anonymous functions. In the first case:

```<code>strictList.map(f => f).head
</code>```

you're just mapping over the list and returning the function.  In the second case:

```<code>strictList.map(f => f()).head
</code>```

you're actually invoking each anonymous function and building up a list of the results of calling each function.

There seems to be a mistake in the file you link to.  Line 19:

```<code>strictList.map(f => f).head should be(3)
</code>```

is incorrect.  The value should be an anonymous function, not 3.

Body:
Here in the Scala Koans for Lazy Sequences they have:

var x = 0
def inc = {x += 1; x}

val strictList = List(inc _, inc _, inc _)
strictList.map(f => f).head should be(_)

This last line

strictList.map(f => f).head

returns a function.

Now this last line compiles - but to achieve the goal they want in the koan you have to modify it to:

strictList.map(f => f()).head should be(1)

(ie you add the parens after the second reference to f. )

What would cause that difference? (Assuming it is not a mistake). Has the Scala language changed?

My question is: What is the difference between these two ways of mapping functions in scala?

Body:
strictList is a list of anonymous functions. In the first case:

strictList.map(f => f).head

you're just mapping over the list and returning the function.  In the second case:

strictList.map(f => f()).head

you're actually invoking each anonymous function and building up a list of the results of calling each function.

There seems to be a mistake in the file you link to.  Line 19:

strictList.map(f => f).head should be(3)

is incorrect.  The value should be an anonymous function, not 3.


问:
Finding the value and index of the first occurence of the largest element in an array
I'm looking for a way to find the value and index of the first occurrence of the largest element in an array (in ruby). I have not been able to find a way to achieve this with fewer than 2 lines of code and without traversing the array more than I would like.

First I tried:

```<code>example = [1, 100, 2, 100, 3]
value, index = example.each_with_index.max
</code>```

But this gives me the index of the last occurrence of the largest element.

My current approach is:

```<code>example = [1, 100, 2, 100, 3]
value = example.max
index = example.find_index(value)
</code>```

Which works, but if the first and last occurrences of the largest element are the last two elements of the array, my current code has to traverse pretty much the entire array twice.

I'm more interested in performance than code size, but if there is a non-wasteful one-line solution that would be great!

答:
Here is a one-pass solution, but I would be surprised if it were faster than the OP’s two-pass solution, considering that Array#max and Array#find_index are both implemented in C and are optimized for arrays (as opposed to their Enumerable counterparts).

```<code> value, index = example.each_with_index.max_by { |n,i| [n,-i] }
  #=> [100, 1]
</code>```

When you tried example.each_with_index.max, you first computed

```<code>enum = example.each_with_index
  #=> #<Enumerator: [1, 100, 2, 100, 3]:each_with_index>
</code>```

We can convert this enumerator to an array to see what elements it will generate.

```<code>enum.to_a
  #=> [[1, 0], [100, 1], [2, 2], [100, 3], [3, 4]]
</code>```

When Array#max is sent to enum it orders the elements generated by enum, largest to smallest, as follows.

```<code>[[100, 3], [100, 1], [3, 4], [2, 2], [1, 0]]
</code>```

The reason for this ordering is explained in the third paragraph in the doc for Array#<=>.

That's why you obtained

```<code>enum.max
  #=> [100, 3]
</code>```

By contrast, I have Enumerable#max_by searching for the largest value in

```<code>a = [[1, 0], [100, -1], [2, -2], [100, -3], [3, -4]]
</code>```

which is

```<code>a.max
  #=> [100, -1]
</code>```

so [100, 1] is returned.

Body:
I'm looking for a way to find the value and index of the first occurrence of the largest element in an array (in ruby). I have not been able to find a way to achieve this with fewer than 2 lines of code and without traversing the array more than I would like.

First I tried:

example = [1, 100, 2, 100, 3]
value, index = example.each_with_index.max

But this gives me the index of the last occurrence of the largest element.

My current approach is:

example = [1, 100, 2, 100, 3]
value = example.max
index = example.find_index(value)

Which works, but if the first and last occurrences of the largest element are the last two elements of the array, my current code has to traverse pretty much the entire array twice.

I'm more interested in performance than code size, but if there is a non-wasteful one-line solution that would be great!

Body:
Here is a one-pass solution, but I would be surprised if it were faster than the OP’s two-pass solution, considering that Array#max and Array#find_index are both implemented in C and are optimized for arrays (as opposed to their Enumerable counterparts).

 value, index = example.each_with_index.max_by { |n,i| [n,-i] }
  #=> [100, 1]

When you tried example.each_with_index.max, you first computed

enum = example.each_with_index
  #=> #<Enumerator: [1, 100, 2, 100, 3]:each_with_index>

We can convert this enumerator to an array to see what elements it will generate.

enum.to_a
  #=> [[1, 0], [100, 1], [2, 2], [100, 3], [3, 4]]

When Array#max is sent to enum it orders the elements generated by enum, largest to smallest, as follows.

[[100, 3], [100, 1], [3, 4], [2, 2], [1, 0]]

The reason for this ordering is explained in the third paragraph in the doc for Array#<=>.

That's why you obtained

enum.max
  #=> [100, 3]

By contrast, I have Enumerable#max_by searching for the largest value in

a = [[1, 0], [100, -1], [2, -2], [100, -3], [3, -4]]

which is

a.max
  #=> [100, -1]

so [100, 1] is returned.


问:
TypeError: 'question_text' is an invalid keyword argument for this function in django 2.0 tutorial
I am fairly new to django and I am trying to follow the tutorial ( https://docs.djangoproject.com/en/2.0/intro/tutorial02/ ) but have encountered the above error.

Here is my code for the models.py

```<code>import datetime

from django.db import models
from django.utils import timezone

# Create your models here.

class Question(models.Model):
    question_text = models.CharField(max_length=200),
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE),
    choice_text = models.CharField(max_length=200),
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text
</code>```

Also the question text and choice text is not appearing on the django-admin page

答: In django, modelname_somefieldname is a system operator syntax, so the reason of your error is the question_text keyword contains question_. The question is a model name.

ContentLicense: CC BY-SA 4.0

Body:
I am fairly new to django and I am trying to follow the tutorial ( https://docs.djangoproject.com/en/2.0/intro/tutorial02/ ) but have encountered the above error.

Here is my code for the models.py

import datetime

from django.db import models
from django.utils import timezone

# Create your models here.

class Question(models.Model):
    question_text = models.CharField(max_length=200),
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE),
    choice_text = models.CharField(max_length=200),
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

Also the question text and choice text is not appearing on the django-admin page


问:
Generate multiple sheets in one pdf file
I am trying to generate a pdf from a Tableau workbook which has two sheets using the url method:
E.g: https://TableauServer/views/workbook/sheet1?:format=pdf&parameter=value

I am doing this in a program which will issue the url request to the url. The url works fine for one sheet. But the problem is how to generate one pdf file with both sheets in it?

答:
We know it's possible because within the Tableau pages itself if you download a PDF it gives you several formatting options, including the option to put all the worksheets in a workbook into a single PDF.

I couldn't find any documentation on it though. What I ended up doing was looking at the network console in the browser (usually F12) when I downloaded the PDF from the browser by clicking the Download button. That showed me the URL end point and the JSON body the server expected in the request payload.

The endpoint URL wasn't too cryptic and ended with "commands/tabsrv/pdf-export-server". The challenge was to take the JSON in the request payload and find the right settings to get it into a single PDF.

This method is a more technical approach and requires very little coding skills; any language that has functions for http calls will work (I use python for it).

If you don't mind doing it outside a browser, tabcmd has lots of functionality to control PDF generation at the command line.


问:
Make Sum in Json Array With JOLT
I am Trying to make a sum in Json Array with Jolt but i did not succeess.

This is my json :

```<code>[
  {
"times-entries": {
  "offset": 0,
  "time_entries": [
    {
      "hours": 1
    },
    {
      "hours": 2
    }
  ]
}}]
</code>```

This is what I expect :

{"sum_hours" : 3}

So do you know how I can do this ?

答:
Spec</p>

```<code>[
  {
    "operation": "shift",
    "spec": {
      "0": {
        "times-entries": {
          "time_entries": {
            "*": {
              // match down to hours, write the value to the
              //  output as an array
              "hours": "hoursAccumulator[]"
            }
          }
        }
      }
    }
  },
  {
    "operation": "modify-overwrite-beta",
    "spec": {
      "sum_hours": "=intSum(@(1,hoursAccumulator))"
    }
  }
]
</code>```

Title: Make Sum in Json Array With JOLT

Body:
I am Trying to make a sum in Json Array with Jolt but i did not succeess.

This is my json :

[
  {
"times-entries": {
  "offset": 0,
  "time_entries": [
    {
      "hours": 1
    },
    {
      "hours": 2
    }
  ]
}}]

This is what I expect :

{"sum_hours" : 3}

So do you know how I can do this ?

Body:
Spec

[
  {
    "operation": "shift",
    "spec": {
      "0": {
        "times-entries": {
          "time_entries": {
            "*": {
              // match down to hours, write the value to the
              //  output as an array
              "hours": "hoursAccumulator[]"
            }
          }
        }
      }
    }
  },
  {
    "operation": "modify-overwrite-beta",
    "spec": {
      "sum_hours": "=intSum(@(1,hoursAccumulator))"
    }
  }
]


问:
easy to use Date time picker
I'm looking for an easy to use date time picker. I tried to use bootstrap date time picker and I'm using bootstrap 4 alpha. It does not work for me.

Here is my code:

```<code>    <script>
    $(function() {
        $('#datetimepicker1').datetimepicker();
    });
    </script>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
   <!-- Moment JS -->
    <script type="text/javascript" src="<?php echo $ROOT; ?>js/moment.min.js"></script>
    <!--Bootstrap JS -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" ></script>
    <!-- dateTimePicker JS -->
    <script type="text/javascript" src="<?php echo $ROOT; ?>js/bootstrap-datetimepicker.min.js"></script>
    <!--bootstrap  -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">
    <!-- dateTimePicker CSS -->
    <link rel="stylesheet" type="text/css" href="<?php echo $ROOT; ?>css/bootstrap-datetimepicker.min.css">

    <div class = "form-group col col-md-4 col-sm-4 col-12">
        <div class='input-group date' id='datetimepicker1'>
          <input type='text' class="form-control" id="servDate"/>
          <span class="input-group-addon">
            <span class="glyphicon glyphicon-calendar"></span>
          </span>
        </div>
    </div>
</code>```

答:
Try to use Bootstrap 3.
Found some helpful link: https://eonasdan.github.io/bootstrap-datetimepicker/
Hope this helps.</p>

Title: easy to use Date time picker

Body:
I'm looking for an easy to use date time picker. I tried to use bootstrap date time picker and I'm using bootstrap 4 alpha. It does not work for me.

Here is my code:

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">

    <link rel="stylesheet" type="text/css" href="<?php echo $ROOT; ?>css/bootstrap-datetimepicker.min.css">

          <input type='text' class="form-control" id="servDate"/>


问:
identify lines in a file in php
I have a file, which contains passwords/usernames:

thomas 123

john 321

What would be the best way to identify lines and add to them contact information? Right in password file I dont want store, because the size of the file matters.. I thought to add an identifier string before records, like this:

[1]

thomas 123

[2]

john 321

What do you think? It is a good way to identify lines? If yes, how I can read out line after identifier [number]?

If I can read out, then in a second file I can store contact information.

[1]

email, etc

[2]

email etc

this is a config file of an offline app, sadly I cant change the structure of that file (max. change: add an identifier before lines) or use database.

Thank you so much,

Adrian

答: Supposedly the usernames in the password file are unique (otherwise it wouldn't be very useful). Assuming that's the case, why can't you leave its structure as is without adding anything to it? Then your contact file could be formatted as an INI file or JSON file as bummzack suggested with the username as the key.</p>

ContentLicense: CC BY-SA 2.5

Title: identify lines in a file in php


问:
React redirect using react-router-dom not working
I want to redirect to home page after ajax response I used Redirect but not working

```<code>$.ajax({
    method: 'post',
    data: {req: data2},
    url: baseUrl+'sentOtp',
    success: function(response){
        console.log(response);
        if (response.status === "success") {
            return <Redirect to="/" />;
        }
    }
});
</code>```

Route.js

```<code>ReactDOM.render(
 <Router>
  <Switch>
    <Route exact path="/" component={App} />
    <Route path="/pdeals/:BrandName/all/:Type" component={BrowseFeedDeals} />
    <Route path="/login" component={Register} />
  </Switch>
</Router>, document.getElementById('root'));
registerServiceWorker();
</code>```

I used react-router-dom with updated version.but it doesn't redirect me to the home page and no errors in console

答:
You should use history.push. See my example below:

index.js

```<code>    import React, { Component } from 'react'
    import { render } from 'react-dom'
    import { Router, Route, BrowserHistory as hashHistory, Switch } from 'react-router-dom'
    import './style.css'
    import history from './history.js'

    import Home from './routes/home.js'

    class App extends Component {
      constructor() {
        super()
        this.state = {
        }
      }

      render() {
        return (
          <Router history={history}>
            <Switch>
              <Route exact path='/' component={Home}/>
            </Switch>
          </Router>
        )
      }
    }

render(<App />, document.getElementById('root'));
</code>```

history.js

```<code>import createHistory from 'history/createBrowserHistory'
export default createHistory()
</code>```

Component

```<code>import React from 'react'
import styled from 'styled-components'
import history from '../../history.js'

export default class NavBar extends React.Component {

  linkClick() {
    history.push('/')
  }

  render() {
    return <div onClick={this.linkClick}>
    </div>
  }
}
</code>```

Body:
I want to redirect to home page after ajax response I used Redirect but not working

$.ajax({
    method: 'post',
    data: {req: data2},
    url: baseUrl+'sentOtp',
    success: function(response){
        console.log(response);
        if (response.status === "success") {
            return <Redirect to="/" />;
        }
    }
});

Route.js

ReactDOM.render(
 <Router>
  <Switch>
    <Route exact path="/" component={App} />
    <Route path="/pdeals/:BrandName/all/:Type" component={BrowseFeedDeals} />
    <Route path="/login" component={Register} />
  </Switch>
</Router>, document.getElementById('root'));
registerServiceWorker();

I used react-router-dom with updated version.but it doesn't redirect me to the home page and no errors in console

Body:
You should use history.push. See my example below:

index.js

    import React, { Component } from 'react'
    import { render } from 'react-dom'
    import { Router, Route, BrowserHistory as hashHistory, Switch } from 'react-router-dom'
    import './style.css'
    import history from './history.js'

    import Home from './routes/home.js'

    class App extends Component {
      constructor() {
        super()
        this.state = {
        }
      }

      render() {
        return (
          <Router history={history}>
            <Switch>
              <Route exact path='/' component={Home}/>
            </Switch>
          </Router>
        )
      }
    }

render(<App />, document.getElementById('root'));

history.js

import createHistory from 'history/createBrowserHistory'
export default createHistory()

Component

import React from 'react'
import styled from 'styled-components'
import history from '../../history.js'

export default class NavBar extends React.Component {

  linkClick() {
    history.push('/')
  }

  render() {
    return <div onClick={this.linkClick}>
    </div>
  }
}


问:
Select a range of column base on value of another column in pandas
My dataset looks like this(first row is header)

```<code>0    1    2    3    4    5
1    3    4    6    2    3
3    8    9    3    2    4
2    2    3    2    1    2
</code>```

I want to select a range of columns of the dataset based on the column [5], e.g:

```<code>1    3    4
3    8    9    3
2    2
</code>```

I have tried the following, but it did not work:

```<code>df.iloc[:,0:df['5'].values]
</code>```

Body:
My dataset looks like this(first row is header)

0    1    2    3    4    5
1    3    4    6    2    3
3    8    9    3    2    4
2    2    3    2    1    2

I want to select a range of columns of the dataset based on the column [5], e.g:

1    3    4
3    8    9    3
2    2

I have tried the following, but it did not work:

df.iloc[:,0:df['5'].values]

Body:
Let's try:

df.apply(lambda x: x[:x.iloc[5]], 1)

Output:

     0    1    2    3
0  1.0  3.0  4.0  NaN
1  3.0  8.0  9.0  3.0
2  2.0  2.0  NaN  NaN


问:
Tone is not playing on Arduino Uno

I am trying to make a bot that follows a line with IR sensors and I also have a IR sensor to prevent collisions. In the if statement that stops movement, I also have it play a tone, but the problem is the tone doesn't play. I know that the if statement is being executed as the servos do stop as intended and resume after the object is removed. Also the speaker setup is confirmed working as other code with tones are working fine. I did hear it beep a few times when I was troubleshooting which is strange.

Here is the statement with the issue;

```<code>    if (irDetect == 0)   // Object detected
    {
      servoLeft.writeMicroseconds(1500);  // Stop left servo
      servoRight.writeMicroseconds(1500);  // Stop right servo
      tone(5, 4000, 100);
      delay(100);
    }
</code>```

I cannot figure out the problem so any help is appreciated.

答: Tone and the ir library you are using are both using timer2.  So you have a timer conflict.  Both can't simultaneously have control over timer2.  You'll either need to find a new library for one function or the other or modify one to use a different timer.  </p>

Title: Tone is not playing on Arduino Uno

Body:
I am trying to make a bot that follows a line with IR sensors and I also have a IR sensor to prevent collisions. In the if statement that stops movement, I also have it play a tone, but the problem is the tone doesn't play. I know that the if statement is being executed as the servos do stop as intended and resume after the object is removed. Also the speaker setup is confirmed working as other code with tones are working fine. I did hear it beep a few times when I was troubleshooting which is strange.

Here is the statement with the issue;

    if (irDetect == 0)   // Object detected
    {
      servoLeft.writeMicroseconds(1500);  // Stop left servo
      servoRight.writeMicroseconds(1500);  // Stop right servo
      tone(5, 4000, 100);
      delay(100);
    }

I cannot figure out the problem so any help is appreciated.


问:
Xamarin Forms Error Handling - Message Center Alert not displaying from Data Store

I was reading this post on messaging center. I wanted to use this method to display errors when I encounter them in my Data Store classes (please let me know if this is not kosher). However, it is not working.

Login Page.xaml.cs

```<code>public partial class LoginPage : ContentPage
{
    public LoginPage()
    {
        InitializeComponent();

        MessagingCenter.Subscribe<LoginDataStore, MessagingCenterAlert>(this, "message", (sender, arg) =>
        {
            Device.BeginInvokeOnMainThread(() =>
            {
                DisplayAlert("UH OH!", arg.Message, "OK");
            });
        });
    }
}
</code>```

LoginDataStore.cs

```<code>public class LoginDataStore
{
    HttpClient client;

    public LoginDataStore()
    {
        client = new HttpClient();
        client.BaseAddress = new Uri($"{App.BackendUrl}/");
    }

    public async void Login(string username, string password)
    {
        var content = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("grant_type", "password"),
            new KeyValuePair<string, string>("email", username),
            new KeyValuePair<string, string>("password", password)
        });

        try
        {
            var result = await client.PostAsync("/oauth/token", content);

            string resultContent = await result.Content.ReadAsStringAsync();

            if (!result.IsSuccessStatusCode)
                throw new Exception(result.StatusCode.ToString() + System.Environment.NewLine + "Please check your email and password.");

            dynamic resultObject = JsonConvert.DeserializeObject(resultContent);

            Settings.AuthToken = (string)resultObject["access_token"].Value;

            Settings.UserId = username;
        }
        catch (Exception e)
        {
            // remove later when the messaging center works
            await Application.Current.MainPage.DisplayAlert("Login Failed!", e.Message, "OK");

            MessagingCenter.Send(new MessagingCenterAlert
            {
                Title = "Login Failed",
                Message = e.Message,
                Cancel = "OK"
            }, e.Message);

            return;
        }
    }
}
</code>```

When I run the code, with breakpoints, I can see that the Message is getting created and the Login Page is subscribed, but the code inside the subscription never gets called and no message appears. The brute force code of direct calling the page works, but it's not exactly elegant.

答:
Your subscriber is not listening for the same message key that the sender is sending.  They need to match, like this:

```<code>MessagingCenter.Subscribe<LoginDataStore, MessagingCenterAlert> (this, "LoginFailureMessage", (sender, args) => {
    // do something whenever the "LoginFailureMessage" message is sent
});

MessagingCenter.Send<LoginDataStore, MessagingCenterAlert> (this, "LoginFailureMessage", new MessagingCenterAlert
        {
            Title = "Login Failed",
            Message = e.Message,
            Cancel = "OK"
        });
</code>```

Body:
I was reading this post on messaging center. I wanted to use this method to display errors when I encounter them in my Data Store classes (please let me know if this is not kosher). However, it is not working.

Login Page.xaml.cs

public partial class LoginPage : ContentPage
{
    public LoginPage()
    {
        InitializeComponent();

        MessagingCenter.Subscribe<LoginDataStore, MessagingCenterAlert>(this, "message", (sender, arg) =>
        {
            Device.BeginInvokeOnMainThread(() =>
            {
                DisplayAlert("UH OH!", arg.Message, "OK");
            });
        });
    }
}

LoginDataStore.cs

public class LoginDataStore
{
    HttpClient client;

    public LoginDataStore()
    {
        client = new HttpClient();
        client.BaseAddress = new Uri($"{App.BackendUrl}/");
    }

    public async void Login(string username, string password)
    {
        var content = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("grant_type", "password"),
            new KeyValuePair<string, string>("email", username),
            new KeyValuePair<string, string>("password", password)
        });

        try
        {
            var result = await client.PostAsync("/oauth/token", content);

            string resultContent = await result.Content.ReadAsStringAsync();

            if (!result.IsSuccessStatusCode)
                throw new Exception(result.StatusCode.ToString() + System.Environment.NewLine + "Please check your email and password.");

            dynamic resultObject = JsonConvert.DeserializeObject(resultContent);

            Settings.AuthToken = (string)resultObject["access_token"].Value;

            Settings.UserId = username;
        }
        catch (Exception e)
        {
            // remove later when the messaging center works
            await Application.Current.MainPage.DisplayAlert("Login Failed!", e.Message, "OK");

            MessagingCenter.Send(new MessagingCenterAlert
            {
                Title = "Login Failed",
                Message = e.Message,
                Cancel = "OK"
            }, e.Message);

            return;
        }
    }
}

When I run the code, with breakpoints, I can see that the Message is getting created and the Login Page is subscribed, but the code inside the subscription never gets called and no message appears. The brute force code of direct calling the page works, but it's not exactly elegant.

Body:
Your subscriber is not listening for the same message key that the sender is sending.  They need to match, like this:

MessagingCenter.Subscribe<LoginDataStore, MessagingCenterAlert> (this, "LoginFailureMessage", (sender, args) => {
    // do something whenever the "LoginFailureMessage" message is sent
});

MessagingCenter.Send<LoginDataStore, MessagingCenterAlert> (this, "LoginFailureMessage", new MessagingCenterAlert
        {
            Title = "Login Failed",
            Message = e.Message,
            Cancel = "OK"
        });


问:
How can I sort dataframe with str+number
I got a dataframe now and try to sort it by 'No.'
dataframe is like:

```<code>         No.              value1                  value2
 0     NODE11              1654                     14
 1     NODE10              1710                    817
 2      NODE9              1162                     23
 3      NODE8              1883                    198
 4   no match              2303                      0
 5      NODE1              1098                     67
 6      NODE3              1488                     78
 7      NODE2              2426                     49
 8      NODE5              1974                     90
 9      NODE4              1767                     11
 10     NODE7              1708                     26
 11     NODE6              2418                    248
</code>```

I tried:

```<code>df.to_csv('count.csv',index = False)
df = pd.read_csv('count.csv', thousands=',', parse_dates=['No.'])
df = df.sort_values(by=['No.', 'only can on this node'], ascending=[True, False])
df.to_csv('count.csv',index = False)
</code>```

Its work but:

```<code>         No.              value1                 value2
 5      NODE1              1098                     67
 1     NODE10              1710                    817  -------error
 0     NODE11              1654                     14   -------error
 7      NODE2              2426                     49
 6      NODE3              1488                     78
 9      NODE4              1767                     11
 8      NODE5              1974                     90
 11     NODE6              2418                    248
 10     NODE7              1708                     26
 3      NODE8              1883                    198
 2      NODE9              1162                     23
 4   no match              2303                      0
</code>```

I dont know how to sort this dataframe because this sort key is str+number. any ideas? Thanks!

答:
Your column is a string and is sorted as such.

However, you can parse the No. column to a new data frame with a column of strings and a columns of integers, sort that data frame, and use the sorted index to rearrange your original data frame.

```<code>df2 = df['No.'].str.extractall('([A-Za-z ]+)(\d+)?').reset_index(drop=True)
df2[1] = df2[1].astype(float)
df.loc[df2.sort_values([0,1]).index]

# returns:
         No.  value1  value2
5      NODE1    1098      67
7      NODE2    2426      49
6      NODE3    1488      78
9      NODE4    1767      11
8      NODE5    1974      90
11     NODE6    2418     248
10     NODE7    1708      26
3      NODE8    1883     198
2      NODE9    1162      23
1     NODE10    1710     817
0     NODE11    1654      14
4   no match    2303       0
</code>```

Body:
I got a dataframe now and try to sort it by 'No.'
dataframe is like:

         No.              value1                  value2
 0     NODE11              1654                     14
 1     NODE10              1710                    817
 2      NODE9              1162                     23
 3      NODE8              1883                    198
 4   no match              2303                      0
 5      NODE1              1098                     67
 6      NODE3              1488                     78
 7      NODE2              2426                     49
 8      NODE5              1974                     90
 9      NODE4              1767                     11
 10     NODE7              1708                     26
 11     NODE6              2418                    248

I tried:

df.to_csv('count.csv',index = False)
df = pd.read_csv('count.csv', thousands=',', parse_dates=['No.'])
df = df.sort_values(by=['No.', 'only can on this node'], ascending=[True, False])
df.to_csv('count.csv',index = False)

Its work but:

         No.              value1                 value2
 5      NODE1              1098                     67
 1     NODE10              1710                    817  -------error
 0     NODE11              1654                     14   -------error
 7      NODE2              2426                     49
 6      NODE3              1488                     78
 9      NODE4              1767                     11
 8      NODE5              1974                     90
 11     NODE6              2418                    248
 10     NODE7              1708                     26
 3      NODE8              1883                    198
 2      NODE9              1162                     23
 4   no match              2303                      0

I dont know how to sort this dataframe because this sort key is str+number. any ideas? Thanks!

Body:
Your column is a string and is sorted as such.

However, you can parse the No. column to a new data frame with a column of strings and a columns of integers, sort that data frame, and use the sorted index to rearrange your original data frame.

df2 = df['No.'].str.extractall('([A-Za-z ]+)(\d+)?').reset_index(drop=True)
df2[1] = df2[1].astype(float)
df.loc[df2.sort_values([0,1]).index]

# returns:
         No.  value1  value2
5      NODE1    1098      67
7      NODE2    2426      49
6      NODE3    1488      78
9      NODE4    1767      11
8      NODE5    1974      90
11     NODE6    2418     248
10     NODE7    1708      26
3      NODE8    1883     198
2      NODE9    1162      23
1     NODE10    1710     817
0     NODE11    1654      14
4   no match    2303       0


答:
Use stable library, may be you doesn't know where is bug in beta version ;)
Try this

```<code><script type="text/javascript" src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<!-- Moment JS -->
<script type="text/javascript" src="//momentjs.com/downloads/moment.js"></script>
<!--Bootstrap JS -->
<script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<!-- dateTimePicker JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>
<!-- bootstrap  -->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet" />
<!-- dateTimePicker CSS -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.min.css" rel="stylesheet" />
<script>
$(function() {
    $('#datetimepicker1').datetimepicker();
});
</script>
<div class = "form-group col col-md-4 col-sm-4 col-12">
    <div class='input-group date' id='datetimepicker1'>
        <input type='text' class="form-control" id="servDate"/>
        <span class="input-group-addon">
            <span class="glyphicon glyphicon-calendar"></span>
        </span>
    </div>
</div>
</code>```

Might be a little help ^_^

Title: easy to use Date time picker

Body:
Use stable library, may be you doesn't know where is bug in beta version ;)
Try this

<script type="text/javascript" src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<!-- Moment JS -->
<script type="text/javascript" src="//momentjs.com/downloads/moment.js"></script>
<!--Bootstrap JS -->
<script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<!-- dateTimePicker JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>
<!-- bootstrap  -->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet" />
<!-- dateTimePicker CSS -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.min.css" rel="stylesheet" />
<script>
$(function() {
    $('#datetimepicker1').datetimepicker();
});
</script>
<div class = "form-group col col-md-4 col-sm-4 col-12">
    <div class='input-group date' id='datetimepicker1'>
        <input type='text' class="form-control" id="servDate"/>
        <span class="input-group-addon">
            <span class="glyphicon glyphicon-calendar"></span>
        </span>
    </div>
</div>

Might be a little help ^_^


问:
How to empty the logcat buffer in Android Code
When I show the LogCat in Android, I want to clear the buffer Log programmatically.

But when I use this statement:

```<code>Runtime.getRuntime().exec("logcat -c")
</code>```

It doesn't clear the buffer.

How can I solve this problem?

答:
Runtime.getRuntime().exec("logcat -c")  will clear only non-rooted log buffers (main, system ..etc).
Please use Runtime.getRuntime().exec("logcat -b all -c") to clear all the buffers (like radio, kernel..etc)

Body:
When I show the LogCat in Android, I want to clear the buffer Log programmatically.

But when I use this statement:

Runtime.getRuntime().exec("logcat -c")

It doesn't clear the buffer.

How can I solve this problem?


问:
SQL Left Join two tables into one
List consumer names from Madison and number of computer requests for each (0 if no requests)

Right now the following query says that it can not be bound, and I assume it's because I am trying to LEFT JOIN two tables to Tb_Requests. I don't know any other way around this.

```<code>   SELECT Tb_Consumer.Name, COUNT(tb_requests.Prod_ID) 'Number of Requests'
     FROM Tb_Consumer, Tb_Product
LEFT JOIN Tb_Requests
       ON Tb_Consumer.Con_ID = Tb_Requests.Con_ID
    WHERE Tb_Consumer.City = 'Madison'
      AND Tb_Product.Name = 'Computer'
 GROUP BY Tb_Consumer.Name
</code>```

I have the following tables:

Tb_Consumer - Name, City, Con_ID

Tb_Supplier - Name, City, Supp_ID

Tb_Offers - Name, Quantity, Prod_ID, Supp_ID

Tb_Product - Name, Prod_ID

Tb_Requests - Name, Quantity, Prod_ID, Con_ID

Tb_Transactions - Tran_ID, Supp_ID, Con_ID, Quantity, Price

答:
You can resolve this issue using the following query:</p>

```<code>SELECT T1.Name, Count(Tbl_Computer.Prod_ID)
FROM Tbl_Consumer T1 LEFT JOIN
     (SELECT T2.Prod_ID, T2.Con_ID
      FROM Tb_Requests T2
           INNER JOIN Tb_Product T3
           ON T2.Prod_ID = T3.Prod_ID
      WHERE T3.Name = 'Computer') AS Tbl_Computer
      ON T1.Con_ID = Tbl_Computer.Con_ID
 WHERE T1.City = 'Madison'
</code>```

Title: SQL Left Join two tables into one

Body:
List consumer names from Madison and number of computer requests for each (0 if no requests)

Right now the following query says that it can not be bound, and I assume it's because I am trying to LEFT JOIN two tables to Tb_Requests. I don't know any other way around this.

   SELECT Tb_Consumer.Name, COUNT(tb_requests.Prod_ID) 'Number of Requests'
     FROM Tb_Consumer, Tb_Product
LEFT JOIN Tb_Requests
       ON Tb_Consumer.Con_ID = Tb_Requests.Con_ID
    WHERE Tb_Consumer.City = 'Madison'
      AND Tb_Product.Name = 'Computer'
 GROUP BY Tb_Consumer.Name

I have the following tables:

Tb_Consumer - Name, City, Con_ID

Tb_Supplier - Name, City, Supp_ID

Tb_Offers - Name, Quantity, Prod_ID, Supp_ID

Tb_Product - Name, Prod_ID

Tb_Requests - Name, Quantity, Prod_ID, Con_ID

Tb_Transactions - Tran_ID, Supp_ID, Con_ID, Quantity, Price

Body:
You can resolve this issue using the following query:

SELECT T1.Name, Count(Tbl_Computer.Prod_ID)
FROM Tbl_Consumer T1 LEFT JOIN
     (SELECT T2.Prod_ID, T2.Con_ID
      FROM Tb_Requests T2
           INNER JOIN Tb_Product T3
           ON T2.Prod_ID = T3.Prod_ID
      WHERE T3.Name = 'Computer') AS Tbl_Computer
      ON T1.Con_ID = Tbl_Computer.Con_ID
 WHERE T1.City = 'Madison'


问:
Lodash _.set only if object exists
I am looking to set inner properties of an object only if they already exist. Lodash _.set will create the whole hierarchy if it does not exist.

Is there an easy way to do this ? (Without and if statement ?)

Snippet below:

const obj = {a: {b: 1}};

_.set(obj, 'a.b', 2);

console.log(obj); // Great !

_.set(obj, 'a.c', 1);

console.log(obj); // Great but not what I want. I would like c not to be set because it does not exist in the first place```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script></code>```

答:
You could look at Object.seal

Though, you'll want to "deeply" seal the object:

const sealDeep = obj => {
    const sealProps = o => {
        Object.values(o).forEach(value => {
            if (typeof value === 'object') {
                sealProps(value);
                Object.seal(value);
            }
        });
    };
    sealProps(obj);
    Object.seal(obj);
};

var x = {
    hello: {
        world: {
            foo: 1,
            bar: 2
        },
        bat: '3'
    },
    foo2: 4
};
sealDeep(x);
console.log(JSON.stringify(x));
x.newthing = 999;
x.hello.newthing = 999;
x.hello.world.newthing = 999;
x.hello.world.foo = 999;
console.log(JSON.stringify(x));```

Title: Lodash _.set only if object exists


问:
Firebase sorting data in descending order. (only half sorted.)
I am trying to sort my listview into descending order by the value. I have tried using Collections.reverse(list); but I dont know why only half the list is sorted into descending. The bottom half is in ascending order.

The Following is my Code:

```<code>com.firebase.client.Query Queryref = mRef.orderByValue().limitToLast(20);
Queryref.addChildEventListener(new com.firebase.client.ChildEventListener() {
    @Override
    public void onChildAdded(com.firebase.client.DataSnapshot dataSnapshot, String s) {
        String value = dataSnapshot.getValue(String.class);
        String boothname = dataSnapshot.getKey();
        list.add(new Booth(boothname, value));
        adapter.notifyDataSetChanged();

        Collections.reverse(list);
    }
</code>```

The Code above allow me to display the top 20 highest value in ascending.
But I want it to be in descending and tried using Collections.reverse();
But the output I received show only the first 10 data in descending. Please help :(

答:
You're reversing the list after each child individual child is added to it.  That doesn't sound at all like it's going to be a sorted list in the end.

You probably don't want to use a ChildEventListener.  Use a ValueEventListener to get a hold of all the children at once, then sort them when that's done.

Body:
I am trying to sort my listview into descending order by the value. I have tried using Collections.reverse(list); but I dont know why only half the list is sorted into descending. The bottom half is in ascending order.

The Following is my Code:

com.firebase.client.Query Queryref = mRef.orderByValue().limitToLast(20);
Queryref.addChildEventListener(new com.firebase.client.ChildEventListener() {
    @Override
    public void onChildAdded(com.firebase.client.DataSnapshot dataSnapshot, String s) {
        String value = dataSnapshot.getValue(String.class);
        String boothname = dataSnapshot.getKey();
        list.add(new Booth(boothname, value));
        adapter.notifyDataSetChanged();

        Collections.reverse(list);
    }

The Code above allow me to display the top 20 highest value in ascending.
But I want it to be in descending and tried using Collections.reverse();
But the output I received show only the first 10 data in descending. Please help :(


问:
How To Check Azure Storage File Is Key-Vault Encrypted Or Not
When a certain parameter(bool encrypt=true) is set then the file will be uploading to azure storage account with key-vault encryption, user have the flexibility to change that parameter value and file can be uploaded without any encryption(bool encrypt=false).

there is a possibility of having encrypted and unencrypted file in the same storage account in Azure.

So, while downloading a file how can i get to know that the file is
  encrypted and i don't need to decrypt it.

答:
there is a possibility of having encrypted and unencrypted file in the same storage account in Azure.

Yes, we could encrypted or unencrypted a blob as we need.

So, while downloading a file how can i get to know that the file is encrypted and i don't need to decrypt it.

If the blob is encrypted by keyvault, there is an encryptiondata metadata in the blob. You could refer to this tutorial get more info about how to Encrypt and decrypt blobs in Microsoft Azure Storage using Azure Key Vault

```<code> blob.FetchAttributes();

 if (blob.Metadata.ContainsKey("encryptiondata"))
 {
     var encryptiondataVaule = blob.Metadata["encryptiondata"];
     // check to encryptiondataVaule then add your logic here
 }
 else
 {
    // the blob is not encrypted by azure keyvault
 }
</code>```

Body:
there is a possibility of having encrypted and unencrypted file in the same storage account in Azure.

Yes, we could encrypted or unencrypted a blob as we need.

So, while downloading a file how can i get to know that the file is encrypted and i don't need to decrypt it.

If the blob is encrypted by keyvault, there is an encryptiondata metadata in the blob. You could refer to this tutorial get more info about how to Encrypt and decrypt blobs in Microsoft Azure Storage using Azure Key Vault

 blob.FetchAttributes();

 if (blob.Metadata.ContainsKey("encryptiondata"))
 {
     var encryptiondataVaule = blob.Metadata["encryptiondata"];
     // check to encryptiondataVaule then add your logic here
 }
 else
 {
    // the blob is not encrypted by azure keyvault
 }


问:
Simple PHP/MySQL Create Table Script
So I have this script just to create a table in my database. I've copied it over from an old script I did that is working right now. How come this one is not working? Anyone?

The error I am getting is "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near "'= varchar (20) NOT NULL, column_two = int NOT NULL auto_increment, column_thre' at line 2"

```<code><?php

include("server_connect.php");

mysql_select_db("assignment5");

$create = "CREATE TABLE tbltable (
column_one = varchar (20) NOT NULL,
column_two = int NOT NULL auto_increment,
column_three = int NOT NULL,
column_four = varchar (15) NOT NULL,
column_five = year,
PRIMARY KEY = (column_one)
)";

$results = mysql_query($create) or die (mysql_error());

echo "The tables have been created";

?>
</code>```

答:
The solution is to assign all the privileges to the BD user, like this:</p>

```<code>GRANT ALL PRIVILEGES ON *. * TO 'user_name' @ 'localhost';
</code>```

Title: Simple PHP/MySQL Create Table Script

Body:
So I have this script just to create a table in my database. I've copied it over from an old script I did that is working right now. How come this one is not working? Anyone?

The error I am getting is "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near "'= varchar (20) NOT NULL, column_two = int NOT NULL auto_increment, column_thre' at line 2"

<?php

include("server_connect.php");

mysql_select_db("assignment5");

$create = "CREATE TABLE tbltable (
column_one = varchar (20) NOT NULL,
column_two = int NOT NULL auto_increment,
column_three = int NOT NULL,
column_four = varchar (15) NOT NULL,
column_five = year,
PRIMARY KEY = (column_one)
)";

$results = mysql_query($create) or die (mysql_error());

echo "The tables have been created";

?>

Body:
The solution is to assign all the privileges to the BD user, like this:

GRANT ALL PRIVILEGES ON *. * TO 'user_name' @ 'localhost';


问:
R: Suggestion to speed up a function (remove duplicates in data frame)
I run into a bit of trouble with my code and would welcome any suggestion to make it run faster.
I have a data frame that looks like that:

```<code>Name <- c("a","a","a","a","a","b","b","b","b","c")

Category <- c("sun","cat","sun","sun","sea","sun","sea","cat","dog","cat")

More_info <- c("table","table","table","table","table","table","table","table","table","cat")
d <- data.frame(Name,Category,More_info)
</code>```

So I have duplicated entries for each row in column Name (the number of duplicates can vary). For each entry (a,b,...) I want to count the sum of each corresponding element in the Category column and keep the only category that appears the most. If an entry has an equal number of categories, I want to take one of most categories randomly.
So in this case, the output dataframe would look like this:

```<code>Name <- c("a","b","c")

Category <- c("sun","dog","cat")

More_info <- c("table","table","table")
d <- data.frame(Name,Category,More_info)
</code>```

a have sun entry kept because it appears the most, b would be dog or whatever other value as they all appear once with b, and c wouldn't be changed.
My function looks like this:

```<code>    my_choosing_function <- function(x){
      tmp = dbSNP_hapmap[dbSNP_hapmap$refsnp_id==list_of_snps[x],]
      snp_freq <- as.data.frame(table(tmp$consequence_type_tv))
       best_hit <- snp_freq[order(-snp_freq$Freq),]
      best_hit$SNP<-list_of_snps[x]
      top<-best_hit[1,]
      return(top)
    }
    trst <- lapply(1:length(list_of_snps), function(x) my_choosing_function(x))
final <- do.call("rbind",trst)
</code>```

Where I start from a list of unique elements (that would be Name in our case), for each element I do a table of the duplicated entries, I order the table by descending values and keep the top element. I do a lapply for each element of the list of unique values, then do a rbind of the whole thing.

As I have 2500000 rows in my initial data frame and 1500000 unique elements, it takes forever to run. 4 seconds for 100 lines, that would be a total of 34 hours for the lapply.

I'm sure packages like dplyr can do it in a few minutes but can't find a solution to do it. Anyone has an idea?
Thanks a lot for your help!

答:
Note: This should be a very long comment because I use data.table instead of dplyr.

I suggest use data.table because it runs faster. And in the data.table way shown below, it randomly choose one in case of tie, not always the first one.

```<code>library(data.table)
library(dplyr)
library(microbenchmark)

d <- data.frame(
    Name = as.character(sample.int(10000, 2.5e6, replace = T)),
    Category = as.character(sample.int(10000, 2.5e6, replace = T)),
    More_info = rep('table', 2.5e6)
)

Mode <- function(x) {
    ux <- unique(x)
    fr1 <- tabulate(match(x, ux))
    if(n_distinct(fr1)==1) ux[sample(seq_along(fr1), 1)] else ux[which.max(fr1)]
}

system.time({
    d %>%
        group_by(Name) %>%
        slice(which(Category == Mode(Category))[1])
})
#    user  system elapsed
#  45.932   0.808  46.745

system.time({
    dt <- as.data.table(d)
    dt.max <- dt[, .N, by = .(Name, Category)]
    dt.max[, r := frank(-N, ties.method = 'random'), by = .(Name)]
    dt.max <- dt.max[r == 1, .(Name, Category)]

    dt[dt.max, on = .(Name, Category), mult = 'first']
})
#    user  system elapsed
#   2.424   0.004   2.426
</code>```

Body:
I run into a bit of trouble with my code and would welcome any suggestion to make it run faster.
I have a data frame that looks like that:

Name <- c("a","a","a","a","a","b","b","b","b","c")

Category <- c("sun","cat","sun","sun","sea","sun","sea","cat","dog","cat")

More_info <- c("table","table","table","table","table","table","table","table","table","cat")
d <- data.frame(Name,Category,More_info)

So I have duplicated entries for each row in column Name (the number of duplicates can vary). For each entry (a,b,...) I want to count the sum of each corresponding element in the Category column and keep the only category that appears the most. If an entry has an equal number of categories, I want to take one of most categories randomly.
So in this case, the output dataframe would look like this:

Name <- c("a","b","c")

Category <- c("sun","dog","cat")

More_info <- c("table","table","table")
d <- data.frame(Name,Category,More_info)

a have sun entry kept because it appears the most, b would be dog or whatever other value as they all appear once with b, and c wouldn't be changed.
My function looks like this:

    my_choosing_function <- function(x){
      tmp = dbSNP_hapmap[dbSNP_hapmap$refsnp_id==list_of_snps[x],]
      snp_freq <- as.data.frame(table(tmp$consequence_type_tv))
       best_hit <- snp_freq[order(-snp_freq$Freq),]
      best_hit$SNP<-list_of_snps[x]
      top<-best_hit[1,]
      return(top)
    }
    trst <- lapply(1:length(list_of_snps), function(x) my_choosing_function(x))
final <- do.call("rbind",trst)

Where I start from a list of unique elements (that would be Name in our case), for each element I do a table of the duplicated entries, I order the table by descending values and keep the top element. I do a lapply for each element of the list of unique values, then do a rbind of the whole thing.

As I have 2500000 rows in my initial data frame and 1500000 unique elements, it takes forever to run. 4 seconds for 100 lines, that would be a total of 34 hours for the lapply.

I'm sure packages like dplyr can do it in a few minutes but can't find a solution to do it. Anyone has an idea?
Thanks a lot for your help!

Body:
Note: This should be a very long comment because I use data.table instead of dplyr.

I suggest use data.table because it runs faster. And in the data.table way shown below, it randomly choose one in case of tie, not always the first one.

library(data.table)
library(dplyr)
library(microbenchmark)

d <- data.frame(
    Name = as.character(sample.int(10000, 2.5e6, replace = T)),
    Category = as.character(sample.int(10000, 2.5e6, replace = T)),
    More_info = rep('table', 2.5e6)
)

Mode <- function(x) {
    ux <- unique(x)
    fr1 <- tabulate(match(x, ux))
    if(n_distinct(fr1)==1) ux[sample(seq_along(fr1), 1)] else ux[which.max(fr1)]
}

system.time({
    d %>%
        group_by(Name) %>%
        slice(which(Category == Mode(Category))[1])
})
#    user  system elapsed
#  45.932   0.808  46.745

system.time({
    dt <- as.data.table(d)
    dt.max <- dt[, .N, by = .(Name, Category)]
    dt.max[, r := frank(-N, ties.method = 'random'), by = .(Name)]
    dt.max <- dt.max[r == 1, .(Name, Category)]

    dt[dt.max, on = .(Name, Category), mult = 'first']
})
#    user  system elapsed
#   2.424   0.004   2.426


问:
IntelliJ vertical line colouring - how to change it
How do i change the color of the vertical white lines in IntelliJ 2017.3

I found this guide but I think it's an older version. Haven't been able to find anything for 2017

https://intellij-support.jetbrains.com/hc/en-us/community/posts/207073015-Style-vertical-indent-guides

答: found the answer after more googling, posting here if anyone else has trouble as it can be tricky to find


问:
Proxied http response fails to set cookie
I'm developing a web application and testing it using Google Chrome 60.0.3112.113.

To simplify the development process I use a node.js development web server with http-proxy-middleware to proxy my API request to the backend.

Now when I send a HTTP POST request using axios to one of the API endpoints to create a session in my backend, I get back slightly altered responses headers (copied from DevTools):

Direct response

```<code>HTTP/1.1 200 OK
Content-Length: 122
Content-Type: application/json
Set-Cookie: sessionid={4621f755-37da-41da-bdbd-9a6ce0ee02b7}; Max-Age=31536000; Version=1
</code>```

Proxied response

```<code>HTTP/1.1 200 OK
X-Powered-By: Express
connection: close
content-length: 122
content-type: application/json
set-cookie: sessionid={4621f755-37da-41da-bdbd-9a6ce0ee02b7}; Max-Age=31536000; Version=1
Date: Thu, 07 Sep 2017 11:06:43 GMT
</code>```

The problem is that chrome doesn't set the cookie specified in the proxied response (DevTools->Application->Storage->Cookies stays empty), however the direct response sets the cookie as expected.

Cookies are shown correctly in DevTools->Network->My Request->Cookies.
Both versions (direct and proxied) are being accessed via http://localhost:[8080 / 3000]

Could the lowercase set-cookie header be ignored in chrome?
Or could the other headers interfere with setting of the cookie?

Btw: Works fine in Safari 10.1.2 (12603.3.8)

答:
```<code>// proxy middleware options
var options = {
    target: 'http://localhost:8081', // target host
    changeOrigin: true,               // needed for virtual hosted sites
    ws: true,                         // proxy websockets
    logLevel: "debug",
    pathRewrite: {
        '^/src/api/' : '/api/'
    },
    onProxyRes: function (proxyRes, req, res) {
        if (proxyRes.headers['set-cookie'] != undefined) {
            req.session['cookie'] = proxyRes.headers['set-cookie'];  // must be or you will get new session for each call
            req.session['proxy-cookie'] = proxyRes.headers['set-cookie'];  // add to other key because cookie will be lost
        }
        console.log("response: " + req.session.id);
        console.log(req.session);
    },
    onProxyReq: function (proxyReq, req, res) {
        // check for whether the session be freshed
        if (req.session.view)
            req.session.view ++;
        else
            req.session.view = 1;

        // use ower key to restore cookie
        if (req.session['proxy-cookie'] != undefined)
            proxyReq.setHeader('cookie', req.session['proxy-cookie'][0]);

        console.log("request: " + req.session.id);
        console.log(req.session);
    }
};
</code>```

Body:
I'm developing a web application and testing it using Google Chrome 60.0.3112.113.

To simplify the development process I use a node.js development web server with http-proxy-middleware to proxy my API request to the backend.

Now when I send a HTTP POST request using axios to one of the API endpoints to create a session in my backend, I get back slightly altered responses headers (copied from DevTools):

Direct response

HTTP/1.1 200 OK
Content-Length: 122
Content-Type: application/json
Set-Cookie: sessionid={4621f755-37da-41da-bdbd-9a6ce0ee02b7}; Max-Age=31536000; Version=1

Proxied response

HTTP/1.1 200 OK
X-Powered-By: Express
connection: close
content-length: 122
content-type: application/json
set-cookie: sessionid={4621f755-37da-41da-bdbd-9a6ce0ee02b7}; Max-Age=31536000; Version=1
Date: Thu, 07 Sep 2017 11:06:43 GMT

The problem is that chrome doesn't set the cookie specified in the proxied response (DevTools->Application->Storage->Cookies stays empty), however the direct response sets the cookie as expected.

Cookies are shown correctly in DevTools->Network->My Request->Cookies.
Both versions (direct and proxied) are being accessed via http://localhost:[8080 / 3000]

Could the lowercase set-cookie header be ignored in chrome?
Or could the other headers interfere with setting of the cookie?

Btw: Works fine in Safari 10.1.2 (12603.3.8)