问:
How to show data into list in Android
In my application I want show some data in recyclerView and i get this data from server.

I use Retrofit for send or get requests from android to server.

When run the application, it's showing response.body().getData().size() is 0, but in PostMan I see the following data:

I write below code for get data :

```<code>private void getComments() {
    CommentSendData sendData = new CommentSendData();
    sendData.setEntityID(7);
    sendData.setReviewType(5);
    sendData.setReviewUserType(0);
    sendData.setEntityID(newsID);
    sendData.setCelebrityID(0);
    sendData.setPageIndex(0);
    sendData.setPageSize(10);

    InterfaceApi api = ApiClient.getClient().create(InterfaceApi.class);
    Call<CommentResponse> call = api.getComments(sendData);

    call.enqueue(new Callback<CommentResponse>() {
        @Override
        public void onResponse(Call<CommentResponse> call, Response<CommentResponse> response) {
            Toast.makeText(NewsDetailActivity.this, "" + response.body().getData().size(), Toast.LENGTH_SHORT).show();
            Toast.makeText(NewsDetailActivity.this, "" + call.isExecuted(), Toast.LENGTH_SHORT).show();
        }

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

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

When show this Toast :Toast.makeText(NewsDetailActivity.this, "" + call.isExecuted(), Toast.LENGTH_SHORT).show(); show me true in toast.

and when show this Toast : Toast.makeText(NewsDetailActivity.this, "" + response.body().getData().size(), Toast.LENGTH_SHORT).show(); , show me 0 in toast .

My Adapter codes:

```<code>public class CommentsListAdapter extends RecyclerView.Adapter<CommentsListAdapter.ViewHolder> {

    private Context context;
    private List<CommentData> model;

    public CommentsListAdapter(Context context, List<CommentData> model) {
        this.context = context;
        this.model = model;
    }

    @Override
    public CommentsListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_comment, parent, false);

        return new CommentsListAdapter.ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final CommentsListAdapter.ViewHolder holder, final int position) {

        holder.row_commentNameTxt.setText(Html.fromHtml(model.get(position).getOwner().getName()));
        holder.row_commentCommentTxt.setText(Html.fromHtml(model.get(position).getText()));
        Glide.with(context)
                .load(model.get(position).getOwner().getImageUrl())
                .placeholder(R.drawable.default_image)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .listener(new RequestListener<String, GlideDrawable>() {
                    @Override
                    public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable resource, String model,
                                                   Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                        return false;
                    }
                })
                .into(holder.row_commentProfileImage);
        holder.row_commentLikeTxt.setText(model.get(position).getLikeCount() + "");
        holder.row_commentReplayTxt.setText(model.get(position).getRepliesCount() + "");
        holder.row_commentDateTxt.setText(model.get(position).getSubmitDate() + " " + model.get(position).getSubmitTime());
    }

    @Override
    public int getItemCount() {
        return model.size();
    }

    public void addNewItem(List<CommentData> newContent) {
        int start = this.model.size();
        int end = newContent.size();
        model.addAll(newContent);
        notifyDataSetChanged();
    }

    public void clear() {
        model.clear();
        notifyDataSetChanged();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        private CircleImageView row_commentProfileImage;
        private TextView row_commentNameTxt, row_commentCommentTxt, row_commentLikeTxt, row_commentReplayTxt, row_commentDateTxt;

        public ViewHolder(View itemView) {
            super(itemView);

            row_commentProfileImage = (CircleImageView) itemView.findViewById(R.id.row_commentProfileImage);
            row_commentNameTxt = (TextView) itemView.findViewById(R.id.row_commentNameTxt);
            row_commentCommentTxt = (TextView) itemView.findViewById(R.id.row_commentCommentTxt);
            row_commentLikeTxt = (TextView) itemView.findViewById(R.id.row_commentLikeTxt);
            row_commentReplayTxt = (TextView) itemView.findViewById(R.id.row_commentReplayTxt);
            row_commentDateTxt = (TextView) itemView.findViewById(R.id.row_commentDateTxt);

        }
    }
}
</code>```

CommentResponse code:

```<code>public class CommentResponse {
    @SerializedName("statusCode")
    @Expose
    private Integer statusCode;
    @SerializedName("statusMessage")
    @Expose
    private String statusMessage;
    @SerializedName("data")
    @Expose
    private List<CommentData> data = null;

    public Integer getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(Integer statusCode) {
        this.statusCode = statusCode;
    }

    public String getStatusMessage() {
        return statusMessage;
    }

    public void setStatusMessage(String statusMessage) {
        this.statusMessage = statusMessage;
    }

    public List<CommentData> getData() {
        return data;
    }

    public void setData(List<CommentData> data) {
        this.data = data;
    }
}
</code>```

CommentData model :

```<code>public class CommentData {
    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("text")
    @Expose
    private String text;
    @SerializedName("likeCount")
    @Expose
    private Integer likeCount;
    @SerializedName("repliesCount")
    @Expose
    private Integer repliesCount;
    @SerializedName("submitDate")
    @Expose
    private String submitDate;
    @SerializedName("submitTime")
    @Expose
    private String submitTime;
    @SerializedName("owner")
    @Expose
    private CommentOwner owner;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public Integer getLikeCount() {
        return likeCount;
    }

    public void setLikeCount(Integer likeCount) {
        this.likeCount = likeCount;
    }

    public Integer getRepliesCount() {
        return repliesCount;
    }

    public void setRepliesCount(Integer repliesCount) {
        this.repliesCount = repliesCount;
    }

    public String getSubmitDate() {
        return submitDate;
    }

    public void setSubmitDate(String submitDate) {
        this.submitDate = submitDate;
    }

    public String getSubmitTime() {
        return submitTime;
    }

    public void setSubmitTime(String submitTime) {
        this.submitTime = submitTime;
    }

    public CommentOwner getOwner() {
        return owner;
    }

    public void setOwner(CommentOwner owner) {
        this.owner = owner;
    }
}
</code>```

Why when run application show me 0 data but in PostMan show data ?!

答:
There could be a few reasons for that

1.) There might be some error while typing the base or secondary URL. Please cross check them. And Check another thing that "/" came after base URL so no need to use it before secondary URL.

2.) Please cross check the the payloads as they must be accurate. If you don't know how to create accurate payloads then follow this spinet.

```<code>private JsonObject makeJsonObjectPayload() {

        JsonObject requestBean = new JsonObject();
    requestBean.addProperty("key", value);
    requestBean.addProperty("key", value);
    requestBean.addProperty("key", value);
    requestBean.addProperty("key", value);
    requestBean.addProperty("key", value);

    return requestBean;
}
</code>```

3.) In case you haven't noticed you are not updating the data in the recycler view. So update data by using addNewItem(List<CommentData> newContent) method.

Title: How to show data into list in Android

Body:
In my application I want show some data in recyclerView and i get this data from server.

I use Retrofit for send or get requests from android to server.

When run the application, it's showing response.body().getData().size() is 0, but in PostMan I see the following data:

I write below code for get data :

private void getComments() {
    CommentSendData sendData = new CommentSendData();
    sendData.setEntityID(7);
    sendData.setReviewType(5);
    sendData.setReviewUserType(0);
    sendData.setEntityID(newsID);
    sendData.setCelebrityID(0);
    sendData.setPageIndex(0);
    sendData.setPageSize(10);

    InterfaceApi api = ApiClient.getClient().create(InterfaceApi.class);
    Call<CommentResponse> call = api.getComments(sendData);

    call.enqueue(new Callback<CommentResponse>() {
        @Override
        public void onResponse(Call<CommentResponse> call, Response<CommentResponse> response) {
            Toast.makeText(NewsDetailActivity.this, "" + response.body().getData().size(), Toast.LENGTH_SHORT).show();
            Toast.makeText(NewsDetailActivity.this, "" + call.isExecuted(), Toast.LENGTH_SHORT).show();
        }

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

        }
    });
}

When show this Toast :Toast.makeText(NewsDetailActivity.this, "" + call.isExecuted(), Toast.LENGTH_SHORT).show(); show me true in toast.

and when show this Toast : Toast.makeText(NewsDetailActivity.this, "" + response.body().getData().size(), Toast.LENGTH_SHORT).show(); , show me 0 in toast .

My Adapter codes:

public class CommentsListAdapter extends RecyclerView.Adapter<CommentsListAdapter.ViewHolder> {

    private Context context;
    private List<CommentData> model;

    public CommentsListAdapter(Context context, List<CommentData> model) {
        this.context = context;
        this.model = model;
    }

    @Override
    public CommentsListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_comment, parent, false);

        return new CommentsListAdapter.ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final CommentsListAdapter.ViewHolder holder, final int position) {

        holder.row_commentNameTxt.setText(Html.fromHtml(model.get(position).getOwner().getName()));
        holder.row_commentCommentTxt.setText(Html.fromHtml(model.get(position).getText()));
        Glide.with(context)
                .load(model.get(position).getOwner().getImageUrl())
                .placeholder(R.drawable.default_image)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .listener(new RequestListener<String, GlideDrawable>() {
                    @Override
                    public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable resource, String model,
                                                   Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                        return false;
                    }
                })
                .into(holder.row_commentProfileImage);
        holder.row_commentLikeTxt.setText(model.get(position).getLikeCount() + "");
        holder.row_commentReplayTxt.setText(model.get(position).getRepliesCount() + "");
        holder.row_commentDateTxt.setText(model.get(position).getSubmitDate() + " " + model.get(position).getSubmitTime());
    }

    @Override
    public int getItemCount() {
        return model.size();
    }

    public void addNewItem(List<CommentData> newContent) {
        int start = this.model.size();
        int end = newContent.size();
        model.addAll(newContent);
        notifyDataSetChanged();
    }

    public void clear() {
        model.clear();
        notifyDataSetChanged();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        private CircleImageView row_commentProfileImage;
        private TextView row_commentNameTxt, row_commentCommentTxt, row_commentLikeTxt, row_commentReplayTxt, row_commentDateTxt;

        public ViewHolder(View itemView) {
            super(itemView);

            row_commentProfileImage = (CircleImageView) itemView.findViewById(R.id.row_commentProfileImage);
            row_commentNameTxt = (TextView) itemView.findViewById(R.id.row_commentNameTxt);
            row_commentCommentTxt = (TextView) itemView.findViewById(R.id.row_commentCommentTxt);
            row_commentLikeTxt = (TextView) itemView.findViewById(R.id.row_commentLikeTxt);
            row_commentReplayTxt = (TextView) itemView.findViewById(R.id.row_commentReplayTxt);
            row_commentDateTxt = (TextView) itemView.findViewById(R.id.row_commentDateTxt);

        }
    }
}

CommentResponse code:

public class CommentResponse {
    @SerializedName("statusCode")
    @Expose
    private Integer statusCode;
    @SerializedName("statusMessage")
    @Expose
    private String statusMessage;
    @SerializedName("data")
    @Expose
    private List<CommentData> data = null;

    public Integer getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(Integer statusCode) {
        this.statusCode = statusCode;
    }

    public String getStatusMessage() {
        return statusMessage;
    }

    public void setStatusMessage(String statusMessage) {
        this.statusMessage = statusMessage;
    }

    public List<CommentData> getData() {
        return data;
    }

    public void setData(List<CommentData> data) {
        this.data = data;
    }
}

CommentData model :

public class CommentData {
    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("text")
    @Expose
    private String text;
    @SerializedName("likeCount")
    @Expose
    private Integer likeCount;
    @SerializedName("repliesCount")
    @Expose
    private Integer repliesCount;
    @SerializedName("submitDate")
    @Expose
    private String submitDate;
    @SerializedName("submitTime")
    @Expose
    private String submitTime;
    @SerializedName("owner")
    @Expose
    private CommentOwner owner;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public Integer getLikeCount() {
        return likeCount;
    }

    public void setLikeCount(Integer likeCount) {
        this.likeCount = likeCount;
    }

    public Integer getRepliesCount() {
        return repliesCount;
    }

    public void setRepliesCount(Integer repliesCount) {
        this.repliesCount = repliesCount;
    }

    public String getSubmitDate() {
        return submitDate;
    }

    public void setSubmitDate(String submitDate) {
        this.submitDate = submitDate;
    }

    public String getSubmitTime() {
        return submitTime;
    }

    public void setSubmitTime(String submitTime) {
        this.submitTime = submitTime;
    }

    public CommentOwner getOwner() {
        return owner;
    }

    public void setOwner(CommentOwner owner) {
        this.owner = owner;
    }
}

Why when run application show me 0 data but in PostMan show data ?!

Body:
There could be a few reasons for that

1.) There might be some error while typing the base or secondary URL. Please cross check them. And Check another thing that "/" came after base URL so no need to use it before secondary URL.

2.) Please cross check the the payloads as they must be accurate. If you don't know how to create accurate payloads then follow this spinet.

private JsonObject makeJsonObjectPayload() {

        JsonObject requestBean = new JsonObject();
    requestBean.addProperty("key", value);
    requestBean.addProperty("key", value);
    requestBean.addProperty("key", value);
    requestBean.addProperty("key", value);
    requestBean.addProperty("key", value);

    return requestBean;
}

3.) In case you haven't noticed you are not updating the data in the recycler view. So update data by using addNewItem(List<CommentData> newContent) method.


来源: stackexchange

问:
Handle ajax call using angularjs
I want to perform additional operation before calling http request(Ajax GET and POST)

suppose i have following code:

```<code>function CallHTTP()
{

    $.ajax({
        url: '/abcd/abcd',
        type: 'POST',
        success: function () {
            alert("Success");
        },
        error: function (arg1, arg2, arg3) {
            alert("error");
        }

    });

}

