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

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

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

This is my Retrofit client class:

```<code>public class RetrofitGeneral {

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

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

This is my Retrofit Service interface:

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

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

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

}
</code>```

This is my retrofit callBack method:

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

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

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

Please help :)

答:
The error is because of this line

Toast.makeText(context, "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();

listCall.enqueue makes the network call on background Thread and you can't display a toast from background thread, you have to use Main thread to display a toast.

You can use

```<code>runOnUiThread(new Runnable() {
Toast.makeText(context, "Something went wrong...Please try later!",Toast.LENGTH_SHORT).show();
}
</code>```

To fix the error.

For the answer why your call is failing you can print the stacktrace to figure that out

```<code> @Override
    public void onFailure(Call<List<Task>> call, Throwable t) {
        t.printStackTrace();
        runOnUiThread(new Runnable() {
        Toast.makeText(context, "Something went wrong...Please try later!",Toast.LENGTH_SHORT).show();
       }
    }
</code>```

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

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

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

This is my Retrofit client class:

public class RetrofitGeneral {

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

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

This is my Retrofit Service interface:

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

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

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

}

This is my retrofit callBack method:

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

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

        }
    });
}

Please help :)

Body:
The error is because of this line

Toast.makeText(context, "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();

listCall.enqueue makes the network call on background Thread and you can't display a toast from background thread, you have to use Main thread to display a toast.

You can use

runOnUiThread(new Runnable() {
Toast.makeText(context, "Something went wrong...Please try later!",Toast.LENGTH_SHORT).show();
}

To fix the error.

For the answer why your call is failing you can print the stacktrace to figure that out

 @Override
    public void onFailure(Call<List<Task>> call, Throwable t) {
        t.printStackTrace();
        runOnUiThread(new Runnable() {
        Toast.makeText(context, "Something went wrong...Please try later!",Toast.LENGTH_SHORT).show();
       }
    }


来源: stackexchange

问:
Drag and drop with Qt: Knowing target application on hover - is it possible?
I'm currently exploring the possibilities of drag-and-drop from a Qt application, into an unknown target application. The question is whether it is possible for the Qt application to receive information about the application that is about to receive the drop (e.g. process name, or title).

A (made up) example could be dragging a plot from a Qt window to either a text editor or a spreadsheet editor. In the former, it would provide the data as an image, in the latter as the data points.

It seems Qt is somewhat aware of what the underlying target of the drop is while hovering, as the actionChanged signal is emitted when changing DropAction state. If I'm not mistaken, it seems that the target application looks at the mime-type contained in the drag object, and signals what the action would be, if dropped there. I'm also not getting anything out of the targetChanged signal (which as far as I can tell is for dropping within the current Qt application).

Any pointers would be helpful, and I'll gladly follow up.

答:
You can add several data types to your drag mime data. While creating dragable data you can put image and points data (with proper mime-type) and each application will decide what data it accepts and how to interpret it.

For more details check https://doc.qt.io/qt-5/dnd.html#dragging

ContentLicense: CC BY-SA 4.0


问:
Are Erlang behaviours really kind of the same as class inheritance?
Currently I am working on a data pipeline project utilizing Apache Kafka and Erlang as a stream processor language (I have actually no previous experience with erlang except learning the language and the concepts since the beginning of the year). To write Kafka consumers we rely on the rock solid brod module.

I understand, that I have to write a supervisor callback module which is responsible for starting my brod_client and my group_consumer module.

```<code>my_app
  +-- my_sup
        +-- brod_client
        +-- my_group_consumer
</code>```

this group_consumer module I wrote is a callback module for the brod_group_subsriber_v2 behaviour which in itself is a callback module for gen_server.

```<code>my_group_consumer > brod_group_subscriber > gen_server
</code>```

When I run my application, my supervisor is starting the brod_client, but not my consumer erlang:whereis(my_group_consumer). returns undefined. Only after a message reaches in, the brod_group_consumer_v2 itself seems to intitalizes my_group_consumer and calls its message handler function. This "lazy" init makes sense for me, but differs from what I would expect as I configured the supervisor to explicitely take care of my_group_consumer (not its base behaviour).

So after all this I am not sure if I understand behaviours exactly and therefore if I am using the brod modules correctly, as I try to inherit from them as I would with Java class inheritance and polymorphism.

Its very hard to find examples where brod is used in a supervisor and not just on the shell for demo purposes.

EDIT: I am using brod as an example of a situation/use case here, where I expected the implementation of most specialised module to "inherit" from the mst generic one, which doesn't seem to be the case and therefore I am not able to use a module like brod correctly.

Would somebody please explain me the differences of the concepts? If you like to explain it according to my example it would be great, if you can explain it with another example or no example at all...also fine, thanks in advance.

答:
Just like @alexey-romanov states in a comment, I do believe that you end up with a question that's very different than the one in the title.
Nevertheless, if you're still interested in learning how to understand Erlang/Elixir behaviors, I wrote two articles a while back and gave a talk about it on CodeBEAM SF 2019.
Hope this helps :)</p>

Body:
Currently I am working on a data pipeline project utilizing Apache Kafka and Erlang as a stream processor language (I have actually no previous experience with erlang except learning the language and the concepts since the beginning of the year). To write Kafka consumers we rely on the rock solid brod module.

I understand, that I have to write a supervisor callback module which is responsible for starting my brod_client and my group_consumer module.

my_app
  +-- my_sup
        +-- brod_client
        +-- my_group_consumer

this group_consumer module I wrote is a callback module for the brod_group_subsriber_v2 behaviour which in itself is a callback module for gen_server.

my_group_consumer > brod_group_subscriber > gen_server

When I run my application, my supervisor is starting the brod_client, but not my consumer erlang:whereis(my_group_consumer). returns undefined. Only after a message reaches in, the brod_group_consumer_v2 itself seems to intitalizes my_group_consumer and calls its message handler function. This "lazy" init makes sense for me, but differs from what I would expect as I configured the supervisor to explicitely take care of my_group_consumer (not its base behaviour).

So after all this I am not sure if I understand behaviours exactly and therefore if I am using the brod modules correctly, as I try to inherit from them as I would with Java class inheritance and polymorphism.

Its very hard to find examples where brod is used in a supervisor and not just on the shell for demo purposes.

EDIT: I am using brod as an example of a situation/use case here, where I expected the implementation of most specialised module to "inherit" from the mst generic one, which doesn't seem to be the case and therefore I am not able to use a module like brod correctly.

Would somebody please explain me the differences of the concepts? If you like to explain it according to my example it would be great, if you can explain it with another example or no example at all...also fine, thanks in advance.


问:
filter array based on IDs available in another array
I have two arrays. The first array has only id objects:

```<code>arr1 = [
  { id: 1 },
  { id: 2 }
];
</code>```

and another array has list:

```<code>arr2 = [
  { id: 1, name: "kedar" },
  { id: 2, name: "murli" },
  { id: 3, name: "krishnadas" }
];
</code>```

I need to write arr2 filter function which result as, based on ID available in first array

```<code>arr2 = [
  { id: 1, name: "kedar" },
  { id: 2, name: "murli" }
];
</code>```

答:
let a1 = [ {id:1}, {id:2}]
let b1 = [ {id:1, name:'kedar'}, {id:2, name:'murli'}, {id:3, name:'kidu'} ]

let filteredArray = b1.filter(elem => {
      let id_exists = a1.find(id => { return elem.id === id.id });
      return id_exists;
    });

console.log(filteredArray);```

Body:
I have two arrays. The first array has only id objects:

arr1 = [
  { id: 1 },
  { id: 2 }
];

and another array has list:

arr2 = [
  { id: 1, name: "kedar" },
  { id: 2, name: "murli" },
  { id: 3, name: "krishnadas" }
];

I need to write arr2 filter function which result as, based on ID available in first array

arr2 = [
  { id: 1, name: "kedar" },
  { id: 2, name: "murli" }
];


问:
Typo3 Fluid ignoring max image sizes set in typoscript
I've set in my Constants

```<code>styles.content.textmedia.maxW = 400
styles.content.textmedia.maxWInText = 400
styles.content.imgtext.maxW = 800
</code>```

and tried a simple

```<code><f:image src="..."></f:image>
</code>```

without any params and on the frontend the image is still rendered on its original width ignoring my maxW constants

The original problem was to set different maxW for each column in gridelements which also did not work for fluid content. So i tried to break it down to the simplest maxW setting and even that is not working.

If i take the Text & Image contentelement, it works as expected so i assume, the system is behaving correctly but for any reason fluid images are ignoring the setting?!

Is there anything i do wrong or is there something missing which sets the maxW for f:image? I cant set the maxW in the f:image directly cause it may be located in different columns with different sizes, so i have to set it outside of the f:image tag.

Update:
The main target was to be able to use gridelements as the gridengine and using dce for creating content elements while the elements should knew about the column widths, they are located in to scale images properly.

With the help of Mikel Wohlschlegel i got the missing hint, to fix my problem.

答:
Solution:

gridelements config

```<code>tt_content.gridelements_pi1.20.10.setup {

  default < lib.gridelements.defaultGridSetup
  default {
        columns {
            default {
                renderObj = COA
                renderObj {
                    10 = LOAD_REGISTER
                    10.padding1.cObject = TEXT
                    10.padding1.cObject.data = field:parentgrid_flexform_padding1
                    10.padding2.cObject = TEXT
                    10.padding2.cObject.data = field:parentgrid_flexform_padding2
                    10.padding3.cObject = TEXT
                    10.padding3.cObject.data = field:parentgrid_flexform_padding3
                    10.colMaxWidth.cObject = CASE
                    10.colMaxWidth.cObject {
                        key.data = field:parentgrid_flexform_grid
                        default = TEXT
                        default.value = 1224
                        default.prioriCalc = 1
                    }
                    20.image.dataProcessing.20.maxGalleryWidth.data = register:colWidth
                    20.image.dataProcessing.20.maxGalleryWidthInText.data = register:colWidth

                    30 = RESTORE_REGISTER
                }
            }
        }
    }

  3 < .default
  3 {
    cObject = FLUIDTEMPLATE
    cObject {
      file = templates/gridelements/html/3columns.html
    }
    columns {
      default.renderObj.10.colMaxWidth.cObject {
                default.value = 1224/100*33

                grid-20 = TEXT
                grid-20.value = 1224/100*20
                grid-20.prioriCalc = 1
                grid-25 = TEXT
                grid-25.value = 1224/100*25
                grid-25.prioriCalc = 1
                grid-32 = TEXT
                grid-32.value = 1224/100*32
                grid-32.prioriCalc = 1
            }
            0 < .default
            0.renderObj.10.colWidth.cObject = TEXT
            0.renderObj.10.colWidth.cObject {
                data = register:colMaxWidth
                stdWrap.dataWrap = | - {register:padding1} - {register:padding1}
                prioriCalc = 1
            }
            1 < .default
            1.renderObj.10.colWidth.cObject = TEXT
            1.renderObj.10.colWidth.cObject {
                data = register:colMaxWidth
                stdWrap.dataWrap = | - {register:padding2} - {register:padding2}
                prioriCalc = 1
            }
            2 < .default
            2.renderObj.10.colWidth.cObject = TEXT
            2.renderObj.10.colWidth.cObject {
                data = register:colMaxWidth
                stdWrap.dataWrap = | - {register:padding3} - {register:padding3}
                prioriCalc = 1
            }
        }
    }
</code>```

in dce fluid than i can use

```<code>{namespace vhs=FluidTYPO3\Vhs\ViewHelpers}
{vhs:variable.register.get(name: 'colWidth')}
</code>```

to access this register value.

Body:
I've set in my Constants

styles.content.textmedia.maxW = 400
styles.content.textmedia.maxWInText = 400
styles.content.imgtext.maxW = 800

and tried a simple

<f:image src="..."></f:image>

without any params and on the frontend the image is still rendered on its original width ignoring my maxW constants

The original problem was to set different maxW for each column in gridelements which also did not work for fluid content. So i tried to break it down to the simplest maxW setting and even that is not working.

If i take the Text & Image contentelement, it works as expected so i assume, the system is behaving correctly but for any reason fluid images are ignoring the setting?!

Is there anything i do wrong or is there something missing which sets the maxW for f:image? I cant set the maxW in the f:image directly cause it may be located in different columns with different sizes, so i have to set it outside of the f:image tag.

Update:
The main target was to be able to use gridelements as the gridengine and using dce for creating content elements while the elements should knew about the column widths, they are located in to scale images properly.

With the help of Mikel Wohlschlegel i got the missing hint, to fix my problem.

Body:
Solution:

gridelements config

tt_content.gridelements_pi1.20.10.setup {

  default < lib.gridelements.defaultGridSetup
  default {
        columns {
            default {
                renderObj = COA
                renderObj {
                    10 = LOAD_REGISTER
                    10.padding1.cObject = TEXT
                    10.padding1.cObject.data = field:parentgrid_flexform_padding1
                    10.padding2.cObject = TEXT
                    10.padding2.cObject.data = field:parentgrid_flexform_padding2
                    10.padding3.cObject = TEXT
                    10.padding3.cObject.data = field:parentgrid_flexform_padding3
                    10.colMaxWidth.cObject = CASE
                    10.colMaxWidth.cObject {
                        key.data = field:parentgrid_flexform_grid
                        default = TEXT
                        default.value = 1224
                        default.prioriCalc = 1
                    }
                    20.image.dataProcessing.20.maxGalleryWidth.data = register:colWidth
                    20.image.dataProcessing.20.maxGalleryWidthInText.data = register:colWidth

                    30 = RESTORE_REGISTER
                }
            }
        }
    }

  3 < .default
  3 {
    cObject = FLUIDTEMPLATE
    cObject {
      file = templates/gridelements/html/3columns.html
    }
    columns {
      default.renderObj.10.colMaxWidth.cObject {
                default.value = 1224/100*33

                grid-20 = TEXT
                grid-20.value = 1224/100*20
                grid-20.prioriCalc = 1
                grid-25 = TEXT
                grid-25.value = 1224/100*25
                grid-25.prioriCalc = 1
                grid-32 = TEXT
                grid-32.value = 1224/100*32
                grid-32.prioriCalc = 1
            }
            0 < .default
            0.renderObj.10.colWidth.cObject = TEXT
            0.renderObj.10.colWidth.cObject {
                data = register:colMaxWidth
                stdWrap.dataWrap = | - {register:padding1} - {register:padding1}
                prioriCalc = 1
            }
            1 < .default
            1.renderObj.10.colWidth.cObject = TEXT
            1.renderObj.10.colWidth.cObject {
                data = register:colMaxWidth
                stdWrap.dataWrap = | - {register:padding2} - {register:padding2}
                prioriCalc = 1
            }
            2 < .default
            2.renderObj.10.colWidth.cObject = TEXT
            2.renderObj.10.colWidth.cObject {
                data = register:colMaxWidth
                stdWrap.dataWrap = | - {register:padding3} - {register:padding3}
                prioriCalc = 1
            }
        }
    }

in dce fluid than i can use

{namespace vhs=FluidTYPO3\Vhs\ViewHelpers}
{vhs:variable.register.get(name: 'colWidth')}

to access this register value.


问:
which jQuery Class should i use in this scenario?
I'm trying to get the images to move from right to left one-by-one when the mouse is over the arrow button, but I am unable to understand how and which jQuery class I can implement to execute the exact result.

My code is as follows:

```<code><div id="logos">
    <ul>
        <li style="float:left; margin-left:0px; margin-right:40px; "><img src="images/logo&typography_porjects.png" width="300" height="130" /></li>
        <li><img src="images/logo-no-image.jpg" height="130" width="130" /></li>
        <li><img src="images/logo-no-image.jpg" height="130" width="130" /></li>
        <li><img src="images/logo-no-image.jpg" height="130" width="130" /></li>
        <li><img src="images/logo-no-image.jpg" height="130" width="130" /></li>
        <li><img src="images/logo-no-image.jpg" height="130" width="130" /></li>
        <li><img src="images/logo-no-image.jpg" height="130" width="130" /></li>
        <div class="clear"></div>
        <li style="float:left; margin-left:0px;"><img src="images/logo-no-image.jpg" height="130" width="130" /></li>
        <li><img src="images/logo-no-image.jpg" height="130" width="130" /></li>
        <li><img src="images/logo-no-image.jpg" height="130" width="130" /></li>
        <li><img src="images/logo-no-image.jpg" height="130" width="130" /></li>
        <li><img src="images/logo-no-image.jpg" height="130" width="130" /></li>
        <li><img src="images/logo-no-image.jpg" height="130" width="130" /></li>
        <li><img src="images/logo-no-image.jpg" height="130" width="130" /></li>
        <li><img src="images/logo-no-image.jpg" height="130" width="130" /></li>
    </ul>
</div>
</code>```

and the CSS code is:

```<code>#logos { width:1200px; float:right; }
#logos ul { list-style:none; float:right; overflow:hidden; }
#logos ul li { display:inline; margin:0 0 0 10px; }
.clear { height:30px; width:100%; clear:both; }
</code>```

答:
To create this effect is quite simple, you have two divs, one outter div hides the overflow of the inner div which moves left and "right" by altering the margin-left to a negative value.

HTML

```<code><div id="hide_overflow">
<div id="moving_panel">
   <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
      <!-- [... etc ... ] !-->
   </ul>
</div>
</code>```

I'm using
 in the above example but you can easily change these to

CSS

```<code>li {
    background: lightgray;
    padding: 20px;
    margin: 5px;
    float: left;
}

#hide_overflow {
    overflow: hidden;
}

#hide_overflow, #moving_panel {
    height: 70px;
}
</code>```

jQuery

```<code>$('#left').click(function() {
    var $panel = $('#moving_panel');
    if (!parseInt($panel.css('margin-left'))) return;
    $panel.animate({
        marginLeft: '+=200'
    });
});

$('#right').click(function() {
    $('#moving_panel').animate({
        marginLeft: '-=200'
    });
});
</code>```

This is a very basic example to get you started. There are tons of these image slideshow-type plugins available for jQuery.

Fiddle: http://jsfiddle.net/garreh/9mYJk/

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to get the images to move from right to left one-by-one when the mouse is over the arrow button, but I am unable to understand how and which jQuery class I can implement to execute the exact result.

My code is as follows:

and the CSS code is:

#logos { width:1200px; float:right; }
#logos ul { list-style:none; float:right; overflow:hidden; }
#logos ul li { display:inline; margin:0 0 0 10px; }
.clear { height:30px; width:100%; clear:both; }

Body:
To create this effect is quite simple, you have two divs, one outter div hides the overflow of the inner div which moves left and "right" by altering the margin-left to a negative value.

HTML

<div id="hide_overflow">
<div id="moving_panel">
   <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
      <!-- [... etc ... ] !-->
   </ul>
</div>

I'm using <li> in the above example but you can easily change these to <img>

CSS

li {
    background: lightgray;
    padding: 20px;
    margin: 5px;
    float: left;
}

#hide_overflow {
    overflow: hidden;
}

#hide_overflow, #moving_panel {
    height: 70px;
}

jQuery

$('#left').click(function() {
    var $panel = $('#moving_panel');
    if (!parseInt($panel.css('margin-left'))) return;
    $panel.animate({
        marginLeft: '+=200'
    });
});

$('#right').click(function() {
    $('#moving_panel').animate({
        marginLeft: '-=200'
    });
});

This is a very basic example to get you started. There are tons of these image slideshow-type plugins available for jQuery.

Fiddle: http://jsfiddle.net/garreh/9mYJk/


问:
Get Latin Character in C++
I am a rookie with C++. I have a string "tỏa" but I can't get the character 'ỏ' and why the length of that string is 5? How can I get that character as a variable?

```<code>void test() {
    std::string str ("tỏa");
    for(int i=0; i<str.length(); ++i){
        std::cout << str[i] << std::endl;
    }
}
</code>```

And the output of that code is:

```<code>t
�
�
�
a
</code>```

Anyone can help me? Thank in advance.

答:
You probably have saved file as UTF-8. in that case, the middle character will be represented in few bytes, not just single byte. So if you print it with 1 char each line, you will see some strange chars.

If you just remove std::endl, you will probably see your string. Because on that case, console can handle string as UTF-8 output (I think Linux based consoles just do that by default).

Note:
To handle UTF-8, you may need to add the following to your code:

```<code>std::setlocale(LC_ALL, "en_US.UTF-8");
</code>```

Title: Get Latin Character in C++

Body:
I am a rookie with C++. I have a string "tỏa" but I can't get the character 'ỏ' and why the length of that string is 5? How can I get that character as a variable?

void test() {
    std::string str ("tỏa");
    for(int i=0; i<str.length(); ++i){
        std::cout << str[i] << std::endl;
    }
}

And the output of that code is:

t
�
�
�
a

Anyone can help me? Thank in advance.

Body:
You probably have saved file as UTF-8. in that case, the middle character will be represented in few bytes, not just single byte. So if you print it with 1 char each line, you will see some strange chars.

If you just remove std::endl, you will probably see your string. Because on that case, console can handle string as UTF-8 output (I think Linux based consoles just do that by default).

Note:
To handle UTF-8, you may need to add the following to your code:

std::setlocale(LC_ALL, "en_US.UTF-8");


问:
How to restore linear git history after nonlinear merge?
Few commits ago I accidentally did a nonlinear merge in my master branch. I have a habit of always trying to keep a linear history, so now I would like to restore the linearity.

I have made a dummy repo, which simulates the real situation I'm having for the purposes of making this more simple. Here's a GitHub link to it: https://github.com/ruohola/merge-question

Here's the output of git log --oneline --graph --date-order:

```<code>* 88a4b7e (HEAD -> master, origin/master, origin/HEAD) 11
* 5aae63c 10
*   5506f33 Merge branch 'other'
|\
| * b9c56c9 9
* | 3c72a2a 8
| * 8d2c1ea 7
| * 35f124b 6
* | 7ca5bc1 5
* | b9e9776 4
| * fd83f02 3
|/
* 4fa8b2e 2
* cbdcf50 1
</code>```

Same graph in Sourcetree:

And here is a mspaint visualization of how I would like to get my master to look like — it should essentially be like I would've rebased before the merge:

(The hashes would change ofc)

I know that this might not be the best practice and I am familiar with the consequences of rewriting history (no one else is working on this branch though), but would still want to be able to do this. How can this be accomplished?

答:
Perhaps the simplest way this can be done is to "abuse" the default behavior of git rebase. That is, without explicitly passing --rebase-merges to git rebase, it will actually remove all merge commits from the history. This allows us to get the desired result extremely easily:

Before:

```<code>~/merge-question (master) $ git log --oneline --graph --date-order
* 88a4b7e (HEAD -> master, origin/master, origin/HEAD) 11
* 5aae63c 10
*   5506f33 Merge branch 'other'
|\
| * b9c56c9 9
* | 3c72a2a 8
| * 8d2c1ea 7
| * 35f124b 6
* | 7ca5bc1 5
* | b9e9776 4
| * fd83f02 3
|/
* 4fa8b2e 2
* cbdcf50 1
</code>```

Running the command:

```<code>~/merge-question (master) $ git rebase 3c72a2a
First, rewinding head to replay your work on top of it...
Applying: 3
Applying: 6
Applying: 7
Applying: 9
Applying: 10
Applying: 11
</code>```

After:

```<code>~/merge-question (master) $ git log --oneline --graph --date-order
* d72160d (HEAD -> master) 11
* 90a4718 10
* 3c773db 9
* ba00ecf 7
* 9e48199 6
* 24376c7 3
* 3c72a2a 8
* 7ca5bc1 5
* b9e9776 4
* 4fa8b2e 2
* cbdcf50 1
</code>```

After this, just a simple git push --force-with-lease origin master and the remote's history is back to linear.

Body:
Few commits ago I accidentally did a nonlinear merge in my master branch. I have a habit of always trying to keep a linear history, so now I would like to restore the linearity.

I have made a dummy repo, which simulates the real situation I'm having for the purposes of making this more simple. Here's a GitHub link to it: https://github.com/ruohola/merge-question

Here's the output of git log --oneline --graph --date-order:

* 88a4b7e (HEAD -> master, origin/master, origin/HEAD) 11
* 5aae63c 10
*   5506f33 Merge branch 'other'
|\
| * b9c56c9 9
* | 3c72a2a 8
| * 8d2c1ea 7
| * 35f124b 6
* | 7ca5bc1 5
* | b9e9776 4
| * fd83f02 3
|/
* 4fa8b2e 2
* cbdcf50 1

Same graph in Sourcetree:

And here is a mspaint visualization of how I would like to get my master to look like — it should essentially be like I would've rebased before the merge:

(The hashes would change ofc)

I know that this might not be the best practice and I am familiar with the consequences of rewriting history (no one else is working on this branch though), but would still want to be able to do this. How can this be accomplished?

Body:
Perhaps the simplest way this can be done is to "abuse" the default behavior of git rebase. That is, without explicitly passing --rebase-merges to git rebase, it will actually remove all merge commits from the history. This allows us to get the desired result extremely easily:

Before:

~/merge-question (master) $ git log --oneline --graph --date-order
* 88a4b7e (HEAD -> master, origin/master, origin/HEAD) 11
* 5aae63c 10
*   5506f33 Merge branch 'other'
|\
| * b9c56c9 9
* | 3c72a2a 8
| * 8d2c1ea 7
| * 35f124b 6
* | 7ca5bc1 5
* | b9e9776 4
| * fd83f02 3
|/
* 4fa8b2e 2
* cbdcf50 1

Running the command:

~/merge-question (master) $ git rebase 3c72a2a
First, rewinding head to replay your work on top of it...
Applying: 3
Applying: 6
Applying: 7
Applying: 9
Applying: 10
Applying: 11

After:

~/merge-question (master) $ git log --oneline --graph --date-order
* d72160d (HEAD -> master) 11
* 90a4718 10
* 3c773db 9
* ba00ecf 7
* 9e48199 6
* 24376c7 3
* 3c72a2a 8
* 7ca5bc1 5
* b9e9776 4
* 4fa8b2e 2
* cbdcf50 1

After this, just a simple git push --force-with-lease origin master and the remote's history is back to linear.


问:
Why is proxy pattern Structural Pattern and why is State Pattern behavioral pattern?
why is proxy pattern a structural pattern and why is state pattern a behavioral pattern. What is the criteria for determining a new pattern should be considered structural or behavioral?</p>

答:
Patterns are structural if the focus is on how relationships between objects are organised to form larger components whereas behavioral patterns are focused on the allocation of object responsibilities and the communication between them

The proxy is structural because it acts as a surrogate for another object, state is behavioral because the state is passed in to an object to influence its behaviour at runtime.


问:
Breaking down array of objects into separate variables for database storage (React,express,sql server)
I have a stored array of objects within my reactjs application which when console logged looks like this.

```<code>0: {answer: "yes↵", question: "Is the keyboard separate from the screen?", state: "Declined with soloution defined"}
1: {answer: "yes", question: "Does the keyboard tilt?", state: "Accepted"}
2: {answer: "Question declined But not a problem", question: "Is it possible to find a comfortable typing postion?", state: "Accepted"}
3: {answer: "yes", question: "Do you have a good keyboard technique?", state: "Accepted"}
4: {answer: "Question declined But not a problem", question: "Are the characters on the keyboard clear and readable?", state: "Accepted"}
5: {answer: "sgdfgdfgdf", question: "Is your mouse or other pointing device suitable to the task you're using it for?", state: "problem specified"}
6: {answer: "yes", question: "Is the mouse (or other pointing device) located sufficently close to you?  ", state: "Accepted"}
7: {answer: "sdfsdfsdfsd", question: "Is there support for your wrist and forearm when using the mouse(or other pointing device)", state: "Declined with soloution defined"}
8: {answer: "yes", question: "Does the mouse (or other pointing device) work smoothly at a speed that suits you?", state: "Accepted"}
9: {answer: "asdasdas", question: "Can you easily adjust the software settings for speed and accuracy of the pointer?", state: "Declined with soloution defined"}
10: {answer: "asdasdads", question: "Are the characters on your screen clear and readable?", state: "problem specified"}
11: {answer: "yes", question: "Is the text size on your screen confortable to read?", state: "Accepted"}
12: {answer: "asdasdasd", question: "Is the image on your screen free from flicker and jitter?", state: "Declined with soloution defined"}
13: {answer: "asdasdasd", question: "Is your screen's specification suitable for its intended use?", state: "problem specified"}
14: {answer: "yes", question: "Is the brightness and/or contrast on your screen adjustable?", state: "Accepted"}
</code>```

this consists of answer, question and state (state of the answered question not state as in react components)

What I would like to do is pass these through to express so that I can upload them into my SQL database using the npm package mssql. However as these are all stored into the array I'm not sure how to split these up.

Ideally I would love to pass the whole object through to SQL and just store the whole thing in the database e.g (pseudo code)

```<code>insert into table where answer = answer and question = question and state = state
</code>```

Essentially to use this with SQL how would I break these down to be used with my back end or can I pass the whole object with a specific SQL stored procedure.

```<code>create procedure StoreAnswers

@{answer_values}
as

INSERT INTO QuestionResponses
(RUId, QuestionId, Date, QuestionWhenAnswered, QuestionResponse, Accepted, AssignedWorkStation )
VALUES
${answer_values}

</code>```

EDIT

Stored procedure

```<code>create procedure StoreAnswers(@Results varchar(max))
as begin
  insert into QuestionResponses(QuestionResponse, QuestionWhenAnswered, State)
         select substring(value, charindex('{answer: "', value) + 10,  charindex('", ', value, charindex('{answer: "', value) + 10) -  charindex('{answer: "', value) - 10) as answer,
                substring(value, charindex('question: "', value) + 11, charindex('", ', value, charindex('question: "', value) + 11) - charindex('question: "', value) - 11) as question,
                substring(value, charindex('state: "', value) + 8,      charindex('"}', value,  charindex('state: "', value) + 8) -     charindex('state: "', value) - 8) as state
         from string_split(@Results, char(10))
end;
</code>```

How it is passed through to the sql query from express npm

```<code>app.post("/post-question-answers", async (req, res) => {
  console.log("!called");

  let results = req.body.results;

  console.info(results);

  await sql.connect(config, function(err) {
    if (err) console.log(err);

    // create Request object
    var request = new sql.Request();
    request.input("Results", sql.VarChar, results);
    // query to the database and get the records
    request.execute("dbo.StoreAnswers", function(err, recordset) {
      if (err) console.log(err);
      // send records as a response
      res.json(recordset);
    });
  });

  res.statusCode = 400;
  res.statusMessage = "bad request";
  // res.json({ message: "Email Missing" });
});

</code>```

This is the console.info(results)

```<code>[
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the keyboard separate from the screen?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Does the keyboard tilt?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is it possible to find a comfortable typing postion?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Do you have a good keyboard technique?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Are the characters on the keyboard clear and readable?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: "Is your mouse or other pointing device suitable to the task you're using it for?",
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the mouse (or other pointing device) located sufficently close to you?  ',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is there support for your wrist and forearm when using the mouse(or other pointing device)',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Does the mouse (or other pointing device) work smoothly at a speed that suits you?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Can you easily adjust the software settings for speed and accuracy of the pointer?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Are the characters on your screen clear and readable?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the text size on your screen confortable to read?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the image on your screen free from flicker and jitter?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: "Is your screen's specification suitable for its intended use?",
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the brightness and/or contrast on your screen adjustable?',
[0]     state: 'Accepted'
[0]   }
[0] ]
</code>```

error

```<code>RequestError: Invalid length parameter passed to the LEFT or SUBSTRING function.
</code>```

答:
I think you have to create an additional table t_servey(id, name, ...) and use servey_id in t_question table for the future.

```<code>t_question(
id,
servey_id, -- link on t_servey table
answer,
question,
created_at,
updated_at
)
</code>```

And add bining variables (?) for insert into table:

insert into t_question (servey_id, answer, question, created_at, updated_at) values (?, ?, ?, ?, ?)
```

