问:
Parsing a whole file in Perl
I have an HTML file containing a 2-column table which I want to parse in order to extract pairs of strings representing the columns. The page layout of the HTML (white space, new lines) is arbitrary, hence I can't parse the file line by line.

I recall that you can parse such a thing by slurping the whole file into a string and operating on the entire string, which I'm finding a bit more challenging. I'm trying things like the following:

```<code>#!/usr/bin/perl

open(FILE, "Glossary") || die "Couldn't open file\n";
@lines = <FILE>;
close(FILE);

$data = join(' ', @lines);

while ($data =~ /<tr>.*(<td>.*<\/td>).*(<td>.*<\/td>).*<\/tr>/g) {
    print $1, ":", $2, "\n";
}
</code>```

which gives a null output. Here's a section of the input file:

```<code><table class="wikitable">
    <tr>
        <td><b>Term</b>
        </td>
        <td><b>Meaning</b>
        </td></tr>
    <tr>
        <td><span id="0-Day">0-Day</span>
        </td>
        <td>
        <p>See <a href="#Zero_Day">Zero Day</a>.
        </p>
        </td>
</code>```

Can someone help me out?

答:
You already have answers explaining why you shouldn't parse HTML with regexes. And you really shouldn't. But you've asked for an explanation of why your code doesn't work. So here goes...

You have two problems in your code. One stops it working and the other stops it working as you expect.

Firstly, you are using . in your regex to match any character. But . doesn't match any character. It matches any character except a newline. And you have newlines in your string. You fix that by adding the /s option to your match operator (so it has /gs instead of /s).

With that fix in place, you get a result from your code. Using your test data, I see:

```<code><td><b>Term</b>
         </td>:<td><b>Meaning</b>
         </td>
</code>```

Which is correct. But looking at your test data, I wondered why I wasn't getting two results - because of the /g. I soon realised it was because your test data is missing the closing 	. When I added that, I got this result:

```<code><td><span id="0-Day">0-Day</span>
         </td>:<td>
         <p>See <a href="#Zero_Day">Zero Day</a>.
         </p>
         </td>
</code>```

Ok. It's now finding the second result. But what has happened to the first one? That's the second error in your code.

You have .* a few times in your regex. That means "zero or more of any character". But it's the "or more" that is a problem here. By default, Perl regex qualifiers (* or +) are greedy. That means they will use up as much of the string as possible. And the first .* in your regex is eating up a lot of your string. All of it up to the second
 in fact.

The solution to that is to make the .* non-greedy. And you do that by adding ? to the end. So you can replace all of the .* with .*?. Having done that, I get this output:

```<code><td><b>Term</b>
         </td>:<td><b>Meaning</b>
         </td>
<td><span id="0-Day">0-Day</span>
         </td>:<td>
         <p>See <a href="#Zero_Day">Zero Day</a>.
         </p>
         </td>
</code>```

Which seems correct to me.

So, to summarise:

By default, . doesn't match newlines. To do that, you need /s.

Beware of greedy qualifiers.

Title: Parsing a whole file in Perl

Body:
I have an HTML file containing a 2-column table which I want to parse in order to extract pairs of strings representing the columns. The page layout of the HTML (white space, new lines) is arbitrary, hence I can't parse the file line by line.

I recall that you can parse such a thing by slurping the whole file into a string and operating on the entire string, which I'm finding a bit more challenging. I'm trying things like the following:

#!/usr/bin/perl

open(FILE, "Glossary") || die "Couldn't open file\n";
@lines = <FILE>;
close(FILE);

$data = join(' ', @lines);

while ($data =~ /
.*(.*<\/td>).*(.*<\/td>).*<\/tr>/g) {
    print $1, ":", $2, "\n";
}

which gives a null output. Here's a section of the input file:

        Term

        Meaning

        0-Day

See Zero Day.

Can someone help me out?

Body:
You already have answers explaining why you shouldn't parse HTML with regexes. And you really shouldn't. But you've asked for an explanation of why your code doesn't work. So here goes...

You have two problems in your code. One stops it working and the other stops it working as you expect.

Firstly, you are using . in your regex to match any character. But . doesn't match any character. It matches any character except a newline. And you have newlines in your string. You fix that by adding the /s option to your match operator (so it has /gs instead of /s).

With that fix in place, you get a result from your code. Using your test data, I see:

<td><b>Term</b>
         </td>:<td><b>Meaning</b>
         </td>

Which is correct. But looking at your test data, I wondered why I wasn't getting two results - because of the /g. I soon realised it was because your test data is missing the closing </td>. When I added that, I got this result:

<td><span id="0-Day">0-Day</span>
         </td>:<td>
         <p>See <a href="#Zero_Day">Zero Day</a>.
         </p>
         </td>

Ok. It's now finding the second result. But what has happened to the first one? That's the second error in your code.

You have .* a few times in your regex. That means "zero or more of any character". But it's the "or more" that is a problem here. By default, Perl regex qualifiers (* or +) are greedy. That means they will use up as much of the string as possible. And the first .* in your regex is eating up a lot of your string. All of it up to the second <tr> in fact.

The solution to that is to make the .* non-greedy. And you do that by adding ? to the end. So you can replace all of the .* with .*?. Having done that, I get this output:

<td><b>Term</b>
         </td>:<td><b>Meaning</b>
         </td>
<td><span id="0-Day">0-Day</span>
         </td>:<td>
         <p>See <a href="#Zero_Day">Zero Day</a>.
         </p>
         </td>

Which seems correct to me.

So, to summarise:

By default, . doesn't match newlines. To do that, you need /s.

Beware of greedy qualifiers.


来源: stackexchange

问:
Does Naive Bayes Classifier need to know the entire vocabulary?
I am trying to classify tweets in two categories (e.g., basketball and non-basketball). Obviously, the dataset is dynamic, i.e., the document collection is not fixed to a set of N documents (i.e., tweets): the dataset is dilating over and over while one crawls Twitter.

One thing that one should try to apply is the Naive Bayes classifier, which is widely used for text classification. An explanation is provided here. However, one doubt still remains.

I could compute the model starting from the training set (and stating that the vocabulary V is composed by the terms contained in the training set). Now, one could collect a new, unclassified tweet that contains terms that are not present in V (i.e., terms that did not appear in the training set). Is the Naive Bayes classifier still applicable?

Generalizing the question: can the Naive Bayes classifier be applied to those cases in which the vocabulary is not entirely known?

Thank you in advance.

答:
can the Naive Bayes classifier be applied to those cases in which the vocabulary is not entirely known?

If words in the test set are not in the train set these would be given class-conditional probabilities of 0 during training. Because the Naive Bayes classifier involves a product over all words in a test document, a single word in the test doc that was not in the train set would lead to a zero probability of the document belonging to the class under consideration.

The trick that is applied (and I think you are asking for) is called (Laplace) smoothing: adding 1 to the counts of all terms in your test set. It is a default setting in many libraries, for example in Python's Scikit-Learn:

http://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.MultinomialNB.html#sklearn.naive_bayes.MultinomialNB

ContentLicense: CC BY-SA 3.0


问:
Sum of rows in SQL with GROUP BY
I am having a table with data like:

```<code>ID  OrderId TAX%    Quantity UnitCost
1     5      28    2       1280
2     5      18    1       1180
</code>```

I want the output like:

```<code>ORDERID    TaxableValue       TaxValue
   5           3000               740
</code>```

How can I achieve this? I tried with:

```<code>SELECT orderid,
       ROUND((SUM(UnitCost*Quantity)*TAX)/(100+TAX),2) AS taxValue,
       ROUND(SUM(unitCost*quantity)-ROUND((SUM(UnitCost*Quantity)*TAX)/(100+TAX),2),2) AS taxableValue
FROM table1
GROUP BY OrderId;
</code>```

But the query above is not working.

Sorry all, That is the Tax percentage. This is the new Updated Query. Please consider this.

答:
This is how it can be done.</p>

```<code>SELECT
orderid,
sum(unitcost*quantity) - sum(tax*quantity) as taxablevalue,
sum(tax*quantity) as taxvalue
FROM table1
GROUP BY OrderId;
</code>```

Title: Sum of rows in SQL with GROUP BY

Body:
I am having a table with data like:

ID  OrderId TAX%    Quantity UnitCost
1     5      28    2       1280
2     5      18    1       1180

I want the output like:

ORDERID    TaxableValue       TaxValue
   5           3000               740

How can I achieve this? I tried with:

SELECT orderid,
       ROUND((SUM(UnitCost*Quantity)*TAX)/(100+TAX),2) AS taxValue,
       ROUND(SUM(unitCost*quantity)-ROUND((SUM(UnitCost*Quantity)*TAX)/(100+TAX),2),2) AS taxableValue
FROM table1
GROUP BY OrderId;

But the query above is not working.

Sorry all, That is the Tax percentage. This is the new Updated Query. Please consider this.

Body:
This is how it can be done.

SELECT
orderid,
sum(unitcost*quantity) - sum(tax*quantity) as taxablevalue,
sum(tax*quantity) as taxvalue
FROM table1
GROUP BY OrderId;


问:
Android:dynamically pass model class to retrofit callback
In retrofit to map json response to pojo usually we do this

```<code>@POST
Call<User> getDataFromServer(@Url String url, @Body HashMap<String,Object> hashMap);

ApiCalls api = retrofit.create(ApiCalls.class);
    Call<User> call = api.getDataFromServer(StringConstants.URL,hashMap);
    call.enqueue(new Callback<User>() {
         //Response and failure callbacks
    }
</code>```

where User is my Pojo class.
But for every other request i need to make different pojo and write same code for retrofit call.I want to make a single method for calling api and pass the respective pojo class to retrofit call. like this

```<code>ApiCalls api = retrofit.create(ApiCalls.class);
Call<*ClassPassed*> call = api.getDataFromServer(StringConstants.URL,hashMap);
call.enqueue(new Callback<*ClassPassed*>() {
     //Response and failure callbacks
}
</code>```

so now i can any pojo class to single method and get the response.This is just to avoid rewriting  the same code again and again.is this possible

Update
To elaborate more:

Suppose I need to make two requests. First one is to get userDetails and the other is patientDetails.So i have to create two model classes User and Patient.
So in retrofit api i'll be having something like this

```<code>@POST
Call<User> getDataFromServer(@Url String url, @Body HashMap<String,Object> hashMap);

@POST
Call<Patient> getDataFromServer(@Url String url, @Body HashMap<String,Object> hashMap);
</code>```

and in my FragmentUser and FragmentPatient class i'll be doing this

```<code>  ApiCalls api = retrofit.create(ApiCalls.class);
Call<User> call = api.getDataFromServer(StringConstants.URL,hashMap);
call.enqueue(new Callback<User>() {
     //Response and failure callbacks
}

ApiCalls api = retrofit.create(ApiCalls.class);
Call<Patient> call = api.getDataFromServer(StringConstants.URL,hashMap);
call.enqueue(new Callback<Patient>() {
     //Response and failure callbacks
}
</code>```

but here the code is repaeting just beacuse of different pojo classes.I need to repeat the same code in every other fragments for different requests.
So i need to make a generic method where it can accept any pojo class and then from fragment i'll be just passing the pojo to be mapped.

答:
I use following approach:
First I have implemented custom Call

