问:
Webmethod Stops Working
I,m trying to pass value from jquery to webmethod. but when ever 1 pass value webmethod does not starts. and when i remove the passing value code it starts working properly What is the problem?
JS code.

```<code>$(function () {
    $.ajax({
        type: "POST",
        url: "ContryCityDDL.aspx/GetCountry",
        data: '{}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (r) {
            var ddlcontry = $("[id*=ddlcontry]");
            ddlcontry.empty().append('<option selected="selected" value="0">Please select</option>');
            $.each(r.d, function () {
                ddlcontry.append($("<option></option>").val(this['Value']).html(this['Text']));
            });
        }
    });

    $("#ddlcontry").change(function () {
        alert($('option:selected', $(this)).val());
       var countyId = $(this).val();

        $("#HiddenField1").val($('option:selected', $(this)).val());

        $.ajax({
            type: "POST",
            url: "ContryCityDDL.aspx/GetCity&countryId='"+countryId+"'",
            data: '{}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (r) {
                var ddlcity = $("[id*=ddlcity]");
                ddlcity.empty().append('<option selected="selected" value="0">Please select</option>');
                $.each(r.d, function () {
                    ddlcity.append($("<option></option>").val(this['Value']).html(this['Text']));
                });
            }
        });
    });
});
</code>```

C#

```<code>[WebMethod]
public static List<ListItem> GetCity(string countryId)
{

    string constrng;
            string query = "Select CityId,CityName From City";
    //string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;

     constrng = "Data Source=(LocalDB)\\v11.0;AttachDbFilename='C:\\Users\\Abdul Basit Mehmood\\Desktop\\DropdownAJAX\\DropdownAJAX\\App_Data\\ContryCity.mdf';Integrated Security=True";

    using (SqlConnection con = new SqlConnection(constrng))
    {
        using (SqlCommand cmd = new SqlCommand(query))
        {
            List<ListItem> customers = new List<ListItem>();
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            con.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    customers.Add(new ListItem
                    {
                        Value = sdr["CityId"].ToString(),
                        Text = sdr["CityName"].ToString()
                    });
                }
            }
            con.Close();
            return customers;
        }
    }
}
</code>```

when i remove 'string countryId' from c# code and  `var countyId = $(this).val();&countryId='"+countryId+"'" from js the code runs properly.

答:
try this on ddlcontry change function,

```<code> $("#ddlcontry").change(function () {
            alert($('option:selected', $(this)).val());
            var countryId = $(this).val();

            $("#HiddenField1").val($('option:selected', $(this)).val());

            $.ajax({
                type: "POST",
                url: "ContryCityDDL.aspx/GetCity",
                data: "{'countryId':'" + countryId + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (r) {
                    var ddlcity = $("[id*=ddlcity]");
                    ddlcity.empty().append('<option selected="selected" value="0">Please select</option>');
                    $.each(r.d, function () {
                        ddlcity.append($("<option></option>").val(this['Value']).html(this['Text']));
                    });
                }
            });
        });
</code>```

hope this is working.

Title: Webmethod Stops Working

Body:
I,m trying to pass value from jquery to webmethod. but when ever 1 pass value webmethod does not starts. and when i remove the passing value code it starts working properly What is the problem?
JS code.

$(function () {
    $.ajax({
        type: "POST",
        url: "ContryCityDDL.aspx/GetCountry",
        data: '{}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (r) {
            var ddlcontry = $("[id*=ddlcontry]");
            ddlcontry.empty().append('<option selected="selected" value="0">Please select</option>');
            $.each(r.d, function () {
                ddlcontry.append($("<option></option>").val(this['Value']).html(this['Text']));
            });
        }
    });

    $("#ddlcontry").change(function () {
        alert($('option:selected', $(this)).val());
       var countyId = $(this).val();

        $("#HiddenField1").val($('option:selected', $(this)).val());

        $.ajax({
            type: "POST",
            url: "ContryCityDDL.aspx/GetCity&countryId='"+countryId+"'",
            data: '{}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (r) {
                var ddlcity = $("[id*=ddlcity]");
                ddlcity.empty().append('<option selected="selected" value="0">Please select</option>');
                $.each(r.d, function () {
                    ddlcity.append($("<option></option>").val(this['Value']).html(this['Text']));
                });
            }
        });
    });
});

C#

[WebMethod]
public static List<ListItem> GetCity(string countryId)
{

    string constrng;
            string query = "Select CityId,CityName From City";
    //string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;

     constrng = "Data Source=(LocalDB)\\v11.0;AttachDbFilename='C:\\Users\\Abdul Basit Mehmood\\Desktop\\DropdownAJAX\\DropdownAJAX\\App_Data\\ContryCity.mdf';Integrated Security=True";

    using (SqlConnection con = new SqlConnection(constrng))
    {
        using (SqlCommand cmd = new SqlCommand(query))
        {
            List<ListItem> customers = new List<ListItem>();
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            con.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    customers.Add(new ListItem
                    {
                        Value = sdr["CityId"].ToString(),
                        Text = sdr["CityName"].ToString()
                    });
                }
            }
            con.Close();
            return customers;
        }
    }
}

when i remove 'string countryId' from c# code and  `var countyId = $(this).val();&countryId='"+countryId+"'" from js the code runs properly.

Body:
try this on ddlcontry change function,

 $("#ddlcontry").change(function () {
            alert($('option:selected', $(this)).val());
            var countryId = $(this).val();

            $("#HiddenField1").val($('option:selected', $(this)).val());

            $.ajax({
                type: "POST",
                url: "ContryCityDDL.aspx/GetCity",
                data: "{'countryId':'" + countryId + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (r) {
                    var ddlcity = $("[id*=ddlcity]");
                    ddlcity.empty().append('<option selected="selected" value="0">Please select</option>');
                    $.each(r.d, function () {
                        ddlcity.append($("<option></option>").val(this['Value']).html(this['Text']));
                    });
                }
            });
        });

hope this is working.


来源: stackexchange

问:
Bootstrap Theme Not Being Applied
I'm trying to apply the Bootstrap theme to my datatable. I'm using ngx-datatable version 10.4.0 because I'm still on Angular 4 and 11.0 isn't compatible. According to the changelog, the Bootstrap theme was added in version 10.3.0.

Below is my component.html:

```<code><div>
    <ngx-datatable class="bootstrap" [rows]="rows" [columns]="columns" (select)='onSelect($event)' [selected]="selected" [selectionType]="'single'"
        [limit]="10" [columnMode]="'force'" [headerHeight]="40" [footerHeight]="40" [rowHeight]="'auto'">
    </ngx-datatable>
</div>
</code>```

However, this doesn't add the styling as in the demo. I think I have included everything the documentation shows.

I'm using Bootstrap 3.3.7. Is 4.0 required? Am I not including something correctly?

答:
Make sure you are including the scss file to your build.

In .angular-cli.json you should add it:

```<code>"apps": [
  {
    ...
    "styles": [
      ...
      "../node_modules/@swimlane/ngx-datatable/release/themes/bootstrap.css",
      ...
    ],
</code>```

also the <ngx-datatable> element should have both bootstrap and ngx-datatable classes:

```<code><ngx-datatable class="bootstrap ngx-datatable">
</code>```

ContentLicense: CC BY-SA 3.0

Title: Bootstrap Theme Not Being Applied

Body:
I'm trying to apply the Bootstrap theme to my datatable. I'm using ngx-datatable version 10.4.0 because I'm still on Angular 4 and 11.0 isn't compatible. According to the changelog, the Bootstrap theme was added in version 10.3.0.

Below is my component.html:

    <ngx-datatable class="bootstrap" [rows]="rows" [columns]="columns" (select)='onSelect($event)' [selected]="selected" [selectionType]="'single'"
        [limit]="10" [columnMode]="'force'" [headerHeight]="40" [footerHeight]="40" [rowHeight]="'auto'">
    </ngx-datatable>

However, this doesn't add the styling as in the demo. I think I have included everything the documentation shows.

I'm using Bootstrap 3.3.7. Is 4.0 required? Am I not including something correctly?

Body:
Make sure you are including the scss file to your build.

In .angular-cli.json you should add it:

"apps": [
  {
    ...
    "styles": [
      ...
      "../node_modules/@swimlane/ngx-datatable/release/themes/bootstrap.css",
      ...
    ],

also the <ngx-datatable> element should have both bootstrap and ngx-datatable classes:

<ngx-datatable class="bootstrap ngx-datatable">


问:
Crash when applying filter to AVVideoComposition
I want to apply filter to AVVideoComposition by function:

init(asset: AVAsset, applyingCIFiltersWithHandler: (AVAsynchronousCIImageFilteringRequest) -> Void)

In which, the asset is AVComposition. When an AVPlayerItem plays this composition with the videoComposition, app crashes with error:

reason: '*** -[AVCoreImageFilterCustomVideoCompositor startVideoCompositionRequest:] Expecting video composition to contain only AVCoreImageFilterVideoCompositionInstruction'

I wonder how to fix the crash.

PS: I have two videoTracks in composition, each timeRange has its instruction

答:
I guess you are trying to add AVVideoCompositionLayerInstruction to the AVVideoComposition.

Try the simple approach first and see if you need any changes:

```<code>AVURLAsset *asset = [AVURLAsset assetWithURL:videoURL];
CIFilter *filter = [CIFilter filterWithName:@"CIHueAdjust"]; // the filter you want to add: https://developer.apple.com/library/content/documentation/GraphicsImaging/Reference/CoreImageFilterReference/index.html#//apple_ref/doc/filter/ci/
AVMutableVideoComposition *videoComposition = [AVMutableVideoComposition videoCompositionWithAsset:asset applyingCIFiltersWithHandler:^(AVAsynchronousCIImageFilteringRequest * _Nonnull request) {
    // set filter input image
[filter setDefaults];
    [filter setValue:sourceImage forKey:kCIInputImageKey];

    // hue
    NSNumber *angle = [NSNumber numberWithFloat:0.8];
    [filter setValue:angle forKey:kCIInputAngleKey];

    CIImage *outputImage = filter.outputImage;
    [request finishWithImage:outputImage context:nil];
}];

AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPreset1920x1080];
exportSession.outputFileType = AVFileTypeQuickTimeMovie;
exportSession.outputURL = outputURL;
exportSession.videoComposition = videoComposition;

// export the session async
[exportSession exportAsynchronouslyWithCompletionHandler:^{
    switch (exportSession.status) {
        case AVAssetExportSessionStatusCompleted:
            NSLog(@"Yeah!");
            break;

        default:
            NSLog(@"Nooo!");
            break;
    }
}];
</code>```

Body:
I guess you are trying to add AVVideoCompositionLayerInstruction to the AVVideoComposition.

Try the simple approach first and see if you need any changes:

AVURLAsset *asset = [AVURLAsset assetWithURL:videoURL];
CIFilter *filter = [CIFilter filterWithName:@"CIHueAdjust"]; // the filter you want to add: https://developer.apple.com/library/content/documentation/GraphicsImaging/Reference/CoreImageFilterReference/index.html#//apple_ref/doc/filter/ci/
AVMutableVideoComposition *videoComposition = [AVMutableVideoComposition videoCompositionWithAsset:asset applyingCIFiltersWithHandler:^(AVAsynchronousCIImageFilteringRequest * _Nonnull request) {
    // set filter input image
[filter setDefaults];
    [filter setValue:sourceImage forKey:kCIInputImageKey];

    // hue
    NSNumber *angle = [NSNumber numberWithFloat:0.8];
    [filter setValue:angle forKey:kCIInputAngleKey];

    CIImage *outputImage = filter.outputImage;
    [request finishWithImage:outputImage context:nil];
}];

AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPreset1920x1080];
exportSession.outputFileType = AVFileTypeQuickTimeMovie;
exportSession.outputURL = outputURL;
exportSession.videoComposition = videoComposition;

// export the session async
[exportSession exportAsynchronouslyWithCompletionHandler:^{
    switch (exportSession.status) {
        case AVAssetExportSessionStatusCompleted:
            NSLog(@"Yeah!");
            break;

        default:
            NSLog(@"Nooo!");
            break;
    }
}];


问:
Error looping Bitmap class to convert base64 strings into images
I wrote a web service in Java -- what I am trying to do is to read JSON data in Android. The problem is, I receive an error only when looping the Bitmap class. I have the enclosed JSON request code:

```<code>RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());

    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest( Request.Method.GET, URL,null,
            new Response.Listener<JSONArray>() {

                @Override
                public void onResponse(JSONArray response) {

                    try{
                        // Loop through the array elements
                        for(int i=0;i<response.length();i++){

                            JSONObject jsonData = response.getJSONObject(i);

                            String name = jsonData.getString("name");
                            String manufacture = jsonData.getString("manufacture");
                            Double price = Double.valueOf(jsonData.getString("price"));
                            String imageString = jsonData.getString("image");

                            // Display the formatted json data in text view
                            productDetails.append("Name: " + name +"\nManufacture: " + manufacture + "\nPrice: " + price.toString() );
                            productDetails.append("\n\n");

                            // decode base64 string to image
                            decodeImageString( imageString, prodImageButton);

                        }
                    }catch (JSONException e){
                        Toast.makeText( getApplication(), e.getMessage().toString(), Toast.LENGTH_LONG).show();
                    }
                }
            },
            new Response.ErrorListener(){
                @Override
                public void onErrorResponse(VolleyError error){
                    // Do something when error occurred
                    //Toast.makeText( getApplication(), error.getMessage().toString(), Toast.LENGTH_LONG).show();
                }
            });

    // Add JsonArrayRequest to the RequestQueue
    requestQueue.add(jsonArrayRequest);
}

private void decodeImageString(String imageString, ImageButton imageView){

    byte[] decodeString = Base64.decode (imageString, Base64.DEFAULT);
    Bitmap decoded = BitmapFactory.decodeByteArray (decodeString, 0, decodeString.length);
    imageView.setImageBitmap(decoded);
}
</code>```

The error thrown:

```<code> E/AndroidRuntime: FATAL EXCEPTION: main
              Process: lagecy.live.desh.com.shoppincarttest, PID: 5224
              java.lang.IllegalArgumentException: bad base-64
                  at android.util.Base64.decode(Base64.java:161)
                  at android.util.Base64.decode(Base64.java:136)
                  at android.util.Base64.decode(Base64.java:118)
                  at lagecy.live.desh.com.shoppincarttest.MainActivity.decodeImageString(MainActivity.java:106)
                  at lagecy.live.desh.com.shoppincarttest.MainActivity.access$000(MainActivity.java:31)
                  at lagecy.live.desh.com.shoppincarttest.MainActivity$1.onResponse(MainActivity.java:84)
                  at lagecy.live.desh.com.shoppincarttest.MainActivity$1.onResponse(MainActivity.java:61)
                  at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
                  at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
                  at android.os.Handler.handleCallback(Handler.java:751)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6119)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code>```

Sample JSON data:

```<code>[{
    "id": 1,
    "name": "Albany",
    "manufacture": "Albany Superior Low Gi Sliced Brown Seed Bread 700g",
    "price": 15.49,
    "category": "Food",
    "type": "Breads",
    "image": "data:image/jpeg;base64,...[long text string]"
}]
</code>```

答:
Updated codes

```<code>    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest( Request.Method.GET, URL,null,
            new Response.Listener<JSONArray>() {

                @Override
                public void onResponse(JSONArray response) {

                    try{
                        // Loop through the array elements
                        for(int i=0;i<response.length();i++) {

                            JSONObject jsonData = response.getJSONObject(i);

                            String name = jsonData.getString("name");
                            String manufacture = jsonData.getString("manufacture");
                            Double price = Double.valueOf(jsonData.getString("price"));
                            String imageString = jsonData.getString("image");

                            final String pureBase64Encoded = imageString.substring(imageString.indexOf(",") + 1);

                            // Display the formatted json data in text view
                            productDetails.append("Name: " + name + "\nManufacture: " + manufacture + "\nPrice: " + price.toString());
                            productDetails.append("\n\n");

                            productImages.add(i, pureBase64Encoded);

                            String prodImages = productImages.get(i).toString();

                            // decode base64 string to image
                            decodeImageString( prodImages, prodImageButton);

                        }

                    }catch (JSONException e){
                        Toast.makeText( getApplication(), e.getMessage().toString(), Toast.LENGTH_LONG).show();
                    }
                }
            },
            new Response.ErrorListener(){
                @Override
                public void onErrorResponse(VolleyError error){
                    // Do something when error occurred
                    //Toast.makeText( getApplication(), error.getMessage().toString(), Toast.LENGTH_LONG).show();
                }
            });

    // Add JsonArrayRequest to the RequestQueue
    requestQueue.add(jsonArrayRequest);
}

private void decodeImageString(String imageString, ImageButton imageView){

    byte[] decodeString = Base64.decode (imageString, Base64.DEFAULT);
    Bitmap decoded = BitmapFactory.decodeByteArray (decodeString, 0, decodeString.length);
    imageView.setImageBitmap(decoded);

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I wrote a web service in Java -- what I am trying to do is to read JSON data in Android. The problem is, I receive an error only when looping the Bitmap class. I have the enclosed JSON request code:

RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());

    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest( Request.Method.GET, URL,null,
            new Response.Listener<JSONArray>() {

                @Override
                public void onResponse(JSONArray response) {

                    try{
                        // Loop through the array elements
                        for(int i=0;i<response.length();i++){

                            JSONObject jsonData = response.getJSONObject(i);

                            String name = jsonData.getString("name");
                            String manufacture = jsonData.getString("manufacture");
                            Double price = Double.valueOf(jsonData.getString("price"));
                            String imageString = jsonData.getString("image");

                            // Display the formatted json data in text view
                            productDetails.append("Name: " + name +"\nManufacture: " + manufacture + "\nPrice: " + price.toString() );
                            productDetails.append("\n\n");

                            // decode base64 string to image
                            decodeImageString( imageString, prodImageButton);

                        }
                    }catch (JSONException e){
                        Toast.makeText( getApplication(), e.getMessage().toString(), Toast.LENGTH_LONG).show();
                    }
                }
            },
            new Response.ErrorListener(){
                @Override
                public void onErrorResponse(VolleyError error){
                    // Do something when error occurred
                    //Toast.makeText( getApplication(), error.getMessage().toString(), Toast.LENGTH_LONG).show();
                }
            });

    // Add JsonArrayRequest to the RequestQueue
    requestQueue.add(jsonArrayRequest);
}

private void decodeImageString(String imageString, ImageButton imageView){

    byte[] decodeString = Base64.decode (imageString, Base64.DEFAULT);
    Bitmap decoded = BitmapFactory.decodeByteArray (decodeString, 0, decodeString.length);
    imageView.setImageBitmap(decoded);
}

The error thrown:

 E/AndroidRuntime: FATAL EXCEPTION: main
              Process: lagecy.live.desh.com.shoppincarttest, PID: 5224
              java.lang.IllegalArgumentException: bad base-64
                  at android.util.Base64.decode(Base64.java:161)
                  at android.util.Base64.decode(Base64.java:136)
                  at android.util.Base64.decode(Base64.java:118)
                  at lagecy.live.desh.com.shoppincarttest.MainActivity.decodeImageString(MainActivity.java:106)
                  at lagecy.live.desh.com.shoppincarttest.MainActivity.access$000(MainActivity.java:31)
                  at lagecy.live.desh.com.shoppincarttest.MainActivity$1.onResponse(MainActivity.java:84)
                  at lagecy.live.desh.com.shoppincarttest.MainActivity$1.onResponse(MainActivity.java:61)
                  at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
                  at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
                  at android.os.Handler.handleCallback(Handler.java:751)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6119)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Sample JSON data:

[{
    "id": 1,
    "name": "Albany",
    "manufacture": "Albany Superior Low Gi Sliced Brown Seed Bread 700g",
    "price": 15.49,
    "category": "Food",
    "type": "Breads",
    "image": "data:image/jpeg;base64,...[long text string]"
}]

Body:
Updated codes

    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest( Request.Method.GET, URL,null,
            new Response.Listener<JSONArray>() {

                @Override
                public void onResponse(JSONArray response) {

                    try{
                        // Loop through the array elements
                        for(int i=0;i<response.length();i++) {

                            JSONObject jsonData = response.getJSONObject(i);

                            String name = jsonData.getString("name");
                            String manufacture = jsonData.getString("manufacture");
                            Double price = Double.valueOf(jsonData.getString("price"));
                            String imageString = jsonData.getString("image");

                            final String pureBase64Encoded = imageString.substring(imageString.indexOf(",") + 1);

                            // Display the formatted json data in text view
                            productDetails.append("Name: " + name + "\nManufacture: " + manufacture + "\nPrice: " + price.toString());
                            productDetails.append("\n\n");

                            productImages.add(i, pureBase64Encoded);

                            String prodImages = productImages.get(i).toString();

                            // decode base64 string to image
                            decodeImageString( prodImages, prodImageButton);

                        }

                    }catch (JSONException e){
                        Toast.makeText( getApplication(), e.getMessage().toString(), Toast.LENGTH_LONG).show();
                    }
                }
            },
            new Response.ErrorListener(){
                @Override
                public void onErrorResponse(VolleyError error){
                    // Do something when error occurred
                    //Toast.makeText( getApplication(), error.getMessage().toString(), Toast.LENGTH_LONG).show();
                }
            });

    // Add JsonArrayRequest to the RequestQueue
    requestQueue.add(jsonArrayRequest);
}

private void decodeImageString(String imageString, ImageButton imageView){

    byte[] decodeString = Base64.decode (imageString, Base64.DEFAULT);
    Bitmap decoded = BitmapFactory.decodeByteArray (decodeString, 0, decodeString.length);
    imageView.setImageBitmap(decoded);

}


问:
Auto regeneration is not working with _config.yml?
I installed jekyll and run it from cli:

```<code>jekyll --server --auto
</code>```

But when I change _config.yml I can't see that my changes where applied and I have to restart server every time.

I really need to restart server every time when I change _config.yml? Or there is some workaround?

答:
I really need to restart server every time when I change _config.yml?
  Or there is some workaround?

There is some workaround:

1) Install watchy.

```<code>npm i -D watchy
</code>```

2) Restart on config change (for example as a package.json script)

```<code>"scripts": {
  "restart": "watchy -w _config.yml -- bundle exec jekyll serve --drafts --watch",
</code>```

(--drafts is unrelated, but I am assuming you do this locally in dev/authoring mode...)

Body:
I installed jekyll and run it from cli:

jekyll --server --auto

But when I change _config.yml I can't see that my changes where applied and I have to restart server every time.

I really need to restart server every time when I change _config.yml? Or there is some workaround?

Body:
I really need to restart server every time when I change _config.yml?
  Or there is some workaround?

There is some workaround:

1) Install watchy.

npm i -D watchy

2) Restart on config change (for example as a package.json script)

"scripts": {
  "restart": "watchy -w _config.yml -- bundle exec jekyll serve --drafts --watch",

(--drafts is unrelated, but I am assuming you do this locally in dev/authoring mode...)


问:
SQL Server : SELECT DISTINCT Group By with Count
I have a table as below.

Is it possible that I can make the output as above?

Thanks

答:
For sql server, try this :</p>

```<code>SELECT id, max(date) as date, msg, count(id) AS count
FROM table_name
GROUP BY id, msg
</code>```

Body:
For sql server, try this :

SELECT id, max(date) as date, msg, count(id) AS count
FROM table_name
GROUP BY id, msg


问:
How to verify whether validation message is displaying or not using protractor
Test case : I just want to validate the "Name" field by sending "alpha numeric characters" data one at a time into the name field and verify whether "invalid data" validation message is displaying or not

My Spec file code is below.

```<code>   //Testcase 3 : To verify whether "Name" field validation message is displaying or not
// "name field is a required" field
using(CertificationTestData.testData, function(testdata){

    it('validation of Certificate Name field content',()=>{

        //To clear the "Ceritication Name" field data
        page.getCertificationNameField().clear();

        //enter each type of test data one at a time
        page.getCertificationNameField().sendKeys(testdata.data);

        browser.driver.sleep(5000);

        page.getAnyWhereCertificationPage().click();

        //To check whether any validation message is displaying for "Name" field
        expect(page.getValidationMessage().isDisplayed()).toBeFalsy();
    });
});
</code>```

My external test data file is below

```<code> testData :[
    {data:"abcd"},
    {data: "1234"},
    {data:"!@#$%#"},
    {data:"ad123!@##$"}
],
</code>```

My Po file code is below.

```<code> //To return "Certification Name" field
getCertificationNameField(){
    return element(by.css('input[formcontrolname="CertificationsName"]'));
}

 //To return validation message
getValidationMessage(){
    return element(by.className('ui-message ui-messages-error ui-corner-all'));
}
</code>```

When i run my test script it is displaying below error message.

```<code> should test certificate tab validation of Certificate Name field content
</code>```

- Failed: No element found using locator: By(css selector, .ui-message.ui-messages-error.ui-corner-all)

Is there any way to verify whether the validation message is displaying or not ??

答:
isDisplayed() always requires the presence of the element as it executes the ElementFinder and returns the error of it.

If the element is for sure displayed, when it's present, just replace isDisplayed() with isPresent().

Else check if(element.isPresent()){expect(element.isDisplayed()).toBeFalsy()} else {expect(element.isPresent()).toBeFalsy()} ... though it's a bit strange and verbose that way.

Body:
Test case : I just want to validate the "Name" field by sending "alpha numeric characters" data one at a time into the name field and verify whether "invalid data" validation message is displaying or not

My Spec file code is below.

   //Testcase 3 : To verify whether "Name" field validation message is displaying or not
// "name field is a required" field
using(CertificationTestData.testData, function(testdata){

    it('validation of Certificate Name field content',()=>{

        //To clear the "Ceritication Name" field data
        page.getCertificationNameField().clear();

        //enter each type of test data one at a time
        page.getCertificationNameField().sendKeys(testdata.data);

        browser.driver.sleep(5000);

        page.getAnyWhereCertificationPage().click();

        //To check whether any validation message is displaying for "Name" field
        expect(page.getValidationMessage().isDisplayed()).toBeFalsy();
    });
});

My external test data file is below

 testData :[
    {data:"abcd"},
    {data: "1234"},
    {data:"!@#$%#"},
    {data:"ad123!@##$"}
],

My Po file code is below.

 //To return "Certification Name" field
getCertificationNameField(){
    return element(by.css('input[formcontrolname="CertificationsName"]'));
}

 //To return validation message
getValidationMessage(){
    return element(by.className('ui-message ui-messages-error ui-corner-all'));
}

When i run my test script it is displaying below error message.

 should test certificate tab validation of Certificate Name field content

- Failed: No element found using locator: By(css selector, .ui-message.ui-messages-error.ui-corner-all)

Is there any way to verify whether the validation message is displaying or not ??


问:
How can I connect to Android with ADB over TCP?
I am attempting to debug an application on a Motorola Droid, but I am having some difficulty connecting to the device via USB. My development server is a Windows 7 64-bit VM running in Hyper-V, and so I cannot connect directly via USB in the guest or from the host.

I installed a couple of different USB-over-TCP solutions, but the connection appears to have issues since the ADB monitor reports "devicemonitor failed to start monitoring" repeatedly. Is there a way to connect directly from the client on the development machine to the daemon on the device using the network instead of the USB connection or possibly another viable options?

答:
```<code>adb tcpip 5555
</code>```

Weird, but this only works for me if I have the USB cable connected, then I can unplug the usb and go for it with everything else adb.

and the same when returning to usb,

```<code>adb usb
</code>```

will only work if usb is connected.

It doesn't matter if I issue the

```<code>setprop service.adb.tcp.port 5555
</code>```

or

```<code>setprop service.adb.tcp.port -1
</code>```

then stop & start adbd, I still need the usb cable in or it doesn't work.

So, if my ADB over usb wasn't working, I bet I wouldn't be able to enable ADB over WiFi either.

Body:
adb tcpip 5555

Weird, but this only works for me if I have the USB cable connected, then I can unplug the usb and go for it with everything else adb.

and the same when returning to usb,

adb usb

will only work if usb is connected.

It doesn't matter if I issue the

setprop service.adb.tcp.port 5555

or

setprop service.adb.tcp.port -1

then stop & start adbd, I still need the usb cable in or it doesn't work.

So, if my ADB over usb wasn't working, I bet I wouldn't be able to enable ADB over WiFi either.

ContentLicense: CC BY-SA 2.5


问:
How to iterate keys of an object nested in an object in Angular 4?
Variables:

```<code> objectKeys = Object.keys;
  objectValues = Object.values;
</code>```

JSON:

```<code>@Injectable()
export class DbService {
    db:Database[] = [
        {
        "id":0,
        "img":"../../../assets/img/logo/gro.png",
        "name":"CompName",
        "type":"CompType",
        "hours": "9:00AM-9:00PM",
        "number": 999999,
        "email": 'info@company.com',
        "items": [
                    {"Beverage":[
                        {"Bigga":'lg'},
                        {"Soda":'sm'},
                        {"Wata":'fresh'},
                        {"Sprite":'codein'}
                    ]},
                    {'Canned':[
                        {"Tuna":'lg'},
                        {"Salmon":'sm'},
                        {"Mackerel":'fresh'},
                        {"Spam":'codein'}
                    ]}
                ]
        },
</code>```

These lines displays all the keys from the item objects

```<code><div *ngFor="let item of store[0].items" class="ai">
        <div *ngFor="let key of objectKeys(item)">{{key}}</div>
    </div>
</code>```

However trying to get the values from the child object of above object is displaying .."0 1 2 3 0 1 2 3 "

```<code><div *ngFor="let rn of store[0].items" class="items">
            <div *ngFor="let value of objectValues(rn)">
                <div *ngFor="let btn of objectKeys(value)">
                    {{btn}}
                </div>
            </div>
        </div>
</code>```

答:
You are only getting the keys, not the value associated with that key</p>

```<code><div *ngFor="let rn of store[0].items" class="items">
    <div *ngFor="let value of objectValues(rn)">
        <div *ngFor="let btn of objectKeys(value)">
            {{value[btn]}}
        </div>
    </div>
</div>
</code>```

Body:
Variables:

 objectKeys = Object.keys;
  objectValues = Object.values;

JSON:

@Injectable()
export class DbService {
    db:Database[] = [
        {
        "id":0,
        "img":"../../../assets/img/logo/gro.png",
        "name":"CompName",
        "type":"CompType",
        "hours": "9:00AM-9:00PM",
        "number": 999999,
        "email": 'info@company.com',
        "items": [
                    {"Beverage":[
                        {"Bigga":'lg'},
                        {"Soda":'sm'},
                        {"Wata":'fresh'},
                        {"Sprite":'codein'}
                    ]},
                    {'Canned':[
                        {"Tuna":'lg'},
                        {"Salmon":'sm'},
                        {"Mackerel":'fresh'},
                        {"Spam":'codein'}
                    ]}
                ]
        },

These lines displays all the keys from the item objects

{{key}}

However trying to get the values from the child object of above object is displaying .."0 1 2 3 0 1 2 3 "

                    {{btn}}

Body:
You are only getting the keys, not the value associated with that key

<div *ngFor="let rn of store[0].items" class="items">
    <div *ngFor="let value of objectValues(rn)">
        <div *ngFor="let btn of objectKeys(value)">
            {{value[btn]}}
        </div>
    </div>
</div>


问:
How to do paging on Object that isn't Entity?
I'm trying to do paging, very similar to the option of @RepositoryRestResource
but only on object that isn't Entity.

the code:

```<code>public class FloorplanDevice {

private String FloorplanName;
private Long FloorplanId;

private Long DeviceId;
private String DeviceName;
private String macAddress;
private Long groupId;
private LocatableType deviceType;

public String getFloorplanName() {
    return FloorplanName;
}

public void setFloorplanName(String floorplanName) {
    FloorplanName = floorplanName;
}

public Long getFloorplanId() {
    return FloorplanId;
}

public void setFloorplanId(Long floorplanId) {
    FloorplanId = floorplanId;
}

public Long getDeviceId() {
    return DeviceId;
}

public void setDeviceId(Long deviceId) {
    DeviceId = deviceId;
}

public String getDeviceName() {
    return DeviceName;
}

public void setDeviceName(String deviceName) {
    DeviceName = deviceName;
}

public String getMacAddress() {
    return macAddress;
}

public void setMacAddress(String macAddress) {
    this.macAddress = macAddress;
}

public Long getGroupId() {
    return groupId;
}

public void setGroupId(Long groupId) {
    this.groupId = groupId;
}

public LocatableType getDeviceType() {
    return deviceType;
}

public void setDeviceType(LocatableType deviceType) {
    this.deviceType = deviceType;
}

public FloorplanDevice() {
}

public FloorplanDevice(String floorplanName, Long floorplanId, Long deviceId, String deviceName, String macAddress, Long groupId, LocatableType deviceType) {
    FloorplanName = floorplanName;
    FloorplanId = floorplanId;
    DeviceId = deviceId;
    DeviceName = deviceName;
    this.macAddress = macAddress;
    this.groupId = groupId;
    this.deviceType = deviceType;
  }
}
</code>```

This object doesn't have Repository but it has controller:

```<code>   @RequestMapping(
      path = arrayOf("/floorplanDevice/{groupId}", "/floorplanDevice/{groupId}/"),
      method = arrayOf(RequestMethod.GET))
 open fun getFloorplanDevice(@PathVariable("groupId") groupId: Long): ResponseEntity<*>{

var floorplanDevice= floorplanService.getFloorplanDevice(groupId)
return ResponseEntity(floorplanDevice, HttpStatus.OK)

 }
</code>```

So how can I do Paging to this object with page number and size (if it possible sorting also)?

I'm using java Spring

Thank you

答:
Try something like this:</p>

```<code>public Page<FloorplanDevice> getFloorplanDevice(@PathVariable("groupId") Long groupId,
            @PageableDefault Pageable pageable)
    List<FloorplanDevice> list = floorplanService.getFloorplanDevice(groupId);

    MutableSortDefinition sort = pageable.getSort() != null ?
            StreamSupport.stream(pageable.getSort().spliterator(), false)
                .findFirst()
                .map(it -> new MutableSortDefinition(it.getProperty(), it.isIgnoreCase(), it.isAscending()))
                .orElse(null)
            : null;

    PagedListHolder<FloorplanDevice> pageHolder = new PagedListHolder<>(list, sort);
    pageHolder.setPage(pageable.getPageNumber());
    pageHolder.setPageSize(pageable.getPageSize());
    pageHolder.resort();

    List<FloorplanDevice> content = pageHolder.getPageList();
    Page<FloorplanDevice> page = new PageImpl<>(content, pageable, list.size());

    return page;
}
</code>```

Body:
I'm trying to do paging, very similar to the option of @RepositoryRestResource
but only on object that isn't Entity.

the code:

public class FloorplanDevice {

private String FloorplanName;
private Long FloorplanId;

private Long DeviceId;
private String DeviceName;
private String macAddress;
private Long groupId;
private LocatableType deviceType;

public String getFloorplanName() {
    return FloorplanName;
}

public void setFloorplanName(String floorplanName) {
    FloorplanName = floorplanName;
}

public Long getFloorplanId() {
    return FloorplanId;
}

public void setFloorplanId(Long floorplanId) {
    FloorplanId = floorplanId;
}

public Long getDeviceId() {
    return DeviceId;
}

public void setDeviceId(Long deviceId) {
    DeviceId = deviceId;
}

public String getDeviceName() {
    return DeviceName;
}

public void setDeviceName(String deviceName) {
    DeviceName = deviceName;
}

public String getMacAddress() {
    return macAddress;
}

public void setMacAddress(String macAddress) {
    this.macAddress = macAddress;
}

public Long getGroupId() {
    return groupId;
}

public void setGroupId(Long groupId) {
    this.groupId = groupId;
}

public LocatableType getDeviceType() {
    return deviceType;
}

public void setDeviceType(LocatableType deviceType) {
    this.deviceType = deviceType;
}

public FloorplanDevice() {
}

public FloorplanDevice(String floorplanName, Long floorplanId, Long deviceId, String deviceName, String macAddress, Long groupId, LocatableType deviceType) {
    FloorplanName = floorplanName;
    FloorplanId = floorplanId;
    DeviceId = deviceId;
    DeviceName = deviceName;
    this.macAddress = macAddress;
    this.groupId = groupId;
    this.deviceType = deviceType;
  }
}

This object doesn't have Repository but it has controller:

   @RequestMapping(
      path = arrayOf("/floorplanDevice/{groupId}", "/floorplanDevice/{groupId}/"),
      method = arrayOf(RequestMethod.GET))
 open fun getFloorplanDevice(@PathVariable("groupId") groupId: Long): ResponseEntity<*>{

var floorplanDevice= floorplanService.getFloorplanDevice(groupId)
return ResponseEntity(floorplanDevice, HttpStatus.OK)

 }

So how can I do Paging to this object with page number and size (if it possible sorting also)?

I'm using java Spring

Thank you

Body:
Try something like this:

public Page<FloorplanDevice> getFloorplanDevice(@PathVariable("groupId") Long groupId,
            @PageableDefault Pageable pageable)
    List<FloorplanDevice> list = floorplanService.getFloorplanDevice(groupId);

    MutableSortDefinition sort = pageable.getSort() != null ?
            StreamSupport.stream(pageable.getSort().spliterator(), false)
                .findFirst()
                .map(it -> new MutableSortDefinition(it.getProperty(), it.isIgnoreCase(), it.isAscending()))
                .orElse(null)
            : null;

    PagedListHolder<FloorplanDevice> pageHolder = new PagedListHolder<>(list, sort);
    pageHolder.setPage(pageable.getPageNumber());
    pageHolder.setPageSize(pageable.getPageSize());
    pageHolder.resort();

    List<FloorplanDevice> content = pageHolder.getPageList();
    Page<FloorplanDevice> page = new PageImpl<>(content, pageable, list.size());

    return page;
}


问:
GetCursorPos Address below Shape Object
I have a code which displays the cursor position in pixels and the equivalent Range on the spreadsheet. As soon as I put the cursor over a Shape Object the code gives an error because it can't retrieve the cell value below the Shape. Is there any workaround to that? Below is the code:</p>

```<code>Public Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
Public Type POINTAPI
Xcoord As Long
Ycoord As Long
End Type

Sub SetKey()

    Application.OnKey "a", "PositionXY"

End Sub

Sub PositionXY()
Dim llCoord As POINTAPI
Dim rng As Range

Do
GetCursorPos llCoord
Set rng = GetRange(llCoord.Xcoord, llCoord.Ycoord)

Range("A1").Value = "X: " & llCoord.Xcoord & " Y: " & llCoord.Ycoord
Range("A2").Value = rng.Address
DoEvents
Loop
End Sub

Function GetRange(x As Long, y As Long) As Range
    Set GetRange = ActiveWindow.RangeFromPoint(x, y)
End Function
</code>```

答:
Worked it around by placing a Label over the Shape object, and assigning the following code to it:</p>

```<code>Private Sub Label1_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)

rng = ActiveSheet.Shapes("Label1").TopLeftCell.Address
Range("A1").Value = rng

End Sub
</code>```

Title: GetCursorPos Address below Shape Object

Body:
I have a code which displays the cursor position in pixels and the equivalent Range on the spreadsheet. As soon as I put the cursor over a Shape Object the code gives an error because it can't retrieve the cell value below the Shape. Is there any workaround to that? Below is the code:

Public Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
Public Type POINTAPI
Xcoord As Long
Ycoord As Long
End Type

Sub SetKey()

    Application.OnKey "a", "PositionXY"

End Sub

Sub PositionXY()
Dim llCoord As POINTAPI
Dim rng As Range

Do
GetCursorPos llCoord
Set rng = GetRange(llCoord.Xcoord, llCoord.Ycoord)

Range("A1").Value = "X: " & llCoord.Xcoord & " Y: " & llCoord.Ycoord
Range("A2").Value = rng.Address
DoEvents
Loop
End Sub

Function GetRange(x As Long, y As Long) As Range
    Set GetRange = ActiveWindow.RangeFromPoint(x, y)
End Function

Body:
Worked it around by placing a Label over the Shape object, and assigning the following code to it:

Private Sub Label1_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)

rng = ActiveSheet.Shapes("Label1").TopLeftCell.Address
Range("A1").Value = rng

End Sub


问:
Return array of custom class objects from dictionary
I have a super simple class I called a Tuple:

```<code>Private vals(1) As Integer
-----
Public Property Get x()

x = vals(0)

End Property
-----
Public Property Get y()

y = vals(1)

End Property
-----
Public Sub SetVals(x As Integer, y As Integer)

vals(0) = x
vals(1) = y

End Sub
</code>```

I have a dictionary which is populated with arrays of these Tuples:

```<code>for x = whatever to whatever
   Set t = New Tuple
   t.SetVals somevalue, someothervalue
   ReDim Preserve tupleArray(x)
   Set tupleArray(x) = t
next x
theDictionary.Add someKey, tupleArray
</code>```

I want to later retrieve the arrays from the dictionary but I'm struggling with it. Here's what I've tried

```<code>Sub DoStuffWithDictionary(dict as object, index as Integer)

Dim tupleArray() as Tuple

' Error: "Property let procedure not defined and property get procedure did not return an object"
tupleArray = dict.Items(index)

' Error: can't assign to array
Set tupleArray = dict.Items(index)

' Error: same as above
Dim tupleArray as Object

' Error: same as above
Dim tupleArray as Variant

End Sub
</code>```

Looping on the dictionary keys they all print out OK, I just can't get to the arrays.

答:
You should be able to access items by using the key:</p>

```<code>Dim tupleArray As Variant
tupleArray = dict("someKey")
</code>```

Body:
I have a super simple class I called a Tuple:

Private vals(1) As Integer
-----
Public Property Get x()

x = vals(0)

End Property
-----
Public Property Get y()

y = vals(1)

End Property
-----
Public Sub SetVals(x As Integer, y As Integer)

vals(0) = x
vals(1) = y

End Sub

I have a dictionary which is populated with arrays of these Tuples:

for x = whatever to whatever
   Set t = New Tuple
   t.SetVals somevalue, someothervalue
   ReDim Preserve tupleArray(x)
   Set tupleArray(x) = t
next x
theDictionary.Add someKey, tupleArray

I want to later retrieve the arrays from the dictionary but I'm struggling with it. Here's what I've tried

Sub DoStuffWithDictionary(dict as object, index as Integer)

Dim tupleArray() as Tuple

' Error: "Property let procedure not defined and property get procedure did not return an object"
tupleArray = dict.Items(index)

' Error: can't assign to array
Set tupleArray = dict.Items(index)

' Error: same as above
Dim tupleArray as Object

' Error: same as above
Dim tupleArray as Variant

End Sub

Looping on the dictionary keys they all print out OK, I just can't get to the arrays.

Body:
You should be able to access items by using the key:

Dim tupleArray As Variant
tupleArray = dict("someKey")


问:
LINQ and handling rollbacks
I have an image upload handler (.ASHX). I am storing image meta data in the database and am naming the image from the id of that entry into the database. I am using LINQ and getting the ID back after I call SubmitChanges. Then I use that id to save the image. I obviously want to rollback the insert if the File.SaveAs fails. Is my code below correct?

```<code>using (UserDataContext userDataContext = new UserDataContext())
{
    GalleryImage galleryImage = new GalleryImage();
    galleryImage.metaName = "some meta stuff";
    userDataContext.GalleryImages.InsertOnSubmit(galleryImage);
    System.Data.Common.DbTransaction transaction = userClassContext.Transaction;
    userDataContext.SubmitChanges();
    try
    {
        string targetPath = "somepath/" + galleryImage.Id;
        file.SaveAs(targetFilePath);
    }
    catch
    {
        transaction.Rollback();
    }
}
</code>```

Thanks

答:
It is partially correct.

You, however, need to explicitly create a transaction before calling SubmitChanges().

Title: LINQ and handling rollbacks

Body:
I have an image upload handler (.ASHX). I am storing image meta data in the database and am naming the image from the id of that entry into the database. I am using LINQ and getting the ID back after I call SubmitChanges. Then I use that id to save the image. I obviously want to rollback the insert if the File.SaveAs fails. Is my code below correct?

using (UserDataContext userDataContext = new UserDataContext())
{
    GalleryImage galleryImage = new GalleryImage();
    galleryImage.metaName = "some meta stuff";
    userDataContext.GalleryImages.InsertOnSubmit(galleryImage);
    System.Data.Common.DbTransaction transaction = userClassContext.Transaction;
    userDataContext.SubmitChanges();
    try
    {
        string targetPath = "somepath/" + galleryImage.Id;
        file.SaveAs(targetFilePath);
    }
    catch
    {
        transaction.Rollback();
    }
}

Thanks


问:
Organize list of object in java
I have a class

```<code>public class ProductStock {

   private Long id;
   private Integer quantity;

}
</code>```

and a list like

```<code>List<ProductStock> productStocks =
{
  ProductStock(1, 1),
  ProductStock(2, 1),
  ProductStock(3, 1),
  ProductStock(1, 1),
  ProductStock(4, 1),
  ProductStock(5, 1),
  ProductStock(2, 1)
}
</code>```

I want to group productStocks by id.
What is the best way to convert this list like bellow

```<code>productStocks =
{
  ProductStock(1, 2),
  ProductStock(2, 2),
  ProductStock(3, 1),
  ProductStock(4, 1),
  ProductStock(5, 1)
}
</code>```

答:
With Java8 streams you could try it like this:

```<code>productStocks = new ArrayList<>( productStocks.stream().collect(
       Collectors.toMap( p -> p.id, p -> p, (p,o) -> { p.quantity += o.quantity; return p;} ) )
                 .values() );
</code>```

What this does:

productStocks.stream().collect( Collectors.toMap(...) ) creates a stream for the list and collects the values into a map.

p -> p.id uses the product's id as the map key

p -> p uses the product as the map value, if it doesn't exist already

(p,o) -> { p.quantity += o.quantity; return p;} merges the existing product p and the "new" product value o by adding the quantity into p and returning that. Alternatively you could create a new Product instance: (p,o) -> new Product(p.id, p.quantity + o.quantity)

finally we build a new list out of the map's values

Note that collecting the elements into a map like like might not preserve the order of the elements. If you want to keep the order as defined in the source list, you could add a 4th parameter to collect(...): LinkedHashMap::new.

Title: Organize list of object in java

Body:
I have a class

public class ProductStock {

   private Long id;
   private Integer quantity;

}

and a list like

List<ProductStock> productStocks =
{
  ProductStock(1, 1),
  ProductStock(2, 1),
  ProductStock(3, 1),
  ProductStock(1, 1),
  ProductStock(4, 1),
  ProductStock(5, 1),
  ProductStock(2, 1)
}

I want to group productStocks by id.
What is the best way to convert this list like bellow

productStocks =
{
  ProductStock(1, 2),
  ProductStock(2, 2),
  ProductStock(3, 1),
  ProductStock(4, 1),
  ProductStock(5, 1)
}

Body:
With Java8 streams you could try it like this:

productStocks = new ArrayList<>( productStocks.stream().collect(
       Collectors.toMap( p -> p.id, p -> p, (p,o) -> { p.quantity += o.quantity; return p;} ) )
                 .values() );

What this does:

productStocks.stream().collect( Collectors.toMap(...) ) creates a stream for the list and collects the values into a map.

p -> p.id uses the product's id as the map key

p -> p uses the product as the map value, if it doesn't exist already

(p,o) -> { p.quantity += o.quantity; return p;} merges the existing product p and the "new" product value o by adding the quantity into p and returning that. Alternatively you could create a new Product instance: (p,o) -> new Product(p.id, p.quantity + o.quantity)

finally we build a new list out of the map's values

Note that collecting the elements into a map like like might not preserve the order of the elements. If you want to keep the order as defined in the source list, you could add a 4th parameter to collect(...): LinkedHashMap::new.


问:
Big Picture Notification in android
I have done android push notification using FCM.But when I am trying the big picture notification it's not showing the full  image in the notificationn bar.Left and Right side of the image is getting cropped.Please let me know how to fix the issue.i tried by giving 512*256 image and 600*300 size images.</p>

答:
Here is the complete code for BigPicture  from FCM Notification:

```<code>Bitmap bitmap = getBitmapFromURL(imageUrl);

  private void showBigNotification(Bitmap bitmap,NotificationCompat.Builder mBuilder, int icon, String title, String  message, String timeStamp, PendingIntent resultPendingIntent, Uri alarmSound) {

    mBuilder.setSmallIcon(R.drawable.ic_message_alertnoti).setTicker(title).setWhen(0);
    Intent intent = new Intent().setClassName("com.packageName", "com.packageName.activity.YourActivity"); // give any activity name which you want to open
    try {
        intent.putExtra("regId", userInfo.selectOneField(UserInfo.DEVICE_ID));
    } catch (DAOException e) {
        e.printStackTrace();
    }
    PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
    mBuilder.setContentIntent(pendingIntent);
    mBuilder.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher));
    mBuilder.setContentTitle(title);
    mBuilder.setColor(ContextCompat.getColor(mContext, R.color.colorOrange));
    mBuilder.setContentText(message);
    mBuilder.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(bitmap));/*Notification with Image*/
    mBuilder.setPriority(Notification.PRIORITY_MAX);
    mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
    if (Build.VERSION.SDK_INT >= 21) mBuilder.setVibrate(new long[0]);
    NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(mContext.NOTIFICATION_SERVICE);
    notificationManager.notify(Config.NOTIFICATION_ID, mBuilder.build());
}