Body:
I have a stored array of objects within my reactjs application which when console logged looks like this.

0: {answer: "yes↵", question: "Is the keyboard separate from the screen?", state: "Declined with soloution defined"}
1: {answer: "yes", question: "Does the keyboard tilt?", state: "Accepted"}
2: {answer: "Question declined But not a problem", question: "Is it possible to find a comfortable typing postion?", state: "Accepted"}
3: {answer: "yes", question: "Do you have a good keyboard technique?", state: "Accepted"}
4: {answer: "Question declined But not a problem", question: "Are the characters on the keyboard clear and readable?", state: "Accepted"}
5: {answer: "sgdfgdfgdf", question: "Is your mouse or other pointing device suitable to the task you're using it for?", state: "problem specified"}
6: {answer: "yes", question: "Is the mouse (or other pointing device) located sufficently close to you?  ", state: "Accepted"}
7: {answer: "sdfsdfsdfsd", question: "Is there support for your wrist and forearm when using the mouse(or other pointing device)", state: "Declined with soloution defined"}
8: {answer: "yes", question: "Does the mouse (or other pointing device) work smoothly at a speed that suits you?", state: "Accepted"}
9: {answer: "asdasdas", question: "Can you easily adjust the software settings for speed and accuracy of the pointer?", state: "Declined with soloution defined"}
10: {answer: "asdasdads", question: "Are the characters on your screen clear and readable?", state: "problem specified"}
11: {answer: "yes", question: "Is the text size on your screen confortable to read?", state: "Accepted"}
12: {answer: "asdasdasd", question: "Is the image on your screen free from flicker and jitter?", state: "Declined with soloution defined"}
13: {answer: "asdasdasd", question: "Is your screen's specification suitable for its intended use?", state: "problem specified"}
14: {answer: "yes", question: "Is the brightness and/or contrast on your screen adjustable?", state: "Accepted"}

