问:
Internal and External Links Test using Selenium
Want to know how to test internal and external links using webpage. I did the following code to get the links from a page.

```<code>    driver.get("http://newtours.demoaut.com/");
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

    List<WebElement> links = driver.findElements(By.tagName("a"));

    for(int i=0;i<links.size();i++)
    {

        System.out.println(links.get(i).getText());
    }
</code>```

From the above code, getting displayed the link text... Please guide me...

Thanks

答:
I was google it and got the solution.... Sorry if my question is not clear... Thanks for your ansers..

List links = driver.findElements(By.tagName("a"));

```<code>    int internal_count=0;
    int external_count=0;

    for(int i=0;i<links.size();i++)
    {

        String str1 = links.get(i).getAttribute("href");
        boolean b = str1.startsWith("http://newtours.demoaut");

        if(b)
        {
            System.out.println("Internal Link"+str1);
            internal_count++;
        }
        else
        {

            System.out.println("External Link"+str1);
            external_count++;
        }
    }
</code>```

Body:
Want to know how to test internal and external links using webpage. I did the following code to get the links from a page.

    driver.get("http://newtours.demoaut.com/");
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

    List<WebElement> links = driver.findElements(By.tagName("a"));

    for(int i=0;i<links.size();i++)
    {

        System.out.println(links.get(i).getText());
    }

From the above code, getting displayed the link text... Please guide me...

Thanks

Body:
I was google it and got the solution.... Sorry if my question is not clear... Thanks for your ansers..

List links = driver.findElements(By.tagName("a"));

    int internal_count=0;
    int external_count=0;

    for(int i=0;i<links.size();i++)
    {

        String str1 = links.get(i).getAttribute("href");
        boolean b = str1.startsWith("http://newtours.demoaut");

        if(b)
        {
            System.out.println("Internal Link"+str1);
            internal_count++;
        }
        else
        {

            System.out.println("External Link"+str1);
            external_count++;
        }
    }


来源: stackexchange

问:
Can't log in to Google Apps Scripts
I'm using multiple Google accounts. In one of them (not default) I created Google Spreadsheet file and I want to create Script connected to it. Nothing complicated. But the problem is that after clicking Tools > Script Editor I'm being redirected to default user or I see this screen:

The same problem I have when trying to use: script.google.com

What can I do to enable Script editor?

答:
I was not able to reproduce the problem. Perhaps it's a glitch or there is something wrong that requires some troubleshooting techniques that are off-topic on this site.

As a workaround, for the account having problems, use another Google Chrome profile, Incognito mode, or another browser.

By the other hand, it's possible that there isn't any wrong and it's just something related to your specific scenario.

From Sign in to multiple accounts at once

Sometimes settings might carry over

If you're signed in to multiple accounts at the same time, sometimes we can't tell which
  account you're using. For example, if you're signed in to two accounts
  and you open a new browser window, we aren't sure which account you
  want to use. In cases like these, Google might apply settings from
  your default account, like its Web & App Activity and Ads
  Personalization settings.

ContentLicense: CC BY-SA 3.0

Title: Can't log in to Google Apps Scripts


问:
How to send local variables via post
Via a hidden input field I want to send a value from Site 1 to Site 2.
But at Site 2 it says the value is null.

I guess this is because it is local value. But it has to be local and I'm not sure.

Here is my code where I declare the value (page 1):

```<code>string stringproductid = Request.QueryString["id"].tostring();
int productid = stringproductid.AsInt();
</code>```

Here I send it via a hidden field inside a form (page 1):

```<code><input type="hidden" id="@productid" value="@productid" name="@productid">
</code>```

Here I try to receive it (at page 2):

```<code>string idstring = Request.Form["productid"].ToString(); //error
</code>```

答:
On your 2nd page, you should use

```<code>string idstring = Request.Form["@productid"].ToString(); //error
</code>```

On a side note, both Request.QueryString[] and Request.Form[] are always strings, so you don't need to include the .ToString().  I understand it may be defensive coding, but you are just adding CPU cycles. They add up over time.

Title: How to send local variables via post

Body:
Via a hidden input field I want to send a value from Site 1 to Site 2.
But at Site 2 it says the value is null.

I guess this is because it is local value. But it has to be local and I'm not sure.

Here is my code where I declare the value (page 1):

string stringproductid = Request.QueryString["id"].tostring();
int productid = stringproductid.AsInt();

Here I send it via a hidden field inside a form (page 1):

<input type="hidden" id="@productid" value="@productid" name="@productid">

Here I try to receive it (at page 2):

string idstring = Request.Form["productid"].ToString(); //error

Body:
On your 2nd page, you should use

string idstring = Request.Form["@productid"].ToString(); //error

On a side note, both Request.QueryString[] and Request.Form[] are always strings, so you don't need to include the .ToString().  I understand it may be defensive coding, but you are just adding CPU cycles. They add up over time.


问:
Unregistered token error after sending one notification
I am facing this dramatic problem with my android app while using Firebase.
1. My app receives token on the first launch
2. I am able to send notification from firebase console to the registered token
3. If I try to send a notification again with the console just after step 2. It shows me "unregistered token" after 2nd attempt onwards.

I have all necessary configuration already there in the manifest and google service.json file is also in place with the correct configuration. I believe things are correct because the app is able to receive notification once and the problem starts coming only after that.

Update 1:
If I uninstall app and reinstall it then also I am able to receive notification only once.

Those who wants to look at the code, this is how I am getting token:

```<code>@Override
public void onTokenRefresh() {

    //Getting registration token
     refreshedToken = FirebaseInstanceId.getInstance().getToken();

    //Displaying token on logcat
    Log.d(TAG, "Refreshed token: " + refreshedToken);
     saveDeviceToken(refreshedToken);
}
</code>```

This gets calls only first launch and after that, I haven't seen it getting called (which I think is expected behavior).

OnMessage received also gets called on first notification and then it never gets called off:

```<code>@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    Log.d("FCM", "From: " + remoteMessage.getFrom());

    if (remoteMessage.getNotification() != null) {
        Log.d("FCM", "Notification Message Body: " + remoteMessage.getNotification().getBody());
        sendNotification(remoteMessage.getNotification().getBody());
    }
}
</code>```

Update 2 :
Tried to hit the HTTP api of FCM using the same server key and token and got following response:

```<code>   {
  "multicast_id": 6286279702096230688,
  "success": 0,
  "failure": 1,
  "canonical_ids": 0,
  "results": [
    {
      "error": "NotRegistered"
    }
  ]
}
</code>```

Just to avoid cross questions here are few more details:

Android studio  : v2.3.1

Google play service version : 10.0.1

Libraries included : core, database, storage, messaging - all is having same version as google play service 10.0.1

Update 3 : Firebase crash, database and storage is working in the same project (which shows that google service.json file is correct).

Please help me to get it fixed.

答:
Here how I fixed out.

As pointed out by everyone that package name of .json file could be the main reason of this failure which got true here as well but with a twist.

I had downloaded the .json file from Firebase and was assuming that correct .json file was getting downloaded. Unfortunately due to some bug in Firebase on downloading the file, I was always getting the .json file of some of my other project (firebase app).
On investing the downloaded file, I figured it out and change the package name and keys manually on .json file.

I was suggest everyone to check the included .json file before trying anything else as that is the primary reason of this type of issue.

Body:
I am facing this dramatic problem with my android app while using Firebase.
1. My app receives token on the first launch
2. I am able to send notification from firebase console to the registered token
3. If I try to send a notification again with the console just after step 2. It shows me "unregistered token" after 2nd attempt onwards.

I have all necessary configuration already there in the manifest and google service.json file is also in place with the correct configuration. I believe things are correct because the app is able to receive notification once and the problem starts coming only after that.

Update 1:
If I uninstall app and reinstall it then also I am able to receive notification only once.

Those who wants to look at the code, this is how I am getting token:

@Override
public void onTokenRefresh() {

    //Getting registration token
     refreshedToken = FirebaseInstanceId.getInstance().getToken();

    //Displaying token on logcat
    Log.d(TAG, "Refreshed token: " + refreshedToken);
     saveDeviceToken(refreshedToken);
}

This gets calls only first launch and after that, I haven't seen it getting called (which I think is expected behavior).

OnMessage received also gets called on first notification and then it never gets called off:

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    Log.d("FCM", "From: " + remoteMessage.getFrom());

    if (remoteMessage.getNotification() != null) {
        Log.d("FCM", "Notification Message Body: " + remoteMessage.getNotification().getBody());
        sendNotification(remoteMessage.getNotification().getBody());
    }
}

Update 2 :
Tried to hit the HTTP api of FCM using the same server key and token and got following response:

   {
  "multicast_id": 6286279702096230688,
  "success": 0,
  "failure": 1,
  "canonical_ids": 0,
  "results": [
    {
      "error": "NotRegistered"
    }
  ]
}

Just to avoid cross questions here are few more details:

Android studio  : v2.3.1

Google play service version : 10.0.1

Libraries included : core, database, storage, messaging - all is having same version as google play service 10.0.1

Update 3 : Firebase crash, database and storage is working in the same project (which shows that google service.json file is correct).

Please help me to get it fixed.


问:
how to add this in fragment
I am trying to combine fragment with activity. But I end up with an error.

FRAGMENT CODE:

```<code>public class QFragment extends Fragment {@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    //returning our layout file
    //change R.layout.yourlayoutfilename for each of your fragments
    return inflater.inflate(R.layout.fragment_q, container, false);
}

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //you can set the title for your toolbar here for different fragments different titles
        getActivity().setTitle("QFragment");
    }
}
</code>```

One is being used as an activity other is a fragment. I am new to fragment concept.

Main Activity code:

```<code>    public class SpinnerEx4Activity extends Activity implements
    OnItemSelectedListener{
    Spinner s1,s2;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_spinner_ex4);
            s1 = (Spinner)findViewById(R.id.spinner1);
            s2 = (Spinner)findViewById(R.id.spinner2);
            s1.setOnItemSelectedListener(this);
        }
        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub
            String sp1= String.valueOf(s1.getSelectedItem());
            Toast.makeText(this, sp1, Toast.LENGTH_SHORT).show();
            if(sp1.contentEquals("Income")) {
                List<String> list = new ArrayList<String>();
                list.add("Salary");
                list.add("Sales");
                list.add("Others");
                ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, list);
                dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                dataAdapter.notifyDataSetChanged();
                s2.setAdapter(dataAdapter);
            }
            if(sp1.contentEquals("Expense")) {
                List<String> list = new ArrayList<String>();
                list.add("Conveyance");
                list.add("Breakfast");
                list.add("Purchase");
                ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, list);
                dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                dataAdapter2.notifyDataSetChanged();
                s2.setAdapter(dataAdapter2);
            }

        }
        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub

        }
    }
</code>```

So what is the way to solve this? I want the Bottom navigation bar in my app.

答:
you will put your implementation inside the fragment and make fragment transaction manager call it from the activity and here's code sample.
`

```<code>package com.bar.example.androidspinnerexample;

    import java.util.ArrayList;
    import java.util.List;

    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.Spinner;
    import android.widget.AdapterView.OnItemSelectedListener;
    import android.widget.Toast;

    public class SpinnerEx4Activity extends Activity implements
    OnItemSelectedListener{
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            QFragment fragment = new QFragment();
            android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            //container id as first param for replace function
            fragmentTransaction.replace(R.id.activity_spinner_ex4, fragment, null);
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.commit();

        }
    }
</code>```

and for the fragment

```<code>package com.blipclap.engineering_solution;

import android.content.Context;

import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class QFragment extends Fragment implements
    OnItemSelectedListener{@Nullable
            Spinner s1,s2;

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    //returning our layout file
    //change R.layout.yourlayoutfilename for each of your fragments
    View view = inflater.inflate(R.layout.fragment_q, container, false);
    s1 = (Spinner)view.findViewById(R.id.spinner1);
    s2 = (Spinner)view.findViewById(R.id.spinner2);
    s1.setOnItemSelectedListener(this);

    return view;
}

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //you can set the title for your toolbar here for different fragments different titles
        getActivity().setTitle("QFragment");
    }

        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub
            String sp1= String.valueOf(s1.getSelectedItem());
            Toast.makeText(this, sp1, Toast.LENGTH_SHORT).show();
            if(sp1.contentEquals("Income")) {
                List<String> list = new ArrayList<String>();
                list.add("Salary");
                list.add("Sales");
                list.add("Others");
                ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, list);
                dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                dataAdapter.notifyDataSetChanged();
                s2.setAdapter(dataAdapter);
            }
            if(sp1.contentEquals("Expense")) {
                List<String> list = new ArrayList<String>();
                list.add("Conveyance");
                list.add("Breakfast");
                list.add("Purchase");
                ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, list);
                dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                dataAdapter2.notifyDataSetChanged();
                s2.setAdapter(dataAdapter2);
            }

        }
        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub

        }

}
</code>```

ContentLicense: CC BY-SA 4.0

Title: how to add this in fragment

Body:
I am trying to combine fragment with activity. But I end up with an error.

FRAGMENT CODE:

public class QFragment extends Fragment {@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    //returning our layout file
    //change R.layout.yourlayoutfilename for each of your fragments
    return inflater.inflate(R.layout.fragment_q, container, false);
}

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //you can set the title for your toolbar here for different fragments different titles
        getActivity().setTitle("QFragment");
    }
}

One is being used as an activity other is a fragment. I am new to fragment concept.

Main Activity code:

    public class SpinnerEx4Activity extends Activity implements
    OnItemSelectedListener{
    Spinner s1,s2;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_spinner_ex4);
            s1 = (Spinner)findViewById(R.id.spinner1);
            s2 = (Spinner)findViewById(R.id.spinner2);
            s1.setOnItemSelectedListener(this);
        }
        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub
            String sp1= String.valueOf(s1.getSelectedItem());
            Toast.makeText(this, sp1, Toast.LENGTH_SHORT).show();
            if(sp1.contentEquals("Income")) {
                List<String> list = new ArrayList<String>();
                list.add("Salary");
                list.add("Sales");
                list.add("Others");
                ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, list);
                dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                dataAdapter.notifyDataSetChanged();
                s2.setAdapter(dataAdapter);
            }
            if(sp1.contentEquals("Expense")) {
                List<String> list = new ArrayList<String>();
                list.add("Conveyance");
                list.add("Breakfast");
                list.add("Purchase");
                ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, list);
                dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                dataAdapter2.notifyDataSetChanged();
                s2.setAdapter(dataAdapter2);
            }

        }
        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub

        }
    }

So what is the way to solve this? I want the Bottom navigation bar in my app.

Body:
you will put your implementation inside the fragment and make fragment transaction manager call it from the activity and here's code sample.
`

package com.bar.example.androidspinnerexample;

    import java.util.ArrayList;
    import java.util.List;

    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.Spinner;
    import android.widget.AdapterView.OnItemSelectedListener;
    import android.widget.Toast;

    public class SpinnerEx4Activity extends Activity implements
    OnItemSelectedListener{
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            QFragment fragment = new QFragment();
            android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            //container id as first param for replace function
            fragmentTransaction.replace(R.id.activity_spinner_ex4, fragment, null);
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.commit();

        }
    }

and for the fragment

package com.blipclap.engineering_solution;

import android.content.Context;

import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class QFragment extends Fragment implements
    OnItemSelectedListener{@Nullable
            Spinner s1,s2;

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    //returning our layout file
    //change R.layout.yourlayoutfilename for each of your fragments
    View view = inflater.inflate(R.layout.fragment_q, container, false);
    s1 = (Spinner)view.findViewById(R.id.spinner1);
    s2 = (Spinner)view.findViewById(R.id.spinner2);
    s1.setOnItemSelectedListener(this);

    return view;
}

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //you can set the title for your toolbar here for different fragments different titles
        getActivity().setTitle("QFragment");
    }

        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub
            String sp1= String.valueOf(s1.getSelectedItem());
            Toast.makeText(this, sp1, Toast.LENGTH_SHORT).show();
            if(sp1.contentEquals("Income")) {
                List<String> list = new ArrayList<String>();
                list.add("Salary");
                list.add("Sales");
                list.add("Others");
                ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, list);
                dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                dataAdapter.notifyDataSetChanged();
                s2.setAdapter(dataAdapter);
            }
            if(sp1.contentEquals("Expense")) {
                List<String> list = new ArrayList<String>();
                list.add("Conveyance");
                list.add("Breakfast");
                list.add("Purchase");
                ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, list);
                dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                dataAdapter2.notifyDataSetChanged();
                s2.setAdapter(dataAdapter2);
            }

        }
        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub

        }

}


问:
@angular/material no exported member 'OverlayContainer'
I'm trying to get custom theming working and everything is ok until I need to style the OverlayContainer for dialogs and modals. When I try to import OverlayContainer as per the documentation and various guides VS Code throws an error:

Module '../node_modules/@angular/material/material"' has no exported member 'OverlayContainer')

I've tried searching through the node_modules folder in case its just in a different directory but it appears not.

What am I missing? Any help appreciated.

app.component.ts

```<code>import { OverlayContainer } from '@angular/material';
</code>```

package.json

"@angular/material": "^5.0.0-rc.2"

答:
You should try :

import {OverlayContainer} from "@angular/cdk/overlay";

all the "material agnostic" features have been moved to cdk repo.

Regards

Body:
I'm trying to get custom theming working and everything is ok until I need to style the OverlayContainer for dialogs and modals. When I try to import OverlayContainer as per the documentation and various guides VS Code throws an error:

Module '../node_modules/@angular/material/material"' has no exported member 'OverlayContainer')

I've tried searching through the node_modules folder in case its just in a different directory but it appears not.

What am I missing? Any help appreciated.

app.component.ts

import { OverlayContainer } from '@angular/material';

package.json

"@angular/material": "^5.0.0-rc.2"


问:
Is it possible to tell Asterisk to not validate registrations using pjsip?
I am using Asterisk 14 with pjsip.  I would like to disable authentication requirements for certain users, so when that user registers I don't have to send the "REGISTER" request twice (the second containing credentials).  I am not sure where to do this using pjsip.

Thank you

答:
On first register server send back nonce, which used for encrypt password on second attempt.

So no, it is not possible do secure registration without that.

But yes, you can patch any channel driver and do whatever you want with it. Sure you also have patch clients acordinly.


问:
Getting rest history from Django simple History
I am using django-simple-history (1.8.1) and DRF (3.5.3). I want to get a rest service containing the history of each element. Let's take an example !

models.py

```<code>class Product(models.Model):
    name = models.CharField(max_length=50)
    price = models.IntegerField()
    history = HistoricalRecords()

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

So, what must be serializers.py ? I'd like to GET something like :

```<code>[
    {
        "id": 1,
        "name": "Apple",
        "price": 8,
        "history": [
            {
                "history_id": 1,
                "id": 1,
                "name": "Apple",
                "price": 0,
                "history_date": "2016-11-22T08:02:08.739134Z",
                "history_type": "+",
                "history_user": 1
            },
            {
                "history_id": 2,
                "id": 1,
                "name": "Apple",
                "price": 10,
                "history_date": "2016-11-22T08:03:50.845634Z",
                "history_type": "~",
                "history_user": 1
            },
            {
                "history_id": 3,
                "id": 1,
                "name": "Apple",
                "price": 8,
                "history_date": "2016-11-22T08:03:58.243843Z",
                "history_type": "~",
                "history_user": 1
            }
        ]
    }
]
</code>```

After searching whitout finding the solution, I finally found it by myself. But if someone have a better solution...

答:
I know it's been a year, but anyway, maybe someone finds it useful. Here is my solution (it seems far easier to me):

A new serializer field:

class HistoricalRecordField(serializers.ListField):
    child = serializers.DictField()

    def to_representation(self, data):
        return super().to_representation(data.values())
```

