问:
Infinite looping taking place and not able to update the form control value via global service and finally getting maximum stack size error
```<code><input class="form-control dateicon" maxlength="10" minlength="10" [maxDate]="api.maxDate" name="xyz" (ngModelChange)="def($event,2)"[bsConfig]="{ isAnimated: true ,dateInputFormat: 'DD/MM/YYYY'}" formControlName="abc" bsDatepicker placeholder="DD / MM / YYYY"/>
</code>```

The above code is my ngx bootstrap date picker code and i am triggering a method via ngModelchange.

The below code represents component.ts code:

```<code>def(event,type){
if(type == 2){
 this.globals.stacks.controls['abc'].setValue(event);
}
}
</code>```

Below is my global.ts code:

```<code>   stacks: FormGroup = this.formbuilder.group({
    abc: ['',ValideService.ghi],
    xyz: [''],
  });
</code>```

Below is my validate Service code:

```<code>static ghi(control) {

        let temp = control.value;
        var minDate: any = new Date('09/01/2018');
        var maxDate: any = new Date();
        if (temp == 'undefined' || temp == null || temp == '') {
            return { 'minDatemaxDatereq': true };
        } else if (minDate > temp || maxDate < temp) {//&&

            return { 'minDatemaxDate': true };
        }
        else {
            return null;
        }
    }
</code>```

Whenever i select a particular date from the date picker the def()
method from the component.ts file gets triggered and it iterates for n number of times till i get maximum stack size error.

答:
I think you should just remove the (ngModelChange)="def($event,2)".

Reactive Forms will handle the update of your FormControl for you.

You are creating an infinite loop by setting the FormControls value manually.
this.globals.stacks.controls['abc'].setValue(event); also updates your view which then triggers (ngModelChange)="def($event,2)" again.

Body:
<input class="form-control dateicon" maxlength="10" minlength="10" [maxDate]="api.maxDate" name="xyz" (ngModelChange)="def($event,2)"[bsConfig]="{ isAnimated: true ,dateInputFormat: 'DD/MM/YYYY'}" formControlName="abc" bsDatepicker placeholder="DD / MM / YYYY"/>

The above code is my ngx bootstrap date picker code and i am triggering a method via ngModelchange.

The below code represents component.ts code:

def(event,type){
if(type == 2){
 this.globals.stacks.controls['abc'].setValue(event);
}
}

Below is my global.ts code:

   stacks: FormGroup = this.formbuilder.group({
    abc: ['',ValideService.ghi],
    xyz: [''],
  });

Below is my validate Service code:

static ghi(control) {

        let temp = control.value;
        var minDate: any = new Date('09/01/2018');
        var maxDate: any = new Date();
        if (temp == 'undefined' || temp == null || temp == '') {
            return { 'minDatemaxDatereq': true };
        } else if (minDate > temp || maxDate < temp) {//&&

            return { 'minDatemaxDate': true };
        }
        else {
            return null;
        }
    }

Whenever i select a particular date from the date picker the def()
method from the component.ts file gets triggered and it iterates for n number of times till i get maximum stack size error.


来源: stackexchange

问:
Timeout, asp.net c#, account - admin
I have admin page, i edit there my site, which work with sql. after 3-4 min the admin page logout and ask me again to enter the username and password. how can i change the minutes at the timeout ?

i have tried this at the web.config:

```<code><authentication mode="Forms">

  <forms loginUrl="~/Account/Login.aspx" timeout="60"/>
</authentication>
</code>```

and this:

```<code><authentication mode="Forms">

  <forms loginUrl="~/Account/Login.aspx" timeout="7200"/>
</authentication>
</code>```

and...this:

```<code>  <httpRuntime requestValidationMode="2.0" useFullyQualifiedRedirectUrl="true"

         executionTimeout="72000"
         appRequestQueueLimit="90000"
         shutdownTimeout="90000" />
</code>```

and all the results are the same... after 3-4 min (even when i click there, not only when idle) - the system doin logout.

答: the answer was - to generate the keys at the machin key through iis 7 manager, and then change the session time again, at the iis 7 manager.</p>

ContentLicense: CC BY-SA 3.0

Title: Timeout, asp.net c#, account - admin

Body:
I have admin page, i edit there my site, which work with sql. after 3-4 min the admin page logout and ask me again to enter the username and password. how can i change the minutes at the timeout ?

i have tried this at the web.config:

<authentication mode="Forms">

  <forms loginUrl="~/Account/Login.aspx" timeout="60"/>
</authentication>

and this:

<authentication mode="Forms">

  <forms loginUrl="~/Account/Login.aspx" timeout="7200"/>
</authentication>

and...this:

  <httpRuntime requestValidationMode="2.0" useFullyQualifiedRedirectUrl="true"

         executionTimeout="72000"
         appRequestQueueLimit="90000"
         shutdownTimeout="90000" />

and all the results are the same... after 3-4 min (even when i click there, not only when idle) - the system doin logout.


问:
Trouble with ol and ul tags in email sent with Outlook
So I am trying to create an html email that will be sent out through outlook. The problem seems to be with ol and ul groupings and I can't figure out how to fix it. When I look at the html in a browser or in outlook before I hit the send button, it looks like this:

http://i.imgur.com/U3z7O.jpg

But, the email comes out as:

http://i.imgur.com/KbCjF.jpg

I am not as concern about the spacing as I am that the list style is taken away.

Extra info: sending with outlook, viewing in gmail webclient. Also, if I view it in outlook, it look fine.

Someone asked for the html. Here you go:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>

<body style="margin: 0 auto;">