this consists of answer, question and state (state of the answered question not state as in react components)

What I would like to do is pass these through to express so that I can upload them into my SQL database using the npm package mssql. However as these are all stored into the array I'm not sure how to split these up.

Ideally I would love to pass the whole object through to SQL and just store the whole thing in the database e.g (pseudo code)

insert into table where answer = answer and question = question and state = state

Essentially to use this with SQL how would I break these down to be used with my back end or can I pass the whole object with a specific SQL stored procedure.

create procedure StoreAnswers

@{answer_values}
as

INSERT INTO QuestionResponses
(RUId, QuestionId, Date, QuestionWhenAnswered, QuestionResponse, Accepted, AssignedWorkStation )
VALUES
${answer_values}

EDIT

Stored procedure

create procedure StoreAnswers(@Results varchar(max))
as begin
  insert into QuestionResponses(QuestionResponse, QuestionWhenAnswered, State)
         select substring(value, charindex('{answer: "', value) + 10,  charindex('", ', value, charindex('{answer: "', value) + 10) -  charindex('{answer: "', value) - 10) as answer,
                substring(value, charindex('question: "', value) + 11, charindex('", ', value, charindex('question: "', value) + 11) - charindex('question: "', value) - 11) as question,
                substring(value, charindex('state: "', value) + 8,      charindex('"}', value,  charindex('state: "', value) + 8) -     charindex('state: "', value) - 8) as state
         from string_split(@Results, char(10))