$(document).ready(function () {
    CallHTTP();
});
</code>```

i want to handle above request using angularjs interceptor. is it possible ?

I tried following:

```<code> angular.module('app', [])
          .config(['$httpProvider', function ($httpProvider) {
              $httpProvider.interceptors.push(['$location', '$q', function ($location, $q) {
                  return {
                      'request': function (request) {
                          console.log("abcd");
                          return request;
                      },
                      'responseError': function (response) {
                          if (response.status === 401) {
                              console.log("abcd2");
                              // do stuff
                          }
                          console.log("abcd1");
                          // otherwise, default behaviour
                          return $q.reject(response);
                      }
                  };
              }]);
          }]);
</code>```

but above code doesn't execute when ajax call happens. how to achieve it ?

Thanks.

答: You are using jquery ajax call and your settings are in the angular interceptor. Use $http to make use of your angular settings.</p>

ContentLicense: CC BY-SA 3.0

Title: Handle ajax call using angularjs

Body:
I want to perform additional operation before calling http request(Ajax GET and POST)

suppose i have following code:

function CallHTTP()
{

    $.ajax({
        url: '/abcd/abcd',
        type: 'POST',
        success: function () {
            alert("Success");
        },
        error: function (arg1, arg2, arg3) {
            alert("error");
        }

    });

}

$(document).ready(function () {
    CallHTTP();
});

i want to handle above request using angularjs interceptor. is it possible ?

I tried following:

 angular.module('app', [])
          .config(['$httpProvider', function ($httpProvider) {
              $httpProvider.interceptors.push(['$location', '$q', function ($location, $q) {
                  return {
                      'request': function (request) {
                          console.log("abcd");
                          return request;
                      },
                      'responseError': function (response) {
                          if (response.status === 401) {
                              console.log("abcd2");
                              // do stuff
                          }
                          console.log("abcd1");
                          // otherwise, default behaviour
                          return $q.reject(response);
                      }
                  };
              }]);
          }]);

but above code doesn't execute when ajax call happens. how to achieve it ?

Thanks.


问:
assigning GET response to the scope variable
I have developed my application on simulated data like below .

```<code>$scope.products=[{serial:1,quantity:30,name:"aaa"},
                 {serial:2,quantity:10,name:"bbb"}];
</code>```

also i have prepared the rest resource which fetched data from database and available at http://localhost:8080/myrests/shop/productresource

can you please help me how can i assign this resource return results to the above $scope.products.

答:
if you want it asynchronously use promis

    //below code wrap inside a function

```<code>var deferred = $q.defer();
$http.get(URL)
.then(function(data, status, headers, config) {
    deferred.resolve(data);
    console.log("Success " + data);
},
function(data, status, headers, config) {
    deferred.reject(data);
    console.log("Failure " + status);
});
return deferred.promise;
</code>```

else simply use $http

```<code>$http.get("http://localhost:8080/myrests/shop/productresource")
.then(function(data, status, headers, config) {
    $scope.products = data;
},
function(data, status, headers, config) {
    console.log("Failure " + status);
});
</code>```

Body:
I have developed my application on simulated data like below .

$scope.products=[{serial:1,quantity:30,name:"aaa"},
                 {serial:2,quantity:10,name:"bbb"}];

also i have prepared the rest resource which fetched data from database and available at http://localhost:8080/myrests/shop/productresource

can you please help me how can i assign this resource return results to the above $scope.products.

Body:
if you want it asynchronously use promis

    //below code wrap inside a function

var deferred = $q.defer();
$http.get(URL)
.then(function(data, status, headers, config) {
    deferred.resolve(data);
    console.log("Success " + data);
},
function(data, status, headers, config) {
    deferred.reject(data);
    console.log("Failure " + status);
});
return deferred.promise;

else simply use $http

$http.get("http://localhost:8080/myrests/shop/productresource")
.then(function(data, status, headers, config) {
    $scope.products = data;
},
function(data, status, headers, config) {
    console.log("Failure " + status);
});


问:
Pinch to Zoom on ListBox on windows phone 7
I am trying to add pinch to zoom feature to a data bound ListBox. What is the most efficient way to do this? I have placed the ListBox inside a Grid control and made it scrollable.

This is my current code.

```<code>    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="10,0,10,10" Background="Black" >
        <ListBox Name="lstText" FontSize="24"  Foreground="White" SelectionMode="Single" Margin="10,0,10,10"  ScrollViewer.VerticalScrollBarVisibility="Visible"  >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel >
                        <TextBlock Text="{Binding Text}" TextWrapping="Wrap"></TextBlock>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
    <toolkit:GestureService.GestureListener>
        <toolkit:GestureListener
            Tap="GestureListener_Tap"
            PinchCompleted="GestureListener_PinchCompleted"
            Flick="GestureListener_Flick">

        </toolkit:GestureListener>
    </toolkit:GestureService.GestureListener>