<table width="640" border="0" cellspacing="0" cellpadding="0" style="border:thin #e7e8e9 solid;">
  <tr>
    <td style="padding: 10px 25px;"><p style="text-align:right; color: #808285; font-family:Arial, Helvetica, sans-serif; font-size: 12px;">Problems viewing email? <a href="#" style="color: #0077c0;">View online version</a></p></td>
  </tr>
  <tr>
    <td style="background-color: #0077c0"><a style="border: none; margin: 0; padding: 0" href="#"><img style="border: none; margin: 0; padding: 0;" src="images/top-image.jpg" width="640" height="300" alt="The 2013 Health and Group Benefit Options are Here." border="0" /></a></td>
  </tr>
  <tr>
    <td style="border-bottom:thin #e7e8e9 solid; padding: 20px 20px;">
        <h1 style="color: #0077c0; font-family:Arial, Helvetica, sans-serif; font-size: 20px; font-weight: normal; line-height: 1.5; margin: 0 0 20px">Annual Enrollment for Your 2013 Benefits Is Open</h1>
        <h2 style="color: #808285; font-family:Arial, Helvetica, sans-serif; font-size: 20px; font-weight: normal; line-height: 1.5; margin: 15px 0 10px; ">Overview</h2>
        <p style="color: #808285; font-family:Arial, Helvetica, sans-serif; font-size: 12px; font-weight: normal; line-height: 1.5; margin: 15px 0 10px;">The Annual Enrollment period for 2013 health and group benefits is open <span style="letter-spacing: 1px; color: #0077c0;">now through Friday, Nov. 16.</span> Log on to <a style="text-decoration: none; color: #0077c0;" href="#">Your Benefits Resources</a> to review your options and enroll. The online tools can help determine the option that best meets your and your family’s needs.</p>
    </td>
  </tr>
  <tr>
    <td style="border-bottom:thin #e7e8e9 solid; padding: 20px 0;">
        <h2 style="color: #808285; font-family:Arial, Helvetica, sans-serif; font-size: 20px; font-weight: normal; line-height: 1.5; margin: 0 0 10px 20px;">Who should enroll</h2>
        <ul style="margin: 0 45px; padding: 0; list-style-type:disc;">
            <li style="color: #808285; font-family:Arial, Helvetica, sans-serif; font-size: 12px; font-weight: normal; line-height: 1.5; margin: 10px 0;">Anyone who wants to change their benefits coverage for 2013.</li>
            <li style="color: #808285; font-family:Arial, Helvetica, sans-serif; font-size: 12px; font-weight: normal; line-height: 1.5; margin: 10px 0;">Anyone who wants to enroll in a Health Care or Dependent Care Flexible Spending Account for 2013.</li>
        </ul>
    </td>
  </tr>
  <tr>
    <td style="border-bottom:thin #e7e8e9 solid; padding: 20px 0;">
        <h2 style="color: #808285; font-family:Arial, Helvetica, sans-serif; font-size: 20px; font-weight: normal; line-height: 1.5; margin: 0 0 10px 20px;">If you don't enroll</h2>
        <ul style="margin: 0 45px; padding: 0; list-style-type:disc;">
            <li style="color: #808285; font-family:Arial, Helvetica, sans-serif; font-size: 12px; font-weight: normal; line-height: 1.5; margin: 10px 0; padding: 0;">Your 2013 benefits enrollment will default to the coverage most similar to your 2012 coverage.</li>
            <li style="color: #808285; font-family:Arial, Helvetica, sans-serif; font-size: 12px; font-weight: normal; line-height: 1.5; margin: 10px 0; padding: 0;">You won’t be signed up for Health Savings Account or Flexible Spending Account deductions. Health Savings Account and Flexible Spending Account elections do not carry over from year to year. </li>
        </ul>
    </td>
  </tr>
  <tr>
    <td></td>
  </tr>
  <tr>
    <td>
        <table width="640" border="0" cellspacing="0" cellpadding="0" style="background-color:#f1f1f2;">
          <tr>
            <td colspan="2" style="padding:20px 20px;"><h2 style="color: #808285; font-family:Arial, Helvetica, sans-serif; font-size: 20px; font-weight: normal; line-height: 1.5; margin:0; padding:0;">How to Enroll</h2></td>
          </tr>
          <tr>
            <td colspan="2">
              <table width="640" border="0" cellspacing="0" cellpadding="0" style="background-color: #0077c0;">
                <tr>
                  <td><img style="margin: 0; padding: 0" src="images/enroll-online.jpg" width="197" height="70" alt="Enroll online" border="0" /></td>
                  <td><a style="border: none; margin: 0; padding: 0" href="#"><img style="margin: 0; padding: 0" src="images/enroll-now-button.jpg" width="108" height="70" alt="Enroll now!" border="0" /></a></td>
                  <td><img style="margin: 0; padding: 0" src="images/enroll-by-phone.jpg" width="335" height="70" alt="Enroll by Phone" border="0" /></td>
                </tr>
              </table>
            </td>
          </tr>
          <tr>
            <td style="border-right:thin #e7e8e9 solid; width: 270px;">
                <ol style="margin: 15px 20px 0 40px; padding: 0; width: 260px; list-style-type:decimal;">
                    <li style="color: #808285; font-family:Arial, Helvetica, sans-serif; font-size: 12px; font-weight: normal; line-height: 1.5; margin: 10px 0;">Log on to <a style="text-decoration: none; color: #0077c0;" href="http://resources.hewitt.com/williams">Your Benefits Resources.</a> A log-on ID (your Social Security number) and password are required.</li>
                    <li style="color: #808285; font-family:Arial, Helvetica, sans-serif; font-size: 12px; font-weight: normal; line-height: 1.5; margin: 10px 0;">Use the online tools to compare your medical options to determine the best option for you and your family, and to estimate the amount to contribute to your Health Savings Account and Health Care and/or Dependent Care Flexible Spending Accounts. </li>
                    <li style="color: #808285; font-family:Arial, Helvetica, sans-serif; font-size: 12px; font-weight: normal; line-height: 1.5; margin: 10px 0;">Make your choices online.</li>
                    <li style="color: #808285; font-family:Arial, Helvetica, sans-serif; font-size: 12px; font-weight: normal; line-height: 1.5; margin: 10px 0;">Print your confirmation statement. You will also receive a confirmation of your enrollment at the home address on file. </li>
                </ol>
            </td>
            <td valign="top" style="width:280px; margin: 0 20px 0 20px;"><p style="color: #808285; font-family:Arial, Helvetica, sans-serif; font-size: 12px; padding: 0 20px; font-weight: normal; line-height: 1.5; margin: 15px 0;">Call the Williams Benefits Center (at Hewitt) at <span style="color: #0077c0;">866-</span> or <span style="color: #0077c0;">866-9</span> weekdays from 8am to 5pm CT.</p>  </td>
          </tr>
        </table>
    </td>
  </tr>
  <tr>
    <td style="padding: 10px 20px;"><p style="font-size: 10px; color: #939598; font-family:Arial, Helvetica, sans-serif; font-weight: normal; line-height: 1.5;">©2012 Williams Companies Inc</p></td>
  </tr>
</table>

</body>
</html>
</code>```

答:
I solve the problem with set some extra margin to ul and ol tags:

It is because outlook set some negative margin to lists(I think) so you should set some extra margin to them:

```<code> <!– [if gte mso 9]>
 <style>
     li {text-align:-webkit-match-parent; display:list-item;text-indent: -1em;}
     ul, ol{    margin-left: 40px !important;}
 </style>
 <![endif]–>
</code>```

Body:
So I am trying to create an html email that will be sent out through outlook. The problem seems to be with ol and ul groupings and I can't figure out how to fix it. When I look at the html in a browser or in outlook before I hit the send button, it looks like this:

http://i.imgur.com/U3z7O.jpg

But, the email comes out as:

http://i.imgur.com/KbCjF.jpg

I am not as concern about the spacing as I am that the list style is taken away.

Extra info: sending with outlook, viewing in gmail webclient. Also, if I view it in outlook, it look fine.

Someone asked for the html. Here you go:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>

Problems viewing email? View online version

Annual Enrollment for Your 2013 Benefits Is Open

Overview

The Annual Enrollment period for 2013 health and group benefits is open now through Friday, Nov. 16. Log on to Your Benefits Resources to review your options and enroll. The online tools can help determine the option that best meets your and your family’s needs.

Who should enroll

Anyone who wants to change their benefits coverage for 2013.

Anyone who wants to enroll in a Health Care or Dependent Care Flexible Spending Account for 2013.

If you don't enroll

Your 2013 benefits enrollment will default to the coverage most similar to your 2012 coverage.

You won’t be signed up for Health Savings Account or Flexible Spending Account deductions. Health Savings Account and Flexible Spending Account elections do not carry over from year to year.

How to Enroll

Log on to Your Benefits Resources. A log-on ID (your Social Security number) and password are required.

Use the online tools to compare your medical options to determine the best option for you and your family, and to estimate the amount to contribute to your Health Savings Account and Health Care and/or Dependent Care Flexible Spending Accounts.

Make your choices online.

Print your confirmation statement. You will also receive a confirmation of your enrollment at the home address on file.

Call the Williams Benefits Center (at Hewitt) at 866- or 866-9 weekdays from 8am to 5pm CT.

©2012 Williams Companies Inc

Body:
I solve the problem with set some extra margin to ul and ol tags:

It is because outlook set some negative margin to lists(I think) so you should set some extra margin to them:

 <!– [if gte mso 9]>
 <style>
     li {text-align:-webkit-match-parent; display:list-item;text-indent: -1em;}
     ul, ol{    margin-left: 40px !important;}
 </style>
 <![endif]–>

ContentLicense: CC BY-SA 4.0


问:
Android NullPointerException in Retrofit response
In my activity I have more than one Retrofit services operations and these services relay on same Retrofit Callback methods. And these causes null pointer when one service try to get a callback at the same time callback is used by other service, how to fix this problem?

I have been using retrofit for my webservice calls. It is working fine in emulator but when I use a real device it crashes and got the error log as:

```<code>  java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.List.get(int)' on a null object reference
    at com.itmam.info.jadara.Notiﬁcations.Notifications_Items_Adapter$4.onResponse(Notifications_Items_Adapter.java:309)
    at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
    at android.os.Handler.handleCallback(Handler.java:888)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:213)
    at android.app.ActivityThread.main(ActivityThread.java:8147)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