end;

How it is passed through to the sql query from express npm

app.post("/post-question-answers", async (req, res) => {
  console.log("!called");

  let results = req.body.results;

  console.info(results);

  await sql.connect(config, function(err) {
    if (err) console.log(err);

    // create Request object
    var request = new sql.Request();
    request.input("Results", sql.VarChar, results);
    // query to the database and get the records
    request.execute("dbo.StoreAnswers", function(err, recordset) {
      if (err) console.log(err);
      // send records as a response
      res.json(recordset);
    });
  });

  res.statusCode = 400;
  res.statusMessage = "bad request";
  // res.json({ message: "Email Missing" });
});

This is the console.info(results)

[
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the keyboard separate from the screen?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Does the keyboard tilt?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is it possible to find a comfortable typing postion?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Do you have a good keyboard technique?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Are the characters on the keyboard clear and readable?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: "Is your mouse or other pointing device suitable to the task you're using it for?",
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the mouse (or other pointing device) located sufficently close to you?  ',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is there support for your wrist and forearm when using the mouse(or other pointing device)',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Does the mouse (or other pointing device) work smoothly at a speed that suits you?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Can you easily adjust the software settings for speed and accuracy of the pointer?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Are the characters on your screen clear and readable?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the text size on your screen confortable to read?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the image on your screen free from flicker and jitter?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: "Is your screen's specification suitable for its intended use?",
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the brightness and/or contrast on your screen adjustable?',
[0]     state: 'Accepted'
[0]   }
[0] ]

error

RequestError: Invalid length parameter passed to the LEFT or SUBSTRING function.

Body:
I think you have to create an additional table t_servey(id, name, ...) and use servey_id in t_question table for the future.

t_question(
id,
servey_id, -- link on t_servey table
answer,
question,
created_at,
updated_at
)

And add bining variables (?) for insert into table:

insert into t_question (servey_id, answer, question, created_at, updated_at) values (?, ?, ?, ?, ?)


问:
Python Regex: Apostrophes only when placed within letters, not as quotation marks
define each word to be the longest contiguous sequence of alphabetic characters (or just letters), including up to one apostrophe if that apostrophe is sandwiched between two letters. </p>

```<code>[a-z]+[a-z/'?a-z]*[a-z$]
</code>```

<p>It doesn't match the letter 'a'. </p>

答:
I'd use:

```<code>^(?:[a-z]+|[a-z]+'[a-z]+)$
</code>```

with re.IGNORECASE

Demo & explanation

Body:
define each word to be the longest contiguous sequence of alphabetic characters (or just letters), including up to one apostrophe if that apostrophe is sandwiched between two letters.