```<code>public class ProxyConvertCall<Tin,Tout> implements Call<Tout> {
    Converter<Tin,Tout> converter;
    Call<Tin> innerCall;

    public ProxyConvertCall2(Call<Tin> jcall, Converter<Tin,Tout> converter){
        this.innerCall = jcall;
        this.converter = converter;
        }

    @Override
    public Response<Tout> execute() throws IOException {
        Response<Tin> response = innerCall.execute();
        if (response.isSuccessful()){
            return Response.success(converter.Convert(response.body()),response.raw());
        }
        else return Response.error(response.code(), response.errorBody());
    }

    @Override
    public void enqueue(final Callback<Tout> callback) {
        final Call<Tout> self = this;
        this.innerCall.enqueue(new Callback<Tin>() {
            @Override
            public void onResponse(Call<Tin> call, Response<Tin> response) {
                if (response.isSuccessful()){
                    callback.onResponse(self, Response.success(converter.Convert(response.body()), response.raw()));
                }
                else callback.onResponse(self, Response.error(response.code(), response.errorBody()));
            }
            @Override
            public void onFailure(Call<Tin> call, Throwable t) {
                callback.onFailure(self,t);
            }
        });

    }

    @Override
    public boolean isExecuted() {
        return innerCall.isExecuted();
    }

    @Override
    public void cancel() {
        innerCall.cancel();

    }

    @Override
    public boolean isCanceled() {
        return innerCall.isCanceled();
    }

    @Override
    public Call<Tout> clone() {
        return new ProxyConvertCall2<>(innerCall,converter);
    }

    @Override
    public Request request() {
        return innerCall.request();
    }
}
</code>```

It wrappes Call<Tin> and converts it's result to <Tout> by converter.

```<code>@FunctionalInterface
public interface Converter<Tin, Tout> {
    public Tout Convert(Tin in);
}
</code>```

For your service you must create service interface, that return JsonObject for single object and JsonArray for arrays

```<code>public interface ApiCalls {
    @POST
    Call<JsonObject> getDataFromServer(@Url String url, @Body HashMap<String,Object> hashMap);

    @POST
    Call<JsonArray> getArrayFromServer(@Url String url, @Body HashMap<String,Object> hashMap);
}
</code>```

Then wrap it with generic class, with converters from JsonElement to any Type <T>:

```<code>public class ApiCallsGeneric<T> {
    Converter<JsonObject,T> fromJsonObject;
    Converter<JsonArray,List<T>> fromJsonArray;
    ApiCalls service;

    public ApiCallsGeneric(Class<T> classOfT, ApiCalls service){
        this.service = service;
        Gson gson  = new GsonBuilder().create();
        GenericListType<T> genericListTypeOfT = new GenericListType<T>(classOfT);
        fromJsonObject = (t)->gson.fromJson(t,classOfT);
        fromJsonArray =(t)->gson.fromJson(t,genericListTypeOfT);
    }

    public Call<T> getDataFromServer(String url, HashMap<String,Object> hashMap){
        return new ProxyConvertCall<>(service.getDataFromServer(url, hashMap), fromJsonObject);
     }

    public Call<List<T>> getArrayFromServer(String url, HashMap<String,Object> hashMap){
        return new ProxyConvertCall<>(service.getArrayFromServer(url, hashMap), fromJsonArray);
     }
}
</code>```

GenericListType is ParaterizedType. It is used for passing type parameter to gson for List<T>

```<code>import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

public class GenericListType<T> implements ParameterizedType {

    private Type wrapped;

    public GenericListType(Type wrapped) {
        this.wrapped = wrapped;
    }

    public Type[] getActualTypeArguments() {
        return new Type[] {wrapped};
    }

    public Type getRawType() {
        return  List.class;
    }

    public Type getOwnerType() {
        return null;
    }

}
</code>```

Then you can instantiate ApiCallsGeneric with type you want.

```<code>ApiCallsGeneric<User> userService= new ApiCallsGeneric<User>(User.class, retrofit.create(ApiCalls.class));
Call<User> call = userService.getDataFromServer(StringConstants.URL,hashMap);
call.enqueue(new Callback<User>() {
         //Response and failure callbacks
    }
</code>```

Body:
In retrofit to map json response to pojo usually we do this

@POST
Call<User> getDataFromServer(@Url String url, @Body HashMap<String,Object> hashMap);