<p>Now simply use it as a a field in your serializer:</p>

<pre class="lang-python prettyprint-override"><code>history = HistoricalRecordField(read_only=True)
</code>```

This makes use of DRF's built in list and dict serializers, only trick is to pass it the correct iterable, which is being done by calling .values() on the simple-history model manager class.

Body:
I am using django-simple-history (1.8.1) and DRF (3.5.3). I want to get a rest service containing the history of each element. Let's take an example !

models.py

class Product(models.Model):
    name = models.CharField(max_length=50)
    price = models.IntegerField()
    history = HistoricalRecords()

    def __str__(self):
        return self.name

So, what must be serializers.py ? I'd like to GET something like :

[
    {
        "id": 1,
        "name": "Apple",
        "price": 8,
        "history": [
            {
                "history_id": 1,
                "id": 1,
                "name": "Apple",
                "price": 0,
                "history_date": "2016-11-22T08:02:08.739134Z",
                "history_type": "+",
                "history_user": 1
            },
            {
                "history_id": 2,
                "id": 1,
                "name": "Apple",
                "price": 10,
                "history_date": "2016-11-22T08:03:50.845634Z",
                "history_type": "~",
                "history_user": 1
            },
            {
                "history_id": 3,
                "id": 1,
                "name": "Apple",
                "price": 8,
                "history_date": "2016-11-22T08:03:58.243843Z",
                "history_type": "~",
                "history_user": 1
            }
        ]
    }
]

After searching whitout finding the solution, I finally found it by myself. But if someone have a better solution...

Body:
I know it's been a year, but anyway, maybe someone finds it useful. Here is my solution (it seems far easier to me):

A new serializer field:

class HistoricalRecordField(serializers.ListField):
    child = serializers.DictField()

    def to_representation(self, data):
        return super().to_representation(data.values())

Now simply use it as a a field in your serializer:

history = HistoricalRecordField(read_only=True)

This makes use of DRF's built in list and dict serializers, only trick is to pass it the correct iterable, which is being done by calling .values() on the simple-history model manager class.


问:
Android Intents: Start activity using class name from another app that has the same sharedUserId
All my apps have the same sharedUserId. I would like to start a class of another app using the class of my current app. I want to use intent extras but I do not want to use intent URLs. I also would prefer not to have to change the AndroidManifest of my target activity's app.</p>

答:
Its pretty easy since you have the sharedUserId set.

```<code>Intent res = new Intent();
String mPackage = "com.your.package";
String mClass = ".actYouAreLaunching";
res.setComponent(new ComponentName(mPackage,mPackage+mClass));
startActivity(res);
</code>```

And that's all there is to it. You can add intent extras like you normally would.

ContentLicense: CC BY-SA 2.5

Body:
Its pretty easy since you have the sharedUserId set.

Intent res = new Intent();
String mPackage = "com.your.package";
String mClass = ".actYouAreLaunching";
res.setComponent(new ComponentName(mPackage,mPackage+mClass));
startActivity(res);

And that's all there is to it. You can add intent extras like you normally would.


问:
TCP Service & REST APIs
I have a GPS Tracker Device, I have run a TCP/IP Server Code which Successfully establishes connection with each device in a separate Thread and Device Keep sending its heart beat after one minute and server replies ON. When I send a command to get device location it gives me location and everything is working fine.

Now I want to get location from an android device using web service, Now I'm confuse how can I use running thread of a specific device from an Android App?

答:
Try making code look like this</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace ConsoleApplication16
{
    class Program
    {
        const string IP = "123.456.789.000";
        const int PORT_NUMBER = 1234;
        static AutoResetEvent autoEvent = new AutoResetEvent(false);

        static void Main(string[] args)
        {
            GPSClient client = new GPSClient(IP, PORT_NUMBER);
            //start http client or equivalent here

            while (true)
            {
                autoEvent.Reset();

                autoEvent.WaitOne();

                //wait for message from user/client on service port

                string message = client.message;

                //send message back to user/client

            }
        }
    }
    public class WebServer
    {

    }
    public class GPSClient
    {
        const int BUFFER_SIZE = 256;
        TcpClient client = null;
        NetworkStream stream = null;
        Byte[] bytes = new Byte[BUFFER_SIZE];
        public string message { get; set; }

        public GPSClient(string ip, int port)
        {
            try
            {

                Console.WriteLine("Connecting to Device... ");

                client.Connect(ip, port);
                Console.WriteLine("Connected!");
                stream = client.GetStream();

                stream.BeginRead(bytes, 0, BUFFER_SIZE, new AsyncCallback(HandleDeivce), stream);
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }
        }

        public void HandleDeivce(IAsyncResult ar)
        {
            NetworkStream stream = ar.AsyncState as NetworkStream;

            string data = null;

            int i = stream.Read(bytes, 0, BUFFER_SIZE);

            data = Encoding.ASCII.GetString(bytes, 0, i);
            Console.WriteLine("Received: {0}", data);
            message = data;

            if (data.StartsWith("##"))
            {
               data = "LOAD";
            }
            else
            {
               data = "ON";
            }

            byte[] msg = Encoding.ASCII.GetBytes(data);
            stream.Write(msg, 0, msg.Length);

            Console.WriteLine("Sent: {0}", data);

            stream.BeginRead(bytes, 0, BUFFER_SIZE, new AsyncCallback(HandleDeivce), stream);
        }
    }
}
</code>```

Title: TCP Service & REST APIs

Body:
Try making code look like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace ConsoleApplication16
{
    class Program
    {
        const string IP = "123.456.789.000";
        const int PORT_NUMBER = 1234;
        static AutoResetEvent autoEvent = new AutoResetEvent(false);

        static void Main(string[] args)
        {
            GPSClient client = new GPSClient(IP, PORT_NUMBER);
            //start http client or equivalent here

            while (true)
            {
                autoEvent.Reset();

                autoEvent.WaitOne();

                //wait for message from user/client on service port

                string message = client.message;

                //send message back to user/client

            }
        }
    }
    public class WebServer
    {

    }
    public class GPSClient
    {
        const int BUFFER_SIZE = 256;
        TcpClient client = null;
        NetworkStream stream = null;
        Byte[] bytes = new Byte[BUFFER_SIZE];
        public string message { get; set; }

        public GPSClient(string ip, int port)
        {
            try
            {

                Console.WriteLine("Connecting to Device... ");

                client.Connect(ip, port);
                Console.WriteLine("Connected!");
                stream = client.GetStream();

                stream.BeginRead(bytes, 0, BUFFER_SIZE, new AsyncCallback(HandleDeivce), stream);
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }
        }

        public void HandleDeivce(IAsyncResult ar)
        {
            NetworkStream stream = ar.AsyncState as NetworkStream;

            string data = null;

            int i = stream.Read(bytes, 0, BUFFER_SIZE);

            data = Encoding.ASCII.GetString(bytes, 0, i);
            Console.WriteLine("Received: {0}", data);
            message = data;

            if (data.StartsWith("##"))
            {
               data = "LOAD";
            }
            else
            {
               data = "ON";
            }

            byte[] msg = Encoding.ASCII.GetBytes(data);
            stream.Write(msg, 0, msg.Length);

            Console.WriteLine("Sent: {0}", data);

            stream.BeginRead(bytes, 0, BUFFER_SIZE, new AsyncCallback(HandleDeivce), stream);
        }
    }
}


问:
GAE - app.yaml for static page AND Python
I am trying to create a static html component (that will be usable offline) for a Google App that is otherwise Python.

I can't seem to get the app.yaml file configured correctly for that.

```<code>handlers:

  # Serve images and JSON as static resources.
- url: /(.+\.(gif|png|jpg|json|ico))$
  static_files: \1
  upload: .+\.(gif|png|jpg|json|ico)$
  application_readable: true

- url: \/(static)\/(index)\.html
  static_files: static/\1/index.html
  upload: static\/index.html

- url: /
  script: roomusage.app
  login: required
  secure: always

- url: /welcome
  script: roomusage.app
  login: required
  secure: always

- url: /record
  script: record_usage.app
  login: required
  secure: always
</code>```

Here's the error message I'm getting:

```<code>appcfg.py: error: Error parsing C:\gcloud\dev-myapp\app.yaml: Unable to assign value '\/(static)\/(index)\.html' to attribute 'url':
Value '\/(static)\/(index)\.html' for url does not match expression '^(?:(?!\^)/.*|\..*|(\(.).*(?!\$).)$'
  in "C:\gcloud\dev-myapp\app.yaml", line 25, column 8.
2017-12-08 09:27:50 (Process exited with code 2)
</code>```

答:
Your \/(static)\/(index)\.html pattern is an invalid URL regex pattern.

First - the pattern can't start with \ - you don't need to escape /.

The round paranthesis in the pattern are used to identify positional groupings which can then be referred to as parameters by \1, \2, etc in subsequent statements, like  static_files, for example. From the url row in the Handlers elements table:

url

Required element under handlers. The URL pattern, as a regular
  expression. The expression can contain groupings that can be referred
  to in the file path to the script with regular expression
  back-references. For example, /profile/(.)/(.) would match the
  URL /profile/edit/manager and use edit and manager as the
  first and second groupings.

If you don't need such grouping/parameters then don't use the round paranthesis in your patterns. So to match just /static/index.html you could have:

```<code>- url: /static/index\.html
  static_files: static/index.html
  upload: static/index.html
</code>```

But you should note that the above is redundant if you also have:

```<code>- url: /static
  static_dir: static
</code>```

Body:
I am trying to create a static html component (that will be usable offline) for a Google App that is otherwise Python.

I can't seem to get the app.yaml file configured correctly for that.

handlers:

  # Serve images and JSON as static resources.
- url: /(.+\.(gif|png|jpg|json|ico))$
  static_files: \1
  upload: .+\.(gif|png|jpg|json|ico)$
  application_readable: true

- url: \/(static)\/(index)\.html
  static_files: static/\1/index.html
  upload: static\/index.html

- url: /
  script: roomusage.app
  login: required
  secure: always