/**
 * Downloading push notification image before displaying it in
 * the notification tray
 */
public Bitmap getBitmapFromURL(String strURL) {
    try {
        URL url = new URL(strURL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
</code>```

Title: Big Picture Notification in android

Body:
Here is the complete code for BigPicture  from FCM Notification:

Bitmap bitmap = getBitmapFromURL(imageUrl);

  private void showBigNotification(Bitmap bitmap,NotificationCompat.Builder mBuilder, int icon, String title, String  message, String timeStamp, PendingIntent resultPendingIntent, Uri alarmSound) {

    mBuilder.setSmallIcon(R.drawable.ic_message_alertnoti).setTicker(title).setWhen(0);
    Intent intent = new Intent().setClassName("com.packageName", "com.packageName.activity.YourActivity"); // give any activity name which you want to open
    try {
        intent.putExtra("regId", userInfo.selectOneField(UserInfo.DEVICE_ID));
    } catch (DAOException e) {
        e.printStackTrace();
    }
    PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
    mBuilder.setContentIntent(pendingIntent);
    mBuilder.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher));
    mBuilder.setContentTitle(title);
    mBuilder.setColor(ContextCompat.getColor(mContext, R.color.colorOrange));
    mBuilder.setContentText(message);
    mBuilder.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(bitmap));/*Notification with Image*/
    mBuilder.setPriority(Notification.PRIORITY_MAX);
    mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
    if (Build.VERSION.SDK_INT >= 21) mBuilder.setVibrate(new long[0]);
    NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(mContext.NOTIFICATION_SERVICE);
    notificationManager.notify(Config.NOTIFICATION_ID, mBuilder.build());
}

/**
 * Downloading push notification image before displaying it in
 * the notification tray
 */
public Bitmap getBitmapFromURL(String strURL) {
    try {
        URL url = new URL(strURL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}


问:
jquery functions are not working in safari but working properly in other browsers
I am working on the following code. I want to show only option elements depending on the first selected value. As this code is working properly in chrome but not in safari.
the hide() and show() functions are not working. How i can improve this code so that it will work in safari also?
my html code is as follows:

```<code><body>
<select id="shopcategory">
    <option></option>
    <option value="american" selected="selected">american</option>
    <option value="indian">indian</option>
    <option value="chinese">chinese</option>
</select>
<select id="shop-ar">
    <option class="american">1</option>
    <option class="american">2</option>
    <option class="american">3</option>
    <option class="indian">4</option>
    <option class="indian">5</option>
    <option class="indian">6</option>
    <option class="chinese">7</option>
    <option class="chinese">8</option>
    <option class="chinese">9</option>
</select>
</code>```

my jquery code as follows:

```<code>$(document).ready(function(){
    $("#shopcategory").change(function(){
        select= $("#shopcategory option:selected").attr("value");
        $("#shop-ar").children().each(function(){
            if($(this).attr("class")== select){
        //  only selected category options must be displayed
                $(this).show();
            }
            else{
                $(this).hide();
            }
        })
    })
})
</code>```

答:
I tried again and this time i got desired solution which is as follows:sorry for not formatting it correctly..here is my html:

```<code> <select name="shopcategory" id="shopcategory">
   <option  value="all" selected disabled="disabled">cuisane</option>
   <option  value="american">american</option>
   <option  value="indian">indian</option>
   <option  value="chinese">chinese</option>
</select>
<select name="shop-ar" id="shop-ar" >
  <option class="button" selected="selected">All</option>
  <option data-val="american" value="beverly-hills" >Beverly Hil</option>
  <option data-val="american" value="santa-monica" >Santa </option>
  <option data-val="indian" value="hialea" >Hia</option>
  <option data-val="indian" value="little-havana">Little </option>
  <option data-val="indian" value="north-miami">North </option>
  <option data-val="indian" value="south-beach">South </option>
  <option data-val="chinese" value="chelsea">Chel</option>
  <option data-val="chinese" value="harlem">Har</option>
  <option data-val="chinese" value="noho">No</option>
  <option data-val="chinese" value="soho">So</option>
</select>
</code>```

jquery code:

```<code>  $(document).ready(function(){
         var select_clone = $('#shop-ar option');
         $('#shopcategory').change(function() {
         $("option").show();
         $('#shop-ar').html(select_clone.filter('[data-val="' + this.value + '"]')).show();
         $("#shop-ar").prepend("<option value='' disabled='disabled'>Restaurants</option>").val('');
</code>```

})
})

Body:
I am working on the following code. I want to show only option elements depending on the first selected value. As this code is working properly in chrome but not in safari.
the hide() and show() functions are not working. How i can improve this code so that it will work in safari also?
my html code is as follows:

<select id="shopcategory">
    <option></option>
    <option value="american" selected="selected">american</option>
    <option value="indian">indian</option>
    <option value="chinese">chinese</option>
</select>
<select id="shop-ar">
    <option class="american">1</option>
    <option class="american">2</option>
    <option class="american">3</option>
    <option class="indian">4</option>
    <option class="indian">5</option>
    <option class="indian">6</option>
    <option class="chinese">7</option>
    <option class="chinese">8</option>
    <option class="chinese">9</option>
</select>

my jquery code as follows:

$(document).ready(function(){
    $("#shopcategory").change(function(){
        select= $("#shopcategory option:selected").attr("value");
        $("#shop-ar").children().each(function(){
            if($(this).attr("class")== select){
        //  only selected category options must be displayed
                $(this).show();
            }
            else{
                $(this).hide();
            }
        })
    })
})

Body:
I tried again and this time i got desired solution which is as follows:sorry for not formatting it correctly..here is my html:

 <select name="shopcategory" id="shopcategory">
   <option  value="all" selected disabled="disabled">cuisane</option>
   <option  value="american">american</option>
   <option  value="indian">indian</option>
   <option  value="chinese">chinese</option>
</select>
<select name="shop-ar" id="shop-ar" >
  <option class="button" selected="selected">All</option>
  <option data-val="american" value="beverly-hills" >Beverly Hil</option>
  <option data-val="american" value="santa-monica" >Santa </option>
  <option data-val="indian" value="hialea" >Hia</option>
  <option data-val="indian" value="little-havana">Little </option>
  <option data-val="indian" value="north-miami">North </option>
  <option data-val="indian" value="south-beach">South </option>
  <option data-val="chinese" value="chelsea">Chel</option>
  <option data-val="chinese" value="harlem">Har</option>
  <option data-val="chinese" value="noho">No</option>
  <option data-val="chinese" value="soho">So</option>
</select>

jquery code:

  $(document).ready(function(){
         var select_clone = $('#shop-ar option');
         $('#shopcategory').change(function() {
         $("option").show();
         $('#shop-ar').html(select_clone.filter('[data-val="' + this.value + '"]')).show();
         $("#shop-ar").prepend("<option value='' disabled='disabled'>Restaurants</option>").val('');

})
})


问:
IntelliJ IDEA - could not find org.jetbrains.kotlin:kotlin-gradle-plugins
Trying to open a Corda demo in IntelliJ IDEA and getting this error when it tries to import gradle settings

Error:Could not find org.jetbrains.kotlin:kotlin-gradle-plugins:1.1.4.
  Searched in the following locations:
      file:/C:/Users/Default/.m2/repository/org/jetbrains/kotlin/kotlin-gradle-plugins/1.1.4/kotlin-gradle-plugins-1.1.4.pom
      file:/C:/Users/Default/.m2/repository/org/jetbrains/kotlin/kotlin-gradle-plugins/1.1.4/kotlin-gradle-plugins-1.1.4.jar
      https://repo1.maven.org/maven2/org/jetbrains/kotlin/kotlin-gradle-plugins/1.1.4/kotlin-gradle-plugins-1.1.4.pom
      https://repo1.maven.org/maven2/org/jetbrains/kotlin/kotlin-gradle-plugins/1.1.4/kotlin-gradle-plugins-1.1.4.jar
      https://jcenter.bintray.com/org/jetbrains/kotlin/kotlin-gradle-plugins/1.1.4/kotlin-gradle-plugins-1.1.4.pom
      https://jcenter.bintray.com/org/jetbrains/kotlin/kotlin-gradle-plugins/1.1.4/kotlin-gradle-plugins-1.1.4.jar
  Required by:
      project :

I can't find any documentation to suggest how to fix this, Any ideas?

答:
There seems to be a typo in the build script: the correct name of the artifact is kotlin-gradle-plugin (without s).

Check the dependency declaration in your build.gradle:

```<code>classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:..."
</code>```

It's described in the docs here: Using Gradle

Body:
There seems to be a typo in the build script: the correct name of the artifact is kotlin-gradle-plugin (without s).

Check the dependency declaration in your build.gradle:

classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:..."

It's described in the docs here: Using Gradle


问:
How to use tomcat with spring without web.xml?
I have a JAX-RS application deployed on Tomcat 7. I am deploying the application on Tomcat without any web.xml file.

I want to use spring for injecting some of the dependencies in my project. I am not using any XML file to configure beans, instead I have created a class and annotated it with @Configuration annotation, which contains all the bean definitions. Now, I am trying to use that bean by annotating a field in a separate class with @Autowired, but the field is null.

How should I make spring work with this setup ?

EDIT:
I was able to initialize spring application context , by creating a web.xml in WEB-INF/ with the following contents.

```<code><web-app>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>
</code>```

I checked the tomcat logs , and verified that the bean is created by spring. But the problem is when I try to use that bean, the field in the class is null.

答:
web.xml is used as a starting point while tomcat container starts.
If you want to bypass this, you can write a simple Java program and inside main() function just call Spring to load application context and provide the path of your apps applicationContext.

More details : https://www.tutorialspoint.com/spring/spring_java_based_configuration.htm

Body:
I have a JAX-RS application deployed on Tomcat 7. I am deploying the application on Tomcat without any web.xml file.

I want to use spring for injecting some of the dependencies in my project. I am not using any XML file to configure beans, instead I have created a class and annotated it with @Configuration annotation, which contains all the bean definitions. Now, I am trying to use that bean by annotating a field in a separate class with @Autowired, but the field is null.

How should I make spring work with this setup ?

EDIT:
I was able to initialize spring application context , by creating a web.xml in WEB-INF/ with the following contents.

<web-app>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>

I checked the tomcat logs , and verified that the bean is created by spring. But the problem is when I try to use that bean, the field in the class is null.


问:
app.get("/api/current_user".. not firing after passport.js authenticated. NODE
I am new to NodeJS. And I am trying to create a simple web server.
I am only using NodeJS and Passport.js (using a google strategy) right now.

Currently, all the app.get("") calls are working when I am not authenticated, but once I authenticate with google and the callback happens, I can no longer access any of the app.get routes. I try and put a break point in the arrow function and it is never calls, and just hangs when loading from the browser with auth cookie.

Here is my current code:

Index.js

```<code>const express = require('express');
const mongoose = require('mongoose');
const cookieSession = require("cookie-session");
const passport = require("passport");
const keys = require('./config/keys');
require('./models/User');
require('./services/passport');

mongoose.connect(keys.mongoURI);

const app = express();

app.use(
    cookieSession({
        maxAge: 30 * 24 * 60 * 60 * 1000,   //30 days
        keys: [keys.cookieKey]
    })
);

app.use(passport.initialize());
app.use(passport.session());

require('./routes/authRoutes')(app);

const PORT = process.env.PORT || 5000;
app.listen(PORT);
</code>```

authRoutes.js

```<code>   const passport = require('passport');

   module.exports = (app) => {
    app.get(
        "/auth/google",
        passport.authenticate('google', {
            scope: ['profile', 'email']
        })
    );

    app.get(
        '/auth/google/callback',
        passport.authenticate('google')
    );

    app.get("/api/logout", (req, res) => {
        req.logout();
        res.send(req.user);
    });

    app.get("/api/current_user", (req, res) => {
            res.send("test");//req.user);   //Tried as a test, is called when
                                           //not authenticated, but does not get
                                          //called when authenticated
    });
   }
</code>```

passport.js

```<code>const passport = require('passport');
const googleStrategy = require('passport-google-oauth20');
const mongoose = require('mongoose');
const keys = require('../config/keys');
const User = mongoose.model("users");

passport.serializeUser((user, done) => {
 done(null, user.id);
});

passport.deserializeUser((id, done)=> {
    User.findById(id)
    .then(user =>{
        doen(null, user);
    });
});

passport.use(new googleStrategy({
    clientID: keys.googleClientID,
    clientSecret: keys.googleclientSecret,
    callbackURL: '/auth/google/callback'
    },
    (accessToken, refreshToken, profile, done) => {
        User.findOne({ googleId: profile.id })
        .then((existingUser) => {
            if (existingUser){
                //we already have a user
                done(null, existingUser);
            }
            else{
                new User({ googleId: profile.id })
                .save()
                .then (user => done(null, user));
            }
        });
    })
);
</code>```

答:
this probably wont help anyone besides for the fact to check for TYPOS!

I found my problem here:

```<code>passport.deserializeUser((id, done)=> {
    User.findById(id)
    .then(user =>{
        doen(null, user);
    });
});
</code>```

notice doen should be done

I got no error messages that helped me on this one.

Body:
I am new to NodeJS. And I am trying to create a simple web server.
I am only using NodeJS and Passport.js (using a google strategy) right now.

Currently, all the app.get("") calls are working when I am not authenticated, but once I authenticate with google and the callback happens, I can no longer access any of the app.get routes. I try and put a break point in the arrow function and it is never calls, and just hangs when loading from the browser with auth cookie.

Here is my current code:

Index.js

const express = require('express');
const mongoose = require('mongoose');
const cookieSession = require("cookie-session");
const passport = require("passport");
const keys = require('./config/keys');
require('./models/User');
require('./services/passport');

mongoose.connect(keys.mongoURI);

const app = express();

app.use(
    cookieSession({
        maxAge: 30 * 24 * 60 * 60 * 1000,   //30 days
        keys: [keys.cookieKey]
    })
);

app.use(passport.initialize());
app.use(passport.session());

require('./routes/authRoutes')(app);

const PORT = process.env.PORT || 5000;
app.listen(PORT);

authRoutes.js

   const passport = require('passport');

   module.exports = (app) => {
    app.get(
        "/auth/google",
        passport.authenticate('google', {
            scope: ['profile', 'email']
        })
    );

    app.get(
        '/auth/google/callback',
        passport.authenticate('google')
    );

    app.get("/api/logout", (req, res) => {
        req.logout();
        res.send(req.user);
    });

    app.get("/api/current_user", (req, res) => {
            res.send("test");//req.user);   //Tried as a test, is called when
                                           //not authenticated, but does not get
                                          //called when authenticated
    });
   }

passport.js

const passport = require('passport');
const googleStrategy = require('passport-google-oauth20');
const mongoose = require('mongoose');
const keys = require('../config/keys');
const User = mongoose.model("users");

passport.serializeUser((user, done) => {
 done(null, user.id);
});

passport.deserializeUser((id, done)=> {
    User.findById(id)
    .then(user =>{
        doen(null, user);
    });
});

passport.use(new googleStrategy({
    clientID: keys.googleClientID,
    clientSecret: keys.googleclientSecret,
    callbackURL: '/auth/google/callback'
    },
    (accessToken, refreshToken, profile, done) => {
        User.findOne({ googleId: profile.id })
        .then((existingUser) => {
            if (existingUser){
                //we already have a user
                done(null, existingUser);
            }
            else{
                new User({ googleId: profile.id })
                .save()
                .then (user => done(null, user));
            }
        });
    })
);

Body:
this probably wont help anyone besides for the fact to check for TYPOS!

I found my problem here:

passport.deserializeUser((id, done)=> {
    User.findById(id)
    .then(user =>{
        doen(null, user);
    });
});

notice doen should be done

I got no error messages that helped me on this one.


问:
How to POST a input string value using thyemeleaf?

My project based on spring boot,Thymeleaf,mysql,html and Jquery.

i tried to post the input String data to @RestController page,but it received as EMPTY which means null.
Here is my Code Details

HTML

```<code><form id="addchargesformid" method="post" th:action="@{/addcharge}">
 <!-- input box add -->
 <div class="form-group">
    <label for="chargeName">Add New Charge*</label>
    <input th:id="chargeName" th:name="chargeName" th:value="${chargeName}" type="text" class="form-control" placeholder="Ex : Maintanence charge">
</div>
<br/>
<button th:type="submit" id="addchargebtnid" class="btn btn-info">Add New Charge</button>
</form>
</code>```

@RestController

```<code>/*To Add Individual charges into list*/
@PostMapping(value="/addcharge")
public ModelAndView doAddCharge(@ModelAttribute String chargeName)
{
    ModelAndView respondResult = new ModelAndView();
    try {
        String result  = serAssignCharges.doAddCharges(chargeName);
        if(result.equals("success"))
        {
            doGetChargesList();
        }
        else {
            respondResult.addObject("warning","sorry! failed to add");
        }

    } catch (Exception e) {
        // TODO: handle exception
    }
    return respondResult;
}
</code>```

Please help me to resolve this...

答:
Since you don't do any binding activities from that form to a model class, and you just want to pass the string, try using @RequestParam instead of @ModelAttribute:</p>

```<code>public ModelAndView doAddCharge(@RequestParam("chargeName") String chargeName)
</code>```

Body:
My project based on spring boot,Thymeleaf,mysql,html and Jquery.

i tried to post the input String data to @RestController page,but it received as EMPTY which means null.
Here is my Code Details

HTML

<form id="addchargesformid" method="post" th:action="@{/addcharge}">

    Add New Charge*
    <input th:id="chargeName" th:name="chargeName" th:value="${chargeName}" type="text" class="form-control" placeholder="Ex : Maintanence charge">

<button th:type="submit" id="addchargebtnid" class="btn btn-info">Add New Charge</button>
</form>

@RestController

/*To Add Individual charges into list*/
@PostMapping(value="/addcharge")
public ModelAndView doAddCharge(@ModelAttribute String chargeName)
{
    ModelAndView respondResult = new ModelAndView();
    try {
        String result  = serAssignCharges.doAddCharges(chargeName);
        if(result.equals("success"))
        {
            doGetChargesList();
        }
        else {
            respondResult.addObject("warning","sorry! failed to add");
        }

    } catch (Exception e) {
        // TODO: handle exception
    }
    return respondResult;
}

Please help me to resolve this...

Body:
Since you don't do any binding activities from that form to a model class, and you just want to pass the string, try using @RequestParam instead of @ModelAttribute:

public ModelAndView doAddCharge(@RequestParam("chargeName") String chargeName)


问:
EventBus annotation processor won't accept ThreadMode.MAIN_ORDERED in AndroidStudio 3.1
I'm using AndroidStudio 3.1 Canary 3 at the moment along with D8. I've tried without D8 and have tried 3.1.0 also. The consistent issue is that MAIN_ORDERED throws an error in the annotation processor where it can't find the ENUM. However, when I check the EventBus code, the ENUM is there. Android Studio also auto-completes the MAIN_ORDERED enum.

In my Activity I have:

@Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
public void fragmentDone(FragmentResult msg) {

This fails to build with an error from the annotation processor:

07:28:26.857 [ERROR] [system.err] error: Unexpected error in EventBusAnnotationProcessor: java.lang.EnumConstantNotPresentException: org.greenrobot.eventbus.ThreadMode.MAIN_ORDERED

which goes away if I revert to using ThreadMode.MAIN.

I'm building using the org.greenrobot:eventbus:3.1.1 and org.greenrobot:eventbus-annotation-processor:3.1.0 which seems to be the correct version.

```<code>20:47:37.023 [ERROR] [system.err] java.lang.EnumConstantNotPresentException: org.greenrobot.eventbus.ThreadMode.MAIN_ORDERED
20:47:37.129 [ERROR] [system.err]   at sun.reflect.annotation.EnumConstantNotPresentExceptionProxy.generateException(EnumConstantNotPresentExceptionProxy.java:46)
20:47:37.130 [ERROR] [system.err]   at sun.reflect.annotation.AnnotationInvocationHandler.invoke(AnnotationInvocationHandler.java:84)
20:47:37.130 [ERROR] [system.err]   at com.sun.proxy.$Proxy142.threadMode(Unknown Source)
20:47:37.130 [ERROR] [system.err]   at org.greenrobot.eventbus.annotationprocessor.EventBusAnnotationProcessor.writeCreateSubscriberMethods(EventBusAnnotationProcessor.java:287)
20:47:37.130 [ERROR] [system.err]   at org.greenrobot.eventbus.annotationprocessor.EventBusAnnotationProcessor.writeIndexLines(EventBusAnnotationProcessor.java:373)
20:47:37.130 [ERROR] [system.err]   at org.greenrobot.eventbus.annotationprocessor.EventBusAnnotationProcessor.createInfoIndexFile(EventBusAnnotationProcessor.java:333)
20:47:37.130 [ERROR] [system.err]   at org.greenrobot.eventbus.annotationprocessor.EventBusAnnotationProcessor.process(EventBusAnnotationProcessor.java:106)
20:47:37.130 [ERROR] [system.err]   at com.sun.tools.javac.processing.JavacProcessingEnvironment.callProcessor(JavacProcessingEnvironment.java:794)
20:47:37.130 [ERROR] [system.err]   at com.sun.tools.javac.processing.JavacProcessingEnvironment.discoverAndRunProcs(JavacProcessingEnvironment.java:705)
</code>```

This results in a broken EventBusIndex.java file being generated:-

```<code>package com.company.product;

import org.greenrobot.eventbus.meta.SimpleSubscriberInfo;
import org.greenrobot.eventbus.meta.SubscriberMethodInfo;
import org.greenrobot.eventbus.meta.SubscriberInfo;
import org.greenrobot.eventbus.meta.SubscriberInfoIndex;

import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

/** This class is generated by EventBus, do not edit. */
public class EventBusIndex implements SubscriberInfoIndex {
    private static final Map<Class<?>, SubscriberInfo> SUBSCRIBER_INDEX;

    static {
        SUBSCRIBER_INDEX = new HashMap<Class<?>, SubscriberInfo>();

        putIndex(new SimpleSubscriberInfo(com.company.product.activities.MainActivity.class, true,
                new SubscriberMethodInfo[] {
</code>```

And again, looking at the import org.greenrobot.eventbus.ThreadMode; file, the enum looks to include the MAIN_ORDERED declaration.

I'm out of ideas...

答:
An update has been released for the EventBusAnnotationProcessor.

Please check the issue thread.

Gradle dependency

```<code>annotationProcessor 'org.greenrobot:eventbus-annotation-processor:3.1.1'
</code>```

Successfully Generated Index

```<code>import org.greenrobot.eventbus.meta.SimpleSubscriberInfo;
import org.greenrobot.eventbus.meta.SubscriberMethodInfo;
import org.greenrobot.eventbus.meta.SubscriberInfo;
import org.greenrobot.eventbus.meta.SubscriberInfoIndex;

import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

/** This class is generated by EventBus, do not edit. */
public class MyEventBusIndex implements SubscriberInfoIndex {
    private static final Map<Class<?>, SubscriberInfo> SUBSCRIBER_INDEX;

    static {
        SUBSCRIBER_INDEX = new HashMap<Class<?>, SubscriberInfo>();

        putIndex(new SimpleSubscriberInfo(MainActivity.class, true, new SubscriberMethodInfo[] {
            new SubscriberMethodInfo("onEvent", MainActivity.TestEvent.class, ThreadMode.MAIN_ORDERED),
        }));

    }

    private static void putIndex(SubscriberInfo info) {
        SUBSCRIBER_INDEX.put(info.getSubscriberClass(), info);
    }

    @Override
    public SubscriberInfo getSubscriberInfo(Class<?> subscriberClass) {
        SubscriberInfo info = SUBSCRIBER_INDEX.get(subscriberClass);
        if (info != null) {
            return info;
        } else {
            return null;
        }
    }
}
</code>```

Body:
I'm using AndroidStudio 3.1 Canary 3 at the moment along with D8. I've tried without D8 and have tried 3.1.0 also. The consistent issue is that MAIN_ORDERED throws an error in the annotation processor where it can't find the ENUM. However, when I check the EventBus code, the ENUM is there. Android Studio also auto-completes the MAIN_ORDERED enum.

In my Activity I have:

@Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
public void fragmentDone(FragmentResult msg) {

This fails to build with an error from the annotation processor:

07:28:26.857 [ERROR] [system.err] error: Unexpected error in EventBusAnnotationProcessor: java.lang.EnumConstantNotPresentException: org.greenrobot.eventbus.ThreadMode.MAIN_ORDERED

which goes away if I revert to using ThreadMode.MAIN.

I'm building using the org.greenrobot:eventbus:3.1.1 and org.greenrobot:eventbus-annotation-processor:3.1.0 which seems to be the correct version.

20:47:37.023 [ERROR] [system.err] java.lang.EnumConstantNotPresentException: org.greenrobot.eventbus.ThreadMode.MAIN_ORDERED
20:47:37.129 [ERROR] [system.err]   at sun.reflect.annotation.EnumConstantNotPresentExceptionProxy.generateException(EnumConstantNotPresentExceptionProxy.java:46)
20:47:37.130 [ERROR] [system.err]   at sun.reflect.annotation.AnnotationInvocationHandler.invoke(AnnotationInvocationHandler.java:84)
20:47:37.130 [ERROR] [system.err]   at com.sun.proxy.$Proxy142.threadMode(Unknown Source)
20:47:37.130 [ERROR] [system.err]   at org.greenrobot.eventbus.annotationprocessor.EventBusAnnotationProcessor.writeCreateSubscriberMethods(EventBusAnnotationProcessor.java:287)
20:47:37.130 [ERROR] [system.err]   at org.greenrobot.eventbus.annotationprocessor.EventBusAnnotationProcessor.writeIndexLines(EventBusAnnotationProcessor.java:373)
20:47:37.130 [ERROR] [system.err]   at org.greenrobot.eventbus.annotationprocessor.EventBusAnnotationProcessor.createInfoIndexFile(EventBusAnnotationProcessor.java:333)
20:47:37.130 [ERROR] [system.err]   at org.greenrobot.eventbus.annotationprocessor.EventBusAnnotationProcessor.process(EventBusAnnotationProcessor.java:106)
20:47:37.130 [ERROR] [system.err]   at com.sun.tools.javac.processing.JavacProcessingEnvironment.callProcessor(JavacProcessingEnvironment.java:794)
20:47:37.130 [ERROR] [system.err]   at com.sun.tools.javac.processing.JavacProcessingEnvironment.discoverAndRunProcs(JavacProcessingEnvironment.java:705)

This results in a broken EventBusIndex.java file being generated:-

package com.company.product;

import org.greenrobot.eventbus.meta.SimpleSubscriberInfo;
import org.greenrobot.eventbus.meta.SubscriberMethodInfo;
import org.greenrobot.eventbus.meta.SubscriberInfo;
import org.greenrobot.eventbus.meta.SubscriberInfoIndex;

import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

/** This class is generated by EventBus, do not edit. */
public class EventBusIndex implements SubscriberInfoIndex {
    private static final Map<Class<?>, SubscriberInfo> SUBSCRIBER_INDEX;

    static {
        SUBSCRIBER_INDEX = new HashMap<Class<?>, SubscriberInfo>();

        putIndex(new SimpleSubscriberInfo(com.company.product.activities.MainActivity.class, true,
                new SubscriberMethodInfo[] {

And again, looking at the import org.greenrobot.eventbus.ThreadMode; file, the enum looks to include the MAIN_ORDERED declaration.

I'm out of ideas...

Body:
An update has been released for the EventBusAnnotationProcessor.

Please check the issue thread.

Gradle dependency

annotationProcessor 'org.greenrobot:eventbus-annotation-processor:3.1.1'

Successfully Generated Index

import org.greenrobot.eventbus.meta.SimpleSubscriberInfo;
import org.greenrobot.eventbus.meta.SubscriberMethodInfo;
import org.greenrobot.eventbus.meta.SubscriberInfo;
import org.greenrobot.eventbus.meta.SubscriberInfoIndex;

import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

/** This class is generated by EventBus, do not edit. */
public class MyEventBusIndex implements SubscriberInfoIndex {
    private static final Map<Class<?>, SubscriberInfo> SUBSCRIBER_INDEX;

    static {
        SUBSCRIBER_INDEX = new HashMap<Class<?>, SubscriberInfo>();

        putIndex(new SimpleSubscriberInfo(MainActivity.class, true, new SubscriberMethodInfo[] {
            new SubscriberMethodInfo("onEvent", MainActivity.TestEvent.class, ThreadMode.MAIN_ORDERED),
        }));

    }

    private static void putIndex(SubscriberInfo info) {
        SUBSCRIBER_INDEX.put(info.getSubscriberClass(), info);
    }

    @Override
    public SubscriberInfo getSubscriberInfo(Class<?> subscriberClass) {
        SubscriberInfo info = SUBSCRIBER_INDEX.get(subscriberClass);
        if (info != null) {
            return info;
        } else {
            return null;
        }
    }
}


问:
How to Cast String to Array of Structs in Hive?
My table in hive has schema like:

```<code>DESCRIBE struct_demo;
+-------------------+-------------------------------+
| name              | type                          |
+-------------------+-------------------------------+
| lr_id             | string                        |
| segment_info      | ARRAY<struct<                 |
|                   |   idlpSegmentName:string,     |
|                   |   idlpSegmentValue:string >   |
|                   |      >                        |
|                   |                               |
+-------------------+-------------------------------+
</code>```

I create tables in Redshift (or any Sql database for that matter)
which creates has rows with similar format for the above data types in hive ,
but as string.

How do I cast while inserting data from from redshift to hive?
More specifically, how can I cast from String to Array of Structs?

My SQL table:

```<code>lr_id    |          segment_info
---------|------------------------------------------------------------
1        |      [{"idlpsegmentname":"axciom","idlpsegmentvalue":"200"},{"idlpsegmentname":"people","idlpsegmentvalue":"z"}]
</code>```

So far, unable to find any udfs matching the requirement.

答:
Anyway, found the solution.</p>

```<code>package hive;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.io.Text;

public class UAStructUDF extends GenericUDF {
private Object[] result;

@Override
public String getDisplayString(String[] arg0) {
    return "My display string";
}

public static void main(String... args) {
    UAStructUDF ua = new UAStructUDF();
    ua.parseUAString("");
}

@Override
public ObjectInspector initialize(ObjectInspector[] arg0) throws UDFArgumentException {
    // Define the field names for the struct<> and their types
    ArrayList<String> structFieldNames = new ArrayList<String>();
    ArrayList<ObjectInspector> structFieldObjectInspectors = new ArrayList<ObjectInspector>();
    // fill struct field names
    // segmentname
    structFieldNames.add("idlpsegmentname");
    structFieldObjectInspectors.add(PrimitiveObjectInspectorFactory.writableStringObjectInspector);
    // segmentvalue
    structFieldNames.add("idlpsegmentvalue");
    structFieldObjectInspectors.add(PrimitiveObjectInspectorFactory.writableStringObjectInspector);
    StructObjectInspector si = ObjectInspectorFactory.getStandardStructObjectInspector(structFieldNames,
            structFieldObjectInspectors);
    return ObjectInspectorFactory.getStandardListObjectInspector(si);
    // return si;
}

@Override
public Object evaluate(DeferredObject[] args) throws HiveException {
    if (args == null || args.length < 1) {
        throw new HiveException("args is empty");
    }
    if (args[0].get() == null) {
        throw new HiveException("args contains null instead of object");
    }
    Object argObj = args[0].get();
    // get argument
    String argument = null;
    if (argObj instanceof Text) {
        argument = ((Text) argObj).toString();
    } else if (argObj instanceof String) {
        argument = (String) argObj;
    } else {
        throw new HiveException(
                "Argument is neither a Text nor String, it is a " + argObj.getClass().getCanonicalName());
    }
    // parse UA string and return struct, which is just an array of objects:
    // Object[]
    return parseUAString(argument);
}

private Object parseUAString(String argument) {
    String test = "acxiom_cluster,03|aff_celeb_ent,Y";
    List<Object[]> ret = new ArrayList<Object[]>();
    for (String s : test.split("\\|")) {
        String arr[] = s.split(",");
        Object[] o = new Object[2];
        o[0] = new Text(arr[0]);
        o[1] = new Text(arr[1]);
        ret.add(o);
    }
    return ret;
}
}
</code>```

Body:
My table in hive has schema like:

DESCRIBE struct_demo;
+-------------------+-------------------------------+
| name              | type                          |
+-------------------+-------------------------------+
| lr_id             | string                        |
| segment_info      | ARRAY<struct<                 |
|                   |   idlpSegmentName:string,     |
|                   |   idlpSegmentValue:string >   |
|                   |      >                        |
|                   |                               |
+-------------------+-------------------------------+

I create tables in Redshift (or any Sql database for that matter)
which creates has rows with similar format for the above data types in hive ,
but as string.

How do I cast while inserting data from from redshift to hive?
More specifically, how can I cast from String to Array of Structs?

My SQL table:

lr_id    |          segment_info
---------|------------------------------------------------------------
1        |      [{"idlpsegmentname":"axciom","idlpsegmentvalue":"200"},{"idlpsegmentname":"people","idlpsegmentvalue":"z"}]

So far, unable to find any udfs matching the requirement.

Body:
Anyway, found the solution.

package hive;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.io.Text;

public class UAStructUDF extends GenericUDF {
private Object[] result;

@Override
public String getDisplayString(String[] arg0) {
    return "My display string";
}

public static void main(String... args) {
    UAStructUDF ua = new UAStructUDF();
    ua.parseUAString("");
}

@Override
public ObjectInspector initialize(ObjectInspector[] arg0) throws UDFArgumentException {
    // Define the field names for the struct<> and their types
    ArrayList<String> structFieldNames = new ArrayList<String>();
    ArrayList<ObjectInspector> structFieldObjectInspectors = new ArrayList<ObjectInspector>();
    // fill struct field names
    // segmentname
    structFieldNames.add("idlpsegmentname");
    structFieldObjectInspectors.add(PrimitiveObjectInspectorFactory.writableStringObjectInspector);
    // segmentvalue
    structFieldNames.add("idlpsegmentvalue");
    structFieldObjectInspectors.add(PrimitiveObjectInspectorFactory.writableStringObjectInspector);
    StructObjectInspector si = ObjectInspectorFactory.getStandardStructObjectInspector(structFieldNames,
            structFieldObjectInspectors);
    return ObjectInspectorFactory.getStandardListObjectInspector(si);
    // return si;
}

@Override
public Object evaluate(DeferredObject[] args) throws HiveException {
    if (args == null || args.length < 1) {
        throw new HiveException("args is empty");
    }
    if (args[0].get() == null) {
        throw new HiveException("args contains null instead of object");
    }
    Object argObj = args[0].get();
    // get argument
    String argument = null;
    if (argObj instanceof Text) {
        argument = ((Text) argObj).toString();
    } else if (argObj instanceof String) {
        argument = (String) argObj;
    } else {
        throw new HiveException(
                "Argument is neither a Text nor String, it is a " + argObj.getClass().getCanonicalName());
    }
    // parse UA string and return struct, which is just an array of objects:
    // Object[]
    return parseUAString(argument);
}

private Object parseUAString(String argument) {
    String test = "acxiom_cluster,03|aff_celeb_ent,Y";
    List<Object[]> ret = new ArrayList<Object[]>();
    for (String s : test.split("\\|")) {
        String arr[] = s.split(",");
        Object[] o = new Object[2];
        o[0] = new Text(arr[0]);
        o[1] = new Text(arr[1]);
        ret.add(o);
    }
    return ret;
}
}