</code>```

This is my Retrofit client class:

```<code>public class RetrofitGeneral {

private static Retrofit retrofit;
private static final String BASE_URL = "My_URL";

public static Retrofit getRetrofitInstance() {
    if (retrofit == null) {
        retrofit = new retrofit2.Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
 }
}
</code>```

This is my Retrofit Service interface:

```<code>public interface getClientDetails {
@FormUrlEncoded
@POST("WebService.asmx/SelectClientById")
Call<List<ClientDetails>> getClientdetails(
        @Field("ClientID") int ClientID,
        @Field("Token") String Token,
        @Field("CurrentEmployeeID") int CurrentEmployeeID
 );
}
</code>```

And this way i am making a call to Retrofit service from my adapter onBindViewHolder that call the retrofit more than one time:

```<code>@Override
public void onBindViewHolder(Notifications_Items_Adapter.Notifications_Holder holder, int position) {
    myHolder = holder;
    holderList.add(holder);
    getTaskId(position);
    getTaskDetails(taskID);

}
</code>```

This is my retrofit callBack method:

```<code>private void getTaskDetails(int taskID){
    getTaskDetails getTaskDetails=RetrofitGeneral.getRetrofitInstance().create(getTaskDetails.class);
    Call<List<Task>> listCall=getTaskDetails.getDetails(taskID,Log_in.getToken(),Log_in.CurrentEmployeeID);
    listCall.enqueue(new Callback<List<Task>>(){
        @Override
        public void onResponse(Call<List<Task>> call, Response<List<Task>> response) {
            task = response.body().get(0); // Error here after the second call.
            tasksList.add(task);
        }

        @Override
        public void onFailure(Call<List<Task>> call, Throwable t) {

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

Please help :)

答:
```<code>public void onResponse(Call<SalaryListModel> call, Response<SalaryListModel>
response) {

 if (response.isSuccessful()) {

    Log.e(TAG, "onResponse: calling");

 if (response.body().getStatus_code() == 200) {

    Log.e(TAG, "onResponse: calling 200");

            }

        } else {
            Log.e(TAG, "onResponse: else--");
            if (response.code() == 500) {
                Log.e(TAG, "onResponse: 500");

                //and if you want to parse your error body try this

                /*
                try {
                    Gson gson = new Gson();
                    YourErrorClass error = gson.fromJson(response.errorBody().charStream(), YourErrorClass.class);

                } catch (Exception e) {
                     Log.e(TAG, "onResponse error: " + e.getMessage());
                }*/

            } else if (response.code() == 406) {
                Log.e(TAG, "onResponse: 406");
            } else {
                Log.e(TAG, "onResponse: esle");
            }

        }

    }
</code>```

Body:
In my activity I have more than one Retrofit services operations and these services relay on same Retrofit Callback methods. And these causes null pointer when one service try to get a callback at the same time callback is used by other service, how to fix this problem?

I have been using retrofit for my webservice calls. It is working fine in emulator but when I use a real device it crashes and got the error log as:

  java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.List.get(int)' on a null object reference
    at com.itmam.info.jadara.Notiﬁcations.Notifications_Items_Adapter$4.onResponse(Notifications_Items_Adapter.java:309)
    at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
    at android.os.Handler.handleCallback(Handler.java:888)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:213)
    at android.app.ActivityThread.main(ActivityThread.java:8147)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)

This is my Retrofit client class:

public class RetrofitGeneral {

private static Retrofit retrofit;
private static final String BASE_URL = "My_URL";

public static Retrofit getRetrofitInstance() {
    if (retrofit == null) {
        retrofit = new retrofit2.Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
 }
}

This is my Retrofit Service interface:

public interface getClientDetails {
@FormUrlEncoded
@POST("WebService.asmx/SelectClientById")
Call<List<ClientDetails>> getClientdetails(
        @Field("ClientID") int ClientID,
        @Field("Token") String Token,
        @Field("CurrentEmployeeID") int CurrentEmployeeID
 );
}

And this way i am making a call to Retrofit service from my adapter onBindViewHolder that call the retrofit more than one time:

@Override
public void onBindViewHolder(Notifications_Items_Adapter.Notifications_Holder holder, int position) {
    myHolder = holder;
    holderList.add(holder);
    getTaskId(position);
    getTaskDetails(taskID);

}

This is my retrofit callBack method:

private void getTaskDetails(int taskID){
    getTaskDetails getTaskDetails=RetrofitGeneral.getRetrofitInstance().create(getTaskDetails.class);
    Call<List<Task>> listCall=getTaskDetails.getDetails(taskID,Log_in.getToken(),Log_in.CurrentEmployeeID);
    listCall.enqueue(new Callback<List<Task>>(){
        @Override
        public void onResponse(Call<List<Task>> call, Response<List<Task>> response) {
            task = response.body().get(0); // Error here after the second call.
            tasksList.add(task);
        }

        @Override
        public void onFailure(Call<List<Task>> call, Throwable t) {

        }
    });
}

Please help :)


问:
gradle sonarqube plugin on non-java module
I have multi-module gradle project as shown here

```<code>prj-root
    -prj-react-js
        -src/main/web
    -prj-java
         -prj-java-mod-1
             -src/main/java
         -prj-java-mod-2
             -src/main/java
</code>```

The prj-react-js module is javascript module and only plugin id 'base' is applied in its gradle file.
The sonarqube server is running on remote server.

The sonarqube plugin configuration in the root prj-root/build.gradle is very simple as shown here. There are no other configurations.

```<code>plugins {
    id "org.sonarqube" version "2.8"
}
</code>```

When I run gradle sonarqube only the java code gets analyzed. I also require the javascript code to be analyzed. What configuration am I missing? Is there something to be enabled on the server?

答:
Solved:

The below configuration solved my issue.

Explanation:

The javascript module had sources in the src/main/web directory which I guess the sonarqube plugin do not analyze implicitly. Setting the property sonar.sources to src/main/web will trigger analysis of all javascript code in this directory and below.

```<code>plugins {
    id "org.sonarqube" version "2.8"
}

allprojects {
}

project(":prj-react-js") {
    sonarqube {
        properties {
            property "sonar.sources", "src/main/web"
        }
    }
}
</code>```

Body:
I have multi-module gradle project as shown here

prj-root
    -prj-react-js
        -src/main/web
    -prj-java
         -prj-java-mod-1
             -src/main/java
         -prj-java-mod-2
             -src/main/java

The prj-react-js module is javascript module and only plugin id 'base' is applied in its gradle file.
The sonarqube server is running on remote server.

The sonarqube plugin configuration in the root prj-root/build.gradle is very simple as shown here. There are no other configurations.

plugins {
    id "org.sonarqube" version "2.8"
}

When I run gradle sonarqube only the java code gets analyzed. I also require the javascript code to be analyzed. What configuration am I missing? Is there something to be enabled on the server?

Body:
Solved:

The below configuration solved my issue.

Explanation:

The javascript module had sources in the src/main/web directory which I guess the sonarqube plugin do not analyze implicitly. Setting the property sonar.sources to src/main/web will trigger analysis of all javascript code in this directory and below.

plugins {
    id "org.sonarqube" version "2.8"
}

allprojects {
}

project(":prj-react-js") {
    sonarqube {
        properties {
            property "sonar.sources", "src/main/web"
        }
    }
}


问:
Remove array item if it has a duplicate id
I have an array with the following values:

```<code>expandedComponents: {
  components: [
    {componentName: "hero", componentId: "hero-5856bvC6"},
    {componentName: "features", componentId: "features-iAnIKgJN"},
    {componentName: "features", componentId: "features-ncf3WpTA"},
    {componentName: "features", componentId: "features-iAnIKgJN"},
    {componentName: "features", componentId: "features-ncf3WpTA"},
    {componentName: "footer", componentId: "footer-cUSAiiVd"}
  ]
}
</code>```

I want to filter out any array items with a duplicate componentId.

```<code>this.removeDuplicatesBy(x => x.componentId, this.expandedComponents['components']);

removeDuplicatesBy(keyFn, array) {
  var set = new Set();
  return array.filter(function(x) {
    var key = keyFn(x), isNew = !set.has(key);
    if (isNew) set.add(key);
    return isNew;
  });
 }
</code>```

However nothing seems to be happening and the duplicate features fields still persists. How do I fix this?

答:
Try this out :

    let expandedComponents = {
      components: [
        {componentName: "hero", componentId: "hero-5856bvC6"},
        {componentName: "features", componentId: "features-iAnIKgJN"},
        {componentName: "features", componentId: "features-ncf3WpTA"},
        {componentName: "features", componentId: "features-iAnIKgJN"},
        {componentName: "features", componentId: "features-ncf3WpTA"},
        {componentName: "footer", componentId: "footer-cUSAiiVd"}
      ]
    }
    results = expandedComponents['components'].filter(function(a) {
        return !this[a.componentId] && (this[a.componentId] = true);
    }, Object.create(null));

    console.log(results);```

Body:
I have an array with the following values:

expandedComponents: {
  components: [
    {componentName: "hero", componentId: "hero-5856bvC6"},
    {componentName: "features", componentId: "features-iAnIKgJN"},
    {componentName: "features", componentId: "features-ncf3WpTA"},
    {componentName: "features", componentId: "features-iAnIKgJN"},
    {componentName: "features", componentId: "features-ncf3WpTA"},
    {componentName: "footer", componentId: "footer-cUSAiiVd"}
  ]
}

I want to filter out any array items with a duplicate componentId.

this.removeDuplicatesBy(x => x.componentId, this.expandedComponents['components']);

removeDuplicatesBy(keyFn, array) {
  var set = new Set();
  return array.filter(function(x) {
    var key = keyFn(x), isNew = !set.has(key);
    if (isNew) set.add(key);
    return isNew;
  });
 }

However nothing seems to be happening and the duplicate features fields still persists. How do I fix this?


问:
How can I check if a process was started by Visual Studio > 2015
In Visual Studio 2015 it was possible to check whether a running application had been started from Visual Studio by checking if a debugger is active and if the process was vshost.exe like this:

```<code>bool isInVisualStudio = Debugger.IsAttached && AppDomain.CurrentDomain.FriendlyName.EndsWith("vshost.exe");
</code>```

Since Visual Studio 2017 this is no longer possible as the current domain is always the application executable name regardless of how it was started.

I have been trying without success to do the same thing in VS2019.  The closest I can get is to check if a debugger is attached and if Visual Studio is running at the same time:

```<code>bool devEnvIsRunning = Process.GetProcessesByName("devenv").Length > 0;
bool isInVisualStudio = Debugger.IsAttached && devEnvIsRunning;
</code>```

The problem with this for my purposes is that I want to skip some code when it is running from source in my copy of VS on my machine, but I definitely do NOT want to skip that code just because another debugger is installed.

I have been trying to find a way to get the name of the attached debugger which would solve the problem, but have been unable to do so.

Anyone got any suggestions on how to achieve in VS2019 that which was so easy in VS2015 and earlier?

答:
The answer turned out to be in the comment provided by Hans Passant referencing his answer to another question:  stackoverflow.com/a/2533287/17034

Using WMI as suggested by Hans, and checking for the new remote debugger MSVSMON rather than DEVENV as before, we get the answer we need:

```<code>using System.Management;

var myId = Process.GetCurrentProcess().Id;
var query = $"SELECT ParentProcessId FROM Win32_Process WHERE ProcessId = {myId}";
var search = new ManagementObjectSearcher("root\\CIMV2", query);
var results = search.Get().GetEnumerator();
results.MoveNext();
var queryObj = results.Current;
var parentId = (uint)queryObj["ParentProcessId"];
var parent = Process.GetProcessById((int)parentId);
bool isInVisualStudio = parent.ProcessName.ToLower() == "msvsmon";
</code>```

This even allows us to dispense with call to Debugger.IsAttached, since if the parent process is the debugger than it must be attached.

I would have been more than happy to accept Hans' answer but he made it only as a comment.  Therefore I am posting the answer in case someone else needs it but freely and very gratefully acknowledge that the answer came almost entirely from Hans Passant.

Body:
In Visual Studio 2015 it was possible to check whether a running application had been started from Visual Studio by checking if a debugger is active and if the process was vshost.exe like this:

bool isInVisualStudio = Debugger.IsAttached && AppDomain.CurrentDomain.FriendlyName.EndsWith("vshost.exe");

Since Visual Studio 2017 this is no longer possible as the current domain is always the application executable name regardless of how it was started.

I have been trying without success to do the same thing in VS2019.  The closest I can get is to check if a debugger is attached and if Visual Studio is running at the same time:

bool devEnvIsRunning = Process.GetProcessesByName("devenv").Length > 0;
bool isInVisualStudio = Debugger.IsAttached && devEnvIsRunning;

The problem with this for my purposes is that I want to skip some code when it is running from source in my copy of VS on my machine, but I definitely do NOT want to skip that code just because another debugger is installed.

I have been trying to find a way to get the name of the attached debugger which would solve the problem, but have been unable to do so.

Anyone got any suggestions on how to achieve in VS2019 that which was so easy in VS2015 and earlier?

Body:
The answer turned out to be in the comment provided by Hans Passant referencing his answer to another question:  stackoverflow.com/a/2533287/17034

Using WMI as suggested by Hans, and checking for the new remote debugger MSVSMON rather than DEVENV as before, we get the answer we need:

using System.Management;

var myId = Process.GetCurrentProcess().Id;
var query = $"SELECT ParentProcessId FROM Win32_Process WHERE ProcessId = {myId}";
var search = new ManagementObjectSearcher("root\\CIMV2", query);
var results = search.Get().GetEnumerator();
results.MoveNext();
var queryObj = results.Current;
var parentId = (uint)queryObj["ParentProcessId"];
var parent = Process.GetProcessById((int)parentId);
bool isInVisualStudio = parent.ProcessName.ToLower() == "msvsmon";

This even allows us to dispense with call to Debugger.IsAttached, since if the parent process is the debugger than it must be attached.

I would have been more than happy to accept Hans' answer but he made it only as a comment.  Therefore I am posting the answer in case someone else needs it but freely and very gratefully acknowledge that the answer came almost entirely from Hans Passant.


问:
What project would you recommend me to get up to speed with C++
I know that C++ is a very complex language that takes many years of practice to master.

Taking that into account do you know of a small project (around a 1k of loc) that tests all of C++ major features (inheritance, pointers, memory management, etc).

The thing is I'm a Java/Python programmer and I really want to learn C++ so I've been studying C++ for a while but haven't tested anything of what I've learned beyond small exercises.

I want to take all of that knowledge and put into practice.

答:
I'm not sure about anything that tests all major features. There are a lot of them, and some are rarely used together (templates and virtual functions come to mind. Both achieve a form of polymorphism, so you often use one or the other depending on your needs.)

A suitable project in that it'd touch on all the important features might be something apparently simple like writing a correct container class, similar to std::vector or std::list. Ensure exception safety, iterator validity, the appropriate time complexity on all operations and every other requirement specified in the standard.

The problem with this, as well as most other projects, is that you won't really know when you're done. Making a resizable array might take 50 lines of code, and 20 minutes of your time. And then a beginner would think he's done. Making it exception-safe requires you to be able to spot all the places where the class might be thrown into an inconsistent state by an exception.

That's a kind of general problem with C++. It's easy enough to think you get it, and the compiler certainly won't notify you of aspects you've forgotten to handle. So you might think your code is perfect, and yet it'll crash for all sorts of odd special cases.

As sharptooth said, for a language as messy as C++, writing code on your own is risky. It is easy to fall into the trap of "I've written some code, it compiles and it seems to run. Therefore it is correct".
Of course you could post your code here or on other sites for review, or maybe just supplement your coding with reading the docs for actual high quality C++ code (most boost libraries tend to have comprehensive documentation, specifying both the rationale for various design decisions, and how it safely handles all the weird special cases that tend to crop up in C++. The C++ standard itself would be another excellent resource, of course. In either case, these might help you determine what problems to look out for)

OwnerDisplayName: climatewarrior

OwnerDisplayName: jalf

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: jalf


问:
Basic maths for animation
Assuming I have a form and paint an oval on it. I then want to take a control (such as a picturebox) and (while keeping the top left corner of the control exactly on the line) I want to move the control pixel by pixel following the drawn oval.

Basically I want to calculate the Top/Left point for each position/pixel in my oval. I know its a basic formula but cant for the life of me remember what its called or how its accomplished.

Anyone care to help?

答:
Ellipse canonical form:

```<code>x-x^2/a^2 + y^2/b^2 = 1
</code>```

where a = Xradius and b = Yradius. So, for example, if you want the top-left point of a rectangle on the bottom side of an ellipse:

```<code>y = Sqrt((1-x^2/a^2)*b^2)
</code>```

upd: to move an ellipse to specified point XC,YC, replace each x with (x-XC) and (y-YC). so if you're (in C#) drawing an ellipse in a rectangle, so XC = rect.X + a YC = rect.Y + b and the final equation is y = Sqrt((1 - Pow(x - rect.X - rect.Width / 2, 2) * Pow(rect.Height / 2, 2)) + rect.Y + rect.Height / 2... seems to be correct)

Title: Basic maths for animation

Body:
Ellipse canonical form:

x-x^2/a^2 + y^2/b^2 = 1

where a = Xradius and b = Yradius. So, for example, if you want the top-left point of a rectangle on the bottom side of an ellipse:

y = Sqrt((1-x^2/a^2)*b^2)

upd: to move an ellipse to specified point XC,YC, replace each x with (x-XC) and (y-YC). so if you're (in C#) drawing an ellipse in a rectangle, so XC = rect.X + a YC = rect.Y + b and the final equation is y = Sqrt((1 - Pow(x - rect.X - rect.Width / 2, 2) * Pow(rect.Height / 2, 2)) + rect.Y + rect.Height / 2... seems to be correct)


问:
How to handle "invalid use of non-static data member" in class Implementation in c++?
I've been trying to solve a question Word Search II on LeetCode that requires use of Trie to help make the backtracking calls more efficient and basically tries are to be used, I've been trying to implement my own trie class but I'm running into a road block in my remove function, it requires a copy of root, but I'm not sure how to give it one. Here is the part I'm having trouble with:

TrieNode* crawl = root in the function remove(string word, TrieNode* crawl = root, int depth = 0)

The error: invalid use of non-static data member 'Trie::root'

I don't know the correct way to do it.

```<code>TrieNode* remove(string word, TrieNode* crawl = root, int depth = 0) {
    if(!crawl) return nullptr;

    if(depth == word.size()) {
        if(crawl->isLeaf) crawl->isLeaf = false;
        if(isEmpty(crawl)) {
            delete crawl;
            crawl = nullptr;
        }
        return crawl;
    }

    int index = word[depth] - 'a';
    crawl->arr[index] = remove(word, crawl->arr[index], depth + 1);

    if(isEmpty(crawl) && crawl->isLeaf == false) {
        delete crawl;
        crawl = nullptr;
    }

    return crawl;
}
</code>```

This is what my Trie class looks like:

```<code>class Trie {
    private:
        TrieNode* root;

    public:
        Trie() : root(new TrieNode()) {};

        void insert(const string &word) {
            auto crawl = root;
            // does it's thing
        }

        bool search(const string &word) {
            auto crawl = root;
            // does it's thing
        }

        bool isPrefix(const string &word) {
            auto crawl = root;
            // does it's thing
        }

        bool isEmpty(TrieNode* root) {
            for(int i = 0; i < 26; i++) if(root->arr[i]) return false;
            return true;
        }

        TrieNode* remove(string word, TrieNode* crawl = root, int depth = 0) {
</code>```

With this as the TrieNode:

```<code>struct TrieNode {
    bool isLeaf;
    vector<TrieNode*> arr;
    TrieNode() : isLeaf(false), arr(26, nullptr) {};
};
</code>```

Edit: Special thanks to @SPD for suggesting an improvement on the remove function

答:
An alternate to @darune's answer would be to have an overload:</p>

```<code>TrieNode* remove(const string& word)
{
    return remove(word, root);
}
TrieNode* remove(string word, TrieNode* crawl, int depth = 0) {
//...
</code>```

Body:
I've been trying to solve a question Word Search II on LeetCode that requires use of Trie to help make the backtracking calls more efficient and basically tries are to be used, I've been trying to implement my own trie class but I'm running into a road block in my remove function, it requires a copy of root, but I'm not sure how to give it one. Here is the part I'm having trouble with:

TrieNode* crawl = root in the function remove(string word, TrieNode* crawl = root, int depth = 0)

The error: invalid use of non-static data member 'Trie::root'

I don't know the correct way to do it.

TrieNode* remove(string word, TrieNode* crawl = root, int depth = 0) {
    if(!crawl) return nullptr;

    if(depth == word.size()) {
        if(crawl->isLeaf) crawl->isLeaf = false;
        if(isEmpty(crawl)) {
            delete crawl;
            crawl = nullptr;
        }
        return crawl;
    }

    int index = word[depth] - 'a';
    crawl->arr[index] = remove(word, crawl->arr[index], depth + 1);

    if(isEmpty(crawl) && crawl->isLeaf == false) {
        delete crawl;
        crawl = nullptr;
    }

    return crawl;
}

This is what my Trie class looks like:

class Trie {
    private:
        TrieNode* root;

    public:
        Trie() : root(new TrieNode()) {};

        void insert(const string &word) {
            auto crawl = root;
            // does it's thing
        }

        bool search(const string &word) {
            auto crawl = root;
            // does it's thing
        }

        bool isPrefix(const string &word) {
            auto crawl = root;
            // does it's thing
        }

        bool isEmpty(TrieNode* root) {
            for(int i = 0; i < 26; i++) if(root->arr[i]) return false;
            return true;
        }

        TrieNode* remove(string word, TrieNode* crawl = root, int depth = 0) {

With this as the TrieNode:

struct TrieNode {
    bool isLeaf;
    vector<TrieNode*> arr;
    TrieNode() : isLeaf(false), arr(26, nullptr) {};
};

Edit: Special thanks to @SPD for suggesting an improvement on the remove function

Body:
An alternate to @darune's answer would be to have an overload:

TrieNode* remove(const string& word)
{
    return remove(word, root);
}
TrieNode* remove(string word, TrieNode* crawl, int depth = 0) {
//...


问:
why i cannot able to connect to mysql with python?

C:\Users\alurilalith.sag\Desktop\website>python manage.py runserver
  Watching for file changes with StatReloader Exception in thread
  django-main-thread: Traceback (most recent call last):

django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or
  newer is required; you have 0.9.3.

答:
It seems that you either hav pinned the package version of mysqlclient to version 0.9.3 or one of your other dependencies requires the package in this version.

Have you tried updating mysqlclient? The current release on pypi is 1.4.6

If you are using a requirements.txt try changing

mysqlclient==0.9.3 or just mysqlclient

to

mysqlclient==1.3.13


问:
How to detect multiple clicks in a row on a button - like android developer options
I would like to implement the a similar behaviour to android settings app of the developer options. I mean when a user clicks on a button for a 7 times in a row with a small delay between every click a popup will appear ask him to enable an hidden feature in the app.

How can I implement this behaviour?

答:
I have developed it based on the watchdog concept. An instance of TimerWatchDog does the job if it doesn't refresh in the specified time. ContinuousClicksHandler uses an instance of TimerWatchDog along with counting the clicks.

Usage:

```<code>val clicksCount = 7
val maxInterval = 1000L

val continuousClicksHandler = ContinuousClicksHandler(clicksCount, maxInterval)

continuousClicksHandler.registerCallback(object : ContinuousClicksHandler.ContinuousClicksCallback {

    override fun onContinuousClicksSuccessful() {
        println("onContinuousClicksSuccessful!")
    }

    override fun onContinuousClicksFailed() {
        println("onContinuousClicksFailed!")
    }

})

button.setOnClickListener {
    val count = continuousClicksHandler.click()
    showToast("Needs ${clicksCount - count} more clicks to succeed!")
}
</code>```

ContinuousClicksHandler.kt

```<code>/**
 * @author aminography
 */
class ContinuousClicksHandler(
    private val clicksCount: Int,
    maxInterval: Long
) {

    private var callback: ContinuousClicksCallback? = null
    private val timerWatchDog = TimerWatchDog(maxInterval)
    private var currentClicks = 0

    fun click(): Int {
        if (++currentClicks == clicksCount) {
            timerWatchDog.cancel()
            currentClicks = 0
            callback?.onContinuousClicksSuccessful()
        } else {
            timerWatchDog.refresh {
                currentClicks = 0
                callback?.onContinuousClicksFailed()
            }
        }
        return currentClicks
    }

    fun registerCallback(callback: ContinuousClicksCallback) {
        this.callback = callback
    }

    interface ContinuousClicksCallback {

        fun onContinuousClicksSuccessful()

        fun onContinuousClicksFailed()
    }

}
</code>```

TimerWatchDog.kt

```<code>import java.util.*

/**
 * @author aminography
 */
class TimerWatchDog(private val timeout: Long) {

    private var timer: Timer? = null

    fun refresh(job: () -> Unit) {
        timer?.cancel()
        timer = Timer()
        timer?.schedule(object : TimerTask() {
            override fun run() = job.invoke()
        }, timeout)
    }

    fun cancel() = timer?.cancel()

}
</code>```

Body:
I have developed it based on the watchdog concept. An instance of TimerWatchDog does the job if it doesn't refresh in the specified time. ContinuousClicksHandler uses an instance of TimerWatchDog along with counting the clicks.

Usage:

val clicksCount = 7
val maxInterval = 1000L

val continuousClicksHandler = ContinuousClicksHandler(clicksCount, maxInterval)

continuousClicksHandler.registerCallback(object : ContinuousClicksHandler.ContinuousClicksCallback {

    override fun onContinuousClicksSuccessful() {
        println("onContinuousClicksSuccessful!")
    }

    override fun onContinuousClicksFailed() {
        println("onContinuousClicksFailed!")
    }

})

button.setOnClickListener {
    val count = continuousClicksHandler.click()
    showToast("Needs ${clicksCount - count} more clicks to succeed!")
}

ContinuousClicksHandler.kt

/**
 * @author aminography
 */
class ContinuousClicksHandler(
    private val clicksCount: Int,
    maxInterval: Long
) {

    private var callback: ContinuousClicksCallback? = null
    private val timerWatchDog = TimerWatchDog(maxInterval)
    private var currentClicks = 0

    fun click(): Int {
        if (++currentClicks == clicksCount) {
            timerWatchDog.cancel()
            currentClicks = 0
            callback?.onContinuousClicksSuccessful()
        } else {
            timerWatchDog.refresh {
                currentClicks = 0
                callback?.onContinuousClicksFailed()
            }
        }
        return currentClicks
    }

    fun registerCallback(callback: ContinuousClicksCallback) {
        this.callback = callback
    }

    interface ContinuousClicksCallback {

        fun onContinuousClicksSuccessful()

        fun onContinuousClicksFailed()
    }

}

TimerWatchDog.kt

import java.util.*

/**
 * @author aminography
 */
class TimerWatchDog(private val timeout: Long) {

    private var timer: Timer? = null

    fun refresh(job: () -> Unit) {
        timer?.cancel()
        timer = Timer()
        timer?.schedule(object : TimerTask() {
            override fun run() = job.invoke()
        }, timeout)
    }

    fun cancel() = timer?.cancel()

}


问:
Increase speed of fetching contacts with cursor
In my app I'm fetching all contacts with cursor.

```<code>private static final String[] PROJECTION = new String[]{
        PHONE_CONTACT_ID,
        DISPLAY_NAME,
        TIMESTAMP,
        HAS_PHONE_NUMBER};

CursorLoader cursorLoader = new CursorLoader(ResUtils.getInstance().getContext(),
            ContactsContract.Contacts.CONTENT_URI, PROJECTION, null, null,
            "UPPER(" + ContactsContract.Contacts.DISPLAY_NAME + ")ASC");
    Cursor cursor = cursorLoader.loadInBackground();
    // Loop for every contact in the phone
    if (cursor != null && cursor.getCount() > 0) {
        while (cursor.moveToNext()) {
            ArrayList<String> phoneNumbers = new ArrayList<>();
            String contact_id = cursor.getString(cursor.getColumnIndex(PHONE_CONTACT_ID));
            String   name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));
            String  timeStamp = cursor.getString(cursor.getColumnIndex(TIMESTAMP));
            cursorLoader = new CursorLoader( ResUtils.getInstance().getContext(), ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                    new String[]{EMAIL},ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[]{contact_id}, null);
            Cursor emailCur = cursorLoader.loadInBackground();
            while (emailCur.moveToNext()) {
                String email = emailCur.getString(emailCur.getColumnIndex(EMAIL));
                if (TmlyUtils.isValidEmail(email)) {
                    phoneNumbers.add(ContactUtils.MAIL_TAG + email);
                }
            }
            emailCur.close();
            if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER))) > 0) {
                cursorLoader = new CursorLoader( ResUtils.getInstance().getContext(),   ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        new String[]{NUMBER},ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{contact_id}, null);
                Cursor phones = cursorLoader.loadInBackground();
                while (phones.moveToNext()) {
                    String phoneNumber = phones.getString(phones.getColumnIndex(NUMBER));
                    phoneNumber = isValidMobileNumber(phoneNumber);
                    if (!phoneNumber.isEmpty() && !phoneNumbers.contains(ContactUtils.UPN_TAG + phoneNumber)) {
                        phoneNumbers.add(ContactUtils.UPN_TAG + phoneNumber);
                    }
                }
                phones.close();
            }
        }
        cursor.close();
    }