</code>```

答:
Alex Yakhnin offers a solution for scrolling long text.

Creating Scrollable TextBlock for WP7. - Alex Yakhnin's Blog

You can wrap a TextBlock in a ScrollViewer which may be sufficient for your needs. If your text is long enough you will hit a variety of walls as the text gets larger in size. Alex's solution is a control which wraps a StackPanel in a ScrollViewer and adds TextBlocks to the StackPanel in manageable sections.

ContentLicense: CC BY-SA 2.5

Body:
I am trying to add pinch to zoom feature to a data bound ListBox. What is the most efficient way to do this? I have placed the ListBox inside a Grid control and made it scrollable.

This is my current code.

    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="10,0,10,10" Background="Black" >
        <ListBox Name="lstText" FontSize="24"  Foreground="White" SelectionMode="Single" Margin="10,0,10,10"  ScrollViewer.VerticalScrollBarVisibility="Visible"  >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel >
                        <TextBlock Text="{Binding Text}" TextWrapping="Wrap"></TextBlock>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
    <toolkit:GestureService.GestureListener>
        <toolkit:GestureListener
            Tap="GestureListener_Tap"
            PinchCompleted="GestureListener_PinchCompleted"
            Flick="GestureListener_Flick">

        </toolkit:GestureListener>
    </toolkit:GestureService.GestureListener>


问:
Angular4 How to know when a ViewChild has been reset
Here is the template of main.html :

```<code><button (click)="displayAndUseMyCustomComp()"></button>
<my-custom-comp *ngIf="isMyCustomCompDisplayed" #myCustomComp="myCustomComp"></my-custom-comp>
</code>```

and main.component.ts :

```<code>export class MainComponent {
  constructor() {}
  private isMyCustomCompDisplayed boolean = false
  @ViewChild('myCustomComp') myCustomComp: MyCustomComp

  displayAndUseMyCustomComp() {
     this.isMyCustomCompDisplayed = true
     console.log(this.myCustomComp) // prints undefined
     setTimeout(() => {
       console.log(this.myCustomComp) // prints {object}
     })
  }

}
</code>```

What's happening is that my template isn't yet refreshed after I set isMyCustomCompDisplayed  to true. However, if I use a setTimeout, myCustomComp gets updated and my issue goes away. It is midly hacky, and I was wondering what was the correct way of doing what I am trying to.

答:
Here is why it's undefined after you call displayAndUseMyCustomComp

Angular updates ViewChild query list as part of change detection. When Angular was running initial change detection the isMyCustomCompDisplayed was false and so myCustomComp was hidden. The myCustomComp was set to undefined.

After you make a click the function displayAndUseMyCustomComp is executed and isMyCustomCompDisplayed is set to true. Angular requires a change detection cycle to update the myCustomComp query list. However, you try to read the value immediately and so it's still undefined. You need to wait for another change detection cycle for Angular to update the query list.

Here is why it's working if you wrap the call into setTimeout

If you try to read the myCustomComp inside the timeout, Angular has a chance to run change detection between the update to isMyCustomCompDisplayed and the time you read myCustomComp.

Here is what happens during that change detection cycle

When Angular runs change detection for the MainComponent it detects that isMyCustomCompDisplayed is updated. So it goes and updates bindings for ngIf. It in turn reacts to this change and creates and embedded view with the myCustomComp and attaches it to the MainComponent component:

```<code>  @Input()
  set ngIf(condition: any) {
      if (condidition) {
          this._viewContainer.createEmbeddedView(this._thenTemplateRef, this._context);
</code>```

When is the updated query list available

If you're looking for synchronous solution, it will be available inside all lifecycle hooks that are executed after the view children query list is updated during the next change detection cycle that follows execution of displayAndUseMyCustomComp. At the moment these are ngAfterViewInit and ngAfterViewChecked. Since the former is called only once, we need to use ngAfterViewChecked:

```<code>  ngAfterViewChecked() {
    if(this.isMyCustomCompDisplayed) {
        console.log(this.myCustomComp) // prints {object}
    }
  }

  displayAndUseMyCustomComp() {
     this.isMyCustomCompDisplayed = true
  }
</code>```

Another synchronous solution suggested by @ThinkingMedia is also good. You can use ViewChildren instead of ViewChild and subscribe to changes (btw you don't template reference):

```<code>  @ViewChildren(myCustomComp) as: QueryList<myCustomComp>;

  ngAfterViewInit() {
    this.myCustomComp.changes.subscribe(() => {
      console.log(this.myCustomComp.first); // prints {object}
    });
  }
</code>```

The callback will be triggered during next digest when Angular will be updating query list (slightly earlier than ngAfterViewChecked).

If you're looking for asynchronous solution, use setTimeout as you do it. The Promise.resolve(null).then(()=>{ console.log(this.myCustomComp) }) (microtask) solution won't work because it will be executed after the current stack but before the change detection.

For more information on change detection read

Everything you need to know about change detection in Angular.

Body:
Here is the template of main.html :

<button (click)="displayAndUseMyCustomComp()"></button>
<my-custom-comp *ngIf="isMyCustomCompDisplayed" #myCustomComp="myCustomComp"></my-custom-comp>

and main.component.ts :

export class MainComponent {
  constructor() {}
  private isMyCustomCompDisplayed boolean = false
  @ViewChild('myCustomComp') myCustomComp: MyCustomComp

  displayAndUseMyCustomComp() {
     this.isMyCustomCompDisplayed = true
     console.log(this.myCustomComp) // prints undefined
     setTimeout(() => {
       console.log(this.myCustomComp) // prints {object}
     })
  }

}

What's happening is that my template isn't yet refreshed after I set isMyCustomCompDisplayed  to true. However, if I use a setTimeout, myCustomComp gets updated and my issue goes away. It is midly hacky, and I was wondering what was the correct way of doing what I am trying to.

Body:
Here is why it's undefined after you call displayAndUseMyCustomComp

Angular updates ViewChild query list as part of change detection. When Angular was running initial change detection the isMyCustomCompDisplayed was false and so myCustomComp was hidden. The myCustomComp was set to undefined.

After you make a click the function displayAndUseMyCustomComp is executed and isMyCustomCompDisplayed is set to true. Angular requires a change detection cycle to update the myCustomComp query list. However, you try to read the value immediately and so it's still undefined. You need to wait for another change detection cycle for Angular to update the query list.

Here is why it's working if you wrap the call into setTimeout

If you try to read the myCustomComp inside the timeout, Angular has a chance to run change detection between the update to isMyCustomCompDisplayed and the time you read myCustomComp.

Here is what happens during that change detection cycle

When Angular runs change detection for the MainComponent it detects that isMyCustomCompDisplayed is updated. So it goes and updates bindings for ngIf. It in turn reacts to this change and creates and embedded view with the myCustomComp and attaches it to the MainComponent component:

  @Input()
  set ngIf(condition: any) {
      if (condidition) {
          this._viewContainer.createEmbeddedView(this._thenTemplateRef, this._context);

When is the updated query list available

If you're looking for synchronous solution, it will be available inside all lifecycle hooks that are executed after the view children query list is updated during the next change detection cycle that follows execution of displayAndUseMyCustomComp. At the moment these are ngAfterViewInit and ngAfterViewChecked. Since the former is called only once, we need to use ngAfterViewChecked:

  ngAfterViewChecked() {
    if(this.isMyCustomCompDisplayed) {
        console.log(this.myCustomComp) // prints {object}
    }
  }

  displayAndUseMyCustomComp() {
     this.isMyCustomCompDisplayed = true
  }

Another synchronous solution suggested by @ThinkingMedia is also good. You can use ViewChildren instead of ViewChild and subscribe to changes (btw you don't template reference):

  @ViewChildren(myCustomComp) as: QueryList<myCustomComp>;

  ngAfterViewInit() {
    this.myCustomComp.changes.subscribe(() => {
      console.log(this.myCustomComp.first); // prints {object}
    });
  }

The callback will be triggered during next digest when Angular will be updating query list (slightly earlier than ngAfterViewChecked).

If you're looking for asynchronous solution, use setTimeout as you do it. The Promise.resolve(null).then(()=>{ console.log(this.myCustomComp) }) (microtask) solution won't work because it will be executed after the current stack but before the change detection.

For more information on change detection read

Everything you need to know about change detection in Angular.


问:
Connection String Form to an SQL server
i want to connect to database in an SQL server, so is the form of this connection string correct:</p>

```<code><connectionStrings>
  <add name="OnlineStoreEntities" connectionString="Data Source=SERVERNAME\SQLEXPRESS;Initial Catalog=MVCOnlineShop;Integrated Security=True" providerName="System.Data.SqlClient" />
  <add name="MVCOnlineShop" connectionString="metadata=res://*/Models.ShopModel.csdl|res://*/Models.ShopModel.ssdl|res://*/Models.ShopModel.msl;provider=System.Data.SqlClient;provider connection string="data source=AHMADZAKARIA-PC;initial catalog=MVCOnlineShop;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
</code>```

答:
There is a difference in the data source you specified in those to connection strings.
- in the first connection string you have written SERVERNAME\SQLEXPRESS
- in the second one, your data source is AHMADZAKARIA-PC .
Put the same info in both connections: based on the short info you gave us, you should use AHMADZAKARIA-PC or AHMADZAKARIA-PC\SQLEXPRESS</p>

Title: Connection String Form to an SQL server

Body:
i want to connect to database in an SQL server, so is the form of this connection string correct:

<connectionStrings>
  <add name="OnlineStoreEntities" connectionString="Data Source=SERVERNAME\SQLEXPRESS;Initial Catalog=MVCOnlineShop;Integrated Security=True" providerName="System.Data.SqlClient" />
  <add name="MVCOnlineShop" connectionString="metadata=res://*/Models.ShopModel.csdl|res://*/Models.ShopModel.ssdl|res://*/Models.ShopModel.msl;provider=System.Data.SqlClient;provider connection string="data source=AHMADZAKARIA-PC;initial catalog=MVCOnlineShop;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>


问:
access to Kendo pop up editor input text box
I have a Kendo grid which has a pop up editor,when I click on the edit,it pop ups an editor box which I can edit field,in the editor I have text boxes which is created dynamically,how can access them?because my code is correct but no reaction I get ,here are my fields and at the end is my code:</p>

```<code> columns: [
                                              { field: 'userName', title: 'userName', width: '100px'},
                                              { field: 'Password', title: 'Password', width: '80px' },

                                              { command: ["edit"], title: " ", width: "100px" }],
                        editable: "popup",

 $('[name="userName"]').click(function () {

        alert("you can not edit username");
    });
</code>```

答:
You should hook up the click function within the edit function of the grid itself:

```<code>edit: function(e) {
    $('[name="userName"]').click(function () {
        alert("you can not edit username");
    });
},
</code>```

Here is a Dojo example to illustrate the above in action.

Body:
I have a Kendo grid which has a pop up editor,when I click on the edit,it pop ups an editor box which I can edit field,in the editor I have text boxes which is created dynamically,how can access them?because my code is correct but no reaction I get ,here are my fields and at the end is my code:

 columns: [
                                              { field: 'userName', title: 'userName', width: '100px'},
                                              { field: 'Password', title: 'Password', width: '80px' },

                                              { command: ["edit"], title: " ", width: "100px" }],
                        editable: "popup",

 $('[name="userName"]').click(function () {

        alert("you can not edit username");
    });

Body:
You should hook up the click function within the edit function of the grid itself:

edit: function(e) {
    $('[name="userName"]').click(function () {
        alert("you can not edit username");
    });
},

Here is a Dojo example to illustrate the above in action.


问:
LINQ Except does not work for custom entities
I have this __GlobalHeaderList which contains two entities now i need to add more entities into this list  whose reference are different to the one already in the list lets say

```<code>HeaderEntity1.Reference = 'A'
HeaderEntity2.Reference = 'B'
</code>```

now I have this linq query that retrieves records from database for header entities

```<code>string[] _References = { "A", "B", "C" };

 List<HeaderEntity> _FilteredMatchedHeader = new HeaderRepository().
                     GetHeaderEntitiesByAccountID(__GlobalAccountVariable.MasterAccount.AllChildAccounts.Select(x => x.ID)).
                     Where(x => References.Contains(x.Reference)).Except(__GlobalHeaderList).ToList();
</code>```

that brings 3 entities

```<code>HeaderEntity1.Reference = A
HeaderEntity2.Reference = B
HeaderEntity3.Reference = C
</code>```

but is not excluding the 1&2 and following code contains 5 entities instead of 3

```<code>__GlobalHeaderList.AddRange(_FitleredMatchedHeader);
</code>```

the logic in linq query upto select loads all headers entities after that filtering is applied using where clause but except in the filtering is not working. can any one help please

答:
Except works on the principal of equality. For primitive datatypes that's easy, because .Net has done the work for us.

For custom complex types (read classes), we need to implement that mechanism. One way is to override the Equals method. Other way is to create an EqualityComparer (which suits you as mentioned by you that your entity is closed for modifications).

Except method has an overload which does this type of comparison. SO and internet is full of such examples.

Body:
I have this __GlobalHeaderList which contains two entities now i need to add more entities into this list  whose reference are different to the one already in the list lets say

HeaderEntity1.Reference = 'A'
HeaderEntity2.Reference = 'B'

now I have this linq query that retrieves records from database for header entities

string[] _References = { "A", "B", "C" };

 List<HeaderEntity> _FilteredMatchedHeader = new HeaderRepository().
                     GetHeaderEntitiesByAccountID(__GlobalAccountVariable.MasterAccount.AllChildAccounts.Select(x => x.ID)).
                     Where(x => References.Contains(x.Reference)).Except(__GlobalHeaderList).ToList();

that brings 3 entities

HeaderEntity1.Reference = A
HeaderEntity2.Reference = B
HeaderEntity3.Reference = C

but is not excluding the 1&2 and following code contains 5 entities instead of 3

__GlobalHeaderList.AddRange(_FitleredMatchedHeader);

the logic in linq query upto select loads all headers entities after that filtering is applied using where clause but except in the filtering is not working. can any one help please


问:
Whats the fastest between adding row by row and multiple row in MySQL
I'm parsing a large text file to add it into mySQL database, the file is more than 10K lines, each lines with more than 20 columns (line seperated by ",").

Before I start coding, I wanted to know which is the best way (in term of memory and execution time) between those two solutions :

The easy way : Line by line

Adding row by row (more than 10K insert into) : The easiest way

Complicated way

Parsing the whole file, creating ArrayList for each column, then inserting all the data in only one statement.

Does the "complicated way" save me a lot in the execution time ?

Thanks

答:
Thanks to the solutions of @Gordon Linoff I was able to do it :

The request to execute in Java was :

```<code>LOAD DATA LOCAL INFILE 'file.txt' INTO TABLE TableName FIELDS TERMINATED BY ';';
</code>```

Body:
Thanks to the solutions of @Gordon Linoff I was able to do it :

The request to execute in Java was :

LOAD DATA LOCAL INFILE 'file.txt' INTO TABLE TableName FIELDS TERMINATED BY ';';


问:
Lombok @builder on a class that extends another class
I have two classes Child extends Parent. I need to put @Builder annotation on the classes such that I do not need to create the builder my self.

```<code>package jerry;// Internal compiler error: java.lang.NullPointerException

import lombok.AllArgsConstructor;
import lombok.Builder;

@AllArgsConstructor(onConstructor=@__(@Builder))
public class Child extends Parent {
//Multiple markers at this line
//  - Implicit super constructor Parent() is undefined. Must explicitly invoke another constructor
//  - overrides java.lang.Object.toString

   private String a;
   private int b;
   private boolean c;

}

@Builder
public class Parent {
    private double d;
    private float e;
}
</code>```

I need to be able to build child instance such that

```<code>Child child = Child.builder().a("aVal").b(1000).c(true).d(10.1).e(20.0F).build();
</code>```

But so far I am getting the errors mentioned in side that code comments. Can any one point me to the right direction how to achieve it with lombok or any other similar library ?

Sub-question

Why does @AllArgsConstructor(onConstructor=@__(@Autowired)) compile but @AllArgsConstructor(onConstructor=@__(@Builder)) does not?

答:
See in https://blog.codecentric.de/en/2016/05/reducing-boilerplate-code-project-lombok/ (@Builder and inheritance part)

Adjusted to your classes

```<code>@AllArgsConstructor
public class Parent {
  private double d;
  private float e;
}

public class Child extends Parent {
  private String a;
  private int b;
  private boolean c;

  @Builder
  public Child(String a, int b, boolean c, double d, float e) {
    super(d, e);
    this.a = a;
    this.b = b;
    this.c = c;
  }
}
</code>```

With this setup

```<code>Child child = Child.builder().a("aVal").b(1000).c(true).d(10.1).e(20.0F).build();
</code>```

works correctly

Body:
I have two classes Child extends Parent. I need to put @Builder annotation on the classes such that I do not need to create the builder my self.

package jerry;// Internal compiler error: java.lang.NullPointerException

import lombok.AllArgsConstructor;
import lombok.Builder;

@AllArgsConstructor(onConstructor=@__(@Builder))
public class Child extends Parent {
//Multiple markers at this line
//  - Implicit super constructor Parent() is undefined. Must explicitly invoke another constructor
//  - overrides java.lang.Object.toString

   private String a;
   private int b;
   private boolean c;

}

@Builder
public class Parent {
    private double d;
    private float e;
}

I need to be able to build child instance such that

Child child = Child.builder().a("aVal").b(1000).c(true).d(10.1).e(20.0F).build();

But so far I am getting the errors mentioned in side that code comments. Can any one point me to the right direction how to achieve it with lombok or any other similar library ?

Sub-question

Why does @AllArgsConstructor(onConstructor=@__(@Autowired)) compile but @AllArgsConstructor(onConstructor=@__(@Builder)) does not?

Body:
See in https://blog.codecentric.de/en/2016/05/reducing-boilerplate-code-project-lombok/ (@Builder and inheritance part)

Adjusted to your classes

@AllArgsConstructor
public class Parent {
  private double d;
  private float e;
}

public class Child extends Parent {
  private String a;
  private int b;
  private boolean c;

  @Builder
  public Child(String a, int b, boolean c, double d, float e) {
    super(d, e);
    this.a = a;
    this.b = b;
    this.c = c;
  }
}

With this setup

Child child = Child.builder().a("aVal").b(1000).c(true).d(10.1).e(20.0F).build();

works correctly


问:
Visual Studio 17 Build Failure, Invalid Configuration
I couldn't build my solution, I get this at the Output:

```<code>Build started ...
Build Failure. Error: Invalid Configuration
Parameter name: configurationName
========== Build: 0 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
</code>```

But if I build project one by one (no as all solution) it's ok, Configuration Manager is ok too. It seems to me, that answer is pretty simple, but I don't know how to solve it.

答:
Right click on the solution, Disbale Lightweight Solution Load then reload the solution.
It surely will impact the loading time, but it will fix the problem!

Body:
I couldn't build my solution, I get this at the Output:

Build started ...
Build Failure. Error: Invalid Configuration
Parameter name: configurationName
========== Build: 0 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========

But if I build project one by one (no as all solution) it's ok, Configuration Manager is ok too. It seems to me, that answer is pretty simple, but I don't know how to solve it.


问:
How to make padding of arrow from right side in PickerRenderer xamarin forms IOS
```<code>public class CustomPickerRenderer : PickerRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Picker> e)
{
base.OnElementChanged(e);
if (this.Control != null)
{
var downarrow = UIImage.FromBundle("your image");
var textField = this.Control;
textField.RightViewMode = UITextFieldViewMode.Always;
textField.RightView = new UIImageView(downarrow);
}
}
}
</code>```

I have using PickerRenderer for IOS and I want to make some space from right side.How to make padding from right side ? Here Image, please check

答:
Try using Grid with image and picker.

```<code><Grid>
   <Picker/>
   <Image Source="arrow.png" HorizontalOptions="End" Magin="5"/>