[a-z]+[a-z/'?a-z]*[a-z$]

It doesn't match the letter 'a'.

Body:
I'd use:

^(?:[a-z]+|[a-z]+'[a-z]+)$

with re.IGNORECASE

Demo & explanation


问:
Jmeter: wrapper for jmeter obects in groovy script
H, I have code like this in JSR223 Assertion

```<code>import groovy.json.JsonSlurper;
import org.apache.jmeter.services.FileServer;

failureMessage = "";
sampleLabel = SampleResult.getSampleLabel();

isResponseCodeCorrect("204");

def isResponseCodeCorrect(String expCode)
{
  String actualCode = prev.getResponseCode();

  if(!expCode.equals(actualCode)){

    failureMessage += "ERROR code: Expected <"+ expCode +"> but we got instead  " + actualCode + ";";
  }
}
</code>```

The question is possible to create the some code library in groovy or java and inject the objects form executed sampler (like public variables: ctx, vars, props, SamplerResult)?

The goal is to inject objects like SampleResult, AssertionResult (to invoke -> SampleResult.getSampleLabel()),  AssertionResult.setFailureMessage("failureMessage);
         AssertionResult.setFailure(true); ) and own functions.

Like to have the wrapper (some object) with methods to play with Assertion, saving data to CSV ... The wrapper is going to be imported to JSR223 Assertion and then I would like to call some specific methods.

The expected wrapper:

```<code> @groovy.transform.MapConstructor
   class Foo {
    SampleResult results,
    AssertionResult assertionResult

    isResponseCodeCorrect(String expCode) {
        String actualCode = prev.getResponseCode();

    if(!expCode.equals(actualCode)){

        failureMessage += "ERROR code: Expected <"+ expCode +"> but we got instead  " + actualCode + ";";
     assertionResult.setFailureMessage(failureMessage);
     assertionResult.setFailure(true);

     log.error(sampleLabel + " Error is going to be saved to the logs");
     PrintLogToFile();
       }
    }
}
</code>```

JSR223 Assertion:

```<code>import org.foo. wrapper

Foo wrapper = new Foo();
wrapper.isResponseCodeCorrect("200");
</code>```

Or some useful things to avoid code duplication between calls

答:
You can compile your Groovy or Java code into a .jar file and drop it into JMeter Classpath

Once done you will be able to access the functions available in the .jar file from any JSR223 Test Element and/or from __groovy() function.

I can think only of one class which you need: JMeterContext an instance of which can be obtained as simple as:

```<code>def ctx = org.apache.jmeter.threads.JMeterContextService.getContext()
</code>```

once done you will be able to access whatever you need like:

SampleResult == ctx.getPreviousResult()

AssertionResult == ctx.getPreviousResult().getAssertionResults()

vars == ctx.getVariables()

props == ctx.getProperties()

etc.

Check out How to Reuse Your JMeter Code with JAR Files and Save Time article for more details if needed.

Body:
H, I have code like this in JSR223 Assertion

import groovy.json.JsonSlurper;
import org.apache.jmeter.services.FileServer;

failureMessage = "";
sampleLabel = SampleResult.getSampleLabel();

isResponseCodeCorrect("204");

def isResponseCodeCorrect(String expCode)
{
  String actualCode = prev.getResponseCode();

  if(!expCode.equals(actualCode)){

    failureMessage += "ERROR code: Expected <"+ expCode +"> but we got instead  " + actualCode + ";";
  }
}

The question is possible to create the some code library in groovy or java and inject the objects form executed sampler (like public variables: ctx, vars, props, SamplerResult)?

The goal is to inject objects like SampleResult, AssertionResult (to invoke -> SampleResult.getSampleLabel()),  AssertionResult.setFailureMessage("failureMessage);
         AssertionResult.setFailure(true); ) and own functions.

Like to have the wrapper (some object) with methods to play with Assertion, saving data to CSV ... The wrapper is going to be imported to JSR223 Assertion and then I would like to call some specific methods.

The expected wrapper:

 @groovy.transform.MapConstructor
   class Foo {
    SampleResult results,
    AssertionResult assertionResult

    isResponseCodeCorrect(String expCode) {
        String actualCode = prev.getResponseCode();

    if(!expCode.equals(actualCode)){

        failureMessage += "ERROR code: Expected <"+ expCode +"> but we got instead  " + actualCode + ";";
     assertionResult.setFailureMessage(failureMessage);
     assertionResult.setFailure(true);

     log.error(sampleLabel + " Error is going to be saved to the logs");
     PrintLogToFile();
       }
    }
}

JSR223 Assertion:

import org.foo. wrapper

Foo wrapper = new Foo();
wrapper.isResponseCodeCorrect("200");

Or some useful things to avoid code duplication between calls

Body:
You can compile your Groovy or Java code into a .jar file and drop it into JMeter Classpath

Once done you will be able to access the functions available in the .jar file from any JSR223 Test Element and/or from __groovy() function.

I can think only of one class which you need: JMeterContext an instance of which can be obtained as simple as:

def ctx = org.apache.jmeter.threads.JMeterContextService.getContext()

once done you will be able to access whatever you need like:

SampleResult == ctx.getPreviousResult()

AssertionResult == ctx.getPreviousResult().getAssertionResults()

vars == ctx.getVariables()

props == ctx.getProperties()

etc.

Check out How to Reuse Your JMeter Code with JAR Files and Save Time article for more details if needed.


答:
std::string is not suited for holding characters larger than 1 byte: "ỏ" in your case.

"5" means length of your string in bytes. Because std::string still can store such strings as yours but it is hard to handle strings that way.

Try to use std::wstring.

You can read here about wide characters: https://en.wikipedia.org/wiki/Wide_character

Title: Get Latin Character in C++


问:
What is the reason to initialize or assign an empty string literal to a pointer to char in C, or a pointer to const char in C++?
My question is actually quite simply for those who might know about it, but I ask because I'm not aware of this technique already.

What is the reason for initializing or assigning an empty string literal to a pointer to char in C, or a pointer to const char in C++?

Like f.e.:

```<code>char* p = "";
</code>```

or

```<code>char* p;
p = "";
</code>```

Or, as suggested in the comments, in C++:

```<code>const char* p = "";
</code>```

or

```<code>const char* p;
p = "";
</code>```

I do often see this technique, but don't understand why someone shall assign an empty string literal to a char pointer (or pointer to const char for C++) or where this is coming from.

I have read Initialize a string in C to empty string, but this question is focused on initializing a char array with an empty string.

And I have also read: Initializing a string with the empty string, but this question covers an incorrect approach to assign an empty string to a pointer earlier returned by a malloc() function.

答:
Initializing a a char pointer with an empty string literal does have the advantage, that in fact an empty string literal is not "empty". If you create a dummy program and look at char* p = ""; with a debugger you will see, that an char array with length 1, containing \0 is created. This means that p is pointing to a valid zero terminated string. Therefore you are able to pass p to most functions working with zero terminated strings (e.g. basically all standard library string manipulation functions) without having to worry about them failing/memory errors etc. This is usefull, for example in a case where you are assining some value to p that depends on some condition that might fail, leaving you with a potential undefined behaviour, if you did not initialize the pointer with a proper value.

On that last note, there is also the issue of some coding standards forbidding uninitialised variables, as those are potential sources of bugs.

Body:
My question is actually quite simply for those who might know about it, but I ask because I'm not aware of this technique already.

What is the reason for initializing or assigning an empty string literal to a pointer to char in C, or a pointer to const char in C++?

Like f.e.:

char* p = "";

or

char* p;
p = "";

Or, as suggested in the comments, in C++:

const char* p = "";

or

const char* p;
p = "";

I do often see this technique, but don't understand why someone shall assign an empty string literal to a char pointer (or pointer to const char for C++) or where this is coming from.

I have read Initialize a string in C to empty string, but this question is focused on initializing a char array with an empty string.

And I have also read: Initializing a string with the empty string, but this question covers an incorrect approach to assign an empty string to a pointer earlier returned by a malloc() function.


问:
Parse short US date into yyyy-MM-dd, java
I want to parse the date "3/27/11" which I think is equal to US short date.

```<code>DateFormat df1 = new SimpleDateFormat("MM/dd/yy");
DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
Date date = (Date) df1.parseObject("03/27/11");
System.out.println("New date: " + df2.format(date));
</code>```

I found the code above in several java tutorials but it doesn't seem to work.
For some how I get,

```<code>Exception in thread "main" java.lang.AssertionError: Default directory must be absolute/non-UNC
</code>```

Here is what I want to achieve,

input: 3/27/11

(03/27/11 should also be a valid input)

output: 2011-03-27

Thanks in advance!

答:
```<code>public class date {

    public static void main(String args[])
    {
        String s="03/27/2011";// or 3/27/2011

        SimpleDateFormat dateFormatter=s.length()==9?new SimpleDateFormat("M/dd/yyyy"):new SimpleDateFormat("MM/dd/yyyy");
        try {
            Calendar calendar=Calendar.getInstance();
            Date date=dateFormatter.parse(s);
            calendar.setTime(date);
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
            String str=simpleDateFormat.format(calendar.getTime());
            System.out.println(str);
        } catch (ParseException e) {
              e.printStackTrace();
        }
    }

}

    enter code here
</code>```

Body:
I want to parse the date "3/27/11" which I think is equal to US short date.

DateFormat df1 = new SimpleDateFormat("MM/dd/yy");
DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
Date date = (Date) df1.parseObject("03/27/11");
System.out.println("New date: " + df2.format(date));

I found the code above in several java tutorials but it doesn't seem to work.
For some how I get,

Exception in thread "main" java.lang.AssertionError: Default directory must be absolute/non-UNC

Here is what I want to achieve,

input: 3/27/11

(03/27/11 should also be a valid input)

output: 2011-03-27

Thanks in advance!


问:
Modify list has an affect on another list in java
I have a problem with modify list in java, i want to change value in listTempEnemy with foreach and then the value change as i want, but it has an affect to listEnemy which should not change, this is my code Thank You.

```<code>public void hunt() {
    Enemy enemy = new Enemy();
    enemy.setEnemyName("Poring");
    enemy.setEnemyMinATK(10);
    enemy.setEnemyMaxATK(20);
    listEnemy.add(enemy);

    List<Enemy> listTempEnemy = new ArrayList<Enemy>();
    listTempEnemy.addAll(listEnemy);

    for (Enemy enm : listEnemy) {
        System.out.println("Before "+ enm.getEnemyMinATK() + " | " + enm.getEnemyMaxATK());
    }

    for (Enemy enm : listTempEnemy) {
        enm.setEnemyMinATK((enm.getEnemyMinATK() * 10/100) + enm.getEnemyMinATK());
        enm.setEnemyMaxATK((enm.getEnemyMaxATK() * 10/100) + enm.getEnemyMaxATK());
        System.out.println("Value Changed "+ enm.getEnemyMinATK() + " | " + enm.getEnemyMaxATK());
    }

    for (Enemy enm : listEnemy) {
        System.out.println("After "+ enm.getEnemyMinATK() + " | " + enm.getEnemyMaxATK());
    }
}
</code>```

The result is

```<code>2020-02-18T17:02:33.843+0700|Info: Before 10 | 20
2020-02-18T17:02:33.843+0700|Info: Value Changed 11 | 22
2020-02-18T17:02:33.843+0700|Info: After 11 | 22
</code>```

And then i have change my code

```<code>private List<Enemy> loadEnemy() {
    List<Enemy> listEnemy = new ArrayList<Enemy>();

    Enemy enemy = new Enemy();
    enemy.setEnemyName("Poring");
    enemy.setEnemyHP(100);
    enemy.setEnemyMinATK(10);
    enemy.setEnemyMaxATK(20);
    listEnemy.add(enemy);

    return listEnemy;
}

public void hunt() {
    List<Enemy> listTempEnemy = loadEnemy();

    for (Enemy enm : listEnemy) {
        System.out.println("Before "+ enm.getEnemyMinATK() + " | " + enm.getEnemyMaxATK());
    }

    for (Enemy enm : listTempEnemy) {
        enm.setEnemyMinATK((enm.getEnemyMinATK() * 10/100) + enm.getEnemyMinATK());
        enm.setEnemyMaxATK((enm.getEnemyMaxATK() * 10/100) + enm.getEnemyMaxATK());
        System.out.println("Changed Value " + enm.getEnemyMinATK() + " | " + enm.getEnemyMaxATK());
    }

    for (Enemy enm : listEnemy) {
        System.out.println("After "+ enm.getEnemyMinATK() + " | " + enm.getEnemyMaxATK());
    }
}
</code>```

This is the result that i want

```<code>2020-02-18T17:46:36.387+0700|Info: Before 10 | 20
2020-02-18T17:46:36.387+0700|Info: Changed Value 11 | 22
2020-02-18T17:46:36.387+0700|Info: After 10 | 20
</code>```

答: You've added the same object (pointers/references to the same object in heap (memory)) to the two separate lists. When you change the object in one list it changes it in the other because they are both the same object. This is why immutable objects are preferable as these kind of bugs can be really hard to spot (if you had a lot of complex logic... e.g. which class is mutating the objects?). You'll need 2 copies of your object for list 1 and list 2

Body:
I have a problem with modify list in java, i want to change value in listTempEnemy with foreach and then the value change as i want, but it has an affect to listEnemy which should not change, this is my code Thank You.

public void hunt() {
    Enemy enemy = new Enemy();
    enemy.setEnemyName("Poring");
    enemy.setEnemyMinATK(10);
    enemy.setEnemyMaxATK(20);
    listEnemy.add(enemy);

    List<Enemy> listTempEnemy = new ArrayList<Enemy>();
    listTempEnemy.addAll(listEnemy);

    for (Enemy enm : listEnemy) {
        System.out.println("Before "+ enm.getEnemyMinATK() + " | " + enm.getEnemyMaxATK());
    }

    for (Enemy enm : listTempEnemy) {
        enm.setEnemyMinATK((enm.getEnemyMinATK() * 10/100) + enm.getEnemyMinATK());
        enm.setEnemyMaxATK((enm.getEnemyMaxATK() * 10/100) + enm.getEnemyMaxATK());
        System.out.println("Value Changed "+ enm.getEnemyMinATK() + " | " + enm.getEnemyMaxATK());
    }

    for (Enemy enm : listEnemy) {
        System.out.println("After "+ enm.getEnemyMinATK() + " | " + enm.getEnemyMaxATK());
    }
}

The result is

2020-02-18T17:02:33.843+0700|Info: Before 10 | 20
2020-02-18T17:02:33.843+0700|Info: Value Changed 11 | 22
2020-02-18T17:02:33.843+0700|Info: After 11 | 22

And then i have change my code

private List<Enemy> loadEnemy() {
    List<Enemy> listEnemy = new ArrayList<Enemy>();

    Enemy enemy = new Enemy();
    enemy.setEnemyName("Poring");
    enemy.setEnemyHP(100);
    enemy.setEnemyMinATK(10);
    enemy.setEnemyMaxATK(20);
    listEnemy.add(enemy);

    return listEnemy;
}

public void hunt() {
    List<Enemy> listTempEnemy = loadEnemy();

    for (Enemy enm : listEnemy) {
        System.out.println("Before "+ enm.getEnemyMinATK() + " | " + enm.getEnemyMaxATK());
    }

    for (Enemy enm : listTempEnemy) {
        enm.setEnemyMinATK((enm.getEnemyMinATK() * 10/100) + enm.getEnemyMinATK());
        enm.setEnemyMaxATK((enm.getEnemyMaxATK() * 10/100) + enm.getEnemyMaxATK());
        System.out.println("Changed Value " + enm.getEnemyMinATK() + " | " + enm.getEnemyMaxATK());
    }

    for (Enemy enm : listEnemy) {
        System.out.println("After "+ enm.getEnemyMinATK() + " | " + enm.getEnemyMaxATK());
    }
}

This is the result that i want

2020-02-18T17:46:36.387+0700|Info: Before 10 | 20
2020-02-18T17:46:36.387+0700|Info: Changed Value 11 | 22
2020-02-18T17:46:36.387+0700|Info: After 10 | 20


问:
SendGrid is not an attribute class
I have installed SendGrid Nugget but I am still not able to use it in my code.
I keep getting this error:

SendGrid is not an attribute class

Even though I think I have installed everything there is to install:

What am I missing here? Could be something silly but I am not able to figure it out.

答:
You probably wanted Microsoft.Azure.WebJobs.Extensions.SendGrid which provides the SendGrid bindings for Azure Functions.

The basic SendGrid library knows absolutely nothing about Azure Functions.

Title: SendGrid is not an attribute class


问:
How to display index translation (rails-i18n) in Rails?
Rails 5 adds error indexing using (indexing of errors on nested attributes) for models:

```<code>class Order
    has_many :operations, index_errors: true

    accepts_nested_attributes_for :operations
end
</code>```

```<code>class Operation
    has_many :inv_items, index_errors: true

    accepts_nested_attributes_for :inv_items
end
</code>```

As a result of calling order.errors.full_messages
I get errors in this form:

{:"operations[0].inv_items[0].serial_num"=>["Can't be empty"], :"operations[0].inv_items[1].serial_num"=>["Can't be empty"]}

In file .yml i can directly set the translation

```<code>en:
  activerecord:
    attributes:
      warehouse/order/operations[0]/inv_items[0]:
        serial_num: 'Serial number'
</code>```

But how to organize a translation without indicating each index?

答:
Try setting the translation for the Model without nesting it within its associations. Something like the snippet below.

```<code>en:
  activerecord:
    models:
      inv_item: Inventory Item
    attributes:
      inv_item:
        serial_num: Serial Number

</code>```

Rails Guide

Body:
Rails 5 adds error indexing using (indexing of errors on nested attributes) for models:

class Order
    has_many :operations, index_errors: true

    accepts_nested_attributes_for :operations
end

class Operation
    has_many :inv_items, index_errors: true

    accepts_nested_attributes_for :inv_items
end

As a result of calling order.errors.full_messages
I get errors in this form:

{:"operations[0].inv_items[0].serial_num"=>["Can't be empty"], :"operations[0].inv_items[1].serial_num"=>["Can't be empty"]}

In file .yml i can directly set the translation

en:
  activerecord:
    attributes:
      warehouse/order/operations[0]/inv_items[0]:
        serial_num: 'Serial number'

But how to organize a translation without indicating each index?

Body:
Try setting the translation for the Model without nesting it within its associations. Something like the snippet below.

en:
  activerecord:
    models:
      inv_item: Inventory Item
    attributes:
      inv_item:
        serial_num: Serial Number

Rails Guide


问:
SpatialLines to iGraph conversion simplifies topology
I'm trying to convert from spatialLinesDataFrame to igraph object, and think I may be losing information I want to keep. Fairly new to igraph so please bear with me.  The example below illustrates:

```<code># create sldf object
require(sp); require(igraph); require(shp2graph)
d = data.frame(x = c(0,80,100,0,-20,-8,0,3,-10,-5,80,75),
               y = c(0,-10,5,0,14,33,0,-4,-10,-12,-10,5),
               grp = c(1,1,1,2,2,2,3,3,3,3,4,4))

sl = SpatialLines(list(
  Lines(list(Line(d[d$grp == 1,1:2]),
             Line(d[d$grp == 4,1:2])), ID=1),
  Lines(Line(d[d$grp == 2,1:2]), ID=2),
  Lines(Line(d[d$grp == 3,1:2]), ID=3))
)

sldf = SpatialLinesDataFrame(sl, iris[1:3,])
plot(sldf)
</code>```

Now convert to igraph and plot:

```<code>read_sldf = readshpnw(sldf, ELComputed = T)
g = nel2igraph(read_sldf[[2]], read_sldf[[3]], weight=read_sldf[[4]])
plot(g)
</code>```

Am I right that the off-branch of the first spdf row (sldf[1,]) has been lost?  Calling as_edgelist(g) returns 3 rows not 4.

答:
Just change those options in readshpnw:

```<code># create sldf object
require(sp); require(igraph); require(shp2graph)
d = data.frame(x = c(0,80,100,0,-20,-8,0,3,-10,-5,80,75),
               y = c(0,-10,5,0,14,33,0,-4,-10,-12,-10,5),
               grp = c(1,1,1,2,2,2,3,3,3,3,4,4))

sl = SpatialLines(list(
    Lines(list(Line(d[d$grp == 1,1:2]),
               Line(d[d$grp == 4,1:2])), ID=1),
    Lines(Line(d[d$grp == 2,1:2]), ID=2),
    Lines(Line(d[d$grp == 3,1:2]), ID=3))
)

sldf = SpatialLinesDataFrame(sl, iris[1:3,])
plot(sldf)

nodes = readshpnw(sldf, ELComputed = TRUE, Detailed = TRUE, ea.prop = names(sldf))
g = nel2igraph(nodes[[2]], nodes[[3]])
plot(g)
</code>```

Body:
I'm trying to convert from spatialLinesDataFrame to igraph object, and think I may be losing information I want to keep. Fairly new to igraph so please bear with me.  The example below illustrates:

# create sldf object
require(sp); require(igraph); require(shp2graph)
d = data.frame(x = c(0,80,100,0,-20,-8,0,3,-10,-5,80,75),
               y = c(0,-10,5,0,14,33,0,-4,-10,-12,-10,5),
               grp = c(1,1,1,2,2,2,3,3,3,3,4,4))

sl = SpatialLines(list(
  Lines(list(Line(d[d$grp == 1,1:2]),
             Line(d[d$grp == 4,1:2])), ID=1),
  Lines(Line(d[d$grp == 2,1:2]), ID=2),
  Lines(Line(d[d$grp == 3,1:2]), ID=3))
)

sldf = SpatialLinesDataFrame(sl, iris[1:3,])
plot(sldf)

Now convert to igraph and plot:

read_sldf = readshpnw(sldf, ELComputed = T)
g = nel2igraph(read_sldf[[2]], read_sldf[[3]], weight=read_sldf[[4]])
plot(g)

Am I right that the off-branch of the first spdf row (sldf[1,]) has been lost?  Calling as_edgelist(g) returns 3 rows not 4.

Body:
Just change those options in readshpnw:

# create sldf object
require(sp); require(igraph); require(shp2graph)
d = data.frame(x = c(0,80,100,0,-20,-8,0,3,-10,-5,80,75),
               y = c(0,-10,5,0,14,33,0,-4,-10,-12,-10,5),
               grp = c(1,1,1,2,2,2,3,3,3,3,4,4))

sl = SpatialLines(list(
    Lines(list(Line(d[d$grp == 1,1:2]),
               Line(d[d$grp == 4,1:2])), ID=1),
    Lines(Line(d[d$grp == 2,1:2]), ID=2),
    Lines(Line(d[d$grp == 3,1:2]), ID=3))
)

sldf = SpatialLinesDataFrame(sl, iris[1:3,])
plot(sldf)

nodes = readshpnw(sldf, ELComputed = TRUE, Detailed = TRUE, ea.prop = names(sldf))
g = nel2igraph(nodes[[2]], nodes[[3]])
plot(g)


问:
creating text in webpage like in the gif below
i want to create a text in a webpage like a timer goes out using js like in the gif image

my code is given below .. it show text like 12345678910...

var i;
for (i=0 ; i < 10; i++)
{
document.write(i);
}```

答:
It's possible you want to use

document.body = i

but the best idea would be to make a text element and then put your text into that element --

In your HTML:

then in your JS:

var element = document.getElementById("foo");
element.innerHTML = i

Body:
It's possible you want to use

document.body = i

but the best idea would be to make a text element and then put your text into that element --

In your HTML:
<p id="foo"></p>

then in your JS:

var element = document.getElementById("foo");
element.innerHTML = i


问:
Is it possible and how create a trigger with Entity Framework Core
Is it possible to create a SQL trigger with Entity Framework Core.

Maybe by using instruction in

```<code>protected override void OnModelCreating(DbModelBuilder dbModelBuilder)
{
}
</code>```

Or simply by executing SQL statements in Migration scripts

```<code>public override void Up()
{
}
</code>```

答:
```<code>    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.Sql(@"create trigger .....");
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.Sql(@"drop trigger <triggerName>");
    }
</code>```

Body:
Is it possible to create a SQL trigger with Entity Framework Core.

Maybe by using instruction in

protected override void OnModelCreating(DbModelBuilder dbModelBuilder)
{
}

Or simply by executing SQL statements in Migration scripts

public override void Up()
{
}


答:
Both lists contain the same players. Therefore, if you change a player in 1 list, you implicitely change the player in the other list as well.

You could try to fill the second list with clones of those in the first.

Something like this:

```<code>listPlayer.add(game);
listTempPlayer.add((Game)game.clone());
</code>```

Of course, you Game class should implement the Cloneable interface.

Title: Modify list has an affect on another list in java

Body:
Both lists contain the same players. Therefore, if you change a player in 1 list, you implicitely change the player in the other list as well.

You could try to fill the second list with clones of those in the first.

Something like this:

listPlayer.add(game);
listTempPlayer.add((Game)game.clone());

Of course, you Game class should implement the Cloneable interface.


问:
Is there an extensible way to initialize a struct from an array in C++?
```<code>struct SomeStruct {
    int a;
    int b;
    int c;
    int d;
};

void main() {
    std::array<int, 4> arr {1, 2, 3, 4};
    SomeStruct someStruct { ??? }; // <------ Initialize with arr? (Ideal would be {arr})
}
</code>```

As seen in the code example, is there some shortcut to initialize someStruct with arr?
Instead of resorting to:

```<code>    SomeStruct someStruct {arr[0], arr[1], arr[2], arr[3]};
</code>```

答:
You can use std::apply to create a parameter pack and use that in the initializer:

```<code>auto someStruct = std::apply([](auto&&... args){return SomeStruct{decltype(args)(args)...};}, arr);
</code>```

You can put this in a function to use it comfortably:

```<code>template<typename T, typename A>
constexpr T make_from_tuple_list_init(A&& a) {
    return std::apply([](auto&&... args){return T{decltype(args)(args)...};}, std::forward<A>(a));
}
</code>```

Then use it as

```<code>auto someStruct = make_from_tuple_list_init<SomeStruct>(arr);
</code>```

This requires C++17 and #include<tuple>, but can be implemented in earlier C++ versions (with some more effort) as well. Also in C++17 this is guaranteed to use copy elision, so there will be only one SomeStruct constructed. Before C++17 some move constructions might be involved (although compilers were already permitted to and did implement return value optimization with the same effect).

std::apply also has the benefit that it works with every type that implements std::get and std::tuple_size, meaning that it will work for example with std::array, std::tuple, std::pair and other user-defined types with that interface.

One might want to make two versions of this function, one that uses T{...} as above and one that uses T(...), so that one is able to choose between list-initialization and direct-initialization.

However, the T(...) version has been implemented in the standard library since C++17 as std::make_from_tuple. In C++20, aggregate initialization will also work with parentheses, so std::make_from_tuple will work for your case then directly.

For a C++14 implementation, take this example from cppreference's page on std::make_from_tuple:

```<code>namespace detail {
template <class T, class Tuple, std::size_t... I>
constexpr T make_from_tuple_impl( Tuple&& t, std::index_sequence<I...> )
{
  return T(std::get<I>(std::forward<Tuple>(t))...);
}
} // namespace detail

template <class T, class Tuple>
constexpr T make_from_tuple( Tuple&& t )
{
   return detail::make_from_tuple_impl<T>(std::forward<Tuple>(t),
       std::make_index_sequence<std::tuple_size_v<std::remove_reference_t<Tuple>>>{});
}
</code>```

and replace std::tuple_size_v<...> with std::tuple_size<...>::value.

This is for the T(...) version. You would need to replace T(...) with T{...} to get the T{...} version I implemented above.

Body:
struct SomeStruct {
    int a;
    int b;
    int c;
    int d;
};

void main() {
    std::array<int, 4> arr {1, 2, 3, 4};
    SomeStruct someStruct { ??? }; // <------ Initialize with arr? (Ideal would be {arr})
}

As seen in the code example, is there some shortcut to initialize someStruct with arr?
Instead of resorting to:

    SomeStruct someStruct {arr[0], arr[1], arr[2], arr[3]};

Body:
You can use std::apply to create a parameter pack and use that in the initializer:

auto someStruct = std::apply([](auto&&... args){return SomeStruct{decltype(args)(args)...};}, arr);

You can put this in a function to use it comfortably:

template<typename T, typename A>
constexpr T make_from_tuple_list_init(A&& a) {
    return std::apply([](auto&&... args){return T{decltype(args)(args)...};}, std::forward<A>(a));
}

Then use it as

auto someStruct = make_from_tuple_list_init<SomeStruct>(arr);

This requires C++17 and #include<tuple>, but can be implemented in earlier C++ versions (with some more effort) as well. Also in C++17 this is guaranteed to use copy elision, so there will be only one SomeStruct constructed. Before C++17 some move constructions might be involved (although compilers were already permitted to and did implement return value optimization with the same effect).

std::apply also has the benefit that it works with every type that implements std::get and std::tuple_size, meaning that it will work for example with std::array, std::tuple, std::pair and other user-defined types with that interface.

One might want to make two versions of this function, one that uses T{...} as above and one that uses T(...), so that one is able to choose between list-initialization and direct-initialization.

However, the T(...) version has been implemented in the standard library since C++17 as std::make_from_tuple. In C++20, aggregate initialization will also work with parentheses, so std::make_from_tuple will work for your case then directly.

For a C++14 implementation, take this example from cppreference's page on std::make_from_tuple:

namespace detail {
template <class T, class Tuple, std::size_t... I>
constexpr T make_from_tuple_impl( Tuple&& t, std::index_sequence<I...> )
{
  return T(std::get<I>(std::forward<Tuple>(t))...);
}
} // namespace detail

template <class T, class Tuple>
constexpr T make_from_tuple( Tuple&& t )
{
   return detail::make_from_tuple_impl<T>(std::forward<Tuple>(t),
       std::make_index_sequence<std::tuple_size_v<std::remove_reference_t<Tuple>>>{});
}

and replace std::tuple_size_v<...> with std::tuple_size<...>::value.

This is for the T(...) version. You would need to replace T(...) with T{...} to get the T{...} version I implemented above.


问:
Action Result File - Filename when downloading is wrong in some cases
So this is the Code that returns the file. It is in a Method named GetMainReport.

```<code>var mBytes = MergePDF(formLanguage, mergedForms);
                        if (mBytes != null)
                        {
                            var cd = new System.Net.Mime.ContentDisposition
                            {
                                FileName = formLanguage.FileName,
                                Inline = formLanguage.FileExtension == FileExtension.PDF
                            };

                            Response.Headers.Add("content-disposition", cd.ToString());

                            AddDownloadedForm(formLanguage.Id);
                            return File(mBytes, type);
                        }
</code>```

My Problem now is that if i go via this url:
http://localhost:8090/Library/105020.pdf
The filename when downloaded is 105020.pdf

if i use this one

http://localhost:8090/FormSearch/FormSearch/getMainReport?FormNumber=105020%20%20de

The filename is GetMainReport.pdf

any ideas why?

答:
try this settings for ContentDisposition:</p>

```<code> var cd = new System.Net.Mime.ContentDisposition
  {
    FileName = formLanguage.FileName,
    DispositionType = DispositionTypeNames.Attachment,
    Inline = formLanguage.FileExtension == FileExtension.PDF
   };
</code>```

Body:
So this is the Code that returns the file. It is in a Method named GetMainReport.

var mBytes = MergePDF(formLanguage, mergedForms);
                        if (mBytes != null)
                        {
                            var cd = new System.Net.Mime.ContentDisposition
                            {
                                FileName = formLanguage.FileName,
                                Inline = formLanguage.FileExtension == FileExtension.PDF
                            };

                            Response.Headers.Add("content-disposition", cd.ToString());

                            AddDownloadedForm(formLanguage.Id);
                            return File(mBytes, type);
                        }

My Problem now is that if i go via this url:
http://localhost:8090/Library/105020.pdf
The filename when downloaded is 105020.pdf

if i use this one

http://localhost:8090/FormSearch/FormSearch/getMainReport?FormNumber=105020%20%20de

The filename is GetMainReport.pdf

any ideas why?

Body:
try this settings for ContentDisposition:

 var cd = new System.Net.Mime.ContentDisposition
  {
    FileName = formLanguage.FileName,
    DispositionType = DispositionTypeNames.Attachment,
    Inline = formLanguage.FileExtension == FileExtension.PDF
   };


答:
You can define a constructor taking a pair of iterators. Sometimes simplicity wins over flexibility.

```<code>#include <array>

struct SomeStruct {
    int a;
    int b;
    int c;
    int d;

    template<class InputIt>
    SomeStruct(InputIt begin, InputIt end)
    {
        if (begin != end) a = *begin++;
        if (begin != end) b = *begin++;
        if (begin != end) c = *begin++;
        if (begin != end) d = *begin++;
    }
};
</code>```

Demo: https://coliru.stacked-crooked.com/a/7e235a8022b048ac

Title: Is there an extensible way to initialize a struct from an array in C++?

Body:
You can define a constructor taking a pair of iterators. Sometimes simplicity wins over flexibility.

#include <array>

struct SomeStruct {
    int a;
    int b;
    int c;
    int d;

    template<class InputIt>
    SomeStruct(InputIt begin, InputIt end)
    {
        if (begin != end) a = *begin++;
        if (begin != end) b = *begin++;
        if (begin != end) c = *begin++;
        if (begin != end) d = *begin++;
    }
};

Demo: https://coliru.stacked-crooked.com/a/7e235a8022b048ac


问:
how to write custom function/method in java? (RFT)
I need to process few lines of code over and over in RFT (java) so custom method/function/procedure is the best (and only) solution to this.

I have no java experience so I need some help with that.

The method will receive some parameters and will return no value.

Basically it will be entering new records into a database (web based application). How many records? It depends on data so I need to make it argument based.

the current code looks like

```<code>    text__firstname(ANY,NO_FLAGS).setText(dpString("StudentName"));
    text__surname(ANY,NO_FLAGS).setText(dpString("StudentSurnameName"));
</code>```

in php the desired function would look like

```<code>   function add_student($first_name,$surname){
    text__firstname(ANY,NO_FLAGS).setText($first_name);
    text__surname(ANY,NO_FLAGS).setText($surname);
   }
</code>```

so I can call it

```<code>   add_student(dpString("StudentName"),dpString("StudentSurnameName"));
</code>```

答:
You can write a method like this..

```<code>public void setTextValues(TestObject firstName , TestObject surName){

while(dp.dpnext()){
firstName(ANY,NO_FLAGS).setText(dpString("StudentName"));
    surName(ANY,NO_FLAGS).setText(dpString("StudentSurnameName"));

}

}
</code>```

dpnext command automatically iterates to the next record in data pool.

Hope this helps you!!

ContentLicense: CC BY-SA 2.5

Body:
I need to process few lines of code over and over in RFT (java) so custom method/function/procedure is the best (and only) solution to this.

I have no java experience so I need some help with that.

The method will receive some parameters and will return no value.

Basically it will be entering new records into a database (web based application). How many records? It depends on data so I need to make it argument based.

the current code looks like

    text__firstname(ANY,NO_FLAGS).setText(dpString("StudentName"));
    text__surname(ANY,NO_FLAGS).setText(dpString("StudentSurnameName"));

in php the desired function would look like

   function add_student($first_name,$surname){
    text__firstname(ANY,NO_FLAGS).setText($first_name);
    text__surname(ANY,NO_FLAGS).setText($surname);
   }

so I can call it

   add_student(dpString("StudentName"),dpString("StudentSurnameName"));

Body:
You can write a method like this..

public void setTextValues(TestObject firstName , TestObject surName){

while(dp.dpnext()){
firstName(ANY,NO_FLAGS).setText(dpString("StudentName"));
    surName(ANY,NO_FLAGS).setText(dpString("StudentSurnameName"));

}

}

dpnext command automatically iterates to the next record in data pool.

Hope this helps you!!


问:
Spring-Batch: Testing custom itemReader
I am trying to test my custom itemReader :

```<code>@Bean
@StepScope
MyMultiLineItemReader itemReader(@Value("#{stepExecutionContext['fileName']}") String filename) throws MalformedURLException {
MyMultiLineItemReader itemReader = new MyMultiLineItemReader();
itemReader.setDelegate(myFlatFileItemReader(filename));

return itemReader;
}

@Bean
@StepScope
public FlatFileItemReader<String> myFlatFileItemReader(@Value("#{stepExecutionContext['fileName']}") String filename) throws MalformedURLException {
return new FlatFileItemReaderBuilder<String>()
.name("myFlatFileItemReader")
.resource(new UrlResource(filename))
.lineMapper(new PassThroughLineMapper())
.build();
}
</code>```

my test class looks like

```<code>@Test
public void givenMockedStep_whenReaderCalled_thenSuccess() throws Exception {
    // given
    JobExecution jobExecution = new JobExecution(5l);
    ExecutionContext ctx = new ExecutionContext();
    ctx.put("fileName", "src/main/resources/data/input.txt");
    jobExecution.setExecutionContext(ctx);

    JobSynchronizationManager.register(jobExecution);
    StepExecution stepExecution = MetaDataInstanceFactory.createStepExecution(ctx);

    // when
    StepScopeTestUtils.doInStepScope(stepExecution, () -> {
     ...
     });
}
</code>```

When I run the test case, the process fails because the fileName parameter is null.

I am looking for the right way of testing the itemReader.

Thanks

答:
You don't need to create a JobExecution and register it in a JobSynchronizationManager to test a step-scoped component. Mocking a step execution and using it in StepScopeTestUtils.doInStepScope is enough. Here is a complete example:

```<code>import java.util.ArrayList;
import java.util.List;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder;
import org.springframework.batch.item.file.mapping.PassThroughLineMapper;
import org.springframework.batch.test.MetaDataInstanceFactory;
import org.springframework.batch.test.StepScopeTestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = StepScopedComponentTest.MyConfiguration.class)
public class StepScopedComponentTest {