</code>```

The code works fine but when you have thousands of contacts the app freeze during several seconds.

I'm using three cursor, the first one allow me to get all contacts in my phone

```<code>CursorLoader cursorLoader = new CursorLoader(ResUtils.getInstance().getContext(),
        ContactsContract.Contacts.CONTENT_URI, PROJECTION, null, null,
        "UPPER(" + ContactsContract.Contacts.DISPLAY_NAME + ")ASC");
Cursor cursor = cursorLoader.loadInBackground();
</code>```

The second one loop for every email adress

```<code> cursorLoader = new CursorLoader( ResUtils.getInstance().getContext(), ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                new String[]{EMAIL},ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[]{contact_id}, null);
        Cursor emailCur = cursorLoader.loadInBackground();
</code>```

The third one loop for every phone

```<code>cursorLoader = new CursorLoader( ResUtils.getInstance().getContext(),   ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    new String[]{NUMBER},ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{contact_id}, null);
            Cursor phones = cursorLoader.loadInBackground();
</code>```

I need to use the second and the third one If I'm not using it I can't get all phones and email for every contacts, because one contact can have several phones and email address

I try to use CursorLoader for speed up, but it's not sufficient, is it possible to get rid of the second and the third cursor ?

EDIT : I forgot to say that all the query is already inside a Retrofit call

答: If your app is freeze that means that your SQL query runs on UI thread. Better wrap your SQL query into asynchronous code with HandlerThreads, RxJava, Coroutines e.t.c. This helps you not to block UI thread and therefore freeze your app. </p>

Body:
In my app I'm fetching all contacts with cursor.

private static final String[] PROJECTION = new String[]{
        PHONE_CONTACT_ID,
        DISPLAY_NAME,
        TIMESTAMP,
        HAS_PHONE_NUMBER};

CursorLoader cursorLoader = new CursorLoader(ResUtils.getInstance().getContext(),
            ContactsContract.Contacts.CONTENT_URI, PROJECTION, null, null,
            "UPPER(" + ContactsContract.Contacts.DISPLAY_NAME + ")ASC");
    Cursor cursor = cursorLoader.loadInBackground();
    // Loop for every contact in the phone
    if (cursor != null && cursor.getCount() > 0) {
        while (cursor.moveToNext()) {
            ArrayList<String> phoneNumbers = new ArrayList<>();
            String contact_id = cursor.getString(cursor.getColumnIndex(PHONE_CONTACT_ID));
            String   name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));
            String  timeStamp = cursor.getString(cursor.getColumnIndex(TIMESTAMP));
            cursorLoader = new CursorLoader( ResUtils.getInstance().getContext(), ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                    new String[]{EMAIL},ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[]{contact_id}, null);
            Cursor emailCur = cursorLoader.loadInBackground();
            while (emailCur.moveToNext()) {
                String email = emailCur.getString(emailCur.getColumnIndex(EMAIL));
                if (TmlyUtils.isValidEmail(email)) {
                    phoneNumbers.add(ContactUtils.MAIL_TAG + email);
                }
            }
            emailCur.close();
            if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER))) > 0) {
                cursorLoader = new CursorLoader( ResUtils.getInstance().getContext(),   ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        new String[]{NUMBER},ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{contact_id}, null);
                Cursor phones = cursorLoader.loadInBackground();
                while (phones.moveToNext()) {
                    String phoneNumber = phones.getString(phones.getColumnIndex(NUMBER));
                    phoneNumber = isValidMobileNumber(phoneNumber);
                    if (!phoneNumber.isEmpty() && !phoneNumbers.contains(ContactUtils.UPN_TAG + phoneNumber)) {
                        phoneNumbers.add(ContactUtils.UPN_TAG + phoneNumber);
                    }
                }
                phones.close();
            }
        }
        cursor.close();
    }

The code works fine but when you have thousands of contacts the app freeze during several seconds.

I'm using three cursor, the first one allow me to get all contacts in my phone

CursorLoader cursorLoader = new CursorLoader(ResUtils.getInstance().getContext(),
        ContactsContract.Contacts.CONTENT_URI, PROJECTION, null, null,
        "UPPER(" + ContactsContract.Contacts.DISPLAY_NAME + ")ASC");
Cursor cursor = cursorLoader.loadInBackground();

The second one loop for every email adress

 cursorLoader = new CursorLoader( ResUtils.getInstance().getContext(), ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                new String[]{EMAIL},ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[]{contact_id}, null);
        Cursor emailCur = cursorLoader.loadInBackground();

The third one loop for every phone

cursorLoader = new CursorLoader( ResUtils.getInstance().getContext(),   ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    new String[]{NUMBER},ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{contact_id}, null);
            Cursor phones = cursorLoader.loadInBackground();

I need to use the second and the third one If I'm not using it I can't get all phones and email for every contacts, because one contact can have several phones and email address

I try to use CursorLoader for speed up, but it's not sufficient, is it possible to get rid of the second and the third cursor ?

EDIT : I forgot to say that all the query is already inside a Retrofit call


问:
Difference between Casting and Parsing
I have been working on some code for a while. for now i have just used the keywords as-is without actually understanding them. So here is my question

What is the difference between Casting and Parsing?

UserAdapter.GetIdAndUserTypeByEmailAndPassword(Email, Password).Rows[0]["UserType"] as String--> is this Casting or parsing?

(String) UserAdapter.GetIdAndUserTypeByEmailAndPassword(Email, Password).Rows[0]["UserType"]
-->is this Casting or parsing?

UserAdapter.GetIdAndUserTypeByEmailAndPassword(Email, Password).Rows[0]["UserType"].ToString()

What is the difference bewtween x.ToString() and (String) x?

答:
What is the difference between Casting and Parsing?

Those are unrelated.

Casting is changing the type of the variable.

Parsing is 'examining' the string and assigning its logical value to some variable.

(ADDITION: Well, they are related in a sense, because from far far away both can serve to 'convert' data, however, data is really converted ONLY in case of parsing)

UserAdapter.GetIdAndUserTypeByEmailAndPassword(Email, Password).Rows[0]["UserType"] as String

is this Casting or parsing?

This is special kind of casting that will not fail if types aren't convertible (look here), but will get you null.

(String) UserAdapter.GetIdAndUserTypeByEmailAndPassword(Email, Password).Rows[0]["UserType"]

is this Casting or parsing?

This again is casting, but will throw an exception if expression isn't of type string.

What is the difference bewtween x.ToString() and (String) x?

x.ToString() will try to call ToString() on the object x.

(String) x will try to cast x to string, and will fail if x isn't string.

Title: Difference between Casting and Parsing


问:
Override the style in one component A when the component B is present on the view - Angular
I have two components on same level:

```<code><app-parent>
    <app-component-a></app-component-a>
    <app-component-b></app-component-b>