</Grid>
</code>```

may be it's help you

Body:
public class CustomPickerRenderer : PickerRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Picker> e)
{
base.OnElementChanged(e);
if (this.Control != null)
{
var downarrow = UIImage.FromBundle("your image");
var textField = this.Control;
textField.RightViewMode = UITextFieldViewMode.Always;
textField.RightView = new UIImageView(downarrow);
}
}
}

I have using PickerRenderer for IOS and I want to make some space from right side.How to make padding from right side ? Here Image, please check

Body:
Try using Grid with image and picker.

<Grid>
   <Picker/>
   <Image Source="arrow.png" HorizontalOptions="End" Magin="5"/>
</Grid>

may be it's help you


问:
Removing characters in a java string
I want to remove charecters from a string. Example: I have an application that as the users check off the check mark its building the sql script, so if they check female it adds to the String And Gender = 'Female'. and if they select Male it adds And Where gender = 'Male'. The script is working well when adding to string as they check off but when you uncheck a item I am not sure how to remove the char that were added when it was checked. I tried .Replace .ReplaceAll and all the other replace. I know the string I want to remove, why won't it replace it with "".

```<code>String SQL;
SQL += " AND Gender = 'Female'";
SQL.Replace("AND Gender = 'Female'","");
</code>```

This won't work!

答: Don't use a String if you want something mutable. Instead you're better off using a StringBuilder object. Then when you're done modifying it, you can call toString() on it to get the String you need. The API will show you the methods of this flexible class.</p>

Title: Removing characters in a java string

Body:
I want to remove charecters from a string. Example: I have an application that as the users check off the check mark its building the sql script, so if they check female it adds to the String And Gender = 'Female'. and if they select Male it adds And Where gender = 'Male'. The script is working well when adding to string as they check off but when you uncheck a item I am not sure how to remove the char that were added when it was checked. I tried .Replace .ReplaceAll and all the other replace. I know the string I want to remove, why won't it replace it with "".

String SQL;
SQL += " AND Gender = 'Female'";
SQL.Replace("AND Gender = 'Female'","");

This won't work!


问:
How to write out integer
Is it possible to convert an integer to a written out word? IE, convert '29' to 'twentynine'?

There is a comment on the strval() page of the PHP Manual, but it's from 13 years ago, before PHP 5 was introduced. Is there a standard PHP function that can do the same, or maybe an easier way to write out the function?

https://secure.php.net/manual/en/function.strval.php

答:
Please, use this: http://dk2.php.net/manual/en/class.numberformatter.php

Example:

```<code>$f = new NumberFormatter("en", NumberFormatter::SPELLOUT);
echo $f->format(1432);
</code>```

That would output "one thousand four hundred thirty-two"

Title: How to write out integer

Body:
Please, use this: http://dk2.php.net/manual/en/class.numberformatter.php

Example:

$f = new NumberFormatter("en", NumberFormatter::SPELLOUT);
echo $f->format(1432);

That would output "one thousand four hundred thirty-two"


问:
write results sequentially in a loop in r
I have a bunt of single files which need to apply a test. I need to find the way to write automatically results of each file into a file. Here is what I do:

```<code>library(ape)
stud_files <- list.files("path/dir/data",full.names = T)
for (f in stud_files)  {
df <- read.table(f, header=TRUE, sep=";")
df_xts <- as.xts(df$cola, order.by = as.Date(df$colb,"%m/%d/%Y"))
pet <- testa(df_xts)
res <- data.frame(estimate = pet$estimate,
                 p.value=pet$p.value,
                logi = pet$alternative)
write.dna(res,file = "res_testa.xls",format = "sequential")
}
</code>```

This loop works well, except the last command which aim to write the results of each file consecutively, it saved only the last performance. And the results save as string, not a table as I define above (data.frame). Any idea in this case? Thanks in advance

答:
Check help(write.dna).

write.dna(x, file, format = "interleaved", append = FALSE,
            nbcol = 6, colsep = " ", colw = 10, indent = NULL,
            blocksep = 1)

append a logical, if TRUE the data are appended to the file without
  erasing the data possibly existing in the file, otherwise the file (if
  it exists) is overwritten (FALSE the default).

Set append = TRUE and you should be all set.

As some of the comments point out, however, you are probably better off generating your table, and then writing it all at once to a file. Unless you have billions of files, you likely won't run out of memory.

Here is how I would approach this.

```<code>library(ape)
library(data.table)