    @Autowired
    private FlatFileItemReader<String> reader;

    @Test
    public void givenMockedStep_whenReaderCalled_thenSuccess() throws Exception {
        // given
        ExecutionContext ctx = new ExecutionContext();
        ctx.put("fileName", "data/input.txt");
        StepExecution stepExecution = MetaDataInstanceFactory.createStepExecution(ctx);

        // when
        List<String> items = StepScopeTestUtils.doInStepScope(stepExecution, () -> {
            List<String> result = new ArrayList<>();
            String item;
            reader.open(stepExecution.getExecutionContext());
            while ((item = reader.read()) != null) {
                result.add(item);
            }
            reader.close();
            return result;
        });

        // then
        Assert.assertEquals(2, items.size());
        Assert.assertEquals("foo", items.get(0));
        Assert.assertEquals("bar", items.get(1));
    }

    @Configuration
    @EnableBatchProcessing
    static class MyConfiguration {

        @Bean
        @StepScope
        public FlatFileItemReader<String> myFlatFileItemReader(@Value("#{stepExecutionContext['fileName']}") String filename) {
            return new FlatFileItemReaderBuilder<String>()
                    .name("myFlatFileItemReader")
                    .resource(new ClassPathResource(filename))
                    .lineMapper(new PassThroughLineMapper())
                    .build();
        }
    }

}
</code>```

This test passes assuming the class path resource data/input.txt contains two lines foo and bar.

Title: Spring-Batch: Testing custom itemReader

Body:
I am trying to test my custom itemReader :

@Bean
@StepScope
MyMultiLineItemReader itemReader(@Value("#{stepExecutionContext['fileName']}") String filename) throws MalformedURLException {
MyMultiLineItemReader itemReader = new MyMultiLineItemReader();
itemReader.setDelegate(myFlatFileItemReader(filename));

return itemReader;
}

@Bean
@StepScope
public FlatFileItemReader<String> myFlatFileItemReader(@Value("#{stepExecutionContext['fileName']}") String filename) throws MalformedURLException {
return new FlatFileItemReaderBuilder<String>()
.name("myFlatFileItemReader")
.resource(new UrlResource(filename))
.lineMapper(new PassThroughLineMapper())
.build();
}

my test class looks like

@Test
public void givenMockedStep_whenReaderCalled_thenSuccess() throws Exception {
    // given
    JobExecution jobExecution = new JobExecution(5l);
    ExecutionContext ctx = new ExecutionContext();
    ctx.put("fileName", "src/main/resources/data/input.txt");
    jobExecution.setExecutionContext(ctx);

    JobSynchronizationManager.register(jobExecution);
    StepExecution stepExecution = MetaDataInstanceFactory.createStepExecution(ctx);

    // when
    StepScopeTestUtils.doInStepScope(stepExecution, () -> {
     ...
     });
}

When I run the test case, the process fails because the fileName parameter is null.

I am looking for the right way of testing the itemReader.

Thanks

Body:
You don't need to create a JobExecution and register it in a JobSynchronizationManager to test a step-scoped component. Mocking a step execution and using it in StepScopeTestUtils.doInStepScope is enough. Here is a complete example:

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

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder;
import org.springframework.batch.item.file.mapping.PassThroughLineMapper;
import org.springframework.batch.test.MetaDataInstanceFactory;
import org.springframework.batch.test.StepScopeTestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = StepScopedComponentTest.MyConfiguration.class)
public class StepScopedComponentTest {

    @Autowired
    private FlatFileItemReader<String> reader;

    @Test
    public void givenMockedStep_whenReaderCalled_thenSuccess() throws Exception {
        // given
        ExecutionContext ctx = new ExecutionContext();
        ctx.put("fileName", "data/input.txt");
        StepExecution stepExecution = MetaDataInstanceFactory.createStepExecution(ctx);

        // when
        List<String> items = StepScopeTestUtils.doInStepScope(stepExecution, () -> {
            List<String> result = new ArrayList<>();
            String item;
            reader.open(stepExecution.getExecutionContext());
            while ((item = reader.read()) != null) {
                result.add(item);
            }
            reader.close();
            return result;
        });

        // then
        Assert.assertEquals(2, items.size());
        Assert.assertEquals("foo", items.get(0));
        Assert.assertEquals("bar", items.get(1));
    }

    @Configuration
    @EnableBatchProcessing
    static class MyConfiguration {

        @Bean
        @StepScope
        public FlatFileItemReader<String> myFlatFileItemReader(@Value("#{stepExecutionContext['fileName']}") String filename) {
            return new FlatFileItemReaderBuilder<String>()
                    .name("myFlatFileItemReader")
                    .resource(new ClassPathResource(filename))
                    .lineMapper(new PassThroughLineMapper())
                    .build();
        }
    }

}

This test passes assuming the class path resource data/input.txt contains two lines foo and bar.