</app-parent>
</code>```

The Component-A:

Has the below styles:

```<code>:host {
    .container {
       height: 10rem;
     }
}
</code>```

But I want to change the height of the container of the component-a, when the component-b is present on the view. So let's say the componen-b is hidden and the default height from above can be used, but when component-b is visible the style below should override the height given above.

```<code>height: 2rem;
</code>```

Any suggestions on how to achieve this.
I have tried using the below on component-b but it doesn't help:

```<code>:host-context(.container) {
 height: 2rem;
}
</code>```

Have updated the code to make this work if there is a [ngClass] added to the code:

```<code><div class="container" [ngClass]="{'area-height': showArea}">
</code>```

Adding the Stackblitz code for easy understanding

Now I want to see if there is a way if we can connect the boolean value from the other component?
Added the random boolean generator, for now, to show/hide the component-b

答:
Here is my stackblitz sample

https://stackblitz.com/edit/angular-components-styles-override-78a9ni

Actually all you need is to apply some class based on some compB property

Body:
I have two components on same level:

<app-parent>
    <app-component-a></app-component-a>
    <app-component-b></app-component-b>
</app-parent>

The Component-A:

Has the below styles:

:host {
    .container {
       height: 10rem;
     }
}

But I want to change the height of the container of the component-a, when the component-b is present on the view. So let's say the componen-b is hidden and the default height from above can be used, but when component-b is visible the style below should override the height given above.

height: 2rem;

Any suggestions on how to achieve this.
I have tried using the below on component-b but it doesn't help:

:host-context(.container) {
 height: 2rem;
}

Have updated the code to make this work if there is a [ngClass] added to the code:

Adding the Stackblitz code for easy understanding

Now I want to see if there is a way if we can connect the boolean value from the other component?
Added the random boolean generator, for now, to show/hide the component-b


问:
simplest way to send an object with Tcpclinet c#
im new to c# and i was wondering , what is the simplest way to send an object using tcpClient , itried the following code but it throws a wierd error
client code :

```<code>TcpClient client = new TcpClient(ip, port);
StreamWriter writer = new StreamWriter(client.GetStream());
NetworkStream strm = client.GetStream();
BinaryFormatter formatter = new BinaryFormatter();
Transaction tx = new transaction();