stud_files <- list.files("path/dir/data",full.names = T)

sumfunc <- function(f) {

  df <- read.table(f, header=TRUE, sep=";")
  df_xts <- as.xts(df$cola, order.by = as.Date(df$colb,"%m/%d/%Y"))
  pet <- testa(df_xts)
  res <- data.table(estimate = pet$estimate,
                    p.value=pet$p.value,
                    logi = pet$alternative)
  return(res)

}

lres <- lapply(stud_files, sumfunc)
dat <- rbindlist(lres)

write.table(dat,
            file = "res_testa.csv",
            sep = ",",
            quote = FALSE,
            row.names = FALSE)
</code>```

Body:
I have a bunt of single files which need to apply a test. I need to find the way to write automatically results of each file into a file. Here is what I do:

library(ape)
stud_files <- list.files("path/dir/data",full.names = T)
for (f in stud_files)  {
df <- read.table(f, header=TRUE, sep=";")
df_xts <- as.xts(df$cola, order.by = as.Date(df$colb,"%m/%d/%Y"))
pet <- testa(df_xts)
res <- data.frame(estimate = pet$estimate,
                 p.value=pet$p.value,
                logi = pet$alternative)
write.dna(res,file = "res_testa.xls",format = "sequential")
}

This loop works well, except the last command which aim to write the results of each file consecutively, it saved only the last performance. And the results save as string, not a table as I define above (data.frame). Any idea in this case? Thanks in advance

Body:
Check help(write.dna).

write.dna(x, file, format = "interleaved", append = FALSE,
            nbcol = 6, colsep = " ", colw = 10, indent = NULL,
            blocksep = 1)

append a logical, if TRUE the data are appended to the file without
  erasing the data possibly existing in the file, otherwise the file (if
  it exists) is overwritten (FALSE the default).

Set append = TRUE and you should be all set.

As some of the comments point out, however, you are probably better off generating your table, and then writing it all at once to a file. Unless you have billions of files, you likely won't run out of memory.

Here is how I would approach this.

library(ape)
library(data.table)

stud_files <- list.files("path/dir/data",full.names = T)

sumfunc <- function(f) {

  df <- read.table(f, header=TRUE, sep=";")
  df_xts <- as.xts(df$cola, order.by = as.Date(df$colb,"%m/%d/%Y"))
  pet <- testa(df_xts)
  res <- data.table(estimate = pet$estimate,
                    p.value=pet$p.value,
                    logi = pet$alternative)
  return(res)

}

lres <- lapply(stud_files, sumfunc)
dat <- rbindlist(lres)

write.table(dat,
            file = "res_testa.csv",
            sep = ",",
            quote = FALSE,
            row.names = FALSE)


问:
HttpWebResponse hangs/freezes when running in a WebAPI
I am using a C# WebAPI project which would call an external API based on its URL. However, when I am trying to retrieve the data back, it hangs/freezes.

The code where it stops is:

```<code>var response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
</code>```

I don't understand why it is stopping though. Could it be interfering with the API request I am also making? When I run this code as part of a unit test, I would get a response back within seconds. I don't think it is the API service itself, I think it is my code. I have already tried various API URLS. None of them work.

My full code is:

```<code>public static async Task<string> CallWebAPi<T>(string url)
{
    string returnValue;

    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
    request.ContentType = "application/json";
    request.Method = "GET";

    var response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);

    Stream stream = response.GetResponseStream();
    StreamReader strReader = new StreamReader(stream);
    returnValue = await strReader.ReadToEndAsync();

    return returnValue;
}
</code>```

Any help would be appreciated.

答:
Possible deadlock ConfigureAwait(false),  here are a good explanation from Stephen on what cause deadlocks.</p>

```<code>  var response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null).ConfigureAwait(false);
</code>```

Body:
I am using a C# WebAPI project which would call an external API based on its URL. However, when I am trying to retrieve the data back, it hangs/freezes.

The code where it stops is:

var response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);

I don't understand why it is stopping though. Could it be interfering with the API request I am also making? When I run this code as part of a unit test, I would get a response back within seconds. I don't think it is the API service itself, I think it is my code. I have already tried various API URLS. None of them work.

My full code is:

public static async Task<string> CallWebAPi<T>(string url)
{
    string returnValue;

    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
    request.ContentType = "application/json";
    request.Method = "GET";

    var response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);

    Stream stream = response.GetResponseStream();
    StreamReader strReader = new StreamReader(stream);
    returnValue = await strReader.ReadToEndAsync();

    return returnValue;
}

Any help would be appreciated.

Body:
Possible deadlock ConfigureAwait(false),  here are a good explanation from Stephen on what cause deadlocks.

  var response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null).ConfigureAwait(false);


问:
How to link 3 drop down list together using HTML & javascript
I was able to link two drop down list together but, I am facing problem to link 3 drop down list together in such away that 2 depends on 1 and 3 depends on 2.

This is the code of my 2 drop down list linked together:-

```<code><head>

 <script type = "text/javascript">