- url: /welcome
  script: roomusage.app
  login: required
  secure: always

- url: /record
  script: record_usage.app
  login: required
  secure: always

Here's the error message I'm getting:

appcfg.py: error: Error parsing C:\gcloud\dev-myapp\app.yaml: Unable to assign value '\/(static)\/(index)\.html' to attribute 'url':
Value '\/(static)\/(index)\.html' for url does not match expression '^(?:(?!\^)/.*|\..*|(\(.).*(?!\$).)$'
  in "C:\gcloud\dev-myapp\app.yaml", line 25, column 8.
2017-12-08 09:27:50 (Process exited with code 2)

Body:
Your \/(static)\/(index)\.html pattern is an invalid URL regex pattern.

First - the pattern can't start with \ - you don't need to escape /.

The round paranthesis in the pattern are used to identify positional groupings which can then be referred to as parameters by \1, \2, etc in subsequent statements, like  static_files, for example. From the url row in the Handlers elements table:

url

Required element under handlers. The URL pattern, as a regular
  expression. The expression can contain groupings that can be referred
  to in the file path to the script with regular expression
  back-references. For example, /profile/(.)/(.) would match the
  URL /profile/edit/manager and use edit and manager as the
  first and second groupings.

If you don't need such grouping/parameters then don't use the round paranthesis in your patterns. So to match just /static/index.html you could have:

- url: /static/index\.html
  static_files: static/index.html
  upload: static/index.html

But you should note that the above is redundant if you also have:

- url: /static
  static_dir: static


问:
Adjust Elements after Manipulating String into AttributedString - Swift 4
I have the following which allows me to create a bullet list which works really well, however, after the bullet list is created I need to manipulate the outputted Attributed string to have certain elements either in bold or in italics or both.

The function I have is:

```<code>@IBOutlet var label: UILabel!
let bulletString = ["String 1","String 2","String 3"]

label.attributedText = label.bulletPoints(stringList: bulletString, font: UIFont.stdFontMediumSeventeen, bullet: "•", lineSpacing: 4, paragraphSpacing: 4, textColor: UIColor.darkGreyColor, bulletColor: UIColor.darkGreyColor)

func bulletPoints(stringList: [String],font: UIFont,bullet: String = "\u{2022}",indentation: CGFloat = 20,lineSpacing: CGFloat = 2,paragraphSpacing: CGFloat = 12,textColor: UIColor = .gray,bulletColor: UIColor = .red) -> NSAttributedString{
    let textAttributes: [NSAttributedStringKey: Any] = [NSAttributedStringKey.font: font, NSAttributedStringKey.foregroundColor: textColor]
    let bulletAttributes: [NSAttributedStringKey: Any] = [NSAttributedStringKey.font: font, NSAttributedStringKey.foregroundColor: bulletColor]

    let paragraphStyle = NSMutableParagraphStyle()
    let nonOptions = [NSTextTab.OptionKey: Any]()
    paragraphStyle.tabStops = [NSTextTab(textAlignment: .left, location: indentation, options: nonOptions)]
    paragraphStyle.defaultTabInterval = indentation
    paragraphStyle.lineSpacing = lineSpacing
    paragraphStyle.paragraphSpacing = paragraphSpacing
    paragraphStyle.headIndent = indentation

    let bulletList = NSMutableAttributedString()
    for string in stringList {
        let formattedString = "\(bullet)\t\(string)\n"
        let attributedString = NSMutableAttributedString(string: formattedString)

        attributedString.addAttributes(
            [NSAttributedStringKey.paragraphStyle : paragraphStyle],
            range: NSMakeRange(0, attributedString.length))

        attributedString.addAttributes(
            textAttributes,
            range: NSMakeRange(0, attributedString.length))

        let string:NSString = NSString(string: formattedString)
        let rangeForBullet:NSRange = string.range(of: bullet)
        attributedString.addAttributes(bulletAttributes, range: rangeForBullet)
        bulletList.append(attributedString)
    }
    return bulletList
}
</code>```

What I am looking for is a way to pass in a boolean to state if the bullet string requires either bold or italic text and if so what the elements of the intital string are that need this treatment.

The bulletPoints function sits in an extension file and works as expected.

答:
You can achieve it using multiple fonts and text ranges. If you know the ranges of the text on which you want to apply multiple styles, you can just use fonts. Check the below example.

```<code>let fullString = "Bold normal italic"
let attrString = NSMutableAttributedString(string: fullString, attributes: [.font: UIFont.systemFont(ofSize: 18.0)])

let range1 = (fullString as NSString).range(of: "Bold")
let range2 = (fullString as NSString).range(of: "italic")
attrString.addAttributes([.font: UIFont.boldSystemFont(ofSize: 20.0)], range: range1)
attrString.addAttributes([.font: UIFont.boldSystemFont(ofSize: 20.0).italics()], range: range2)

label.attributedText = attrString
</code>```

Whereas I use simple extension for UIFont.

```<code>extension UIFont {
    func withTraits(_ traits: UIFontDescriptorSymbolicTraits) -> UIFont {
        if let fd = fontDescriptor.withSymbolicTraits(traits) {
            return UIFont(descriptor: fd, size: pointSize)
        }
        return self
    }

    func italics() -> UIFont {
        return withTraits(.traitItalic)
    }
}
</code>```

So basically, what you need to know is, which text should be marked as italic, bold and normal. Afterwards just calculate the ranges for those texts in your original text using NSString.range(of: ) and update the attributes appropriately.

Note: You can also calculate the range using start and endIndex. For reference check this SO answer.

Body:
I have the following which allows me to create a bullet list which works really well, however, after the bullet list is created I need to manipulate the outputted Attributed string to have certain elements either in bold or in italics or both.

The function I have is:

@IBOutlet var label: UILabel!
let bulletString = ["String 1","String 2","String 3"]

label.attributedText = label.bulletPoints(stringList: bulletString, font: UIFont.stdFontMediumSeventeen, bullet: "•", lineSpacing: 4, paragraphSpacing: 4, textColor: UIColor.darkGreyColor, bulletColor: UIColor.darkGreyColor)

func bulletPoints(stringList: [String],font: UIFont,bullet: String = "\u{2022}",indentation: CGFloat = 20,lineSpacing: CGFloat = 2,paragraphSpacing: CGFloat = 12,textColor: UIColor = .gray,bulletColor: UIColor = .red) -> NSAttributedString{
    let textAttributes: [NSAttributedStringKey: Any] = [NSAttributedStringKey.font: font, NSAttributedStringKey.foregroundColor: textColor]
    let bulletAttributes: [NSAttributedStringKey: Any] = [NSAttributedStringKey.font: font, NSAttributedStringKey.foregroundColor: bulletColor]

    let paragraphStyle = NSMutableParagraphStyle()
    let nonOptions = [NSTextTab.OptionKey: Any]()
    paragraphStyle.tabStops = [NSTextTab(textAlignment: .left, location: indentation, options: nonOptions)]
    paragraphStyle.defaultTabInterval = indentation
    paragraphStyle.lineSpacing = lineSpacing
    paragraphStyle.paragraphSpacing = paragraphSpacing
    paragraphStyle.headIndent = indentation

    let bulletList = NSMutableAttributedString()
    for string in stringList {
        let formattedString = "\(bullet)\t\(string)\n"
        let attributedString = NSMutableAttributedString(string: formattedString)

        attributedString.addAttributes(
            [NSAttributedStringKey.paragraphStyle : paragraphStyle],
            range: NSMakeRange(0, attributedString.length))

        attributedString.addAttributes(
            textAttributes,
            range: NSMakeRange(0, attributedString.length))

        let string:NSString = NSString(string: formattedString)
        let rangeForBullet:NSRange = string.range(of: bullet)
        attributedString.addAttributes(bulletAttributes, range: rangeForBullet)
        bulletList.append(attributedString)
    }
    return bulletList
}

What I am looking for is a way to pass in a boolean to state if the bullet string requires either bold or italic text and if so what the elements of the intital string are that need this treatment.

The bulletPoints function sits in an extension file and works as expected.

Body:
You can achieve it using multiple fonts and text ranges. If you know the ranges of the text on which you want to apply multiple styles, you can just use fonts. Check the below example.

let fullString = "Bold normal italic"
let attrString = NSMutableAttributedString(string: fullString, attributes: [.font: UIFont.systemFont(ofSize: 18.0)])

let range1 = (fullString as NSString).range(of: "Bold")
let range2 = (fullString as NSString).range(of: "italic")
attrString.addAttributes([.font: UIFont.boldSystemFont(ofSize: 20.0)], range: range1)
attrString.addAttributes([.font: UIFont.boldSystemFont(ofSize: 20.0).italics()], range: range2)

label.attributedText = attrString

Whereas I use simple extension for UIFont.

extension UIFont {
    func withTraits(_ traits: UIFontDescriptorSymbolicTraits) -> UIFont {
        if let fd = fontDescriptor.withSymbolicTraits(traits) {
            return UIFont(descriptor: fd, size: pointSize)
        }
        return self
    }

    func italics() -> UIFont {
        return withTraits(.traitItalic)
    }
}

So basically, what you need to know is, which text should be marked as italic, bold and normal. Afterwards just calculate the ranges for those texts in your original text using NSString.range(of: ) and update the attributes appropriately.

Note: You can also calculate the range using start and endIndex. For reference check this SO answer.