string msg = string.Empty;

msg = "transaction";
writer.WriteLine(msg);
writer.Flush();

formatter.Serialize(strm,tx);
</code>```

and on the receiving end

Server Code :

```<code>while(true){
TcpClient client = server.AcceptTcpClient();
IFormatter formatter = new BinaryFormatter();
NetworkStream strm = client.GetStream();
StreamReader reader = new StreamReader(client.GetStream());
string msg = string.Empty;
while (!((msg = reader.ReadLine()).Equals("exit"))){

Transaction tx = (Transaction)formatter.Deserialize(strm);

}
</code>```

it produces this error on the server

```<code>input stream is not a valid ibinary format intital content is :0c-02-00-00 .....
</code>```

so can someone please help me or if there another simple and clean way of sending objects using tcpclient ?

答:
There are a lot of reasons not to use BinaryFormatter. If this was me (and I'm biased in this), I would switch to something like protobuf-net, which doesn't have the same concerns as BinaryFormatter, but: it does require some tweaks to your types - usually annotating them with some attributes to help the library, for example:

public class Transaction {
    public int Id {get;set;}
    public string Name {get;set;}
}
```

<p>might become</p>

<pre class="lang-cs prettyprint-override"><code>[ProtoContract]
public class Transaction {
    [ProtoMember(1)]
    public int Id {get;set;}
    [ProtoMember(2)]
    public string Name {get;set;}
}
</code>```

After that, the code should be simply:

Serializer.Serialize(strm, tx); // this is ProtoBuf.Serializer
// and now close the "send" pipe; fine to leave the "receive" pipe, though
```

<p>and</p>

<pre class="lang-cs prettyprint-override"><code>Serializer.Deserialize<Transaction>(strm); // again, ProtoBuf.Serializer
</code>```

However! There's something slightly odd in play, as as far as I can see, the code shown in the question should work, unless something odd is happening.

Note: if you are sending multiple payloads (i.e. you need to partition it into frames), or if you don't want to have to worry about closing the send pipe, then:

Serializer.SerializeWithLengthPrefix(strm, tx, PrefixStyle.Base128);
```

<p>and</p>

<pre class="lang-cs prettyprint-override"><code>Serializer.DeserializeWithLengthPrefix<Transaction>(strm, PrefixStyle.Base128);
</code>```

Body:
im new to c# and i was wondering , what is the simplest way to send an object using tcpClient , itried the following code but it throws a wierd error
client code :

TcpClient client = new TcpClient(ip, port);
StreamWriter writer = new StreamWriter(client.GetStream());
NetworkStream strm = client.GetStream();
BinaryFormatter formatter = new BinaryFormatter();
Transaction tx = new transaction();

string msg = string.Empty;

msg = "transaction";
writer.WriteLine(msg);
writer.Flush();

formatter.Serialize(strm,tx);

and on the receiving end

Server Code :

while(true){
TcpClient client = server.AcceptTcpClient();
IFormatter formatter = new BinaryFormatter();
NetworkStream strm = client.GetStream();
StreamReader reader = new StreamReader(client.GetStream());
string msg = string.Empty;
while (!((msg = reader.ReadLine()).Equals("exit"))){

Transaction tx = (Transaction)formatter.Deserialize(strm);

}

it produces this error on the server

input stream is not a valid ibinary format intital content is :0c-02-00-00 .....

so can someone please help me or if there another simple and clean way of sending objects using tcpclient ?

Body:
There are a lot of reasons not to use BinaryFormatter. If this was me (and I'm biased in this), I would switch to something like protobuf-net, which doesn't have the same concerns as BinaryFormatter, but: it does require some tweaks to your types - usually annotating them with some attributes to help the library, for example:

public class Transaction {
    public int Id {get;set;}
    public string Name {get;set;}
}

might become

[ProtoContract]
public class Transaction {
    [ProtoMember(1)]
    public int Id {get;set;}
    [ProtoMember(2)]
    public string Name {get;set;}
}

After that, the code should be simply:

Serializer.Serialize(strm, tx); // this is ProtoBuf.Serializer
// and now close the "send" pipe; fine to leave the "receive" pipe, though

and

Serializer.Deserialize<Transaction>(strm); // again, ProtoBuf.Serializer

However! There's something slightly odd in play, as as far as I can see, the code shown in the question should work, unless something odd is happening.

Note: if you are sending multiple payloads (i.e. you need to partition it into frames), or if you don't want to have to worry about closing the send pipe, then:

Serializer.SerializeWithLengthPrefix(strm, tx, PrefixStyle.Base128);

and

Serializer.DeserializeWithLengthPrefix<Transaction>(strm, PrefixStyle.Base128);


问:
Getting back 401 from Dynamics 365 despite being issued valid token
I am attempting to rewrite a client app that currently connects to Dynamics 365 using JavaScript

```<code>let URL = "https://<company-name>.operations.dynamics.com/data/FinancialDimensionValues?cross-company=true";
let  body = '';
var headers = {'Content-Type':'application/json'};
let response = ai.https.authorizedRequest(URL, 'GET', body, headers);
</code>```

Currently this JavaScript application works and gets back JSON data. I am attempting to rewrite this application using C#. I am first starting with Postman to make sure I have all the authentication steps in place before moving on the writing the C# code.

Using Postman I am able to successfully obtain a JWT token using the "Client Credentials" flow where I pass the Client ID and the Client Secret to the Access Token Request URL. However, when trying to access an API endpoint within Dynamics 365 I receive back an HTTP 401 even though I am passing the JWT access token properly.

Here is the Access Token Request URL:

https://login.microsoftonline.com/722b0db7-9629-4304-92a0-dfb4a1debe62/oauth2/token?resource=https://<company-domain-here>.dynamics.com

I am thinking that I must be authenticating properly or I would not get back a valid access token. Also since the JavaScript application already in place works without issue I am assuming that Dynamics 365 is provisioned properly to allow API access.

What I am trying to figure out is what I might be doing wrong within Postman that results in my receiving a 401? What could be different between the working JavaScript request and what I am sending via Postman?

答:
Issue is finally solved.
As mentioned follow the documentation mentioned.

If you face 401 Error, here is the last trick.

In postman Under Authorization--> Add authorization data to--> select Request Headers.

Now fire the query you shall have the 200 ok.

Ref Article which helped me figure it out.

Body:
I am attempting to rewrite a client app that currently connects to Dynamics 365 using JavaScript

let URL = "https://<company-name>.operations.dynamics.com/data/FinancialDimensionValues?cross-company=true";
let  body = '';
var headers = {'Content-Type':'application/json'};
let response = ai.https.authorizedRequest(URL, 'GET', body, headers);

Currently this JavaScript application works and gets back JSON data. I am attempting to rewrite this application using C#. I am first starting with Postman to make sure I have all the authentication steps in place before moving on the writing the C# code.

Using Postman I am able to successfully obtain a JWT token using the "Client Credentials" flow where I pass the Client ID and the Client Secret to the Access Token Request URL. However, when trying to access an API endpoint within Dynamics 365 I receive back an HTTP 401 even though I am passing the JWT access token properly.

Here is the Access Token Request URL:

https://login.microsoftonline.com/722b0db7-9629-4304-92a0-dfb4a1debe62/oauth2/token?resource=https://<company-domain-here>.dynamics.com

I am thinking that I must be authenticating properly or I would not get back a valid access token. Also since the JavaScript application already in place works without issue I am assuming that Dynamics 365 is provisioned properly to allow API access.

What I am trying to figure out is what I might be doing wrong within Postman that results in my receiving a 401? What could be different between the working JavaScript request and what I am sending via Postman?


问:
passing JSON from ASIHTTPRequest to django
I've exhausted other threads, so I'm posting this question here.  Please pardon any newbie mistakes I've made along the way.  I've been reading a lot, and I think I'm getting confused.

The Goal:
I'm trying to pass data from a form in objective-c to my django web service.  In an effort to assist with this, I've employed the ASIHTTPRequest class to facilitate information transfer.  Once sent to the web service, I'd like to save that data to my sqlite3 database.

Procedure:
On the Objective-C side:
I've stored the inputted form data and their respective keys in an NSDictionary, like this:

```<code>NSDictionary *personInfo = [NSDictionary dictionaryWithObjectsAndKeys:firstName.text, @"fName", middleName.text, @"mName", lastName.text, @"lName", nil];
</code>```

I've added it to my ASIHTTPRequest in a different class by using a delegate.  I've made the NSDictionary the same as above in the code block below for simplicity, like so:

```<code>NSString *jsonPerson = [personInfo JSONRepresentation];
[request addRequestHeader: @"Content-Type" value:@"application/json; charset=utf-8"];
[request appendPostData:[jsonPerson dataUsingEncoding:NSUTF8StringEncoding]];
[request setRequestMethod:@"POST"];
[request startAsynchronous];
</code>```

And a NSLog shows the string I'm passing to look like this, which validates at least in JSONLint

```<code>{"mName":"Arthur","lName":"Smith","fName":"Bob"}
</code>```

Because I'm seeing what appears to be valid JSON coming from my ASIHTTPRequest, and actions are running from requestfinished: rather than requestfailed:, I'm making the assumption that the problem more than likely isn't on the Objective-C side, but rather on the django side.

Here's what I've tried so far:

```<code>json.loads(request.POST)
>>expected string or buffer

json.loads('request.POST')
>>no JSON object to decode

json.loads(request.raw_post_data)
>>mNamelNamefName

incoming = request.POST
>>{"mName":"Arthur","lName":"Smith","fName":"Bob"}

incoming = request.POST
onlyValues = incoming.iterlists()
>>(u'{"mName":"Arthur","lName":"Smith","fName":"Bob"}', [u''])
</code>```

...and a smattering of other seemingly far-fetched variations.  I've kept a log, and can elaborate.  The only hope I've been able to find is in the last example; it looks like it's treating the entire string as the key, rather than breaking up each dict object and key as I would have expected.

I realize this is terribly elementary and I don't normally ask, but this problem has me particularly stumped.  I do also remember reading somewhere that python won't recognize the double-quotes around each object and key, that to get it to something django likes, each should be surrounded by single-quotes.  I just don't have any idea how to get them that way.

Thanks!

答:
This might be a little cumbersome but you may try some simple regexp in objective c just to see if that is really the case

```<code>NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\"" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *json = [regex stringByReplacingMatchesInString:jsonPerson options:0 range:NSMakeRange(0, [jsonPerson length]) withTemplate:@"'"];
</code>```

There might be some errors because I didn't run the code.

Body:
I've exhausted other threads, so I'm posting this question here.  Please pardon any newbie mistakes I've made along the way.  I've been reading a lot, and I think I'm getting confused.

The Goal:
I'm trying to pass data from a form in objective-c to my django web service.  In an effort to assist with this, I've employed the ASIHTTPRequest class to facilitate information transfer.  Once sent to the web service, I'd like to save that data to my sqlite3 database.

Procedure:
On the Objective-C side:
I've stored the inputted form data and their respective keys in an NSDictionary, like this:

NSDictionary *personInfo = [NSDictionary dictionaryWithObjectsAndKeys:firstName.text, @"fName", middleName.text, @"mName", lastName.text, @"lName", nil];

I've added it to my ASIHTTPRequest in a different class by using a delegate.  I've made the NSDictionary the same as above in the code block below for simplicity, like so:

NSString *jsonPerson = [personInfo JSONRepresentation];
[request addRequestHeader: @"Content-Type" value:@"application/json; charset=utf-8"];
[request appendPostData:[jsonPerson dataUsingEncoding:NSUTF8StringEncoding]];
[request setRequestMethod:@"POST"];
[request startAsynchronous];

And a NSLog shows the string I'm passing to look like this, which validates at least in JSONLint

{"mName":"Arthur","lName":"Smith","fName":"Bob"}

Because I'm seeing what appears to be valid JSON coming from my ASIHTTPRequest, and actions are running from requestfinished: rather than requestfailed:, I'm making the assumption that the problem more than likely isn't on the Objective-C side, but rather on the django side.

Here's what I've tried so far:

json.loads(request.POST)
>>expected string or buffer

json.loads('request.POST')
>>no JSON object to decode

json.loads(request.raw_post_data)
>>mNamelNamefName

incoming = request.POST
>>{"mName":"Arthur","lName":"Smith","fName":"Bob"}

incoming = request.POST
onlyValues = incoming.iterlists()
>>(u'{"mName":"Arthur","lName":"Smith","fName":"Bob"}', [u''])

...and a smattering of other seemingly far-fetched variations.  I've kept a log, and can elaborate.  The only hope I've been able to find is in the last example; it looks like it's treating the entire string as the key, rather than breaking up each dict object and key as I would have expected.

I realize this is terribly elementary and I don't normally ask, but this problem has me particularly stumped.  I do also remember reading somewhere that python won't recognize the double-quotes around each object and key, that to get it to something django likes, each should be surrounded by single-quotes.  I just don't have any idea how to get them that way.

Thanks!

Body:
This might be a little cumbersome but you may try some simple regexp in objective c just to see if that is really the case

NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\"" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *json = [regex stringByReplacingMatchesInString:jsonPerson options:0 range:NSMakeRange(0, [jsonPerson length]) withTemplate:@"'"];

There might be some errors because I didn't run the code.


问:
Using a dictionary to plot graph in D3.js
I have a dictionary of the form:

```<code>[('2019-10', 273), ('2019-11', 299), ('2019-12', 244), ('2020-01', 231), ('2020-02', 232)]
</code>```

I want to plot this dictionary as a graph, with the dates as the x axis and the corresponding values as the bars. How can I achieve this? I am new to D3, hence have very little knowledge of it. Any help is appreciated!

答:
Assuming that your data is in the format:

```<code>[{'2019-10': 273}, {'2019-11': 299}, {'2019-12': 244}, {'2020-01': 231}, {'2020-02': 232}]
</code>```

You could first apply some mapping function to transform this into a more convenient format and go from there, e.g.:

var height = 200;
var width = 400;

var data = [{'2019-10': 273}, {'2019-11': 299}, {'2019-12': 244}, {'2020-01': 231}, {'2020-02': 232}];

var mapped = data.map(d => {
  return {
    date: Object.keys(d)[0],
    count: d[Object.keys(d)[0]]
  }
});

var x = d3.scale.ordinal().rangeRoundBands([0, width], .05);
var y = d3.scale.linear().range([height, 0]);

x.domain(mapped.map(d => d.date));
y.domain([0, d3.max(mapped, d => d.count)]);

var svg = d3.select("#simple").append("svg")
    .attr("width", width)
    .attr("height", height);

svg.selectAll("bar")
    .data(mapped)
    .enter().append("rect")
      .style("fill", "steelblue")
      .attr("x", d => x(d.date))
      .attr("width", x.rangeBand())
      .attr("y", d => y(d.count))
      .attr("height", d => height - y(d.count));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
<div id="simple"></div></code>```

Body:
I have a dictionary of the form:

[('2019-10', 273), ('2019-11', 299), ('2019-12', 244), ('2020-01', 231), ('2020-02', 232)]

I want to plot this dictionary as a graph, with the dates as the x axis and the corresponding values as the bars. How can I achieve this? I am new to D3, hence have very little knowledge of it. Any help is appreciated!

Body:
Assuming that your data is in the format:

[{'2019-10': 273}, {'2019-11': 299}, {'2019-12': 244}, {'2020-01': 231}, {'2020-02': 232}]

You could first apply some mapping function to transform this into a more convenient format and go from there, e.g.:

var height = 200;
var width = 400;

var data = [{'2019-10': 273}, {'2019-11': 299}, {'2019-12': 244}, {'2020-01': 231}, {'2020-02': 232}];

var mapped = data.map(d => {
  return {
    date: Object.keys(d)[0],
    count: d[Object.keys(d)[0]]
  }
});

var x = d3.scale.ordinal().rangeRoundBands([0, width], .05);
var y = d3.scale.linear().range([height, 0]);

x.domain(mapped.map(d => d.date));
y.domain([0, d3.max(mapped, d => d.count)]);

var svg = d3.select("#simple").append("svg")
    .attr("width", width)
    .attr("height", height);

svg.selectAll("bar")
    .data(mapped)
    .enter().append("rect")
      .style("fill", "steelblue")
      .attr("x", d => x(d.date))
      .attr("width", x.rangeBand())
      .attr("y", d => y(d.count))
      .attr("height", d => height - y(d.count));

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
<div id="simple"></div>