ApiCalls api = retrofit.create(ApiCalls.class);
    Call<User> call = api.getDataFromServer(StringConstants.URL,hashMap);
    call.enqueue(new Callback<User>() {
         //Response and failure callbacks
    }

where User is my Pojo class.
But for every other request i need to make different pojo and write same code for retrofit call.I want to make a single method for calling api and pass the respective pojo class to retrofit call. like this

ApiCalls api = retrofit.create(ApiCalls.class);
Call<*ClassPassed*> call = api.getDataFromServer(StringConstants.URL,hashMap);
call.enqueue(new Callback<*ClassPassed*>() {
     //Response and failure callbacks
}

so now i can any pojo class to single method and get the response.This is just to avoid rewriting  the same code again and again.is this possible

Update
To elaborate more:

Suppose I need to make two requests. First one is to get userDetails and the other is patientDetails.So i have to create two model classes User and Patient.
So in retrofit api i'll be having something like this

@POST
Call<User> getDataFromServer(@Url String url, @Body HashMap<String,Object> hashMap);

@POST
Call<Patient> getDataFromServer(@Url String url, @Body HashMap<String,Object> hashMap);

and in my FragmentUser and FragmentPatient class i'll be doing this

  ApiCalls api = retrofit.create(ApiCalls.class);
Call<User> call = api.getDataFromServer(StringConstants.URL,hashMap);
call.enqueue(new Callback<User>() {
     //Response and failure callbacks
}

ApiCalls api = retrofit.create(ApiCalls.class);
Call<Patient> call = api.getDataFromServer(StringConstants.URL,hashMap);
call.enqueue(new Callback<Patient>() {
     //Response and failure callbacks
}

but here the code is repaeting just beacuse of different pojo classes.I need to repeat the same code in every other fragments for different requests.
So i need to make a generic method where it can accept any pojo class and then from fragment i'll be just passing the pojo to be mapped.

Body:
I use following approach:
First I have implemented custom Call

public class ProxyConvertCall<Tin,Tout> implements Call<Tout> {
    Converter<Tin,Tout> converter;
    Call<Tin> innerCall;

    public ProxyConvertCall2(Call<Tin> jcall, Converter<Tin,Tout> converter){
        this.innerCall = jcall;
        this.converter = converter;
        }

    @Override
    public Response<Tout> execute() throws IOException {
        Response<Tin> response = innerCall.execute();
        if (response.isSuccessful()){
            return Response.success(converter.Convert(response.body()),response.raw());
        }
        else return Response.error(response.code(), response.errorBody());
    }

    @Override
    public void enqueue(final Callback<Tout> callback) {
        final Call<Tout> self = this;
        this.innerCall.enqueue(new Callback<Tin>() {
            @Override
            public void onResponse(Call<Tin> call, Response<Tin> response) {
                if (response.isSuccessful()){
                    callback.onResponse(self, Response.success(converter.Convert(response.body()), response.raw()));
                }
                else callback.onResponse(self, Response.error(response.code(), response.errorBody()));
            }
            @Override
            public void onFailure(Call<Tin> call, Throwable t) {
                callback.onFailure(self,t);
            }
        });

    }

    @Override
    public boolean isExecuted() {
        return innerCall.isExecuted();
    }

    @Override
    public void cancel() {
        innerCall.cancel();

    }

    @Override
    public boolean isCanceled() {
        return innerCall.isCanceled();
    }

    @Override
    public Call<Tout> clone() {
        return new ProxyConvertCall2<>(innerCall,converter);
    }

    @Override
    public Request request() {
        return innerCall.request();
    }
}

It wrappes Call<Tin> and converts it's result to <Tout> by converter.

@FunctionalInterface
public interface Converter<Tin, Tout> {
    public Tout Convert(Tin in);
}

For your service you must create service interface, that return JsonObject for single object and JsonArray for arrays

public interface ApiCalls {
    @POST
    Call<JsonObject> getDataFromServer(@Url String url, @Body HashMap<String,Object> hashMap);

    @POST
    Call<JsonArray> getArrayFromServer(@Url String url, @Body HashMap<String,Object> hashMap);
}

Then wrap it with generic class, with converters from JsonElement to any Type <T>:

public class ApiCallsGeneric<T> {
    Converter<JsonObject,T> fromJsonObject;
    Converter<JsonArray,List<T>> fromJsonArray;
    ApiCalls service;

    public ApiCallsGeneric(Class<T> classOfT, ApiCalls service){
        this.service = service;
        Gson gson  = new GsonBuilder().create();
        GenericListType<T> genericListTypeOfT = new GenericListType<T>(classOfT);
        fromJsonObject = (t)->gson.fromJson(t,classOfT);
        fromJsonArray =(t)->gson.fromJson(t,genericListTypeOfT);
    }

    public Call<T> getDataFromServer(String url, HashMap<String,Object> hashMap){
        return new ProxyConvertCall<>(service.getDataFromServer(url, hashMap), fromJsonObject);
     }

    public Call<List<T>> getArrayFromServer(String url, HashMap<String,Object> hashMap){
        return new ProxyConvertCall<>(service.getArrayFromServer(url, hashMap), fromJsonArray);
     }
}

GenericListType is ParaterizedType. It is used for passing type parameter to gson for List<T>

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

public class GenericListType<T> implements ParameterizedType {

    private Type wrapped;

    public GenericListType(Type wrapped) {
        this.wrapped = wrapped;
    }

    public Type[] getActualTypeArguments() {
        return new Type[] {wrapped};
    }

    public Type getRawType() {
        return  List.class;
    }

    public Type getOwnerType() {
        return null;
    }

}

Then you can instantiate ApiCallsGeneric with type you want.

ApiCallsGeneric<User> userService= new ApiCallsGeneric<User>(User.class, retrofit.create(ApiCalls.class));
Call<User> call = userService.getDataFromServer(StringConstants.URL,hashMap);
call.enqueue(new Callback<User>() {
         //Response and failure callbacks
    }


问:
Can someone suggest a good way to understand how MPI works?
Can someone suggest a good way to understand how MPI works?</p>

答:
Parallel programming is one of those subjects that is "intrinsically" complex (as opposed to the "accidental" complexity, as noted by Fred Brooks).  </p>

<p>I used Parallel Programming in MPI by Peter Pacheco.  This book gives a good overview of the basic MPI topics, available API's, and common patterns for parallel program construction.  </p>

ContentLicense: CC BY-SA 2.5

Body:
Parallel programming is one of those subjects that is "intrinsically" complex (as opposed to the "accidental" complexity, as noted by Fred Brooks).

I used Parallel Programming in MPI by Peter Pacheco.  This book gives a good overview of the basic MPI topics, available API's, and common patterns for parallel program construction.


问:
how to get height value before click event?
I tried to get height of div block before each click event in jquery and have to set as a global variable for some action.

Currently, I'm handling slide up/down action, I want to set height for slide up before each click event. I tried various way but its failed. Anyone suggest me how to get the value.

答:
It's as simple as that  </p>

```<code>var somevar = $('#someDiv').height();
</code>```

Body:
It's as simple as that

var somevar = $('#someDiv').height();


问:
Video overlay issue
I'd like to create a video overlay. It works great in Chrome with https://stackoverflow.com/a/30310041/8254123, but has some issues in Safari. When I add controls to the video tag and want to pause the video, Safari returns this error:

Unhandled Promise Rejection: [object DOMError]

If I remove the controls attribute it works, but I need controls and don't want to add custom controls.

jQuery('.video_home_1').click(function() {
  if (jQuery(this).children("video").get(0).paused) {
    jQuery(this).children("video").get(0).play();
    jQuery(this).find(".playpause").fadeOut();
    jQuery(this).find(".home_video_overlay").fadeOut();
  } else {
    jQuery(this).children("video").get(0).pause();
    jQuery(this).find(".playpause").fadeIn();
    jQuery(this).find(".home_video_overlay").fadeIn();
    jQuery(this).children(".home_video_overlay").css('background', 'transparent');
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.video_home_1 {
  display: table;
  width: auto;
  position: relative;
  width: auto;
  height: 425px;
}

.video_home_1 .playpause {
  background: url(https://www.squaresigns.com/wp-content/uploads/2017/11/play.png) 58% 50% no-repeat;
  background-repeat: no-repeat;
  width: 100px;
  height: 100px;
  position: absolute;
  left: 0%;
  right: 0%;
  background-size: 64px 64px;
  top: 0%;
  bottom: 0%;
  z-index: 100;
  margin: auto;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, .3);
}

.video_home_1 .home_video_overlay {
  position: absolute;
  z-index: 2;
  top: 0;
  left: 0;
  width: 100%;
  height: 425px;
  background-repeat: no-repeat;
  background-position: center;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  background-size: cover;
  cursor: pointer;
}

.video_home_1 video {
  height: 425px;
  width: auto;
  padding-right: 4px;
}</code>```

  <video controls>
    <source type="video/mp4" src="https://www.squaresigns.com/wp-content/uploads/2017/11/SquareSigns.mp4">
    <source type="video/webm" src="https://www.squaresigns.com/wp-content/uploads/2017/11/SquareSigns.webm">
  </video>

```

答:
Resolved it with this js code </p>

```<code>jQuery('.video_home_1').attr("played","no");
    jQuery('.video_home_1').click(function () {
        if(jQuery(this).attr('played')=="no"){
            jQuery(this).attr("played","yes");
            jQuery(this).children("video").get(0).play();
            jQuery(this).find(".playpause").fadeOut();
            jQuery(this).find(".home_video_overlay").fadeOut();
            jQuery(this).children("video").css("z-index","99");
        }else{
            jQuery(this).attr("played","no");
            jQuery(this).children("video").get(0).pause();
            jQuery(this).find(".playpause").fadeIn();
            jQuery(this).find(".home_video_overlay").fadeIn();
            jQuery(this).children(".home_video_overlay").css('background', 'transparent');
            jQuery(this).children("video").css("z-index","1");
        }
}   );
</code>```

Title: Video overlay issue

Body:
I'd like to create a video overlay. It works great in Chrome with https://stackoverflow.com/a/30310041/8254123, but has some issues in Safari. When I add controls to the video tag and want to pause the video, Safari returns this error:

Unhandled Promise Rejection: [object DOMError]

If I remove the controls attribute it works, but I need controls and don't want to add custom controls.

jQuery('.video_home_1').click(function() {
  if (jQuery(this).children("video").get(0).paused) {
    jQuery(this).children("video").get(0).play();
    jQuery(this).find(".playpause").fadeOut();
    jQuery(this).find(".home_video_overlay").fadeOut();
  } else {
    jQuery(this).children("video").get(0).pause();
    jQuery(this).find(".playpause").fadeIn();
    jQuery(this).find(".home_video_overlay").fadeIn();
    jQuery(this).children(".home_video_overlay").css('background', 'transparent');
  }
});

.video_home_1 {
  display: table;
  width: auto;
  position: relative;
  width: auto;
  height: 425px;
}

.video_home_1 .playpause {
  background: url(https://www.squaresigns.com/wp-content/uploads/2017/11/play.png) 58% 50% no-repeat;
  background-repeat: no-repeat;
  width: 100px;
  height: 100px;
  position: absolute;
  left: 0%;
  right: 0%;
  background-size: 64px 64px;
  top: 0%;
  bottom: 0%;
  z-index: 100;
  margin: auto;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, .3);
}

.video_home_1 .home_video_overlay {
  position: absolute;
  z-index: 2;
  top: 0;
  left: 0;
  width: 100%;
  height: 425px;
  background-repeat: no-repeat;
  background-position: center;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  background-size: cover;
  cursor: pointer;
}

.video_home_1 video {
  height: 425px;
  width: auto;
  padding-right: 4px;
}

  <video controls>
    <source type="video/mp4" src="https://www.squaresigns.com/wp-content/uploads/2017/11/SquareSigns.mp4">
    <source type="video/webm" src="https://www.squaresigns.com/wp-content/uploads/2017/11/SquareSigns.webm">
  </video>

Body:
Resolved it with this js code

jQuery('.video_home_1').attr("played","no");
    jQuery('.video_home_1').click(function () {
        if(jQuery(this).attr('played')=="no"){
            jQuery(this).attr("played","yes");
            jQuery(this).children("video").get(0).play();
            jQuery(this).find(".playpause").fadeOut();
            jQuery(this).find(".home_video_overlay").fadeOut();
            jQuery(this).children("video").css("z-index","99");
        }else{
            jQuery(this).attr("played","no");
            jQuery(this).children("video").get(0).pause();
            jQuery(this).find(".playpause").fadeIn();
            jQuery(this).find(".home_video_overlay").fadeIn();
            jQuery(this).children(".home_video_overlay").css('background', 'transparent');
            jQuery(this).children("video").css("z-index","1");
        }
}   );


问:
Android Firebase: The user remains not verified, when using a dynamic link
My task requires of me to ask an account verification inside the App, so I use sendEmailVerification with ActionCodeSettings as fallowed:

```<code>ActionCodeSettings settings = ActionCodeSettings.newBuilder()
                .setAndroidPackageName("***", false, null)
                .setHandleCodeInApp(true)
                .setUrl(url)
                .build();
...
user.sendEmailVerification(settings)...
</code>```

Then I get the dynamic link:

```<code>FirebaseDynamicLinks.getInstance().getDynamicLink(getIntent()).addOnSuccessListener
</code>```

All works as it should, but when I check if the user is verified:

```<code>user.reload().addOnCompleteListener(task -> if (user.isEmailVerified())...)
</code>```

it returns false. Am I doing something wrong? Should I somehow set the user as verified manually?

答: After you get the dynamic link, you would parse the deep link using FDL library. You then parse the code (oobCode) and call auth.applyActionCode(actionCode). This would complete verification. You can then call reload() on the user to pick the changes. Check this documentation for how to do it on web which is similar to Android: https://firebase.google.com/docs/auth/custom-email-handler

Body:
My task requires of me to ask an account verification inside the App, so I use sendEmailVerification with ActionCodeSettings as fallowed:

ActionCodeSettings settings = ActionCodeSettings.newBuilder()
                .setAndroidPackageName("***", false, null)
                .setHandleCodeInApp(true)
                .setUrl(url)
                .build();
...
user.sendEmailVerification(settings)...

Then I get the dynamic link:

FirebaseDynamicLinks.getInstance().getDynamicLink(getIntent()).addOnSuccessListener

All works as it should, but when I check if the user is verified:

user.reload().addOnCompleteListener(task -> if (user.isEmailVerified())...)

it returns false. Am I doing something wrong? Should I somehow set the user as verified manually?


问:
Case within a Select returning "missing expression ORA-00905"
this is my first post here, I'd like to ask for help on a theoretically simple query.

The current query I'm creating is to try and generate a random number, which will be identified as even or odd. Depending on that value, it should print either "M" as even, or "W" as odd. Though when I try using a case inside the select, I'm getting the "missing keyword" error. This is my following code:

```<code>select
  case
    when mod(round(dbms_random.value(1,100)),2) = 0 then dbms_output.put_line('M');
    when mod(round(dbms_random.value(1,100)),2) = 1 then dbms_output.put_line('W');
  end
from dual
</code>```

I've tried checking the website for similar problems, and while I've found similar problems and people getting the solution correctly, I don't quite know what I'm missing here. When I run the select alone, I get the even or odd number I want to get, but not when I try to print out a result.

答:
SELECT statement cannot PRINT, it can only RETURN something.

You may use query like

```<code>select
  v,
  case when mod(v, 2) = 0 then 'M' else 'W' end l
from
  (select round(dbms_random.value(1, 100)) v from dual)
</code>```

and process it's result as you wish (print, for example).

Body:
this is my first post here, I'd like to ask for help on a theoretically simple query.

The current query I'm creating is to try and generate a random number, which will be identified as even or odd. Depending on that value, it should print either "M" as even, or "W" as odd. Though when I try using a case inside the select, I'm getting the "missing keyword" error. This is my following code:

select
  case
    when mod(round(dbms_random.value(1,100)),2) = 0 then dbms_output.put_line('M');
    when mod(round(dbms_random.value(1,100)),2) = 1 then dbms_output.put_line('W');
  end
from dual

I've tried checking the website for similar problems, and while I've found similar problems and people getting the solution correctly, I don't quite know what I'm missing here. When I run the select alone, I get the even or odd number I want to get, but not when I try to print out a result.

Body:
SELECT statement cannot PRINT, it can only RETURN something.

You may use query like

select
  v,
  case when mod(v, 2) = 0 then 'M' else 'W' end l
from
  (select round(dbms_random.value(1, 100)) v from dual)

and process it's result as you wish (print, for example).


问:
How to use angular 'title' API?
I want to get or set title of my page dynamically. I found this but i don't know how to using it.</p>

答:
You can do it like this:

```<code>export class AppComponent {
  public constructor(private titleService: Title ) { }

  public setTitle( newTitle: string) {
    this.titleService.setTitle( newTitle );
  }
}
</code>```

Source: https://angular.io/guide/set-document-title

Title: How to use angular 'title' API?

Body:
You can do it like this:

export class AppComponent {
  public constructor(private titleService: Title ) { }

  public setTitle( newTitle: string) {
    this.titleService.setTitle( newTitle );
  }
}

Source: https://angular.io/guide/set-document-title


问:
Scrapy get pre-redirect url
I've a crawler running without troubles but i need to get the start_url and not the redirected one.

The problem is i'm using rules to pass parameters to the URL ( like field-keywords=xxxxx ) and finally get the correct url.

The parse function starts getting the item attributes without any troubles but when i want the start URL ( the true one ) it stores the redirected one ...

I've tryed:

```<code>response.url
response.request.meta.get('redirect_urls')
</code>```

Both returns the final url ( the redirected one ) and not the start_url.

Some one know why, or has any clue ?

Thanks in advance.

答:
Have you tried response.request.url? I personally would override the start_requests method adding the original url in the meta, something like:

```<code>yield Request(url, meta={'original_request': url})
</code>```

And then extract it using response.meta['original_request']

Title: Scrapy get pre-redirect url

Body:
I've a crawler running without troubles but i need to get the start_url and not the redirected one.

The problem is i'm using rules to pass parameters to the URL ( like field-keywords=xxxxx ) and finally get the correct url.

The parse function starts getting the item attributes without any troubles but when i want the start URL ( the true one ) it stores the redirected one ...

I've tryed:

response.url
response.request.meta.get('redirect_urls')

Both returns the final url ( the redirected one ) and not the start_url.

Some one know why, or has any clue ?

Thanks in advance.

Body:
Have you tried response.request.url? I personally would override the start_requests method adding the original url in the meta, something like:

yield Request(url, meta={'original_request': url})

And then extract it using response.meta['original_request']


问:
Modifying an element in a dataframe by checking a dictionary
I am trying to categorise elements in a list using a dictionary:

```<code>mydict = {'beach': ['beach', 'sand', 'coast'], 'package': ['package', 'inclusive']}
</code>```

given dataframe:

```<code>Keyword                         |cat |
--------------------------------|----|
beach holiday                   |    |
package beach holiday           |    |
inclusive beach holiday         |    |
</code>```

I want to check that if an element is in the dictionary it applies the keyword to the category column e.g.:

```<code>Keyword                         |cat |
--------------------------------|----|
beach holiday                   |beach  |
package beach holiday           |package|
inclusive package beach holiday |package|
</code>```

I have attempted with the following code:

```<code>df = get_csv(csv)
mydict = {'beach': ['beach', 'sand', 'coast'], 'package': ['package', 'inclusive']}

for key in mydict.keys():
    item = key
    if item in mydict[key]:
        target_cats = item
        find_keywords = lambda kw: [s for s in kw.split() if s in target_cats]

        df.loc[:, 'cat_list'] = df['Keyword'].apply(lambda x: find_keywords(x))
        for i in range(1, 4):
            df.loc[:, 'cat{0}'.format(i)] = df['cat_list'].apply(lambda x: x[i-1] if len(x) >= i else '')

print(df)
df.to_csv('kuoniTesting.csv')
</code>```

However this just gives an empty category list, the code to check against a list works, how do i modify this to use a dictionary?

```<code>target_cats = ['cat', 'dog', 'cow']
df = pd.DataFrame({'Keyword': ['cat dog cow', 'cat dog', 'dog sheep']})
find_keywords = lambda kw: [s for s in kw.split() if s in target_cats]

df.loc[:, 'cat_list'] = df['Keyword'].apply(lambda x: find_keywords(x))
for i in range(1, 4):
    df.loc[:, 'cat{0}'.format(i)] = df['cat_list'].apply(lambda x: x[i-1] if
    len(x) >= i else '')

 Keyword      cat_list         cat1 cat2 cat3
  0  cat dog cow  [cat, dog, cow]  cat  dog  cow
  1      cat dog       [cat, dog]  cat  dog
  2    dog sheep            [dog]  dog
</code>```

答:
You can swap values in dictionary with keys, but it return multiple values:

```<code>mydict = {'beach': ['beach', 'sand', 'coast'], 'package': ['package', 'inclusive']}
d = {k: oldk for oldk, oldv in mydict.items() for k in oldv}
print (d)
{'sand': 'beach', 'package': 'package', 'beach': 'beach',
 'inclusive': 'package', 'coast': 'beach'}

find_keywords = lambda kw: [d[s] for s in kw.split() if s in d.keys()]
df['cat_list'] = df['Keyword'].apply(lambda x: find_keywords(x))
print (df)
                   Keyword          cat_list
0            beach holiday           [beach]
1    package beach holiday  [package, beach]
2  inclusive beach holiday  [package, beach]
</code>```

And for new columns:

```<code>df = df.join(pd.DataFrame(df['cat_list'].values.tolist(), columns=['cat1','cat2']))
print (df)
                   Keyword          cat_list     cat1   cat2
0            beach holiday           [beach]    beach   None
1    package beach holiday  [package, beach]  package  beach
2  inclusive beach holiday  [package, beach]  package  beach
</code>```

Body:
I am trying to categorise elements in a list using a dictionary:

mydict = {'beach': ['beach', 'sand', 'coast'], 'package': ['package', 'inclusive']}

given dataframe:

Keyword                         |cat |
--------------------------------|----|
beach holiday                   |    |
package beach holiday           |    |
inclusive beach holiday         |    |

I want to check that if an element is in the dictionary it applies the keyword to the category column e.g.:

Keyword                         |cat |
--------------------------------|----|
beach holiday                   |beach  |
package beach holiday           |package|
inclusive package beach holiday |package|

I have attempted with the following code:

df = get_csv(csv)
mydict = {'beach': ['beach', 'sand', 'coast'], 'package': ['package', 'inclusive']}

for key in mydict.keys():
    item = key
    if item in mydict[key]:
        target_cats = item
        find_keywords = lambda kw: [s for s in kw.split() if s in target_cats]

        df.loc[:, 'cat_list'] = df['Keyword'].apply(lambda x: find_keywords(x))
        for i in range(1, 4):
            df.loc[:, 'cat{0}'.format(i)] = df['cat_list'].apply(lambda x: x[i-1] if len(x) >= i else '')

print(df)
df.to_csv('kuoniTesting.csv')

However this just gives an empty category list, the code to check against a list works, how do i modify this to use a dictionary?

target_cats = ['cat', 'dog', 'cow']
df = pd.DataFrame({'Keyword': ['cat dog cow', 'cat dog', 'dog sheep']})
find_keywords = lambda kw: [s for s in kw.split() if s in target_cats]

df.loc[:, 'cat_list'] = df['Keyword'].apply(lambda x: find_keywords(x))
for i in range(1, 4):
    df.loc[:, 'cat{0}'.format(i)] = df['cat_list'].apply(lambda x: x[i-1] if
    len(x) >= i else '')

 Keyword      cat_list         cat1 cat2 cat3
  0  cat dog cow  [cat, dog, cow]  cat  dog  cow
  1      cat dog       [cat, dog]  cat  dog
  2    dog sheep            [dog]  dog

Body:
You can swap values in dictionary with keys, but it return multiple values:

mydict = {'beach': ['beach', 'sand', 'coast'], 'package': ['package', 'inclusive']}
d = {k: oldk for oldk, oldv in mydict.items() for k in oldv}
print (d)
{'sand': 'beach', 'package': 'package', 'beach': 'beach',
 'inclusive': 'package', 'coast': 'beach'}

find_keywords = lambda kw: [d[s] for s in kw.split() if s in d.keys()]
df['cat_list'] = df['Keyword'].apply(lambda x: find_keywords(x))
print (df)
                   Keyword          cat_list
0            beach holiday           [beach]
1    package beach holiday  [package, beach]
2  inclusive beach holiday  [package, beach]

And for new columns:

df = df.join(pd.DataFrame(df['cat_list'].values.tolist(), columns=['cat1','cat2']))
print (df)
                   Keyword          cat_list     cat1   cat2
0            beach holiday           [beach]    beach   None
1    package beach holiday  [package, beach]  package  beach
2  inclusive beach holiday  [package, beach]  package  beach


问:
detect if telegram client installed via browser js
Is there any way to detect from site javascript, if telegram client installed, and what type of client (mobile, desktop, web) ?</p>

答: You can't do this in modern browsers, but you can try to open tg:// URL directly, just like what t.me do.


问:
When i add numbers in a list and print them it only adds the first number
When I print(sum(n)) I get 7 instead of the sum of the elements of the list which would be 32. What am I doing wrong?

```<code>def sum(numbers):
    total = 0
    for number in numbers:
        total += number
        return total

n = [7, 12, 5, 8]
print (sum(n))
</code>```

答:
Let's explain step by step:</p>

```<code>def sum(numbers):
    total = 0
    for number in numbers:
        total += number
        #If you return here, you wont sum the rest, just the first

    return total # Return must go outside the for loop, because it breaks the execution

n = [7, 12, 5, 8]
print (sum(n))
</code>```

Body:
When I print(sum(n)) I get 7 instead of the sum of the elements of the list which would be 32. What am I doing wrong?

def sum(numbers):
    total = 0
    for number in numbers:
        total += number
        return total

n = [7, 12, 5, 8]
print (sum(n))

Body:
Let's explain step by step:

def sum(numbers):
    total = 0
    for number in numbers:
        total += number
        #If you return here, you wont sum the rest, just the first

    return total # Return must go outside the for loop, because it breaks the execution

n = [7, 12, 5, 8]
print (sum(n))


问:
In hadoop, how do I initialize the a DistributedFileSystem object via the initialize method?
There are two arguments, a URI and a Configuration. I assume that the JobConf object that the client is set to should work for Configuration, but what about the URI?

Here is the code I have for the driver:

```<code>JobClient client = new JobClient();
JobConf conf = new JobConf(ClickViewSessions.class);

conf.setJobName("ClickViewSessions");

conf.setOutputKeyClass(LongWritable.class);
conf.setOutputValueClass(MinMaxWritable.class);

FileInputFormat.addInputPath(conf, new Path("input"));
FileOutputFormat.setOutputPath(conf, new Path("output"));

conf.setMapperClass(ClickViewSessionsMapper.class);
conf.setReducerClass(ClickViewSessionsReducer.class);

client.setConf(conf);

DistributedFileSystem dfs = new DistributedFileSystem();
try {
    dfs.initialize(new URI("blah") /* what goes here??? */, conf);
} catch (Exception e) {
    throw new RuntimeException(e.toString());
}
</code>```

How do I get the URI to supply to the call to initialize above?

答:
The URI is the location of the HDFS that you are running. The default value for the filesystem name should be in conf/core-site.xml.  The value of 'fs.default.name' should be the URI that you connect to.

If you haven't yet looked at the tutorial on how to set up a simple single-node system, I would highly recommend it:

http://hadoop.apache.org/common/docs/current/single_node_setup.html

Body:
There are two arguments, a URI and a Configuration. I assume that the JobConf object that the client is set to should work for Configuration, but what about the URI?

Here is the code I have for the driver:

JobClient client = new JobClient();
JobConf conf = new JobConf(ClickViewSessions.class);

conf.setJobName("ClickViewSessions");

conf.setOutputKeyClass(LongWritable.class);
conf.setOutputValueClass(MinMaxWritable.class);

FileInputFormat.addInputPath(conf, new Path("input"));
FileOutputFormat.setOutputPath(conf, new Path("output"));

conf.setMapperClass(ClickViewSessionsMapper.class);
conf.setReducerClass(ClickViewSessionsReducer.class);

client.setConf(conf);

DistributedFileSystem dfs = new DistributedFileSystem();
try {
    dfs.initialize(new URI("blah") /* what goes here??? */, conf);
} catch (Exception e) {
    throw new RuntimeException(e.toString());
}

How do I get the URI to supply to the call to initialize above?


问:
Get different test and training sets from the same sample
I have some data for which I want to compare a few different linear models. I can use caTools::sample.split() to get one training/test set.

I would like to see how the model would change if I had used a different training/test set from the same sample. If I do not use set.seed() I should get a different set every time I call sample.split.

I am using lapply to call the function a certain number of times right now:

```<code>library(data.table)
library(caTools)
dat <- as.data.table(iris)
dat_list <- lapply(1:20, function(z) {
  sample_indices <- sample.split(dat$Sepal.Length, SplitRatio = 3/4)
  inter <- dat
  inter$typ <- "test"
  inter$typ[sample_indices] <- "train"
  inter$set_no <- z
  return(as.data.table(inter))})
</code>```

And for comparing the coefficients:

```<code>coefs <- sapply(1:20, function(z){
  m <- lm(Sepal.Length ~ Sepal.Width, data = dat_list[[z]][typ == "train"])
  return(unname(m$coefficients))
})
</code>```

The last few lines could be edited to return the RMS error when predicting values in the test set (typ=="test").

I'm wondering if there's a better way of doing this?

答:
I'm interested in splitting the data efficiently (my actual data set is quite large)

I'm a big advocate of lists of data frames, but it doesn't make sense to duplicate your data in a list - especially if it's biggish data, you don't need 20 copies of your data to have 20 train-test splits.

Instead, just store the indices of the train and test sets, and give the appropriate subset to the model.

```<code>n = 5
train_ind = replicate(n = n, sample(nrow(iris), size = 0.75 * nrow(iris)), simplify = FALSE)
test_ind = lapply(train_ind, function(x) setdiff(1:nrow(iris), x))

# then modify your loop to subset the right rows
coefs <- sapply(seq_len(n), function(z) {
  m <- lm(Sepal.Length ~ Sepal.Width, data = iris[train_ind[[z]], ])
  return(m$coefficients)
})
</code>```

It's also good to parameterize anything that is used more than once. If you want to change to 20 replicates, set up your code so you change n = 20 at the top and don't have to go through the whole thing looking for every time you used 5 to change it to 20. It might be nice to pull out the split_ratio = 0.75 and put it on it's own line at the top too, even though it's only used once.

Body:
I have some data for which I want to compare a few different linear models. I can use caTools::sample.split() to get one training/test set.

I would like to see how the model would change if I had used a different training/test set from the same sample. If I do not use set.seed() I should get a different set every time I call sample.split.

I am using lapply to call the function a certain number of times right now:

library(data.table)
library(caTools)
dat <- as.data.table(iris)
dat_list <- lapply(1:20, function(z) {
  sample_indices <- sample.split(dat$Sepal.Length, SplitRatio = 3/4)
  inter <- dat
  inter$typ <- "test"
  inter$typ[sample_indices] <- "train"
  inter$set_no <- z
  return(as.data.table(inter))})

And for comparing the coefficients:

coefs <- sapply(1:20, function(z){
  m <- lm(Sepal.Length ~ Sepal.Width, data = dat_list[[z]][typ == "train"])
  return(unname(m$coefficients))
})

The last few lines could be edited to return the RMS error when predicting values in the test set (typ=="test").

I'm wondering if there's a better way of doing this?

Body:
I'm interested in splitting the data efficiently (my actual data set is quite large)

I'm a big advocate of lists of data frames, but it doesn't make sense to duplicate your data in a list - especially if it's biggish data, you don't need 20 copies of your data to have 20 train-test splits.

Instead, just store the indices of the train and test sets, and give the appropriate subset to the model.

n = 5
train_ind = replicate(n = n, sample(nrow(iris), size = 0.75 * nrow(iris)), simplify = FALSE)
test_ind = lapply(train_ind, function(x) setdiff(1:nrow(iris), x))

# then modify your loop to subset the right rows
coefs <- sapply(seq_len(n), function(z) {
  m <- lm(Sepal.Length ~ Sepal.Width, data = iris[train_ind[[z]], ])
  return(m$coefficients)
})

It's also good to parameterize anything that is used more than once. If you want to change to 20 replicates, set up your code so you change n = 20 at the top and don't have to go through the whole thing looking for every time you used 5 to change it to 20. It might be nice to pull out the split_ratio = 0.75 and put it on it's own line at the top too, even though it's only used once.


问:
Java Recognize specific objects in image
I need to classify bolt, nut, and washer from the image,

but I don't know how to detect those objects from the image.

(This is the part of the image)

I copied every color (used java.awt.Color) value from the image to 2D array,

but I have no idea what I have to do with this.

If I want to classify them, program have to recognize which part is not a background at least.

Does java has library for this?

答:
To see that there is an object in the image, you will want to determine where the edge of that object is. If you look at the image, you'll notice that there is a big difference in the color of the background compared to the color of the edge of each object.

You can have your program read in the color data, as you have done, and whenever it notices that the color has changed by a significant enough amount, the program will highlight this point. This would be done by applying a sobel filter to the color data.

Doing this should highlight the edges of the object. From here, you can try to analyze the size of the area enclosed or the features of these edges to determine the object that is highlighted.

Here is a link to a question asked about applying a sobel filter that has some good answers.

While libraries such as OpenCV do have sobel filtering and image detection, it does not take too much code to implement the sobel filter yourself. I believe it would be a more simple solution as well. Installing and learning OpenCV will likely take more time than just applying your own sobel filter.


问:
How to process a list of files in MATLAB
in MATLAB, my function is like this:

```<code> names = {'d:\C001\C001_Deo.csv','d:\C001\C001_Oxy.csv','d:\C001\C001_Tal.csv'}
 data_conversion(names)         %this function creat a folder in C001 to save results
</code>```

I have 100 folders named as C001, C002, ..., C100. Each folder has three .csv files, named like this: C001_Deo.csv, C001_Oxy.csv, C001_Tal.csv,  C002_Deo.csv, C002_Oxy.csv, C002_Tal.csv, ...

Does anyone can help me to write a loop so I can run data_conversion(names) at a time to get all the results. Then I don't need to run it 100 times.
I tried many times but failed. Thanks!

答:
Your filenames are stored in a cell array. names(1) returns the first cell of names. names{1} returns the content of the first cell, so your loop will look like this

```<code>names = {'d:\C001\C001_Deo.csv','d:\C001\C001_Oxy.csv','d:\C001\C001_Tal.csv'}

for loopi = 1:length(names)
     data_conversion(names{loopi})
end
</code>```

I assume all your files are in a single location, so you might want to get the list of files automatically:

```<code>folders = dir('d:\C*');

for loopi = 1:length(folders)
  % if order matters
  folder = strcat(folders(loopi).folder,'\',folders(loopi).name);
  f1 = dir([folder,'\*_Deo.csv']);
  f2 = dir([folder,'\*_Oxy.csv']);
  f3 = dir([folder,'\*_Tal.csv']);
  data_conversion({f1(1).name, f2(1).name, f3(1).name});
end
</code>```

dir returns a struct array, which is indexed with parenthesis instead of brackets.

Body:
in MATLAB, my function is like this:

 names = {'d:\C001\C001_Deo.csv','d:\C001\C001_Oxy.csv','d:\C001\C001_Tal.csv'}
 data_conversion(names)         %this function creat a folder in C001 to save results

I have 100 folders named as C001, C002, ..., C100. Each folder has three .csv files, named like this: C001_Deo.csv, C001_Oxy.csv, C001_Tal.csv,  C002_Deo.csv, C002_Oxy.csv, C002_Tal.csv, ...

Does anyone can help me to write a loop so I can run data_conversion(names) at a time to get all the results. Then I don't need to run it 100 times.
I tried many times but failed. Thanks!

Body:
Your filenames are stored in a cell array. names(1) returns the first cell of names. names{1} returns the content of the first cell, so your loop will look like this

names = {'d:\C001\C001_Deo.csv','d:\C001\C001_Oxy.csv','d:\C001\C001_Tal.csv'}

for loopi = 1:length(names)
     data_conversion(names{loopi})
end

I assume all your files are in a single location, so you might want to get the list of files automatically:

folders = dir('d:\C*');

for loopi = 1:length(folders)
  % if order matters
  folder = strcat(folders(loopi).folder,'\',folders(loopi).name);
  f1 = dir([folder,'\*_Deo.csv']);
  f2 = dir([folder,'\*_Oxy.csv']);
  f3 = dir([folder,'\*_Tal.csv']);
  data_conversion({f1(1).name, f2(1).name, f3(1).name});
end

dir returns a struct array, which is indexed with parenthesis instead of brackets.


问:
Why should I learn Lisp?
I really feel that I should learn Lisp and there are plenty of good resources out there to help me do it.

I'm not put off by the complicated syntax, but where in "traditional commercial programming" would I find places it would make sense to use it instead of a procedural language.

Is there a commercial killer-app out there that's been written in Lisp ?

答: I can't answer from first-hand experience but you should read what Paul Graham wrote on Lisp. As for the "killer-app" part, read Beating the averages.</p>

Title: Why should I learn Lisp?

LastEditorDisplayName: Mark Biek


问:
How do I monitor the computer's CPU, memory, and disk usage in Java?
I would like to monitor the following system information in Java:

Current CPU usage** (percent)

Available memory* (free/total)

Available disk space (free/total)

*Note that I mean overall memory available to the whole system, not just the JVM.

I'm looking for a cross-platform solution (Linux, Mac, and Windows) that doesn't rely on my own code calling external programs or using JNI. Although these are viable options, I would prefer not to maintain OS-specific code myself if someone already has a better solution.

If there's a free library out there that does this in a reliable, cross-platform manner, that would be great (even if it makes external calls or uses native code itself).

Any suggestions are much appreciated.

To clarify, I would like to get the current CPU usage for the whole system, not just the Java process(es).

The SIGAR API provides all the functionality I'm looking for in one package, so it's the best answer to my question so far. However, due it being licensed under the GPL, I cannot use it for my original purpose (a closed source, commercial product). It's possible that Hyperic may license SIGAR for commercial use, but I haven't looked into it. For my GPL projects, I will definitely consider SIGAR in the future.

For my current needs, I'm leaning towards the following:

For CPU usage, OperatingSystemMXBean.getSystemLoadAverage() / OperatingSystemMXBean.getAvailableProcessors() (load average per cpu)

For memory, OperatingSystemMXBean.getTotalPhysicalMemorySize() and OperatingSystemMXBean.getFreePhysicalMemorySize()

For disk space, File.getTotalSpace() and File.getUsableSpace()

Limitations:

The getSystemLoadAverage() and disk space querying methods are only available under Java 6. Also, some JMX functionality may not be available to all platforms (i.e. it's been reported that getSystemLoadAverage() returns -1 on Windows).

Although originally licensed under GPL, it has been changed to Apache 2.0, which can generally be used for closed source, commercial products.

答:
Along the lines of what I mentioned in this post. I recommend you use the SIGAR API.  I use the SIGAR API in one of my own applications and it is great.  You'll find it is stable, well supported, and full of useful examples.  It is open-source with a GPL 2 Apache 2.0 license.  Check it out.  I have a feeling it will meet your needs.

Using Java and the Sigar API you can get Memory, CPU, Disk, Load-Average, Network Interface info and metrics, Process Table information, Route info, etc.

OwnerDisplayName: David Crow

OwnerDisplayName: MDC


问:
SAFEARRAY of COM objects
I'm using COM library and I have interface defined in .tlh file as following:

```<code>_COM_SMARTPTR_TYPEDEF(IMyInterface, __uuidof(IMyInterface));
</code>```

Then I create object:

```<code>//1st object
IMyInterfacePtr pMyInterface1;
pMyInterface1.CreateInstance(CLSID_MyInterface);
pMyInterface1->call_some_method(BSTR("pass example text1"));

//2nd object
IMyInterfacePtr pMyInterface2;
pMyInterface2.CreateInstance(CLSID_MyInterface);
pMyInterface2->call_some_method(BSTR("pass example text2"));
</code>```

Then I need to create SAFEARRAY of these objects:

```<code>SAFEARRAYBOUND rgsabound[1];
rgsabound[0].cElements = 2;
rgsabound[0].lLbound = 0;

SAFEARRAY *pData = SafeArrayCreate(VT_VARIANT, 1, rgsabound);

LONG i = 0;
SafeArrayPutElement(pData, &i, pMyInterface1);
i = 1;
SafeArrayPutElement(pData, &i, pMyInterface2);
</code>```

But unfortunately after this array elements remains empty. Which is the proper way to fill this array of IMyInterfacePtr objects?

Thank you so much for help.

------EDIT------

Thanks for answers. I tried these solutions from comments, but unfortunately, it still doesn't work. I need to send back this array to COM by COM method. So I'm creating a new object:

```<code>IResponsePtr pResponse;//This is also smart com ptr
pResponse.CreateInstance(CLSID_Response);
pResponse->put_Response(pData);//safearray here
</code>```

where put_Response has following signature: (SAFEARRAY *value).
Unfortunately, during calling this method I'm getting the following exception:

```<code>First-chance exception at 0x76BEC54F in MyApp.exe: Microsoft C++ exception: EEException at memory location 0x0042F144.
First-chance exception at 0x76BEC54F (KernelBase.dll) in MyApp.exe: 0xE0434352 (parameters: 0x80131533, 0x00000000, 0x00000000, 0x00000000, 0x72D30000).
</code>```

Any ideas what might be wrong with this SAFEARRAY ptr?

答:
Don't use the pointers. Store the pointers in the variant first and than copy the data.

```<code>VARIANT v;
v.vt = VT_UNKNOWN;
v.punkVal = pMyInterface1;
SafeArrayPutElement(pData, &i, &v);
</code>```

SafeArrayPutElement uses AddRef internally when it copies the variant.

Title: SAFEARRAY of COM objects

Body:
I'm using COM library and I have interface defined in .tlh file as following:

_COM_SMARTPTR_TYPEDEF(IMyInterface, __uuidof(IMyInterface));

Then I create object:

//1st object
IMyInterfacePtr pMyInterface1;
pMyInterface1.CreateInstance(CLSID_MyInterface);
pMyInterface1->call_some_method(BSTR("pass example text1"));

//2nd object
IMyInterfacePtr pMyInterface2;
pMyInterface2.CreateInstance(CLSID_MyInterface);
pMyInterface2->call_some_method(BSTR("pass example text2"));

Then I need to create SAFEARRAY of these objects:

SAFEARRAYBOUND rgsabound[1];
rgsabound[0].cElements = 2;
rgsabound[0].lLbound = 0;

SAFEARRAY *pData = SafeArrayCreate(VT_VARIANT, 1, rgsabound);

LONG i = 0;
SafeArrayPutElement(pData, &i, pMyInterface1);
i = 1;
SafeArrayPutElement(pData, &i, pMyInterface2);

But unfortunately after this array elements remains empty. Which is the proper way to fill this array of IMyInterfacePtr objects?

Thank you so much for help.

------EDIT------

Thanks for answers. I tried these solutions from comments, but unfortunately, it still doesn't work. I need to send back this array to COM by COM method. So I'm creating a new object:

IResponsePtr pResponse;//This is also smart com ptr
pResponse.CreateInstance(CLSID_Response);
pResponse->put_Response(pData);//safearray here

where put_Response has following signature: (SAFEARRAY *value).
Unfortunately, during calling this method I'm getting the following exception:

First-chance exception at 0x76BEC54F in MyApp.exe: Microsoft C++ exception: EEException at memory location 0x0042F144.
First-chance exception at 0x76BEC54F (KernelBase.dll) in MyApp.exe: 0xE0434352 (parameters: 0x80131533, 0x00000000, 0x00000000, 0x00000000, 0x72D30000).

Any ideas what might be wrong with this SAFEARRAY ptr?

Body:
Don't use the pointers. Store the pointers in the variant first and than copy the data.

VARIANT v;
v.vt = VT_UNKNOWN;
v.punkVal = pMyInterface1;
SafeArrayPutElement(pData, &i, &v);

SafeArrayPutElement uses AddRef internally when it copies the variant.


问:
Atom highlighting issue NBSP
Ok so for some reason my atom is highlighting random lengths of code on all my HTML pages after it reads past &NBSP, now this seemingly happened randomly out of the blue, one minute it was fine, the next I tabbed back to my Atom and this was the apparent issue, I've tried reinstalling twice removed all the hidden folders etc from users and alas still no luck.

I have attached a picture highlighting how it's colouring my HTML, & as previously mentioned this happens across the board on all my HTML pages and had no rhyme or reason to how much of my code it turns brown.

答:
& character entities are terminated by a semicolon. You have

```<code>&nbsp
</code>```

But the proper character is

```<code>
</code>```

So all that brown text is Atom waiting for the ; to close the character entity.

This is not just a display issue in Atom. This will probably cause a rendering issue when this page is loaded, even if it just causes a useless &nbsp to appear in the page text.

Title: Atom highlighting issue NBSP

Body:
& character entities are terminated by a semicolon. You have

&nbsp

But the proper character is

&nbsp;

So all that brown text is Atom waiting for the ; to close the character entity.

This is not just a display issue in Atom. This will probably cause a rendering issue when this page is loaded, even if it just causes a useless &nbsp to appear in the page text.


问:
Plotting lists in a Pandas dataframe
Consider the following dataframe example:

```<code>df = pd.DataFrame({'date':['12-01', '12-02', '12-03'],'list1': np.random.randint(0, 10, (3,5)).tolist(),
               'list2': np.random.randint(0, 10, (3,5)).tolist()},
               index=list('ABC'))
</code>```

I would like to plot the lists in the dataframe in such a way that I end up with 3 lines in my graph: A, B and C with for each one, 'list1' as x values and 'list2' as y values.

I started off by trying to plot the columns directly but the following returns an error:

```<code>In: df.iloc[0].plot(x='list1', y='list2')

Out: TypeError: Empty 'DataFrame': no numeric data to plot
</code>```

I could iterate over the rows of the dataframe and append the lists to a new list to plot them, but I feel that this defeats the purpose of storing my data in a dataframe (I have additional columns with ancillary data) and I am sure that there is a better way to do this.

I have about 20 entries in each dataframe (grouped from a larger dataframe) and the main purpose is to visually check if the values (output from an instrument) are in a certain range.

答:
You are using pandas plot method, which requires a dataframe input. If you instead use matplotlib directly, you can plot like so:

plt.plot(df.iloc[0]['list1'], df.iloc[0]['list2'])

Title: Plotting lists in a Pandas dataframe

Body:
Consider the following dataframe example:

df = pd.DataFrame({'date':['12-01', '12-02', '12-03'],'list1': np.random.randint(0, 10, (3,5)).tolist(),
               'list2': np.random.randint(0, 10, (3,5)).tolist()},
               index=list('ABC'))

I would like to plot the lists in the dataframe in such a way that I end up with 3 lines in my graph: A, B and C with for each one, 'list1' as x values and 'list2' as y values.

I started off by trying to plot the columns directly but the following returns an error:

In: df.iloc[0].plot(x='list1', y='list2')

Out: TypeError: Empty 'DataFrame': no numeric data to plot

I could iterate over the rows of the dataframe and append the lists to a new list to plot them, but I feel that this defeats the purpose of storing my data in a dataframe (I have additional columns with ancillary data) and I am sure that there is a better way to do this.

I have about 20 entries in each dataframe (grouped from a larger dataframe) and the main purpose is to visually check if the values (output from an instrument) are in a certain range.


问:
operation on aggregated values SQL
I want to sum my revenue by week, and my expenses by week.

```<code>select *
from (select sum(revenue) earned
            , week(transaction_date) earned_week

    from mytable

    where year(transaction_date) = '1988'

    group by week(transaction_date)

    ) moneyin

    inner join
        (select sum(expenses) spent
                  , week(expense_date) spent_week

          from mytable

          where year(expense_date) = '1988'

          group by week(expense_date)

          ) moneyout

    on moneyin.earned_week = moneyout.spent_week;
</code>```

Now, I would like to add a column containing the difference between money in and money out (earned - spent AS balance), with the same weekly aggregation. but I don't seize at which level I can insert the statement.
Any advice?
Thank you

答:
You can use moneyin and moneyout data groups as any other table, so the query below should work:</p>

```<code>select * , moneyin.earned - moneyout.spent as Difference
    from (select sum(revenue) earned
                , week(transaction_date) earned_week

        from mytable

        where year(transaction_date) = '1988'

        group by week(transaction_date)

        ) moneyin

        inner join
            (select sum(expenses) spent
                      , week(expense_date) spent_week

              from mytable

              where year(expense_date) = '1988'

              group by week(expense_date)

              ) moneyout

        on moneyin.earned_week = moneyout.spent_week;
</code>```

Title: operation on aggregated values SQL

Body:
I want to sum my revenue by week, and my expenses by week.

select *
from (select sum(revenue) earned
            , week(transaction_date) earned_week

    from mytable

    where year(transaction_date) = '1988'

    group by week(transaction_date)

    ) moneyin

    inner join
        (select sum(expenses) spent
                  , week(expense_date) spent_week

          from mytable

          where year(expense_date) = '1988'

          group by week(expense_date)

          ) moneyout

    on moneyin.earned_week = moneyout.spent_week;

Now, I would like to add a column containing the difference between money in and money out (earned - spent AS balance), with the same weekly aggregation. but I don't seize at which level I can insert the statement.
Any advice?
Thank you

Body:
You can use moneyin and moneyout data groups as any other table, so the query below should work:

select * , moneyin.earned - moneyout.spent as Difference
    from (select sum(revenue) earned
                , week(transaction_date) earned_week

        from mytable

        where year(transaction_date) = '1988'

        group by week(transaction_date)

        ) moneyin

        inner join
            (select sum(expenses) spent
                      , week(expense_date) spent_week

              from mytable

              where year(expense_date) = '1988'

              group by week(expense_date)

              ) moneyout

        on moneyin.earned_week = moneyout.spent_week;


答: Your sum is instantly returned, you don't wait for the list to loop through.</p>

Title: When i add numbers in a list and print them it only adds the first number


问:
Significance of finally block
What is the significance of the Finally block in a Try...[Catch]...Finally block?

Isn't this code

```<code>Resource r;
try{
  r = new Resource();
  r.methodThatThrowsException();
} catch (Exception e) {
  e.printStackTrace()
} finally {
  r.close()
}
</code>```

equivalent to

```<code>Resource r;
try{
  r = new Resource();
  r.methodThatThrowsException();
} catch (Exception e) {
  e.printStackTrace()
}
r.close()
</code>```

? I would understand if they have the same scope, but the fact that I have to define Resource r outside the try block anyway to use it in the finally block means that I see no advantage to using a finally block.

Am I missing something? Is there a certain case that I haven't thought of that requires a Finally block?

答:
In this case, they are equivalent since (a) the code catches any exception, including runtime exceptions that are thrown and (b) the catch block doesn't rethrow the exception, so the execution continues.

The finally block is generally used to ensure resource release in cases where either (a) or (b) don't hold. In newer Java implementations, wherever possible, you should use try-with-resources instead.

Title: Significance of finally block

Body:
What is the significance of the Finally block in a Try...[Catch]...Finally block?

Isn't this code

Resource r;
try{
  r = new Resource();
  r.methodThatThrowsException();
} catch (Exception e) {
  e.printStackTrace()
} finally {
  r.close()
}

equivalent to

Resource r;
try{
  r = new Resource();
  r.methodThatThrowsException();
} catch (Exception e) {
  e.printStackTrace()
}
r.close()

? I would understand if they have the same scope, but the fact that I have to define Resource r outside the try block anyway to use it in the finally block means that I see no advantage to using a finally block.

Am I missing something? Is there a certain case that I haven't thought of that requires a Finally block?


问:
vertical headings table - header and row same color
I have a vertical heading html table where i am trying to have the heading and row be the same color, but alternating. The picture illustrates what i want.

Here is my table

```<code>  <table class="dialogTable" cellspacing="0" style="height: 450px">
    <caption><h4>Validation Results</h4></caption>
    <tr>
        <th width="250px">Source Records</th>
        <td width="400px">{{dialogData.totalNumRecords}}</td>
    </tr>
    <tr>
        <th width="250px">New Records</th>
        <td>{{dialogData.numNewRecords}}</td>
    </tr>
    <tr>
        <th width="250px">Updated Records</th>
        <td>{{dialogData.numUpdatedRecords}}</td>
    </tr>
    <tr>
        <th width="250px">Removed Records</th>
        <td>{{dialogData.numDeletedRecords}}</td>
    </tr>
    <tr>
    <th valign="top" width="250px">Error Message</th>
    <td class="dialogstyle" valign="top" >
        <div class="errortext" ng-repeat="error in dialogData.errors" valign="top">{{error}}</div></td>
    </tr>
</table>
</code>```

and the css i have

```<code>.dialogTable {

overflow-y:hidden;
margin-left: 6px;
}

.dialogTable > th:nth-child(even) {
background-color: #eee !important;
}

.dialogTable > th:nth-child(odd) {
background-color: #fff !important;
}
</code>```

right now the headings are all the same color.
Thank you

答:
You want to be like this

tbody tr:nth-child(odd){
  background-color: #EBEBE8;
  color: #666666;
}
tbody tr:nth-child(even){
  background-color: #ffffff;
  color: #666666;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="dialogTable" cellspacing="0" style="height: 450px">
    <caption><h4>Validation Results</h4></caption>
    <tr>
        <th width="250px">Source Records</th>
        <td width="400px">{{dialogData.totalNumRecords}}</td>
    </tr>
    <tr>
        <th width="250px">New Records</th>
        <td>{{dialogData.numNewRecords}}</td>
    </tr>
    <tr>
        <th width="250px">Updated Records</th>
        <td>{{dialogData.numUpdatedRecords}}</td>
    </tr>
    <tr>
        <th width="250px">Removed Records</th>
        <td>{{dialogData.numDeletedRecords}}</td>
    </tr>
    <tr>
    <th valign="top" width="250px">Error Message</th>
    <td class="dialogstyle" valign="top" >
        <div class="errortext" ng-repeat="error in dialogData.errors" valign="top">{{error}}</div></td>
    </tr>
</table></code>```

Body:
I have a vertical heading html table where i am trying to have the heading and row be the same color, but alternating. The picture illustrates what i want.

Here is my table

Validation Results

        Source Records
        {{dialogData.totalNumRecords}}

        New Records
        {{dialogData.numNewRecords}}

        Updated Records
        {{dialogData.numUpdatedRecords}}

        Removed Records
        {{dialogData.numDeletedRecords}}

    Error Message

{{error}}

and the css i have

.dialogTable {

overflow-y:hidden;
margin-left: 6px;
}

.dialogTable > th:nth-child(even) {
background-color: #eee !important;
}

.dialogTable > th:nth-child(odd) {
background-color: #fff !important;
}

right now the headings are all the same color.
Thank you

Body:
You want to be like this

tbody tr:nth-child(odd){
  background-color: #EBEBE8;
  color: #666666;
}
tbody tr:nth-child(even){
  background-color: #ffffff;
  color: #666666;
}

<table class="dialogTable" cellspacing="0" style="height: 450px">
    <caption><h4>Validation Results</h4></caption>
    <tr>
        <th width="250px">Source Records</th>
        <td width="400px">{{dialogData.totalNumRecords}}</td>
    </tr>
    <tr>
        <th width="250px">New Records</th>
        <td>{{dialogData.numNewRecords}}</td>
    </tr>
    <tr>
        <th width="250px">Updated Records</th>
        <td>{{dialogData.numUpdatedRecords}}</td>
    </tr>
    <tr>
        <th width="250px">Removed Records</th>
        <td>{{dialogData.numDeletedRecords}}</td>
    </tr>
    <tr>
    <th valign="top" width="250px">Error Message</th>
    <td class="dialogstyle" valign="top" >
        <div class="errortext" ng-repeat="error in dialogData.errors" valign="top">{{error}}</div></td>
    </tr>
</table>


问:
The program does not crash neither executes completely
it has been a few hours since I am dealing with this issue. I was wondering if someone could point out what am I doing wrong, and if possible - how to fix it. Essentially, I am simply trying to generate n number of object pairs and store them into a vector<pair<Foo, Foo>>. The algorithm involves random number generator. I use STL <random> and its components like m19937, uniform_real_distribution and uniform_int_distribution. Below is the simplified version of what I am trying to do representing the case I got at hand. The second loop always cuts short. However, I fail to see the reason why. Essentially, I never get to see the program execute completely. The last two messages never show.

program

```<code>#include <iostream>
#include <vector>
#include <random>
#include <utility>

// utility
using std::pair;

// random
using std::mt19937;
using std::uniform_int_distribution;
using std::uniform_real_distribution;

// iostream
using std::cout;
using std::endl;

// vector
using std::vector;

class Event{
private:
  double x, y;
public:
  Event(const double X, const double Y);
};

Event::Event(const double X, const double Y): x(X), y(Y){}

int main(){
  cout << "Initializing storage..." << endl;
  vector<Event> population;
  vector<pair<Event,Event>> selection;

  cout << "Initializing necessary member variables..." << endl;
  const unsigned int SEED = 14112017;
  const unsigned int MAX_ITERATIONS = 10000;

  const double MIN = 1;
  const double MAX = 10000;

  mt19937 engine(SEED);

  cout << "Generating the initial population..." << endl;
  uniform_real_distribution<> real_distribution(MIN, MAX);
  for(unsigned int i = 0; i < MAX_ITERATIONS; ++i){
    double x = real_distribution(engine);
    double y = real_distribution(engine);

    Event event(x, y);

    population.push_back(event);
  }
  cout << "Success! The initial population has been generated successfully" << endl;

  population.shrink_to_fit();

  cout << "Starting the selection process..." << endl;
  unsigned int random = 0;
  uniform_int_distribution<> int_distribution(MIN, MAX);
  for(unsigned int i = 0; i < MAX_ITERATIONS; ++i){
    random = int_distribution(engine);
    Event event_x = population.at(random);

    random = int_distribution(engine);
    Event event_y = population.at(random);

    pair<Event, Event> bound(event_x, event_y);

    selection.push_back(bound);
  }
  cout << "Success! The selection process has been completed successfully" << endl;

  selection.shrink_to_fit();

  cout << "population size: " << population.size() << endl;
  cout << "selection size: " << selection.size() << endl;

  return 0;
}
</code>```

I compile the above using cygwins C++ compiler, and I execute the code in command-prompt. The OS is Windows 10 x64. The box has 32 GB memory.

答:
uniform_int_distributions constructor is as follows:

```<code>explicit uniform_int_distribution( IntType a = 0,
    IntType b = std::numeric_limits<IntType>::max() );
</code>```

By default, it returns an integer which covers all positive values of that type. The range includes the value of the second parameter. If it wouldn't, it would be cumbersome to specify we want all positive integers.

cppreference.com does not document it, but the C++ standard does: Thanks @Cubbi

This is documented on cppreference.com, or in the C++ standard:

26.5.8.2.1  Class template uniform_int_distribution  [rand.dist.uni.int]

  1  A uniform_int_distribution random number
  distribution produces random integers i, a ≤ i ≤ b, distributed
  according to the constant discrete probability function

  [...]

  // constructors and reset functions
  explicit uniform_int_distribution(IntType a = 0, IntType b = numeric_limits<IntType>::max());

Here:

```<code>  uniform_int_distribution<> int_distribution(MIN, MAX);
  for(unsigned int i = 0; i < MAX_ITERATIONS; ++i){
    random = int_distribution(engine);
    Event event_x = population.at(random);

    random = int_distribution(engine);
    Event event_y = population.at(random);
</code>```

random can take the value MAX, which is out of the bounds of the population vector.

Body:
it has been a few hours since I am dealing with this issue. I was wondering if someone could point out what am I doing wrong, and if possible - how to fix it. Essentially, I am simply trying to generate n number of object pairs and store them into a vector<pair<Foo, Foo>>. The algorithm involves random number generator. I use STL <random> and its components like m19937, uniform_real_distribution and uniform_int_distribution. Below is the simplified version of what I am trying to do representing the case I got at hand. The second loop always cuts short. However, I fail to see the reason why. Essentially, I never get to see the program execute completely. The last two messages never show.

program

#include <iostream>
#include <vector>
#include <random>
#include <utility>

// utility
using std::pair;

// random
using std::mt19937;
using std::uniform_int_distribution;
using std::uniform_real_distribution;

// iostream
using std::cout;
using std::endl;

// vector
using std::vector;

class Event{
private:
  double x, y;
public:
  Event(const double X, const double Y);
};

Event::Event(const double X, const double Y): x(X), y(Y){}

int main(){
  cout << "Initializing storage..." << endl;
  vector<Event> population;
  vector<pair<Event,Event>> selection;

  cout << "Initializing necessary member variables..." << endl;
  const unsigned int SEED = 14112017;
  const unsigned int MAX_ITERATIONS = 10000;

  const double MIN = 1;
  const double MAX = 10000;

  mt19937 engine(SEED);

  cout << "Generating the initial population..." << endl;
  uniform_real_distribution<> real_distribution(MIN, MAX);
  for(unsigned int i = 0; i < MAX_ITERATIONS; ++i){
    double x = real_distribution(engine);
    double y = real_distribution(engine);

    Event event(x, y);

    population.push_back(event);
  }
  cout << "Success! The initial population has been generated successfully" << endl;

  population.shrink_to_fit();

  cout << "Starting the selection process..." << endl;
  unsigned int random = 0;
  uniform_int_distribution<> int_distribution(MIN, MAX);
  for(unsigned int i = 0; i < MAX_ITERATIONS; ++i){
    random = int_distribution(engine);
    Event event_x = population.at(random);

    random = int_distribution(engine);
    Event event_y = population.at(random);

    pair<Event, Event> bound(event_x, event_y);

    selection.push_back(bound);
  }
  cout << "Success! The selection process has been completed successfully" << endl;

  selection.shrink_to_fit();

  cout << "population size: " << population.size() << endl;
  cout << "selection size: " << selection.size() << endl;

  return 0;
}

I compile the above using cygwins C++ compiler, and I execute the code in command-prompt. The OS is Windows 10 x64. The box has 32 GB memory.

Body:
uniform_int_distributions constructor is as follows:

explicit uniform_int_distribution( IntType a = 0,
    IntType b = std::numeric_limits<IntType>::max() );

By default, it returns an integer which covers all positive values of that type. The range includes the value of the second parameter. If it wouldn't, it would be cumbersome to specify we want all positive integers.

cppreference.com does not document it, but the C++ standard does: Thanks @Cubbi

This is documented on cppreference.com, or in the C++ standard:

26.5.8.2.1  Class template uniform_int_distribution  [rand.dist.uni.int]

  1  A uniform_int_distribution random number
  distribution produces random integers i, a ≤ i ≤ b, distributed
  according to the constant discrete probability function

  [...]

  // constructors and reset functions
  explicit uniform_int_distribution(IntType a = 0, IntType b = numeric_limits<IntType>::max());

Here:

  uniform_int_distribution<> int_distribution(MIN, MAX);
  for(unsigned int i = 0; i < MAX_ITERATIONS; ++i){
    random = int_distribution(engine);
    Event event_x = population.at(random);

    random = int_distribution(engine);
    Event event_y = population.at(random);

random can take the value MAX, which is out of the bounds of the population vector.


问:
UML relationship between the same class
I have an 'Account' class and (every) Account (instance) can have 0 or more guestAccounts (from the same 'Account' class).

I'm stuck of how to model this:
- should I model this as a unary association (recursive)?

Thanks for helping.

答:
Yes indeed you can.

I am not sure that's solved your question, but you can do something like:

I define private for attributes visibility, public or default is often an error.

Title: UML relationship between the same class


问:
Manual ACK for AggregatingMessageHandler
I'm trying to build integration scenario like this Rabbit -> AmqpInboundChannelAdapter(AcknowledgeMode.MANUAL) -> DirectChannel -> AggregatingMessageHandler -> DirectChannel -> AmqpOutboundEndpoint.

I want to aggregate messages in-memory and release it if I aggregate 10 messages, or if timeout of 10 seconds is reached. I suppose this config is OK:

```<code>@Bean
@ServiceActivator(inputChannel = "amqpInputChannel")
public MessageHandler aggregator(){
    AggregatingMessageHandler aggregatingMessageHandler = new AggregatingMessageHandler(new DefaultAggregatingMessageGroupProcessor(), new SimpleMessageStore(10));
    aggregatingMessageHandler.setCorrelationStrategy(new HeaderAttributeCorrelationStrategy(AmqpHeaders.CORRELATION_ID));
    //default false
    aggregatingMessageHandler.setExpireGroupsUponCompletion(true);  //when grp released (using strategy), remove group so new messages in same grp create new group
    aggregatingMessageHandler.setSendPartialResultOnExpiry(true);   //when expired because timeout and not because of strategy, still send messages grouped so far
    aggregatingMessageHandler.setGroupTimeoutExpression(new ValueExpression<>(TimeUnit.SECONDS.toMillis(10)));  //timeout after X

    //timeout is checked only when new message arrives!!
    aggregatingMessageHandler.setReleaseStrategy(new TimeoutCountSequenceSizeReleaseStrategy(10, TimeUnit.SECONDS.toMillis(10)));
    aggregatingMessageHandler.setOutputChannel(amqpOutputChannel());
    return aggregatingMessageHandler;
}
</code>```

Now, my question is - is there any easier way to manualy ack messages except creating my own implementation of AggregatingMessageHandler in this way:

```<code>public class ManualAckAggregatingMessageHandler extends AbstractCorrelatingMessageHandler {
        ...

    private void ackMessage(Channel channel, Long deliveryTag){
        try {
            Assert.notNull(channel, "Channel must be provided");
            Assert.notNull(deliveryTag, "Delivery tag must be provided");
            channel.basicAck(deliveryTag, false);
        }
        catch (IOException e) {
            throw new MessagingException("Cannot ACK message", e);
        }
    }

    @Override
    protected void afterRelease(MessageGroup messageGroup, Collection<Message<?>> completedMessages) {
        Object groupId = messageGroup.getGroupId();
        MessageGroupStore messageStore = getMessageStore();
        messageStore.completeGroup(groupId);

        messageGroup.getMessages().forEach(m -> {
            Channel channel = (Channel)m.getHeaders().get(AmqpHeaders.CHANNEL);
            Long deliveryTag = (Long)m.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
            ackMessage(channel, deliveryTag);
        });

        if (this.expireGroupsUponCompletion) {
            remove(messageGroup);
        }
        else {
            if (messageStore instanceof SimpleMessageStore) {
                ((SimpleMessageStore) messageStore).clearMessageGroup(groupId);
            }
            else {
                messageStore.removeMessagesFromGroup(groupId, messageGroup.getMessages());
            }
        }
    }
}
</code>```

UPDATE

I managed to do it after your help. Most important parts: Connection factory must have factory.setPublisherConfirms(true). AmqpOutboundEndpoint must have this two settings: outboundEndpoint.setConfirmAckChannel(manualAckChannel()) and outboundEndpoint.setConfirmCorrelationExpressionString("#root"), and this is implementation of rest of classes:

```<code>public class ManualAckPair {
    private Channel channel;
    private Long deliveryTag;

    public ManualAckPair(Channel channel, Long deliveryTag) {
        this.channel = channel;
        this.deliveryTag = deliveryTag;
    }

    public void basicAck(){
        try {
            this.channel.basicAck(this.deliveryTag, false);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public abstract class AbstractManualAckAggregatingMessageGroupProcessor extends AbstractAggregatingMessageGroupProcessor {
    public static final String MANUAL_ACK_PAIRS = PREFIX + "manualAckPairs";

    @Override
    protected Map<String, Object> aggregateHeaders(MessageGroup group) {
        Map<String, Object> aggregatedHeaders = super.aggregateHeaders(group);
        List<ManualAckPair> manualAckPairs = new ArrayList<>();
        group.getMessages().forEach(m -> {
            Channel channel = (Channel)m.getHeaders().get(AmqpHeaders.CHANNEL);
            Long deliveryTag = (Long)m.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
            manualAckPairs.add(new ManualAckPair(channel, deliveryTag));
        });
        aggregatedHeaders.put(MANUAL_ACK_PAIRS, manualAckPairs);
        return aggregatedHeaders;
    }
}
</code>```

and

```<code>@Service
public class ManualAckServiceActivator {

    @ServiceActivator(inputChannel = "manualAckChannel")
public void handle(@Header(MANUAL_ACK_PAIRS) List<ManualAckPair> manualAckPairs) {
    manualAckPairs.forEach(manualAckPair -> {
        manualAckPair.basicAck();
    });
}
}
</code>```

答:
Right, you don't need such a complex logic for the aggregator.

You simply can acknowledge them after the aggregator release - in the service activator in between aggregator and that AmqpOutboundEndpoint.

And right you have to use there basicAck() with the multiple flag to true:

```<code>@param multiple true to acknowledge all messages up to and
</code>```

Well, for that purpose you definitely need a custom MessageGroupProcessor to extract the highest AmqpHeaders.DELIVERY_TAG for the whole batch and set it as a header for the output aggregated message.

You might just extend DefaultAggregatingMessageGroupProcessor and override its aggregateHeaders():

```<code>/**
 * This default implementation simply returns all headers that have no conflicts among the group. An absent header
 * on one or more Messages within the group is not considered a conflict. Subclasses may override this method with
 * more advanced conflict-resolution strategies if necessary.
 *
 * @param group The message group.
 * @return The aggregated headers.
 */
protected Map<String, Object> aggregateHeaders(MessageGroup group) {
</code>```

Body:
I'm trying to build integration scenario like this Rabbit -> AmqpInboundChannelAdapter(AcknowledgeMode.MANUAL) -> DirectChannel -> AggregatingMessageHandler -> DirectChannel -> AmqpOutboundEndpoint.

I want to aggregate messages in-memory and release it if I aggregate 10 messages, or if timeout of 10 seconds is reached. I suppose this config is OK:

@Bean
@ServiceActivator(inputChannel = "amqpInputChannel")
public MessageHandler aggregator(){
    AggregatingMessageHandler aggregatingMessageHandler = new AggregatingMessageHandler(new DefaultAggregatingMessageGroupProcessor(), new SimpleMessageStore(10));
    aggregatingMessageHandler.setCorrelationStrategy(new HeaderAttributeCorrelationStrategy(AmqpHeaders.CORRELATION_ID));
    //default false
    aggregatingMessageHandler.setExpireGroupsUponCompletion(true);  //when grp released (using strategy), remove group so new messages in same grp create new group
    aggregatingMessageHandler.setSendPartialResultOnExpiry(true);   //when expired because timeout and not because of strategy, still send messages grouped so far
    aggregatingMessageHandler.setGroupTimeoutExpression(new ValueExpression<>(TimeUnit.SECONDS.toMillis(10)));  //timeout after X

    //timeout is checked only when new message arrives!!
    aggregatingMessageHandler.setReleaseStrategy(new TimeoutCountSequenceSizeReleaseStrategy(10, TimeUnit.SECONDS.toMillis(10)));
    aggregatingMessageHandler.setOutputChannel(amqpOutputChannel());
    return aggregatingMessageHandler;
}

Now, my question is - is there any easier way to manualy ack messages except creating my own implementation of AggregatingMessageHandler in this way:

public class ManualAckAggregatingMessageHandler extends AbstractCorrelatingMessageHandler {
        ...

    private void ackMessage(Channel channel, Long deliveryTag){
        try {
            Assert.notNull(channel, "Channel must be provided");
            Assert.notNull(deliveryTag, "Delivery tag must be provided");
            channel.basicAck(deliveryTag, false);
        }
        catch (IOException e) {
            throw new MessagingException("Cannot ACK message", e);
        }
    }

    @Override
    protected void afterRelease(MessageGroup messageGroup, Collection<Message<?>> completedMessages) {
        Object groupId = messageGroup.getGroupId();
        MessageGroupStore messageStore = getMessageStore();
        messageStore.completeGroup(groupId);

        messageGroup.getMessages().forEach(m -> {
            Channel channel = (Channel)m.getHeaders().get(AmqpHeaders.CHANNEL);
            Long deliveryTag = (Long)m.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
            ackMessage(channel, deliveryTag);
        });

        if (this.expireGroupsUponCompletion) {
            remove(messageGroup);
        }
        else {
            if (messageStore instanceof SimpleMessageStore) {
                ((SimpleMessageStore) messageStore).clearMessageGroup(groupId);
            }
            else {
                messageStore.removeMessagesFromGroup(groupId, messageGroup.getMessages());
            }
        }
    }
}

UPDATE

I managed to do it after your help. Most important parts: Connection factory must have factory.setPublisherConfirms(true). AmqpOutboundEndpoint must have this two settings: outboundEndpoint.setConfirmAckChannel(manualAckChannel()) and outboundEndpoint.setConfirmCorrelationExpressionString("#root"), and this is implementation of rest of classes:

public class ManualAckPair {
    private Channel channel;
    private Long deliveryTag;

    public ManualAckPair(Channel channel, Long deliveryTag) {
        this.channel = channel;
        this.deliveryTag = deliveryTag;
    }

    public void basicAck(){
        try {
            this.channel.basicAck(this.deliveryTag, false);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public abstract class AbstractManualAckAggregatingMessageGroupProcessor extends AbstractAggregatingMessageGroupProcessor {
    public static final String MANUAL_ACK_PAIRS = PREFIX + "manualAckPairs";

    @Override
    protected Map<String, Object> aggregateHeaders(MessageGroup group) {
        Map<String, Object> aggregatedHeaders = super.aggregateHeaders(group);
        List<ManualAckPair> manualAckPairs = new ArrayList<>();
        group.getMessages().forEach(m -> {
            Channel channel = (Channel)m.getHeaders().get(AmqpHeaders.CHANNEL);
            Long deliveryTag = (Long)m.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
            manualAckPairs.add(new ManualAckPair(channel, deliveryTag));
        });
        aggregatedHeaders.put(MANUAL_ACK_PAIRS, manualAckPairs);
        return aggregatedHeaders;
    }
}

and

@Service
public class ManualAckServiceActivator {

    @ServiceActivator(inputChannel = "manualAckChannel")
public void handle(@Header(MANUAL_ACK_PAIRS) List<ManualAckPair> manualAckPairs) {
    manualAckPairs.forEach(manualAckPair -> {
        manualAckPair.basicAck();
    });
}
}

Body:
Right, you don't need such a complex logic for the aggregator.

You simply can acknowledge them after the aggregator release - in the service activator in between aggregator and that AmqpOutboundEndpoint.

And right you have to use there basicAck() with the multiple flag to true:

@param multiple true to acknowledge all messages up to and

Well, for that purpose you definitely need a custom MessageGroupProcessor to extract the highest AmqpHeaders.DELIVERY_TAG for the whole batch and set it as a header for the output aggregated message.

You might just extend DefaultAggregatingMessageGroupProcessor and override its aggregateHeaders():

/**
 * This default implementation simply returns all headers that have no conflicts among the group. An absent header
 * on one or more Messages within the group is not considered a conflict. Subclasses may override this method with
 * more advanced conflict-resolution strategies if necessary.
 *
 * @param group The message group.
 * @return The aggregated headers.
 */
protected Map<String, Object> aggregateHeaders(MessageGroup group) {


答:
If your return statement is in the for loop, then it will return the total after iterating exactly once, and so the value of total will be the first element in the loop: in this case, 7. You should put the return statement after the loop so that the entire total is calculated:

```<code>def sum(numbers):

    total = 0

    for number in numbers:

        total += number

    return total

n = [7, 12, 5, 8]
print(sum(n))
</code>```

However, sum() is already a built-in function in Python, so you could simply reduce your code to the following:

```<code>n = [7, 12, 5, 8]
print(sum(n))
</code>```

Either of which will print 32.

Body:
When I print(sum(n)) I get 7 instead of the sum of the elements of the list which would be 32. What am I doing wrong?

def sum(numbers):
    total = 0
    for number in numbers:
        total += number
        return total

n = [7, 12, 5, 8]
print (sum(n))

Body:
If your return statement is in the for loop, then it will return the total after iterating exactly once, and so the value of total will be the first element in the loop: in this case, 7. You should put the return statement after the loop so that the entire total is calculated:

def sum(numbers):

    total = 0

    for number in numbers:

        total += number

    return total

n = [7, 12, 5, 8]
print(sum(n))

However, sum() is already a built-in function in Python, so you could simply reduce your code to the following:

n = [7, 12, 5, 8]
print(sum(n))

Either of which will print 32.