问:
different regex behaviour on different devices
I'm having a strange bug when I try to check an EditText (I want the text to be an IBAN, like FR76 2894 2894 2894 289), so I'm doing this (overriding my edit text's onTextChanged):

```<code>// format with IBAN regex
@Override
protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
    editText.setText(editText.getText().toString().replaceAll(" ", "")
            .toUpperCase().replaceAll("[a-zA-Z]{2}[0-9]{2}[a-zA-Z0-9]{4}[0-9]{7}([a-zA-Z0-9]?){0,16}", "$0 "));
}
</code>```

I'm doing a comparison with two different Android phones: an Asus Zenfone and an Honor 5C.

Both devices have the same bevahiour on first char typed (valid only if it's a letter). But then, when I type a second letter (text should be FR after this):

Honor 5C: (expected behaviour)

Asus Zenfone: (wrong behaviour)

Any idea?
Thanks for your help.

答:
As you can see in the documentation, it seems like a bad idea to call setText from onTextChanged:

This method is called when the text is changed, in case any subclasses
  would like to know. Within text, the lengthAfter characters beginning
  at start have just replaced old text that had length lengthBefore.

It is an error to attempt to make changes to text from this callback.

Have you tried using a TextWatcher, on your EditText? For instance:

```<code>editText.addTextChangedListener(new TextWatcher() {
      @Override
      public void beforeTextChanged(CharSequence s, int start, int count, int after) {

      }

      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {

      }

      @Override
      public void afterTextChanged(Editable s) {
        // This is only a sample code trying to reproduce your current behavior.
        // I did not test it.
        String iban = s.toString().toUpperCase().replaceAll(" ", "");
        String compactIban = iban.replaceAll("[a-zA-Z]{2}[0-9]{2}[a-zA-Z0-9]{4}[0-9]{7}([a-zA-Z0-9]?){0,16}", "$0 ");
        s.replace(0, s.length(), compactIban);
      }
    });
</code>```

Body:
I'm having a strange bug when I try to check an EditText (I want the text to be an IBAN, like FR76 2894 2894 2894 289), so I'm doing this (overriding my edit text's onTextChanged):

// format with IBAN regex
@Override
protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
    editText.setText(editText.getText().toString().replaceAll(" ", "")
            .toUpperCase().replaceAll("[a-zA-Z]{2}[0-9]{2}[a-zA-Z0-9]{4}[0-9]{7}([a-zA-Z0-9]?){0,16}", "$0 "));
}

I'm doing a comparison with two different Android phones: an Asus Zenfone and an Honor 5C.

Both devices have the same bevahiour on first char typed (valid only if it's a letter). But then, when I type a second letter (text should be FR after this):

Honor 5C: (expected behaviour)

Asus Zenfone: (wrong behaviour)

Any idea?
Thanks for your help.

Body:
As you can see in the documentation, it seems like a bad idea to call setText from onTextChanged:

This method is called when the text is changed, in case any subclasses
  would like to know. Within text, the lengthAfter characters beginning
  at start have just replaced old text that had length lengthBefore.

It is an error to attempt to make changes to text from this callback.

Have you tried using a TextWatcher, on your EditText? For instance:

editText.addTextChangedListener(new TextWatcher() {
      @Override
      public void beforeTextChanged(CharSequence s, int start, int count, int after) {

      }

      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {

      }

      @Override
      public void afterTextChanged(Editable s) {
        // This is only a sample code trying to reproduce your current behavior.
        // I did not test it.
        String iban = s.toString().toUpperCase().replaceAll(" ", "");
        String compactIban = iban.replaceAll("[a-zA-Z]{2}[0-9]{2}[a-zA-Z0-9]{4}[0-9]{7}([a-zA-Z0-9]?){0,16}", "$0 ");
        s.replace(0, s.length(), compactIban);
      }
    });


问:
Calculate total seconds in PHP DateInterval
What is the best way to calculate the total number of seconds between two dates?  So far, I've tried something along the lines of:

```<code>$delta   = $date->diff(new DateTime('now'));
$seconds = $delta->days * 60 * 60 * 24;
</code>```

However, the days property of the DateInterval object seems to be broken in the current PHP5.3 build (at least on Windows, it always returns the same 6015 value).  I also attempted to do it in a way which would fail to preserve number of days in each month (rounds to 30), leap years, etc:

```<code>$seconds = ($delta->s)
         + ($delta->i * 60)
         + ($delta->h * 60 * 60)
         + ($delta->d * 60 * 60 * 24)
         + ($delta->m * 60 * 60 * 24 * 30)
         + ($delta->y * 60 * 60 * 24 * 365);
</code>```

But I'm really not happy with using this half-assed solution.

答:
```<code>static function getIntervalUnits($interval, $unit)
{
    // Day
    $total = $interval->format('%a');
    if ($unit == TimeZoneCalc::Days)
        return $total;
    //hour
    $total = ($total * 24) + ($interval->h );
    if ($unit == TimeZoneCalc::Hours)
        return $total;
    //min
    $total = ($total * 60) + ($interval->i );
    if ($unit == TimeZoneCalc::Minutes)
        return $total;
    //sec
    $total = ($total * 60) + ($interval->s );
    if ($unit == TimeZoneCalc::Seconds)
        return $total;

    return false;
}
</code>```

Body:
What is the best way to calculate the total number of seconds between two dates?  So far, I've tried something along the lines of:

$delta   = $date->diff(new DateTime('now'));
$seconds = $delta->days * 60 * 60 * 24;

However, the days property of the DateInterval object seems to be broken in the current PHP5.3 build (at least on Windows, it always returns the same 6015 value).  I also attempted to do it in a way which would fail to preserve number of days in each month (rounds to 30), leap years, etc:

$seconds = ($delta->s)
         + ($delta->i * 60)
         + ($delta->h * 60 * 60)
         + ($delta->d * 60 * 60 * 24)
         + ($delta->m * 60 * 60 * 24 * 30)
         + ($delta->y * 60 * 60 * 24 * 365);

But I'm really not happy with using this half-assed solution.


问:
tidy nest() unexpected output
In collapsing rows into a list with nest(), the output is not what I would expect. The result is a list like this:

list(X1 = c("..."))

I would have expected:

c("...")

An example using the CNN dataset

```<code>library(tidyverse)
library(readr)

test <-    read_tsv("cnn/stories/0a0a4c90d59df9e36ffec4ba306b4f20f3ba4acb.story",
             col_names = FALSE)

test2 <- test %>%
  nest(X1, .key = articles)
</code>```

EDIT: So, if I wanted a solution that gives me the output of

c("...")

I would have to do :

```<code>test3 <- test %>%
  do(X1 = unique(unlist(.$X1)))
</code>```

答:
From the documentation page for tidyr::nest (emphasis mine):

nest() creates a list of data frames containing all the nested variables: this seems to be the most useful form in practice.

Title: tidy nest() unexpected output

Body:
In collapsing rows into a list with nest(), the output is not what I would expect. The result is a list like this:

list(X1 = c("..."))

I would have expected:

c("...")

An example using the CNN dataset

library(tidyverse)
library(readr)

test <-    read_tsv("cnn/stories/0a0a4c90d59df9e36ffec4ba306b4f20f3ba4acb.story",
             col_names = FALSE)

test2 <- test %>%
  nest(X1, .key = articles)

EDIT: So, if I wanted a solution that gives me the output of

c("...")

I would have to do :

test3 <- test %>%
  do(X1 = unique(unlist(.$X1)))


问:
For loop - how to?
I am trying to run the following code in Android but there seems to be some problem with the for loop. The code builds without any build error but when I try access the second element of the array station_id it gives a runtime error. If I try to access station_id[0], then there is no error at all. I was not sure if the for loop actually loops over and stores the data in every element of the array. Therefore I tried printing the value of i to check if the for loop runs 187 times. However, 'i' is printed only once in the logcat of Android studio. I could not figure out where it goes wrong. Your suggestions would be of great help. Below is my code.

```<code>public class LoadDataOnce {
    private String Url_get_data;
    private String result_fullData;
    private JSONArray fullData;
    // GetData - class that sends http get request and fetches data
    private GetData getfullData;
    private String [] station_id;
    private String []  station_coordinates;
    private int total_num_of_stations;

public LoadDataOnce() {
    Url_get_data = "http://fluggs.wupperverband.de/sos2/api/v1/timeseries/";
    result_fullData = null;
    fullData = null;
    getfullData = new GetData();
    station_id = new String[187];
    station_coordinates = new String[187];
    total_num_of_stations = 0;
}

public String[] getStation_id() {

    return station_id;

}

public String [] getStation_coordinates() {
    return station_coordinates;
}

public int getTotal_num_of_stations() {
    return total_num_of_stations;
}

public void loadData () {

    try {
        result_fullData = getfullData.execute(Url_get_data).get();

        try {
            fullData = new JSONArray(result_fullData);
            total_num_of_stations = fullData.length();
            //station_id =  new String [total_num_of_stations];
            station_coordinates = new String[total_num_of_stations];
            for (int i = 0; i < 187; i++){
                station_id[i] = fullData.getJSONObject(i).getJSONObject("station").getJSONObject("properties").getString("id");
                System.out.println(i);
                station_coordinates[i] = fullData.getJSONObject(i).getJSONObject("geometry").getString("coordinates");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
}

}
</code>```

Exception that I get while testing in Android 7.0 phone.

```<code>    java.lang.RuntimeException: Unable to start activity
    ComponentInfo{com.example.charu.droidar_wupperverband/system.ArActivity}:
    java.lang.IllegalArgumentException: width and height must be > 0
    at
    android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2924)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2985)
    at android.app.ActivityThread.-wrap14(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1635)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6692)
    at java.lang.reflect.Method.invoke(Native Method)
    at

  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
Caused by: java.lang.IllegalArgumentException: width and height must be > 0
    at android.graphics.Bitmap.createBitmap(Bitmap.java:969)
    at android.graphics.Bitmap.createBitmap(Bitmap.java:948)
    at android.graphics.Bitmap.createBitmap(Bitmap.java:915)
    at util.IO.loadBitmapFromView(IO.java:158)
    at util.IO.loadBitmapFromView(IO.java:140)
    at gl.GLFactory.newTextObject(GLFactory.java:611)
    at com.example.charu.droidar_wupperverband.WupperAugment._b_addWorldsToRenderer(WupperAugment.java:106)
    at system.Setup.run(Setup.java:254)
    at system.ArActivity.runSetup(ArActivity.java:61)
    at system.ArActivity.onCreate(ArActivity.java:38)
    at android.app.Activity.performCreate(Activity.java:6912)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2877)
    ... 9 more

 <Debug Infos>
 OS Version: 3.18.14-12365438 (G930FXXU1DQJ8)
 OS API Level: 24
 Device: herolte
 Model (and Product): SM-G930F (heroltexx)
 Manufacturer: samsung
 Other TAGS: release-keys
 screenWidth: 1080
 screenHeigth: 1920
 Keyboard available: false
 Trackball available: false
 SD Card state: mounted
</code>```

答:
maybe JSON return null value or is not a valid definition:</p>

```<code> for (int i = 0; i < 187; i++){
            String s1=fullData.getJSONObject(i).getJSONObject("station").getJSONObject("properties").getString("id");
            if(s1!=null)
                 station_id[i] =s1
            System.out.println(i);

            String s2= fullData.getJSONObject(i).getJSONObject("geometry").getString("coordinates");
            if(s2!=null)
                station_coordinates[i] =s2
        }
</code>```

Title: For loop - how to?

Body:
I am trying to run the following code in Android but there seems to be some problem with the for loop. The code builds without any build error but when I try access the second element of the array station_id it gives a runtime error. If I try to access station_id[0], then there is no error at all. I was not sure if the for loop actually loops over and stores the data in every element of the array. Therefore I tried printing the value of i to check if the for loop runs 187 times. However, 'i' is printed only once in the logcat of Android studio. I could not figure out where it goes wrong. Your suggestions would be of great help. Below is my code.

public class LoadDataOnce {
    private String Url_get_data;
    private String result_fullData;
    private JSONArray fullData;
    // GetData - class that sends http get request and fetches data
    private GetData getfullData;
    private String [] station_id;
    private String []  station_coordinates;
    private int total_num_of_stations;

public LoadDataOnce() {
    Url_get_data = "http://fluggs.wupperverband.de/sos2/api/v1/timeseries/";
    result_fullData = null;
    fullData = null;
    getfullData = new GetData();
    station_id = new String[187];
    station_coordinates = new String[187];
    total_num_of_stations = 0;
}

public String[] getStation_id() {

    return station_id;

}

public String [] getStation_coordinates() {
    return station_coordinates;
}

public int getTotal_num_of_stations() {
    return total_num_of_stations;
}

public void loadData () {

    try {
        result_fullData = getfullData.execute(Url_get_data).get();

        try {
            fullData = new JSONArray(result_fullData);
            total_num_of_stations = fullData.length();
            //station_id =  new String [total_num_of_stations];
            station_coordinates = new String[total_num_of_stations];
            for (int i = 0; i < 187; i++){
                station_id[i] = fullData.getJSONObject(i).getJSONObject("station").getJSONObject("properties").getString("id");
                System.out.println(i);
                station_coordinates[i] = fullData.getJSONObject(i).getJSONObject("geometry").getString("coordinates");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
}

}

Exception that I get while testing in Android 7.0 phone.

    java.lang.RuntimeException: Unable to start activity
    ComponentInfo{com.example.charu.droidar_wupperverband/system.ArActivity}:
    java.lang.IllegalArgumentException: width and height must be > 0
    at
    android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2924)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2985)
    at android.app.ActivityThread.-wrap14(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1635)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6692)
    at java.lang.reflect.Method.invoke(Native Method)
    at

  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
Caused by: java.lang.IllegalArgumentException: width and height must be > 0
    at android.graphics.Bitmap.createBitmap(Bitmap.java:969)
    at android.graphics.Bitmap.createBitmap(Bitmap.java:948)
    at android.graphics.Bitmap.createBitmap(Bitmap.java:915)
    at util.IO.loadBitmapFromView(IO.java:158)
    at util.IO.loadBitmapFromView(IO.java:140)
    at gl.GLFactory.newTextObject(GLFactory.java:611)
    at com.example.charu.droidar_wupperverband.WupperAugment._b_addWorldsToRenderer(WupperAugment.java:106)
    at system.Setup.run(Setup.java:254)
    at system.ArActivity.runSetup(ArActivity.java:61)
    at system.ArActivity.onCreate(ArActivity.java:38)
    at android.app.Activity.performCreate(Activity.java:6912)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2877)
    ... 9 more

 <Debug Infos>
 OS Version: 3.18.14-12365438 (G930FXXU1DQJ8)
 OS API Level: 24
 Device: herolte
 Model (and Product): SM-G930F (heroltexx)
 Manufacturer: samsung
 Other TAGS: release-keys
 screenWidth: 1080
 screenHeigth: 1920
 Keyboard available: false
 Trackball available: false
 SD Card state: mounted

Body:
maybe JSON return null value or is not a valid definition:

 for (int i = 0; i < 187; i++){
            String s1=fullData.getJSONObject(i).getJSONObject("station").getJSONObject("properties").getString("id");
            if(s1!=null)
                 station_id[i] =s1
            System.out.println(i);

            String s2= fullData.getJSONObject(i).getJSONObject("geometry").getString("coordinates");
            if(s2!=null)
                station_coordinates[i] =s2
        }


问:
group and filter and array of objects using VanillaJS
I have the following table which contains some objects :

```<code>var data = [
    {
        "userRoleId": 1,
        "userId": 1,
        "roleId": 1,
        "organizationId": "ORG_01",
        "roleTitle": "Admin",
        "organizationTitle": "Organization 01",
        "startDate": "2017-11-15",
        "endDate": "2017-11-15",
        "automatic": false,
        "useDate": "2017-11-15"
    },
    {
        "userRoleId": 2,
        "userId": 1,
        "roleId": 2,
        "organizationId": "ORG_01",
        "roleTitle": "Agent",
        "organizationTitle": "Organization 01",
        "startDate": "2017-11-15",
        "endDate": "2017-11-15",
        "automatic": true,
        "useDate": "2017-11-15"
    },
    {
        "userRoleId": 4,
        "userId": 1,
        "roleId": 4,
        "organizationId": "ORG_02",
        "roleTitle": "Referent",
        "organizationTitle": "Organization 02",
        "startDate": "2017-11-15",
        "endDate": "2017-11-15",
        "automatic": true,
        "useDate": "2017-11-15"
    },
    {
        "userRoleId": 5,
        "userId": 1,
        "roleId": 2,
        "organizationId": "ORG_02",
        "roleTitle": "Agent",
        "organizationTitle": "Organization 02",
        "startDate": "2017-11-15",
        "endDate": "2017-11-15",
        "automatic": true,
        "useDate": "2017-11-15"
    }
];
</code>```

What I want to do is to group these objects using the object property "organizationId" and "organizationTitle", so what I tried is I grouped them using "organizationId" as following :

```<code>var filtered = data.reduce(function(accumulator, currentValue) {
    (accumulator[currentValue['organizationId']] = accumulator[currentValue['organizationId']] || []).push(currentValue);
    return accumulator;
  }, {});
</code>```

This will generate an object with a key which has the value of each "organizationId" used for grouping, and the grouped data as it's value.

Then I want to create an object for each "organizationId" used for grouping which will have three properties: id which will have the value for "organizationId", title which will have the value for "organizationTitle" and roles which is an array.

This array will contain objects for each grouped objects, this object will have two properties: id which will have the value for "roleId" and title which will have the value for "roleTitle".

So the result should look like this:

```<code>[
    {
        id: 'ORG_01',
        lib: 'Organization 01',
        roles: [
            {
                id: 1,
                title: 'Admin'
            },
            {
                id: 2,
                title: 'Agent'
            }
        ]
    },
      {
        id: 'ORG_02',
        lib: 'Organization 02',
        roles: [
            {
                id: 4,
                title: 'Referent'
            },
            {
                id: 2,
                title: 'Agent'
            }
        ]
    }
]
</code>```

So I did the following, which works and I get the expected result :

```<code>var organizations = [];

for(var i in filtered){
    var obj = {};
    obj.id = i;

    var roles = [];
    filtered[i].forEach(function(el){
        roles.push({'id' : el.roleId, 'lib': el.roleTitle})
        obj.lib = el.organizationTitle;
    });
    obj.roles = roles;
    organizations.push(obj);
}

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

As you can see I used too much code for this, first I used the reduce function then a forEeach and inisde it another forEach.

Isn't there a simple way doing that using vanillaJS (ES5) with the minimun code possible ?

Thanks in advance.

答:
ES6 with single iteration:</p>

```<code>const newData = data.reduce(
  (obj, { organizationId: id, organizationTitle: lib, roleId, roleTitle }) => {
    obj[id] = obj[id] || { id, lib, roles: [] };
    obj[id].roles.push({ id: roleId, title: roleTitle });
    return obj;
  }, {});
</code>```

Body:
I have the following table which contains some objects :

var data = [
    {
        "userRoleId": 1,
        "userId": 1,
        "roleId": 1,
        "organizationId": "ORG_01",
        "roleTitle": "Admin",
        "organizationTitle": "Organization 01",
        "startDate": "2017-11-15",
        "endDate": "2017-11-15",
        "automatic": false,
        "useDate": "2017-11-15"
    },
    {
        "userRoleId": 2,
        "userId": 1,
        "roleId": 2,
        "organizationId": "ORG_01",
        "roleTitle": "Agent",
        "organizationTitle": "Organization 01",
        "startDate": "2017-11-15",
        "endDate": "2017-11-15",
        "automatic": true,
        "useDate": "2017-11-15"
    },
    {
        "userRoleId": 4,
        "userId": 1,
        "roleId": 4,
        "organizationId": "ORG_02",
        "roleTitle": "Referent",
        "organizationTitle": "Organization 02",
        "startDate": "2017-11-15",
        "endDate": "2017-11-15",
        "automatic": true,
        "useDate": "2017-11-15"
    },
    {
        "userRoleId": 5,
        "userId": 1,
        "roleId": 2,
        "organizationId": "ORG_02",
        "roleTitle": "Agent",
        "organizationTitle": "Organization 02",
        "startDate": "2017-11-15",
        "endDate": "2017-11-15",
        "automatic": true,
        "useDate": "2017-11-15"
    }
];

What I want to do is to group these objects using the object property "organizationId" and "organizationTitle", so what I tried is I grouped them using "organizationId" as following :

var filtered = data.reduce(function(accumulator, currentValue) {
    (accumulator[currentValue['organizationId']] = accumulator[currentValue['organizationId']] || []).push(currentValue);
    return accumulator;
  }, {});

This will generate an object with a key which has the value of each "organizationId" used for grouping, and the grouped data as it's value.

Then I want to create an object for each "organizationId" used for grouping which will have three properties: id which will have the value for "organizationId", title which will have the value for "organizationTitle" and roles which is an array.

This array will contain objects for each grouped objects, this object will have two properties: id which will have the value for "roleId" and title which will have the value for "roleTitle".

So the result should look like this:

[
    {
        id: 'ORG_01',
        lib: 'Organization 01',
        roles: [
            {
                id: 1,
                title: 'Admin'
            },
            {
                id: 2,
                title: 'Agent'
            }
        ]
    },
      {
        id: 'ORG_02',
        lib: 'Organization 02',
        roles: [
            {
                id: 4,
                title: 'Referent'
            },
            {
                id: 2,
                title: 'Agent'
            }
        ]
    }
]

So I did the following, which works and I get the expected result :

var organizations = [];

for(var i in filtered){
    var obj = {};
    obj.id = i;

    var roles = [];
    filtered[i].forEach(function(el){
        roles.push({'id' : el.roleId, 'lib': el.roleTitle})
        obj.lib = el.organizationTitle;
    });
    obj.roles = roles;
    organizations.push(obj);
}

console.log(organizations);

As you can see I used too much code for this, first I used the reduce function then a forEeach and inisde it another forEach.

Isn't there a simple way doing that using vanillaJS (ES5) with the minimun code possible ?

Thanks in advance.

Body:
ES6 with single iteration:

const newData = data.reduce(
  (obj, { organizationId: id, organizationTitle: lib, roleId, roleTitle }) => {
    obj[id] = obj[id] || { id, lib, roles: [] };
    obj[id].roles.push({ id: roleId, title: roleTitle });
    return obj;
  }, {});


问:
What does "asp.net" mean?
I know asp stands for Active Server Pages but wondering if "Active Server" means anything actually? </p>

答:
According to Microsoft, it refers to the ActiveX components.

Microsoft® Active Server Pages (ASP) is the server-side execution environment in Microsoft Internet Information Server (IIS) 3.0 that enables you to run ActiveX™ scripts and ActiveX server components on the server. By combining scripts and components, developers can create dynamic content and powerful Web-based applications easily.

OwnerDisplayName: Sesh

Title: What does "asp.net" mean?

OwnerDisplayName: Bill the Lizard


问:
Auto delete rows from log table in mysql db with a trigger
Can someone provide me with a mysql 5 trigger creation code that would allow me to delete the first x number of rows in a table when the total number of rows in my table reaches y ?

Thank you

答:
You cannot perform any CRUD on the same table that fires the trigger... ergo this cannot be done using a trigger on the table

You can however use a sequence of two queries.  Since it is a log table, it may or may not matter if the 2nd one failed.  Once in a while, count the total rows and trim it to size again.

```<code>INSERT INTO LOGTABLE .....   # 1 record
DELETE FROM LOGTABLE ORDER BY ID LIMIT 1;
</code>```

EDITED: for a better workaround

A more sensible alternative is to schedule a job (windows task scheduler + mysql.exe or linux + cron) that will run this batch, which preserves only 100 (change to suit) records

```<code>set @sql := (select count(*) from logtable) - 100;
set @sql := concat('delete from logtable order by date limit ', @sql);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
</code>```

Body:
You cannot perform any CRUD on the same table that fires the trigger... ergo this cannot be done using a trigger on the table

You can however use a sequence of two queries.  Since it is a log table, it may or may not matter if the 2nd one failed.  Once in a while, count the total rows and trim it to size again.

INSERT INTO LOGTABLE .....   # 1 record
DELETE FROM LOGTABLE ORDER BY ID LIMIT 1;

EDITED: for a better workaround

A more sensible alternative is to schedule a job (windows task scheduler + mysql.exe or linux + cron) that will run this batch, which preserves only 100 (change to suit) records

set @sql := (select count(*) from logtable) - 100;
set @sql := concat('delete from logtable order by date limit ', @sql);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;


问:
How do I get my inner class to implement an interface?
The question I need to do is "Add an inner class to the Calculatorclass, called SubtractCalculation. The inner class should implement TwoParameterCalculation" TwoParameterCalculation is an interface I had to create earlier.

My code looks like this image of my code

答:
This is how you do it. I didn't use your class names on purpose, so you can try to understand the code and not just copy/paste it.</p>

```<code>public class OuterClass {

    public class InnerClass implements SomeInterface{

        @Override
        public void someMethod() {

        }
    }
}
</code>```

Body:
This is how you do it. I didn't use your class names on purpose, so you can try to understand the code and not just copy/paste it.

public class OuterClass {

    public class InnerClass implements SomeInterface{

        @Override
        public void someMethod() {

        }
    }
}


问:
MONGO- weekly average distance for a given user Id
I have a collection  of

```<code>{
   id
   distance
   time
   date
   userId
}
</code>```

I would like to get the weekly average distance for a given userId.
So far I managed to have

```<code>    Model.aggregate([{
                $project : {
                        year : {
                            $year : "$date"
                        },

                        week : {
                            $week : "$date"
                        }
                }
                }, {
                $group : {
                _id : {
                    year : "$year",
                    week : "$week"
                }
                total : {
                    $sum: 1
                }
        }

} ]
</code>```

And my output is the number of register that I have in my db per week but I coudn´t manage to go any further than that

I really appreciate any suggestion or help

Thanks in advace

答:
Thank to everybody,
At the end this worked for me

```<code> Model.aggregate([
            {   $match: { userId:mongoose.Types.ObjectId(userId) }},
            {   $project : {
                    year : { $year : "$date" },
                    week : { $week : "$date" },
                    userId: "$userId",
                    distance: "$distance",
                }
            },
            {   $group : {
                    _id : {
                        year : "$year",
                        week : "$week"
                    },
                    distance:{ $avg: "$distance" },
                    total : { $sum: 1 }
                }
            }]
</code>```

So the first match to get just the rows for our userId ( notice that the id has to ve a mongoose Object id, not a string or number ).

Then we use year and week as an id to avoid have same week for diferent years and finally we can get the average with $avg

Body:
I have a collection  of

{
   id
   distance
   time
   date
   userId
}

I would like to get the weekly average distance for a given userId.
So far I managed to have

    Model.aggregate([{
                $project : {
                        year : {
                            $year : "$date"
                        },

                        week : {
                            $week : "$date"
                        }
                }
                }, {
                $group : {
                _id : {
                    year : "$year",
                    week : "$week"
                }
                total : {
                    $sum: 1
                }
        }

} ]

And my output is the number of register that I have in my db per week but I coudn´t manage to go any further than that

I really appreciate any suggestion or help

Thanks in advace

Body:
Thank to everybody,
At the end this worked for me

 Model.aggregate([
            {   $match: { userId:mongoose.Types.ObjectId(userId) }},
            {   $project : {
                    year : { $year : "$date" },
                    week : { $week : "$date" },
                    userId: "$userId",
                    distance: "$distance",
                }
            },
            {   $group : {
                    _id : {
                        year : "$year",
                        week : "$week"
                    },
                    distance:{ $avg: "$distance" },
                    total : { $sum: 1 }
                }
            }]

So the first match to get just the rows for our userId ( notice that the id has to ve a mongoose Object id, not a string or number ).

Then we use year and week as an id to avoid have same week for diferent years and finally we can get the average with $avg


问:
Displaytag alternatives
I'm building an application using Struts 2 + Spring 3 + Hibernate 3. I was wondering if any of you knows of any alternative to the "displaytag" library to draw and manage tables.

Not that I dislike it so much, but I read this comment and made me wonder about other options. And I see it has not been updated in a while and I was wondering if there is some reason for that (like a better/more popular alternative available).

答:
I'm moving to a jQuery datagrid, returning the data with S2 json-plugin. The data gets to my action from a service object that then access the entity objects.

Paging is currently in the service objects using the criteria api, backed by hibernate 3.  Still a work in progress but it is working.

Title: Displaytag alternatives


问:
Recently I updated to Android Studio 3.0 .1. Now some layouts are showing cannot render,coordinator layout out overlay
Recently I updated to Android Studio 3.0 .1. Now some layouts are showing cannot render, cordinator layout out overlay and also showing failed to instantiate one or more classes

1.gradle module app file

2.cordinator layout overlay

3.XML code

```<code>    <?xml version="1.0" encoding="utf-8"?>
    <android.support.design.widget.CoordinatorLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/dd_root_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/dd_content_login" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/dd_fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@mipmap/dd_icon_checkmark" />
    </android.support.design.widget.CoordinatorLayout>
</code>```

答:
Change target version and update gradle 3.0 also use implementation instead of compile.

Now what is difference between this three (api,compile,implementation) keyword

It is one of the changes coming with gradle:3.0
is the compile configuration is now deprecated and should be replaced by implementation or api

api:
you leak the interface of this module through your own interface, meaning exactly the same as the old compile dependency.

implementation:
you only use this module internally and does not leak it through your interface.

Just replace all compile with the implementation and try to build the
  project.  If it builds successfully, well and good. otherwise look for
  any leaking dependency you might be using and import those libraries
  using api keyword.

Hope this may help!

Body:
Recently I updated to Android Studio 3.0 .1. Now some layouts are showing cannot render, cordinator layout out overlay and also showing failed to instantiate one or more classes

1.gradle module app file

2.cordinator layout overlay

3.XML code

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.design.widget.CoordinatorLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/dd_root_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/dd_content_login" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/dd_fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@mipmap/dd_icon_checkmark" />
    </android.support.design.widget.CoordinatorLayout>


问:
Change format of date column in CSV

I have CSV file with the following format

Column_a,Column_b,Column_c,Column_date
a,b,c,08-jun-2017 00:00 to UP (ENG)
```

<p>I want to convert the data with name <code>Column_date</code></p>

<p>Example: <code>08-jun-2017 00:00 to UP (ENG)</code> should be converted to <code>17W23D4 to UP (ENG)</code></p>

<p>The format is year within century <code>17</code>; week of year <code>W23</code>; day of week <code>D4</code>. The days go from Monday (1) to Sunday (7).</p>

<p>So the final CSV should look like:</p>

<pre class="lang-none prettyprint-override"><code>Column_a,Column_b,Column_c,Column_date
a,b,c,17W23D4 to UP (ENG)
</code>```

It would be great if can do in a .bat file, but another scripting language is also okay.

答:
I want to convert the data with name Column_date

The following Python solution is based on datetime — Basic date and time types documentation. Please scroll down to strftime() and strptime() Behavior section for meaning of %y, %V, %u, … directives:

```<code>^^> python
Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)]
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> from datetime import datetime
>>>
>>> ColDateOld = '08-jun-2017 00:00'   ### extract from `CSV`
>>> ColDateNew = datetime.strptime(ColDateOld, '%d-%b-%Y %H:%M').strftime("%yW%VD%u")
>>> print( ColDateNew)                 ### populate the result
17W23D4
>>>
>>>
</code>```

Read and follow CSV File Reading and Writing as well.

Title: Change format of date column in CSV

Body:
I have CSV file with the following format

Column_a,Column_b,Column_c,Column_date
a,b,c,08-jun-2017 00:00 to UP (ENG)

I want to convert the data with name Column_date

Example: 08-jun-2017 00:00 to UP (ENG) should be converted to 17W23D4 to UP (ENG)

The format is year within century 17; week of year W23; day of week D4. The days go from Monday (1) to Sunday (7).

So the final CSV should look like:

Column_a,Column_b,Column_c,Column_date
a,b,c,17W23D4 to UP (ENG)

It would be great if can do in a .bat file, but another scripting language is also okay.

Body:
I want to convert the data with name Column_date

The following Python solution is based on datetime — Basic date and time types documentation. Please scroll down to strftime() and strptime() Behavior section for meaning of %y, %V, %u, … directives:

^^> python
Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)]
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> from datetime import datetime
>>>
>>> ColDateOld = '08-jun-2017 00:00'   ### extract from `CSV`
>>> ColDateNew = datetime.strptime(ColDateOld, '%d-%b-%Y %H:%M').strftime("%yW%VD%u")
>>> print( ColDateNew)                 ### populate the result
17W23D4
>>>
>>>

Read and follow CSV File Reading and Writing as well.


问:
Automap objects from different language
I'm trying to find a way to have a mapping configuration that can map between totally different names from a list.

Our database is in Dutch and scaffolding tooling (like scaffold-dbcontext) keeps the table names for the DTO's. Outside our db related layers we would prefer English nouns.

Say I have the following

```<code>Afdeling
  Id: int
  TypeKode: string
  Werkenemers: Persoon[]

Department
  Id: int
  TypeCode: string
  Employees: Person[]
</code>```

Given I know the following word mapping

```<code>Afdeling    Department
Kode        Code
Werkenemers Employees
Persoon     Person
</code>```

Is it then possible to configure AutoMapper to be able to map as such:

```<code>Department department = Mapper.Map<Afdeling, Department>(afdeling);
</code>```

答:
Yes you can do that. Here is code sample, but note it's just sample. It shows general approach but is not complete and contains some unnecessary things, so make sure you understand what's going on there.

First, custom mapper:

```<code>class DictionaryMapper : ISourceToDestinationNameMapper {
    public Dictionary<string, string> Map { get; set; }
    public MemberInfo GetMatchingMemberInfo(IGetTypeInfoMembers getTypeInfoMembers, TypeDetails typeInfo, Type destType, Type destMemberType, string nameToSearch) {
        if (Map == null || !Map.ContainsKey(nameToSearch))
            return null;
        // map properties using Map dictionary
        return typeInfo.DestinationMemberNames
            .Where(c => c.Member.Name == Map[nameToSearch])
            .Select(c => c.Member)
            .FirstOrDefault();
    }
}
</code>```

Then

```<code>var langMappings = new Dictionary<string, string>();
// note that it's better to use two dictionaries - one for type names
// and another for properties
langMappings.Add("Afdeling", "Department");
langMappings.Add("TypeKode", "TypeCode");
langMappings.Add("Werkenemers", "Employees");
langMappings.Add("Persoon", "Person");
// create reverse map
foreach (var kv in langMappings.ToArray())
    langMappings.Add(kv.Value, kv.Key);

var config = new MapperConfiguration(cfg => {
    // this will allow mapping type with name from dictionary key above
    // to another type indicated with name indicated by value
    // so, Afdeling to Department
    cfg.AddConditionalObjectMapper().Where((s, d) => langMappings.ContainsKey(s.Name) && langMappings[s.Name] == d.Name);
    cfg.AddMemberConfiguration()
    // this is default automapper configuration,
    // see http://docs.automapper.org/en/stable/Conventions.html
    .AddMember<NameSplitMember>()
    .AddName<PrePostfixName>(_ => _.AddStrings(p => p.Prefixes, "Get"))
    // and this one is our custom one
    .AddName<DictionaryMapper>(_ => _.Map = langMappings);
});
var mapper = config.CreateMapper();
var result = mapper.Map<Afdeling, Department>(new Afdeling
{
    Id = 1,
    TypeKode = "code",
    Werkenemers = new[] {
        new Persoon() {Id = 2}
    }
});
</code>```

Title: Automap objects from different language

Body:
I'm trying to find a way to have a mapping configuration that can map between totally different names from a list.

Our database is in Dutch and scaffolding tooling (like scaffold-dbcontext) keeps the table names for the DTO's. Outside our db related layers we would prefer English nouns.

Say I have the following

Afdeling
  Id: int
  TypeKode: string
  Werkenemers: Persoon[]

Department
  Id: int
  TypeCode: string
  Employees: Person[]

Given I know the following word mapping

Afdeling    Department
Kode        Code
Werkenemers Employees
Persoon     Person

Is it then possible to configure AutoMapper to be able to map as such:

Department department = Mapper.Map<Afdeling, Department>(afdeling);

Body:
Yes you can do that. Here is code sample, but note it's just sample. It shows general approach but is not complete and contains some unnecessary things, so make sure you understand what's going on there.

First, custom mapper:

class DictionaryMapper : ISourceToDestinationNameMapper {
    public Dictionary<string, string> Map { get; set; }
    public MemberInfo GetMatchingMemberInfo(IGetTypeInfoMembers getTypeInfoMembers, TypeDetails typeInfo, Type destType, Type destMemberType, string nameToSearch) {
        if (Map == null || !Map.ContainsKey(nameToSearch))
            return null;
        // map properties using Map dictionary
        return typeInfo.DestinationMemberNames
            .Where(c => c.Member.Name == Map[nameToSearch])
            .Select(c => c.Member)
            .FirstOrDefault();
    }
}

Then

var langMappings = new Dictionary<string, string>();
// note that it's better to use two dictionaries - one for type names
// and another for properties
langMappings.Add("Afdeling", "Department");
langMappings.Add("TypeKode", "TypeCode");
langMappings.Add("Werkenemers", "Employees");
langMappings.Add("Persoon", "Person");
// create reverse map
foreach (var kv in langMappings.ToArray())
    langMappings.Add(kv.Value, kv.Key);

var config = new MapperConfiguration(cfg => {
    // this will allow mapping type with name from dictionary key above
    // to another type indicated with name indicated by value
    // so, Afdeling to Department
    cfg.AddConditionalObjectMapper().Where((s, d) => langMappings.ContainsKey(s.Name) && langMappings[s.Name] == d.Name);
    cfg.AddMemberConfiguration()
    // this is default automapper configuration,
    // see http://docs.automapper.org/en/stable/Conventions.html
    .AddMember<NameSplitMember>()
    .AddName<PrePostfixName>(_ => _.AddStrings(p => p.Prefixes, "Get"))
    // and this one is our custom one
    .AddName<DictionaryMapper>(_ => _.Map = langMappings);
});
var mapper = config.CreateMapper();
var result = mapper.Map<Afdeling, Department>(new Afdeling
{
    Id = 1,
    TypeKode = "code",
    Werkenemers = new[] {
        new Persoon() {Id = 2}
    }
});


问:
SumIF() Returning 0 Even If I manually Sum() It Is > 0
I want to match the value in Sheet1!A to Sheet3!A and where they match SUM() the matching values in Sheet2!B

I tried this formula, but it is returning a 0 value even when a manual count returns > 0.

What did I set-up incorrectly in this formula?

```<code>=SUMIF(A:A,Sheet3!A:A,Sheet3!B:B)
</code>```

答:
Use this:

```<code>=SUMPRODUCT(SUMIF(Sheet3!A:A,$A$2:INDEX(A:A,MATCH("zzz",A:A)),Sheet3!B:B))
</code>```

If you column A is numbers and not text change the "zzz" to 1E+99.

Edit

By you comments put this in the first cell:

```<code>=SUMIF(Sheet3!A:A,A2,Sheet3!B:B)
</code>```

And copy down.

Body:
I want to match the value in Sheet1!A to Sheet3!A and where they match SUM() the matching values in Sheet2!B

I tried this formula, but it is returning a 0 value even when a manual count returns > 0.

What did I set-up incorrectly in this formula?

=SUMIF(A:A,Sheet3!A:A,Sheet3!B:B)

Body:
Use this:

=SUMPRODUCT(SUMIF(Sheet3!A:A,$A$2:INDEX(A:A,MATCH("zzz",A:A)),Sheet3!B:B))

If you column A is numbers and not text change the "zzz" to 1E+99.

Edit

By you comments put this in the first cell:

=SUMIF(Sheet3!A:A,A2,Sheet3!B:B)

And copy down.