function update()
 {
  var albania = ["Tirana","Durres","Vlore","Shkoder"];
    var kosovo = ["Prishtina","Mitrovica","Peje","Gjakove"];
    var germany = ["Berlin","Frankfurt","Hannover","Bonn"];

     var  countries = document.getElementById("1");
     enter code here`var cities = document.getElementById("2");
    var selected = countries.options[countries.selectedIndex].value;

     if(selected=="1"){
    for(var i = 0; i < albania.length; i++) {
    var opt1 = document.createElement('option');
    opt1.innerHTML = albania[i];
   opt1.value = albania[i];
    cities.appendChild(opt1);
    }
      }
     else if(selected=="2")
    {
     for(var j = 0; j < kosovo.length; j++) {
     var opt2 = document.createElement('option');
      opt2.innerHTML = kosovo[j];
     opt2.value = kosovo[j];
     cities.appendChild(opt2);
     }
      }
   else if(selected=="3")
      {
    for(var k = 0; k < germany.length; k++) {
    var opt3 = document.createElement('option');
    opt3.innerHTML = germany[k];
    opt3.value = germany[k];
     cities.appendChild(opt3);
     }
     }
      else
       var t =0;
     }
      </script>

        </head>
       <body>
<p><select  id= "1" onchange="update()">
   <option selected = "selected" >Select Country</option>
   <option value="1">Albania</option>
   <option value="2">Kosovo</option>
   <option value="3">Germany</option>
   </select>
   </p>
    <p><select  id="2">
   <option selected = "selected" ></option>

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

答:
I would like to thank Umesh Aawte to help me.

Three drop down lists (sectors, industries and companies) are dynamic drop down lists, linked in such a way that, industries depends on sectors and companies depends on industries and sectors.
Concept:
There are 3 sectors (sector1, sector2 and sector3). If sector1 is selected, the drop down list of industries populates with options (industry11, industry12, industry13, industry14). Similar is the case for other sectors. Also if industry11 is selected than drop down list of companies populate with options (company111, company112, company113, company114).

CODE:

```<code>       <html>
        <head>
      <script type="text/javascript">
  var sector1 = ["industry11","industry12","industry13","industry14"];
 var sector2 = ["industry21","industry22","industry23","industry24"];
var sector3 = ["industry31","industry32","industry33","industry34"];

function updateTwo() {
var  sectors = document.getElementById("1");
var industries = document.getElementById("2");
var selected = sectors.options[sectors.selectedIndex].value;
var i;
for(i = industries.options.length - 1 ; i >= 0 ; i--) {
    industries.remove(i);
}
if(selected=="1"){

    for(var i = 0; i < sector1.length; i++) {
        addOption(industries,sector1[i]);
    }
} else if(selected=="2") {
    for(var j = 0; j < sector2.length; j++) {
        addOption(industries,sector2[j]);
    }
} else if(selected=="3") {
    for(var k = 0; k < sector3.length; k++) {
        addOption(industries,sector3[k]);
       }
   }
   }

updateThree = function() {

var industry11 = ["company111","company112","company113","company114"];
var industry12 = ["company121","company122","company123","company124"];
var industry13 = ["company131","company132","company133","company134"];
var industry14 = ["company141","company142","company143","company144"];
var industry21 = ["company211","company212","company213","company214"];
var industry22 = ["company221","company222","company223","company224"];
var industry23 = ["company231","company232","company233","company234"];
var industry24 = ["company241","company242","company243","company244"];
var industry31 = ["company311","company312","company313","company314"];
var industry32 = ["company321","company322","company323","company324"];
var industry33 = ["company331","company332","company333","company334"];
var industry34 = ["company341","company342","company343","company344"];

var  industries = document.getElementById("2");
var companies = document.getElementById("3");
var selected = industries.options[industries.selectedIndex].value;
var i;
for(i = companies.options.length - 1 ; i >= 0 ; i--) {
    companies.remove(i);
}
if(selected=="industry11"){
    for(var i = 0; i < sector1.length; i++) {
        addOption(companies,industry11[i]);
    }
} else if(selected=="industry12") {
    for(var j = 0; j < sector2.length; j++) {
        addOption(companies,industry12[j]);
    }
} else if(selected=="industry13") {
    for(var k = 0; k < sector3.length; k++) {
        addOption(companies,industry13[k]);
    }
} else if(selected=="industry14") {
    for(var k = 0; k < sector3.length; k++) {
        addOption(companies,industry14[k]);
    }
}
else if(selected=="industry21") {
    for(var j = 0; j < sector2.length; j++) {
        addOption(companies,industry21[j]);
    }
} else if(selected=="industry22") {
    for(var k = 0; k < sector3.length; k++) {
        addOption(companies,industry22[k]);
    }
} else if(selected=="industry23") {
    for(var k = 0; k < sector3.length; k++) {
        addOption(companies,industry23[k]);
    }
}
else if(selected=="industry24") {
    for(var j = 0; j < sector2.length; j++) {
        addOption(companies,industry24[j]);
    }
} else if(selected=="industry31") {
    for(var k = 0; k < sector3.length; k++) {
        addOption(companies,industry31[k]);
    }
} else if(selected=="industry32") {
    for(var k = 0; k < sector3.length; k++) {
        addOption(companies,industry32[k]);
    }
}

else if(selected=="industry33") {
    for(var j = 0; j < sector2.length; j++) {
        addOption(companies,industry33[j]);
    }
} else if(selected=="industry34") {
    for(var k = 0; k < sector3.length; k++) {
        addOption(companies,industry34[k]);
    }
}
    else{
    ;
    }
   }

addOption = function(option, value) {
var opt = document.createElement('option');
opt.innerHTML = value;
opt.value = value;
option.appendChild(opt);
 }
</script>
 </head>
<body>
<p>
    <select id="1" onchange="javaScript:updateTwo();">
        <option value="0" selected="selected">Select Sector</option>
        <option value="1">Sector1</option>
        <option value="2">Sector2</option>
        <option value="3">Sector3</option>
    </select>
</p>
<p>
    <select id="2" onchange="javaScript:updateThree();"></select>
</p>
<p>
    <select id="3"></select>
</p>
 </body>
 </html>
</code>```

Body:
I was able to link two drop down list together but, I am facing problem to link 3 drop down list together in such away that 2 depends on 1 and 3 depends on 2.

This is the code of my 2 drop down list linked together:-

<select  id= "1" onchange="update()">
   <option selected = "selected" >Select Country</option>
   <option value="1">Albania</option>
   <option value="2">Kosovo</option>
   <option value="3">Germany</option>
   </select>

<select  id="2">
   <option selected = "selected" ></option>

Body:
I would like to thank Umesh Aawte to help me.

Three drop down lists (sectors, industries and companies) are dynamic drop down lists, linked in such a way that, industries depends on sectors and companies depends on industries and sectors.
Concept:
There are 3 sectors (sector1, sector2 and sector3). If sector1 is selected, the drop down list of industries populates with options (industry11, industry12, industry13, industry14). Similar is the case for other sectors. Also if industry11 is selected than drop down list of companies populate with options (company111, company112, company113, company114).

CODE:

       <html>
        <head>
      <script type="text/javascript">
  var sector1 = ["industry11","industry12","industry13","industry14"];
 var sector2 = ["industry21","industry22","industry23","industry24"];
var sector3 = ["industry31","industry32","industry33","industry34"];

function updateTwo() {
var  sectors = document.getElementById("1");
var industries = document.getElementById("2");
var selected = sectors.options[sectors.selectedIndex].value;
var i;
for(i = industries.options.length - 1 ; i >= 0 ; i--) {
    industries.remove(i);
}
if(selected=="1"){

    for(var i = 0; i < sector1.length; i++) {
        addOption(industries,sector1[i]);
    }
} else if(selected=="2") {
    for(var j = 0; j < sector2.length; j++) {
        addOption(industries,sector2[j]);
    }
} else if(selected=="3") {
    for(var k = 0; k < sector3.length; k++) {
        addOption(industries,sector3[k]);
       }
   }
   }

updateThree = function() {

var industry11 = ["company111","company112","company113","company114"];
var industry12 = ["company121","company122","company123","company124"];
var industry13 = ["company131","company132","company133","company134"];
var industry14 = ["company141","company142","company143","company144"];
var industry21 = ["company211","company212","company213","company214"];
var industry22 = ["company221","company222","company223","company224"];
var industry23 = ["company231","company232","company233","company234"];
var industry24 = ["company241","company242","company243","company244"];
var industry31 = ["company311","company312","company313","company314"];
var industry32 = ["company321","company322","company323","company324"];
var industry33 = ["company331","company332","company333","company334"];
var industry34 = ["company341","company342","company343","company344"];

var  industries = document.getElementById("2");
var companies = document.getElementById("3");
var selected = industries.options[industries.selectedIndex].value;
var i;
for(i = companies.options.length - 1 ; i >= 0 ; i--) {
    companies.remove(i);
}
if(selected=="industry11"){
    for(var i = 0; i < sector1.length; i++) {
        addOption(companies,industry11[i]);
    }
} else if(selected=="industry12") {
    for(var j = 0; j < sector2.length; j++) {
        addOption(companies,industry12[j]);
    }
} else if(selected=="industry13") {
    for(var k = 0; k < sector3.length; k++) {
        addOption(companies,industry13[k]);
    }
} else if(selected=="industry14") {
    for(var k = 0; k < sector3.length; k++) {
        addOption(companies,industry14[k]);
    }
}
else if(selected=="industry21") {
    for(var j = 0; j < sector2.length; j++) {
        addOption(companies,industry21[j]);
    }
} else if(selected=="industry22") {
    for(var k = 0; k < sector3.length; k++) {
        addOption(companies,industry22[k]);
    }
} else if(selected=="industry23") {
    for(var k = 0; k < sector3.length; k++) {
        addOption(companies,industry23[k]);
    }
}
else if(selected=="industry24") {
    for(var j = 0; j < sector2.length; j++) {
        addOption(companies,industry24[j]);
    }
} else if(selected=="industry31") {
    for(var k = 0; k < sector3.length; k++) {
        addOption(companies,industry31[k]);
    }
} else if(selected=="industry32") {
    for(var k = 0; k < sector3.length; k++) {
        addOption(companies,industry32[k]);
    }
}

else if(selected=="industry33") {
    for(var j = 0; j < sector2.length; j++) {
        addOption(companies,industry33[j]);
    }
} else if(selected=="industry34") {
    for(var k = 0; k < sector3.length; k++) {
        addOption(companies,industry34[k]);
    }
}
    else{
    ;
    }
   }

addOption = function(option, value) {
var opt = document.createElement('option');
opt.innerHTML = value;
opt.value = value;
option.appendChild(opt);
 }
</script>
 </head>
<body>
<p>
    <select id="1" onchange="javaScript:updateTwo();">
        <option value="0" selected="selected">Select Sector</option>
        <option value="1">Sector1</option>
        <option value="2">Sector2</option>
        <option value="3">Sector3</option>
    </select>
</p>
<p>
    <select id="2" onchange="javaScript:updateThree();"></select>
</p>
<p>
    <select id="3"></select>
</p>
 </body>
 </html>


问:
InstalledInstances doesn't work
I have a project with a database and I have to create a setup file to run another computer. I try to setup but firstly, I need to know is there any SQL Server already installed on that computer. I searched some code about it and I found:

```<code>RegistryKey rk = Registry.LocalMachine.OpenSubKey("\\SOFTWARE\\Microsoft\\Microsoft SQL Server");
String[] instances = (String[])rk.GetValue("InstalledInstances");
</code>```

but everytime instances equal null everytime. But when I try to look myself on computer I find by hand. What's the wrong this code?

```<code>RegistryKey rk = Registry.LocalMachine.OpenSubKey("\\SOFTWARE\\Microsoft\\Microsoft SQL Server");
String[] instances = (String[])rk.GetValue("InstalledInstances");

if (instances.Length > 0)
{
   foreach (String element in instances)
   {
       if (element == "MSSQLSERVER")
       {
          DialogResult res = MessageBox.Show("are u sure to setup this file?", "UYARI", MessageBoxButtons.YesNo);
          if (res == DialogResult.Yes)
          {
             string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\SQLEXPR.EXE";
             Process p = new Process();
             p.StartInfo.FileName = path;
             p.StartInfo.Arguments = "/qb INSTANCENAME=\"SQLEXPRESS\" INSTALLSQLDIR=\"C:\\Program Files\\Microsoft SQL Server\" INSTALLSQLSHAREDDIR=\"C:\\Program Files\\Microsoft SQL Server\" INSTALLSQLDATADIR=\"C:\\Program Files\\Microsoft SQL Server\" ADDLOCAL=\"All\" SQLAUTOSTART=1 SQLBROWSERAUTOSTART=0 SQLBROWSERACCOUNT=\"NT AUTHORITY\\SYSTEM\" SQLACCOUNT=\"NT AUTHORITY\\SYSTEM\" SECURITYMODE=SQL SAPWD=\"\" SQLCOLLATION=\"SQL_Latin1_General_Cp1_CS_AS\" DISABLENETWORKPROTOCOLS=0 ERRORREPORTING=1 ENABLERANU=0";

             p.StartInfo.CreateNoWindow = true;
             p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
             p.Start();

             p.WaitForExit();
             CreateDB();
          }
          else
          {
             this.Close();
          }
       }
    }
}
</code>```

答:
you need to check what key is taken, because you might not pointing to the correct key, to know what actual key that you have do this:

```<code>string keyValue = registryKey.ToString();
</code>```

if you found a different key that what you have been using which is: SOFTWARE\\Microsoft\\Microsoft SQL Server, then you should change the projects build, since the registries can be for 32 or 64, so specify which CPU, not "any CPU"

Title: InstalledInstances doesn't work

Body:
I have a project with a database and I have to create a setup file to run another computer. I try to setup but firstly, I need to know is there any SQL Server already installed on that computer. I searched some code about it and I found:

RegistryKey rk = Registry.LocalMachine.OpenSubKey("\\SOFTWARE\\Microsoft\\Microsoft SQL Server");
String[] instances = (String[])rk.GetValue("InstalledInstances");

but everytime instances equal null everytime. But when I try to look myself on computer I find by hand. What's the wrong this code?

RegistryKey rk = Registry.LocalMachine.OpenSubKey("\\SOFTWARE\\Microsoft\\Microsoft SQL Server");
String[] instances = (String[])rk.GetValue("InstalledInstances");

if (instances.Length > 0)
{
   foreach (String element in instances)
   {
       if (element == "MSSQLSERVER")
       {
          DialogResult res = MessageBox.Show("are u sure to setup this file?", "UYARI", MessageBoxButtons.YesNo);
          if (res == DialogResult.Yes)
          {
             string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\SQLEXPR.EXE";
             Process p = new Process();
             p.StartInfo.FileName = path;
             p.StartInfo.Arguments = "/qb INSTANCENAME=\"SQLEXPRESS\" INSTALLSQLDIR=\"C:\\Program Files\\Microsoft SQL Server\" INSTALLSQLSHAREDDIR=\"C:\\Program Files\\Microsoft SQL Server\" INSTALLSQLDATADIR=\"C:\\Program Files\\Microsoft SQL Server\" ADDLOCAL=\"All\" SQLAUTOSTART=1 SQLBROWSERAUTOSTART=0 SQLBROWSERACCOUNT=\"NT AUTHORITY\\SYSTEM\" SQLACCOUNT=\"NT AUTHORITY\\SYSTEM\" SECURITYMODE=SQL SAPWD=\"\" SQLCOLLATION=\"SQL_Latin1_General_Cp1_CS_AS\" DISABLENETWORKPROTOCOLS=0 ERRORREPORTING=1 ENABLERANU=0";

             p.StartInfo.CreateNoWindow = true;
             p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
             p.Start();

             p.WaitForExit();
             CreateDB();
          }
          else
          {
             this.Close();
          }
       }
    }
}

Body:
you need to check what key is taken, because you might not pointing to the correct key, to know what actual key that you have do this:

string keyValue = registryKey.ToString();

if you found a different key that what you have been using which is: SOFTWARE\\Microsoft\\Microsoft SQL Server, then you should change the projects build, since the registries can be for 32 or 64, so specify which CPU, not "any CPU"


问:
How to make a dict of multiple lists in python?
I want to make a list of dicts that have the following structure,

```<code>[{'Business' : 'Attorney' , 'Website text' : '(one line from the loaded file)'}, {'Business' : 'Attorney' , 'Website text' : '(one line from the loaded file)'}, ...]
</code>```

However at the moment i only have a csv file consisting of the website text.

Below i have attempted to somehow create lists of the same length as my website text file, then zip them and create a dict from that. I have been unable to find information on here when it comes to creating a dict from more that 2 lists.

```<code>with open('attorneys text.csv') as data_file:
    attorneys = list(line for line in data_file)

website = []
business = []
classes = []
for l in range(len(attorneys)):
    website.append("Website text")

for k in range(len(attorneys)):
    business.append("Business")

for i in range(len(attorneys)):
    classes.append("Attorney")

data = dict(zip((business, classes, website, attorneys)))
</code>```

I am well aware of the ugliness of the try as well...

答:
Since the only difference is the text, you can do the following:

```<code>with open('attorneys text.csv') as data_file:
    data = [{'Business':'Attorney', 'Website text':line} for line in data_file]
</code>```

The 'Business':'Attorney' pair will be the same for each dictionary, while the value corresponding to 'Website text' will be the data from your file.

Body:
I want to make a list of dicts that have the following structure,

[{'Business' : 'Attorney' , 'Website text' : '(one line from the loaded file)'}, {'Business' : 'Attorney' , 'Website text' : '(one line from the loaded file)'}, ...]

However at the moment i only have a csv file consisting of the website text.

Below i have attempted to somehow create lists of the same length as my website text file, then zip them and create a dict from that. I have been unable to find information on here when it comes to creating a dict from more that 2 lists.

with open('attorneys text.csv') as data_file:
    attorneys = list(line for line in data_file)

website = []
business = []
classes = []
for l in range(len(attorneys)):
    website.append("Website text")

for k in range(len(attorneys)):
    business.append("Business")

for i in range(len(attorneys)):
    classes.append("Attorney")

data = dict(zip((business, classes, website, attorneys)))

I am well aware of the ugliness of the try as well...

Body:
Since the only difference is the text, you can do the following:

with open('attorneys text.csv') as data_file:
    data = [{'Business':'Attorney', 'Website text':line} for line in data_file]

The 'Business':'Attorney' pair will be the same for each dictionary, while the value corresponding to 'Website text' will be the data from your file.


问:
Convert a post-order binary tree traversal index to an level-order (breadth-first) index
Assuming a complete binary tree, each node can be adressed with the position it appears in a given tree traversal algorithm.

For example, the node indices of a simple complete tree with height 3 would look like this:

breadth first (aka level-order):

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

post-order dept first:

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

The height of the tree and an index in the post-order traversal is given.

How can i calculate the breadth first index from this information?

答:
Brute-force way, until you find a better answer:

Build the tree from the post-order array/index, making each node's value the current array index.

Consume the index: The first half of the index is your left subtree, the second half is your right subtree, the middle node is the root. Recurse for each subtree.

Traverse the tree breadth-first, putting the calculated breadth-first index into map as the value of the mapped pair, with the key the node's value. map.put( node.value, tree_visitor.current_index)

Interrogate the map, passing on the desired key (which is the index of the post-order node) to get the index of the corresponding breadth-first node.

Body:
Assuming a complete binary tree, each node can be adressed with the position it appears in a given tree traversal algorithm.

For example, the node indices of a simple complete tree with height 3 would look like this:

breadth first (aka level-order):

     0
   /   \
  1     2
 /  \  /  \
3   4  5  6

post-order dept first:

     6
   /   \
  2     5
 /  \  /  \
0   1  3  4

The height of the tree and an index in the post-order traversal is given.

How can i calculate the breadth first index from this information?


问:
Cannot find entry file index.android.js in any of the roots:[ Android ]
I am trying to start my hello world app using react native using windows 7 and an android device. There is a similar issue here but I have failed make it work.

Commands I have run so far to set up and lead to this issue.

Created the app: react-native init helloMe

Moved to the root Dir[helloMe]. react-native run-android

Android Device is set up okay and showing in CMD using adb

Opened another CMD window then ran: react-native start

Ran react-native run-android again.

Red Screen is shown on phone with this error unable to load script from assets index.android.bundle on windows

Trying to fix it with the solution in step 6 leads to another error which is why I am here. below is my CMD log.

```<code>E:\testdir\react_ws\helloMe>react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
Scanning 558 folders for symlinks in E:\testdir\react_ws\helloMe\node_modules (30ms)
Scanning 558 folders for symlinks in E:\testdir\react_ws\helloMe\node_modules (20ms)
Loading dependency graph, done.
Cannot find entry file index.android.js in any of the roots: ["E:\\testdir\\react_ws\\helloMe"]
E:\testdir\react_ws\helloMe>
</code>```

Now I am getting another error when I try to fix the problem with the above solution.

```<code>Cannot find entry file index.android.js in any of the roots: ["E:\\testdir
\\react_ws\\helloMe"]
</code>```

If have tried to apply this fix from here

```<code>npm run start -- --root <directory_with_your_react_component_js_sources>
</code>```

I since I am running the command in the project root, I ran this instead
npm run start -- --root ./ but it did not work.

This is my root project structure

```<code>__tests__  app.json          index.ios.js  node_modules  yarn.lock
android    index.android.js  ios           package.json
</code>```

I hope I am clear, any help would be highly appreciated. Device is stuck on red screen with a 404.

React-native-version

```<code>react-native-cli: 2.0.1
react-native: 0.46.0
</code>```

Thanks.

答:
Changed the version of react project to a lower one from here

```<code>npm install -g rninit

rninit init [Project Name] --source react-native@0.40.0
</code>```

Worked okay for both on both iOS and Android on . If you get Error Could not get BatchedBridge. run this

```<code>adb reverse tcp:8081 tcp:8081
</code>```

This worked for me.

Body:
I am trying to start my hello world app using react native using windows 7 and an android device. There is a similar issue here but I have failed make it work.

Commands I have run so far to set up and lead to this issue.

Created the app: react-native init helloMe

Moved to the root Dir[helloMe]. react-native run-android

Android Device is set up okay and showing in CMD using adb

Opened another CMD window then ran: react-native start

Ran react-native run-android again.

Red Screen is shown on phone with this error unable to load script from assets index.android.bundle on windows

Trying to fix it with the solution in step 6 leads to another error which is why I am here. below is my CMD log.

E:\testdir\react_ws\helloMe>react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
Scanning 558 folders for symlinks in E:\testdir\react_ws\helloMe\node_modules (30ms)
Scanning 558 folders for symlinks in E:\testdir\react_ws\helloMe\node_modules (20ms)
Loading dependency graph, done.
Cannot find entry file index.android.js in any of the roots: ["E:\\testdir\\react_ws\\helloMe"]
E:\testdir\react_ws\helloMe>

Now I am getting another error when I try to fix the problem with the above solution.

Cannot find entry file index.android.js in any of the roots: ["E:\\testdir
\\react_ws\\helloMe"]

If have tried to apply this fix from here

npm run start -- --root <directory_with_your_react_component_js_sources>

I since I am running the command in the project root, I ran this instead
npm run start -- --root ./ but it did not work.

This is my root project structure

__tests__  app.json          index.ios.js  node_modules  yarn.lock
android    index.android.js  ios           package.json

I hope I am clear, any help would be highly appreciated. Device is stuck on red screen with a 404.

React-native-version

react-native-cli: 2.0.1
react-native: 0.46.0

Thanks.

Body:
Changed the version of react project to a lower one from here

npm install -g rninit

rninit init [Project Name] --source react-native@0.40.0

Worked okay for both on both iOS and Android on . If you get Error Could not get BatchedBridge. run this

adb reverse tcp:8081 tcp:8081

This worked for me.


问:
Firebase database rules – `data.exists()` always seems to be true, possible bug?
I am trying to secure my firebase database to allow the creation of new records, but not allow the deletion of existing records. Ultimately, I plan to utilise Firebase authentication in my app as well, and allow users to update existing records if they are the author, but I am trying to get the simple case working first.

However! No matter what I try in the database rules simulator, despite what the documentation seems to suggest, the value of data.exists() seems to always be true. From what I what I can understand from the documentation, the variable data represents a record in the database as it did before an operation took-place. That is to say, for creates, data would not exist, and for updates/deletes, data would refer to a real record that exists in the database. This does not seem to be the case, to the point where I am actually suspecting a bug in Firebase, as when setting the following rules on my database, all write operations are disallowed:

```<code>{
  "rules": {
    ".read": true,
    ".write": "!data.exists()"
  }
}
</code>```

No matter what values I put into the simulator, be it Location or Data. I have even written a small EmberJS app to verify if the Simulator is telling the truth and it too, is denied permission for all write operations.

I really have no idea where to go from here as I am pretty much out of things to try. I tried deleting all records from my database, which lets the simulator think it can perform write operations, but my test app still gets PERMISSION_DENIED, so I don't know what's causing inconsistencies there.

Is my understanding of the predefined data variable correct? If so, why can't I write the rules I want? I have seen snippets literally trying to achieve my "create only, no-delete"  rule that seem to line up with my understanding.

Last note: I am trying this in a totally new Firebase project with JUST the rules above, and only ~a few records of junk data laying around my database.

答:
Because you have placed the !data.exists() at the root location of your database, data refers to the entire database.  You will only be able to write to the database when it is completely empty.

You indicate that you run your tests with only a few records of junk data laying around my database.  Those records will cause data.exists() to be true.

You can achieve your goal by placing the !data.exists() rule in your tree at the specific location where you want to require that no data already exists.  This is typically done at a location with a wildcard key, as in the example you linked:

```<code>{
  "rules": {
    // default rules are false if not specified

    "posts": {
      ".read": true, // everyone can read all posts

      "$postId": {
        // a new post can be created if it does not exist
        // existing posts can only be edited by their original "author"
        ".write": "!data.exists() && newData.exists() || data.child('author').val() == auth.uid",
        ".validate": "newData.hasChildren(['title', 'author', 'timestamp'])",
      }
    }
  }
}
</code>```

Body:
I am trying to secure my firebase database to allow the creation of new records, but not allow the deletion of existing records. Ultimately, I plan to utilise Firebase authentication in my app as well, and allow users to update existing records if they are the author, but I am trying to get the simple case working first.

However! No matter what I try in the database rules simulator, despite what the documentation seems to suggest, the value of data.exists() seems to always be true. From what I what I can understand from the documentation, the variable data represents a record in the database as it did before an operation took-place. That is to say, for creates, data would not exist, and for updates/deletes, data would refer to a real record that exists in the database. This does not seem to be the case, to the point where I am actually suspecting a bug in Firebase, as when setting the following rules on my database, all write operations are disallowed:

{
  "rules": {
    ".read": true,
    ".write": "!data.exists()"
  }
}

No matter what values I put into the simulator, be it Location or Data. I have even written a small EmberJS app to verify if the Simulator is telling the truth and it too, is denied permission for all write operations.

I really have no idea where to go from here as I am pretty much out of things to try. I tried deleting all records from my database, which lets the simulator think it can perform write operations, but my test app still gets PERMISSION_DENIED, so I don't know what's causing inconsistencies there.

Is my understanding of the predefined data variable correct? If so, why can't I write the rules I want? I have seen snippets literally trying to achieve my "create only, no-delete"  rule that seem to line up with my understanding.

Last note: I am trying this in a totally new Firebase project with JUST the rules above, and only ~a few records of junk data laying around my database.

Body:
Because you have placed the !data.exists() at the root location of your database, data refers to the entire database.  You will only be able to write to the database when it is completely empty.

You indicate that you run your tests with only a few records of junk data laying around my database.  Those records will cause data.exists() to be true.

You can achieve your goal by placing the !data.exists() rule in your tree at the specific location where you want to require that no data already exists.  This is typically done at a location with a wildcard key, as in the example you linked:

{
  "rules": {
    // default rules are false if not specified

    "posts": {
      ".read": true, // everyone can read all posts

      "$postId": {
        // a new post can be created if it does not exist
        // existing posts can only be edited by their original "author"
        ".write": "!data.exists() && newData.exists() || data.child('author').val() == auth.uid",
        ".validate": "newData.hasChildren(['title', 'author', 'timestamp'])",
      }
    }
  }
}


问:
Create JavaScript Array From MSSQL Query
I am attempting to create a JavaScript array from a MSSQL query results.  Below is my syntax that I attempt to use, but the array is not created.  How should this be set-up so that the JavaScript array is properly assigned?</p>

```<code><?php
    $mssql = new mssql("localhost", "user", "password", "testdb");
    $data=mssql_query($mssql,"SELECT * FROM test");
?>
<script>
    var firstNames=[<?php
        while($info=mssql_fetch_array($data))
            echo $info['f_name'].',';
?>];
<?php
    $data=mssql_query($mssql,"SELECT * FROM test");
?>
var lastNames=[<?php
        while($info=myssql_fetch_array($data))
            echo '"'.$info['l_name'].'",';
?>];
</script>
<?php
    $mysqli->close();
?>
</code>```

答:
Look at this page: https://www.w3schools.com/jquery/ajax_ajax.asp

I know, W3 Schools isn't the best, but it's okay.

You can do that with jQuery easy, just google a bit and you need php knowledge for creating an array out of a mysql query.

Body:
I am attempting to create a JavaScript array from a MSSQL query results.  Below is my syntax that I attempt to use, but the array is not created.  How should this be set-up so that the JavaScript array is properly assigned?

<?php
    $mssql = new mssql("localhost", "user", "password", "testdb");
    $data=mssql_query($mssql,"SELECT * FROM test");
?>

<?php
    $mysqli->close();
?>


问:
How to open Play Market on Google Play Services page?
I have the app where I need to notify the user that he needs to update Google play services and redirect him to an Play Market on Play Services app page. Can you help me? Thank you in advance!</p>

答:
Place this in your manifest

```<code><meta-data
    android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" />
</code>```

and this code in your activity

```<code>   // Check status of Google Play Services
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);

// Check Google Play Service Available
try {
    if (status != ConnectionResult.SUCCESS) {
        GooglePlayServicesUtil.getErrorDialog(status, this, RQS_GooglePlayServices).show();
    }
} catch (Exception e) {
    Log.e("Error: GooglePlayServiceUtil: ", "" + e);
}
</code>```

Body:
Place this in your manifest

<meta-data
    android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" />

and this code in your activity

   // Check status of Google Play Services
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);

// Check Google Play Service Available
try {
    if (status != ConnectionResult.SUCCESS) {
        GooglePlayServicesUtil.getErrorDialog(status, this, RQS_GooglePlayServices).show();
    }
} catch (Exception e) {
    Log.e("Error: GooglePlayServiceUtil: ", "" + e);
}


问:
Updating a Rails 2.3 app to Rails 3.0.3 but getting undefined method `allow_forgery_protection'
Updating to Rails 3.0.3/Ruby 1.9.2 but getting the following error:

https://gist.github.com/737514

Any ideas?

答:
I just got this as well. It looks like it stems from the fact that Behavior overrides ActionController::Base#config with its own method (really just to provide a helper that has the same functionality as Behavior.config... which I'm a little ticked at, but anyway...)

I've forked "behavior" here and tried to clean up a few other things as well (Rspec2, some other Rails 3 things). The main change is that Behavior.config has been replaced with Behavior.behavior_config (same with the ActionController::Base mixin).


问:
var vs this vs $scope in AngularJS (1.4)
Hi I am learning angular and have lost my mind understanding the difference between 'var', 'this' and '$scope'.

Although I read this link but it went above my head.

When I use ng-controller="myController as ctrl" , I only have access to the variables and function set on this.

Whereas defining ng-controller="myController"  I only have access to variables and function set on $scope.

Can some one please explain this topic in depth?

答:
The keyword var is pure javascript and is just how you declare variables in javascript. Like so:

```<code>var myName = 'Nikolaj';
var myAge = 1700;
// etc.
</code>```

If you're unfamiliar with var you should start by learning Javascript before venturing into Angular, since the learning curve of Angular can be quite steep.

With that said I'll try to explain the other concepts.

Using controllerAs

When using the recommended controllerAs syntax, you get a reference to the controller instance in your template. This is what happens when you use

;

Your controller is basically "newed" and stored in a variable called ctrl which is made available in the template by angular. This allows you to access your controller members (public functions and variables) in the template like this:

```<code><div ng-controller="myController as ctrl">
    <p>{{ctrl.name}}</p>
</div>
</code>```

In order for the variable name to be available in the template, it must first be declared as a public member/variable of your controller. That is where the this-keyword comes into play. When you create your controller, to make the variable name public, you'd do it like this:

```<code>angular.module('app').controller('myController', function(){
    this.name = 'My name variable';
});
</code>```

Here this is a special concept in Javascript that is a reference to the function context - but just basic Javascript.

Using $scope

When you instead use your controller like this:

 you don't have direct access to the controller instance in your template. Instead, every time you use something in an Angular expression, for instance {{name}}, Angular implicitly assumes the variable name exists on the $scope variable. Each controller has a $scope variable associated with it when it is linked to the template. To access this variable inside your controller body, you'll access it like this:

```<code>angular.module('app').controller('myController', function($scope){
    $scope.name = 'My name variable';
});
</code>```

The reason why the controllerAs syntax is recommended, is in part because when using $scope, it can be difficult to determine which scope you're referring to when you have multiple nested scopes (i.e. nested controller). As in this example:

```<code><div ng-controller="FirstController">
    <h1>{{firstControllerVariable}}</h1>
    <div ng-controller="SecondController">
        <h2>{{whereDoIBelong}}</h2>
    </div>
</div>
</code>```

With the controllerAs syntax, it is pretty clear which variable belongs to which controller:

```<code><div ng-controller="FirstController as first">
    <h1>{{first.firstControllerVariable}}</h1>
    <div ng-controller="SecondController as second">
        <h2>{{second.iKnowWhereIBelong}}</h2>
    </div>
</div>
</code>```

Another reason to use the controllerAs syntax is because it'll make it easier to migrate to ES2016 and above.

Body:
The keyword var is pure javascript and is just how you declare variables in javascript. Like so:

var myName = 'Nikolaj';
var myAge = 1700;
// etc.

If you're unfamiliar with var you should start by learning Javascript before venturing into Angular, since the learning curve of Angular can be quite steep.

With that said I'll try to explain the other concepts.

Using controllerAs

When using the recommended controllerAs syntax, you get a reference to the controller instance in your template. This is what happens when you use <div ng-controller="myController as ctrl"></div>;

Your controller is basically "newed" and stored in a variable called ctrl which is made available in the template by angular. This allows you to access your controller members (public functions and variables) in the template like this:

<div ng-controller="myController as ctrl">
    <p>{{ctrl.name}}</p>
</div>

In order for the variable name to be available in the template, it must first be declared as a public member/variable of your controller. That is where the this-keyword comes into play. When you create your controller, to make the variable name public, you'd do it like this:

angular.module('app').controller('myController', function(){
    this.name = 'My name variable';
});

Here this is a special concept in Javascript that is a reference to the function context - but just basic Javascript.

Using $scope

When you instead use your controller like this: <div ng-controller="myController"></div> you don't have direct access to the controller instance in your template. Instead, every time you use something in an Angular expression, for instance {{name}}, Angular implicitly assumes the variable name exists on the $scope variable. Each controller has a $scope variable associated with it when it is linked to the template. To access this variable inside your controller body, you'll access it like this:

angular.module('app').controller('myController', function($scope){
    $scope.name = 'My name variable';
});

The reason why the controllerAs syntax is recommended, is in part because when using $scope, it can be difficult to determine which scope you're referring to when you have multiple nested scopes (i.e. nested controller). As in this example:

<div ng-controller="FirstController">
    <h1>{{firstControllerVariable}}</h1>
    <div ng-controller="SecondController">
        <h2>{{whereDoIBelong}}</h2>
    </div>
</div>

With the controllerAs syntax, it is pretty clear which variable belongs to which controller:

<div ng-controller="FirstController as first">
    <h1>{{first.firstControllerVariable}}</h1>
    <div ng-controller="SecondController as second">
        <h2>{{second.iKnowWhereIBelong}}</h2>
    </div>
</div>

Another reason to use the controllerAs syntax is because it'll make it easier to migrate to ES2016 and above.