问:
High level rest client get only hits' size
i know with transport client can get hits' count like this:

```<code>import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.index.query.QueryBuilders.*;

SearchResponse response = client.prepareSearch("your_index_goes_here")
.setTypes("YourTypeGoesHere")
.setQuery(QueryBuilders.termQuery("some_field", "some_value"))
.setSize(0) // Don't return any documents, we don't need them.
.get();

SearchHits hits = response.getHits();
long hitsCount = hits.getTotalHits();
</code>```

but how can i get hits' size with high level rest client?

答:
If you are using Elasticsearch 6.6 or newer. Maybe you want to use the Count API: https://www.elastic.co/guide/en/elasticsearch/reference/6.6/search-count.html

In high level rest client (https://www.elastic.co/guide/en/elasticsearch/client/java-rest/6.6/java-rest-high-count.html):

```<code>CountRequest countRequest = new CountRequest("your_index_goes_here");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.termQuery("some_field", "some_value"));
countRequest.source(searchSourceBuilder);

CountResponse countResponse = client.count(countRequest, RequestOptions.DEFAULT);
long hitsCount = countResponse.getCount();
</code>```

Body:
i know with transport client can get hits' count like this:

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.index.query.QueryBuilders.*;

SearchResponse response = client.prepareSearch("your_index_goes_here")
.setTypes("YourTypeGoesHere")
.setQuery(QueryBuilders.termQuery("some_field", "some_value"))
.setSize(0) // Don't return any documents, we don't need them.
.get();

SearchHits hits = response.getHits();
long hitsCount = hits.getTotalHits();

but how can i get hits' size with high level rest client?

Body:
If you are using Elasticsearch 6.6 or newer. Maybe you want to use the Count API: https://www.elastic.co/guide/en/elasticsearch/reference/6.6/search-count.html

In high level rest client (https://www.elastic.co/guide/en/elasticsearch/client/java-rest/6.6/java-rest-high-count.html):

CountRequest countRequest = new CountRequest("your_index_goes_here");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.termQuery("some_field", "some_value"));
countRequest.source(searchSourceBuilder);

CountResponse countResponse = client.count(countRequest, RequestOptions.DEFAULT);
long hitsCount = countResponse.getCount();


来源: stackexchange

问:
Does anyone knows how to delete similar elements on a html table using jquery?
I have this table that is assembled by a PHP code (which I don't have access to) but it brings similar results and if I try to delete one of them it will erase all of the similar ones, which is not what I intend to. I want to delete all of the similar results on the table and leave just one.

The table is quite complex so I'll leave here just the tr contents, but when the id is equal to the previous one, all of th information inside the td is equal as well:

`

```<code><table id=ms_evaluations>
<tr id="110732" role="row" class="odd"></tr>
<tr id="110732" role="row" class="odd"></tr>
<tr id="110732" role="row" class="odd"></tr>
<tr id="110321" role="row" class="odd"></tr>
<tr id="110321" role="row" class="odd"></tr>
<tr id="89021" role="row" class="odd"></tr>
<tr id="78901" role="row" class="odd"></tr>
</table>
</code>```

`

I have tried to do something like this on javascript:

```<code>    var ids =[];
$("#dt_evaluations").find("tr").each(function(){ ids.push(this.id); });
    var repeated = [];
    for(var i=0; i<=ids.length; i++){
        var compare = ids[i];
        var count = 0;
        for(var x=0; x<=ids.length; x++){
            var copy = ids[x];
            if (x!=i && compare==copy && count==0){
                repeated.push(copy);
                count++
                $($("#(repeated[0])")[0]).remove();
            }

        }

    }
</code>```

but it does not work. Does anybody knows how to solve this issue?

答:
I've recently found out the resolution for this issue.

```<code>var tableFix = ( function() {
    var seen = {};
    $('tr').each(function() {
        var txt = $(this).text();
        if (seen[txt])
            $(this).remove();
        else
            seen[txt] = true;
    });
});
</code>```

I found it here: JQuery: Remove duplicate elements?

ContentLicense: CC BY-SA 4.0

Body:
I have this table that is assembled by a PHP code (which I don't have access to) but it brings similar results and if I try to delete one of them it will erase all of the similar ones, which is not what I intend to. I want to delete all of the similar results on the table and leave just one.

The table is quite complex so I'll leave here just the tr contents, but when the id is equal to the previous one, all of th information inside the td is equal as well:

`

`

I have tried to do something like this on javascript:

    var ids =[];
$("#dt_evaluations").find("tr").each(function(){ ids.push(this.id); });
    var repeated = [];
    for(var i=0; i<=ids.length; i++){
        var compare = ids[i];
        var count = 0;
        for(var x=0; x<=ids.length; x++){
            var copy = ids[x];
            if (x!=i && compare==copy && count==0){
                repeated.push(copy);
                count++
                $($("#(repeated[0])")[0]).remove();
            }

        }

    }

but it does not work. Does anybody knows how to solve this issue?

Body:
I've recently found out the resolution for this issue.

var tableFix = ( function() {
    var seen = {};
    $('tr').each(function() {
        var txt = $(this).text();
        if (seen[txt])
            $(this).remove();
        else
            seen[txt] = true;
    });
});

I found it here: JQuery: Remove duplicate elements?


问:
Use a raw_input to specify a specific file to create a copy of it's back up and change the file names of the back up and original file
I am working to set up a process that creates a new file from a backup file that is already in a folder. My program currently works, but I would like to eliminate as much of the user input as possible, so that all you have to do is enter the filename that just crashed on you and watch the program do the rest. I am fairly new at python and have been having trouble figuring out a way to get that initial raw_input to be the basis for the rest of the program to run off. I have uploaded the code that I have which currently does the job, so any tips that would help me make this code better would be much appreciated.

Thanks!

```<code>import os
import copy
import shutil

def copy_vrb():
    #Creates a copy of a specific "Filename.vrb" which gets renamed to "Filename_COPY.vrb"
    oldvrb=raw_input("Enter the .vr filename you were working on before it crashed: ") # With file extension
    newvrb=raw_input("Rename the new .vrb file to Filename_COPY")
    shutil.copy(oldvrb, newvrb + ".vrb") # Without file extension
copy_vrb()

def file_rename():
    # Takes original "Filename.vr" that crashed, and changes the filename to "Filename_BAD.vr".
    oldname=raw_input("Enter the Filename.vr that you were working on before it crashed: ") # With file extension
    newname=raw_input("Rename the file as Filename_BAD")
    os.rename(oldname, newname + ".vr")
file_rename()

def rename_copy():
    # Renames Filename_COPY.vrb to Filename_NEW.vr
    oldname=raw_input("Enter the Filename_COPY.vrb: ") # With file extension
    newname=raw_input("Rename to Filename_NEW: ") # Without file extension
    os.rename(oldname, newname, +".vr")
rename_copy()
</code>```

In my data folder that I would work out of, I have multiple pairs of files, (10001.vr(the file that would crash), and 10001.vrb(the backup that is created when I open the file in VR Mapping) What I want is to be able to input the specific file that crashed.

Create a copy of the 10001.vrb file ---> 10001_COPY.vrb

Change the 10001.vr file ---> 10001_BAD.vr

Lastly change the 10001_COPY.vrb file into the new usable file ---> 10001_NEW.vr

答:
One way of doing this is you accept the name of file as a command line input instead of doing raw_input().
https://www.pythonforbeginners.com/system/python-sys-argv

```<code>import os
import copy
import shutil

def copy_vrb(oldvrb):
    newvrb = os.path.splitext(oldvrb)[0] + "_COPY"
    shutil.copy(oldvrb, newvrb + ".vrb") # Without file extension

oldvrb=raw_input("Enter the .vr filename you were working on before it crashed: ")
copy_vrb(oldvrb)

</code>```

And then you do the rest for the other functions.

Body:
I am working to set up a process that creates a new file from a backup file that is already in a folder. My program currently works, but I would like to eliminate as much of the user input as possible, so that all you have to do is enter the filename that just crashed on you and watch the program do the rest. I am fairly new at python and have been having trouble figuring out a way to get that initial raw_input to be the basis for the rest of the program to run off. I have uploaded the code that I have which currently does the job, so any tips that would help me make this code better would be much appreciated.

Thanks!

import os
import copy
import shutil

def copy_vrb():
    #Creates a copy of a specific "Filename.vrb" which gets renamed to "Filename_COPY.vrb"
    oldvrb=raw_input("Enter the .vr filename you were working on before it crashed: ") # With file extension
    newvrb=raw_input("Rename the new .vrb file to Filename_COPY")
    shutil.copy(oldvrb, newvrb + ".vrb") # Without file extension
copy_vrb()

def file_rename():
    # Takes original "Filename.vr" that crashed, and changes the filename to "Filename_BAD.vr".
    oldname=raw_input("Enter the Filename.vr that you were working on before it crashed: ") # With file extension
    newname=raw_input("Rename the file as Filename_BAD")
    os.rename(oldname, newname + ".vr")
file_rename()

def rename_copy():
    # Renames Filename_COPY.vrb to Filename_NEW.vr
    oldname=raw_input("Enter the Filename_COPY.vrb: ") # With file extension
    newname=raw_input("Rename to Filename_NEW: ") # Without file extension
    os.rename(oldname, newname, +".vr")
rename_copy()

In my data folder that I would work out of, I have multiple pairs of files, (10001.vr(the file that would crash), and 10001.vrb(the backup that is created when I open the file in VR Mapping) What I want is to be able to input the specific file that crashed.

Create a copy of the 10001.vrb file ---> 10001_COPY.vrb

Change the 10001.vr file ---> 10001_BAD.vr

Lastly change the 10001_COPY.vrb file into the new usable file ---> 10001_NEW.vr

Body:
One way of doing this is you accept the name of file as a command line input instead of doing raw_input().
https://www.pythonforbeginners.com/system/python-sys-argv

import os
import copy
import shutil

def copy_vrb(oldvrb):
    newvrb = os.path.splitext(oldvrb)[0] + "_COPY"
    shutil.copy(oldvrb, newvrb + ".vrb") # Without file extension

oldvrb=raw_input("Enter the .vr filename you were working on before it crashed: ")
copy_vrb(oldvrb)

And then you do the rest for the other functions.


问:
Why Does RTP use UDP instead of TCP?
I wanted to know why UDP is used in RTP rather than TCP ?. Major VoIP Tools used only UDP as i hacked some of the VoIP OSS.</p>

答:
The others are correct, however the don't really tell you the REAL reason why.  Saua kind of hints at it, but here's a more complete answer.

Audio and Video is real-time.  If you are listening to a radio, or watching TV, and the signal is interrupted, it doesn't pick up where you left off.. you're just "observing" the signal as it streams, and if you can't observe it at any given time, you lose it.

The reason, is simple.  Delay.  VOIP tries very hard to minimize the amount of delay from the time someone speaks into one end and you get it on your end, and your response back.  Otherwise, as errors occured, the amount of delay between when the person spoke and when the signal was received would continuously grow until it became useless.

Remember, each delay from a retransmission has to be replayed, and that causes further data to be delayed, then another error causes an even greater delay.  The only workable solution is to simply drop any data that can't be displayed in real-time.

A 1 second delay from retransmission would mean it would now be 1 second from the time I said something until you heard it.  A second 1 second delay now means it's 2 seconds from the time i say something until you hear it.  This is cumulative because data is played back at the same rate at which it is spoken, and so on...

RTP could be connection oriented, but then it would have to drop (or skip) data to keep up with retransmission errors anyways, so why bother with the extra overhead?

OwnerDisplayName: mahesh

ContentLicense: CC BY-SA 2.5

Title: Why Does RTP use UDP instead of TCP?

LastEditorDisplayName: ceretullis

OwnerDisplayName: Mystere Man


问:
Can not startBeforeActivity at an activity defined in a subprocess
I have a parent process where a subprocess is started with "callActivity". The subprocess contains two tasks, task1 and task2. When I try to start the parentProcess at "task1" or "task2", I get a NotValidException:

```<code>org.camunda.bpm.engine.exception.NotValidException: Element 'task2' does not exist in process parentProcess:1:324: targetElement is null
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at org.camunda.bpm.engine.impl.util.EnsureUtil.generateException(EnsureUtil.java:380)
    at org.camunda.bpm.engine.impl.util.EnsureUtil.ensureNotNull(EnsureUtil.java:54)
    at org.camunda.bpm.engine.impl.cmd.StartProcessInstanceAtActivitiesCmd.determineFirstActivity(StartProcessInstanceAtActivitiesCmd.java:123)
    at org.camunda.bpm.engine.impl.cmd.StartProcessInstanceAtActivitiesCmd.execute(StartProcessInstanceAtActivitiesCmd.java:69)
    at org.camunda.bpm.engine.impl.cmd.StartProcessInstanceAtActivitiesCmd.execute(StartProcessInstanceAtActivitiesCmd.java:46)
    at org.camunda.bpm.engine.impl.interceptor.CommandExecutorImpl.execute(CommandExecutorImpl.java:27)
    at org.camunda.bpm.engine.impl.interceptor.CommandContextInterceptor.execute(CommandContextInterceptor.java:106)
    at org.camunda.bpm.engine.impl.interceptor.ProcessApplicationContextInterceptor.execute(ProcessApplicationContextInterceptor.java:69)
    at org.camunda.bpm.engine.impl.interceptor.LogInterceptor.execute(LogInterceptor.java:32)
    at org.camunda.bpm.engine.impl.ProcessInstantiationBuilderImpl.executeWithVariablesInReturn(ProcessInstantiationBuilderImpl.java:165)
    at org.camunda.bpm.engine.impl.ProcessInstantiationBuilderImpl.execute(ProcessInstantiationBuilderImpl.java:131)
    at org.camunda.bpm.engine.impl.ProcessInstantiationBuilderImpl.execute(ProcessInstantiationBuilderImpl.java:127)
</code>```

Here is how I try to start the process at "task2".

```<code>runtimeService.createProcessInstanceByKey("parentProcess")
    .startBeforeActivity("task2")
    .execute()
</code>```

To contextualize a little: we need to migrate old process instances into new definition, so we need to be able to start at any user task in the process.

What am I missing ?

答:
If I'm reading your question correctly, it would appear that you're attempting to start an instance of the parent process definition at a step that's only valid in the (child) subprocess definition. Is that correct?

If so, then the behavior you're seeing is the intended behavior, and you would need to specify an activity in the parent process definition.

There are options that you could leverage to start the subprocess instance at a specific step once that subprocess invocation is encountered in the parent instance, but that isn't supported by the Call Activity and would need to occur via a Java API call, which could be done in either a Service Task or a Script Task.

Body:
I have a parent process where a subprocess is started with "callActivity". The subprocess contains two tasks, task1 and task2. When I try to start the parentProcess at "task1" or "task2", I get a NotValidException:

org.camunda.bpm.engine.exception.NotValidException: Element 'task2' does not exist in process parentProcess:1:324: targetElement is null
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at org.camunda.bpm.engine.impl.util.EnsureUtil.generateException(EnsureUtil.java:380)
    at org.camunda.bpm.engine.impl.util.EnsureUtil.ensureNotNull(EnsureUtil.java:54)
    at org.camunda.bpm.engine.impl.cmd.StartProcessInstanceAtActivitiesCmd.determineFirstActivity(StartProcessInstanceAtActivitiesCmd.java:123)
    at org.camunda.bpm.engine.impl.cmd.StartProcessInstanceAtActivitiesCmd.execute(StartProcessInstanceAtActivitiesCmd.java:69)
    at org.camunda.bpm.engine.impl.cmd.StartProcessInstanceAtActivitiesCmd.execute(StartProcessInstanceAtActivitiesCmd.java:46)
    at org.camunda.bpm.engine.impl.interceptor.CommandExecutorImpl.execute(CommandExecutorImpl.java:27)
    at org.camunda.bpm.engine.impl.interceptor.CommandContextInterceptor.execute(CommandContextInterceptor.java:106)
    at org.camunda.bpm.engine.impl.interceptor.ProcessApplicationContextInterceptor.execute(ProcessApplicationContextInterceptor.java:69)
    at org.camunda.bpm.engine.impl.interceptor.LogInterceptor.execute(LogInterceptor.java:32)
    at org.camunda.bpm.engine.impl.ProcessInstantiationBuilderImpl.executeWithVariablesInReturn(ProcessInstantiationBuilderImpl.java:165)
    at org.camunda.bpm.engine.impl.ProcessInstantiationBuilderImpl.execute(ProcessInstantiationBuilderImpl.java:131)
    at org.camunda.bpm.engine.impl.ProcessInstantiationBuilderImpl.execute(ProcessInstantiationBuilderImpl.java:127)

Here is how I try to start the process at "task2".

runtimeService.createProcessInstanceByKey("parentProcess")
    .startBeforeActivity("task2")
    .execute()

To contextualize a little: we need to migrate old process instances into new definition, so we need to be able to start at any user task in the process.

What am I missing ?


问:
Array subset unequal sums
I have a requirement to write a function to divide an array in 2 parts {4,5,2,1,3}, such that sum in first array is greater than in second array but length of 1st array is smaller than that of second.The union of their sums is total sum and they dont have any intersection.So, an answer would be {4,5}.

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

public class DP2 {

    public static void main(String args[]) {
        int[] arr= {5,2,10,4,1,11};
        ArrayList<Integer> list=new ArrayList<>();
        //calculate sum
        int finalSum=0;
        /*
        for(int i: arr)
            finalSum+=arr[i];
            */
        int len=arr.length;
        int mid=(len)/2;
        System.out.println(mid);
        int sum=0;
        //initialize 2 pointers

        //will use a stack
        Stack<Integer> stack = new Stack<Integer>();

        int i=0,j=len-1;
        int max=Integer.MIN_VALUE;
        while(i < j ) {
            //int max=Math.max(arr[i], arr[j]);
        //  System.out.println(max);
            while(stack.size() < mid) {

                max=Math.max(arr[i], arr[j]);
                stack.push(max);
                //System.out.println(stack.size());
            //  System.out.println(stack.peek());
                i++;
                j--;
            }

        //  max=Math.max(arr[i], arr[j]);
            i++;
            j--;

            if(stack.size() < mid  && stack.peek() < max  ) {

                    stack.pop();
                    stack.push(max);

                }

        }

        while(!stack.isEmpty())
            System.out.println(stack.pop());

        }
    }
</code>```

It wont return the expected answer. It is not popping out from stack as I had coded to do. Can someone please help what I am doing wrong.

答:
I used recursion. This is the way I did it:

```<code>@Test
public void stackoverflow() {
    int[] array = { 39, 2, 3, 40, 0, 0, 0 };
    System.out.println("index is " + method(array, 0));
}

String method(int[] array, int i) {
    if (i < array.length / 2 && sum(array, 0, i) > sum(array, i + 1, array.length - 1)) {
        return "the sub array goes from 0 to " + i;
    }
    else if (i >= array.length / 2 && sum(array, array.length - 1 - i + array.length / 2, array.length - 1) > sum(array, 0, array.length - i - 2 + array.length / 2)) {
        int index = array.length - 1 - i + array.length / 2;
        return "the sub array goes from " + index + " to " + (array.length - 1);
    }
    return method(array, i + 1);
}

int sum(int[] array, int i, int j) {
    int sum = 0;
    for (int k = i; k <= j; k++) {
        sum = sum + array[k];
    }
    return sum;
}
</code>```

This is the explanation: you start from position 0 of the array. If the sum of the element at [0] is greater than the sum from position [1] to [n-1], you are done. If not, you call the same logic, comparing the sum from [0] to [1] versus [2] to [n-1]. Since you are looking for the smallest array, when you hit the half of the array (n/2), then you do the same starting from the end of the array.

My logic returns the index of the array. The index represents either the last element or the first element of the sub array which contains the greater sum. For example, in this case:

```<code>{ 0, 0, 0, 0, 40, 1, 2, 3 }
</code>```

it will return "4". [4] is this element:

```<code>{ 0, 0, 0, 0, 40, 1, 2, 3 }
               *
</code>```

Is clear here that if the index > n/2, then the sub array goes from index to n-1. If not, then the sub array goes from 0 to n/2.

Title: Array subset unequal sums

Body:
I have a requirement to write a function to divide an array in 2 parts {4,5,2,1,3}, such that sum in first array is greater than in second array but length of 1st array is smaller than that of second.The union of their sums is total sum and they dont have any intersection.So, an answer would be {4,5}.

import java.util.ArrayList;
import java.util.Stack;

public class DP2 {

    public static void main(String args[]) {
        int[] arr= {5,2,10,4,1,11};
        ArrayList<Integer> list=new ArrayList<>();
        //calculate sum
        int finalSum=0;
        /*
        for(int i: arr)
            finalSum+=arr[i];
            */
        int len=arr.length;
        int mid=(len)/2;
        System.out.println(mid);
        int sum=0;
        //initialize 2 pointers

        //will use a stack
        Stack<Integer> stack = new Stack<Integer>();

        int i=0,j=len-1;
        int max=Integer.MIN_VALUE;
        while(i < j ) {
            //int max=Math.max(arr[i], arr[j]);
        //  System.out.println(max);
            while(stack.size() < mid) {

                max=Math.max(arr[i], arr[j]);
                stack.push(max);
                //System.out.println(stack.size());
            //  System.out.println(stack.peek());
                i++;
                j--;
            }

        //  max=Math.max(arr[i], arr[j]);
            i++;
            j--;

            if(stack.size() < mid  && stack.peek() < max  ) {

                    stack.pop();
                    stack.push(max);

                }

        }

        while(!stack.isEmpty())
            System.out.println(stack.pop());

        }
    }

It wont return the expected answer. It is not popping out from stack as I had coded to do. Can someone please help what I am doing wrong.

Body:
I used recursion. This is the way I did it:

@Test
public void stackoverflow() {
    int[] array = { 39, 2, 3, 40, 0, 0, 0 };
    System.out.println("index is " + method(array, 0));
}

String method(int[] array, int i) {
    if (i < array.length / 2 && sum(array, 0, i) > sum(array, i + 1, array.length - 1)) {
        return "the sub array goes from 0 to " + i;
    }
    else if (i >= array.length / 2 && sum(array, array.length - 1 - i + array.length / 2, array.length - 1) > sum(array, 0, array.length - i - 2 + array.length / 2)) {
        int index = array.length - 1 - i + array.length / 2;
        return "the sub array goes from " + index + " to " + (array.length - 1);
    }
    return method(array, i + 1);
}

int sum(int[] array, int i, int j) {
    int sum = 0;
    for (int k = i; k <= j; k++) {
        sum = sum + array[k];
    }
    return sum;
}

This is the explanation: you start from position 0 of the array. If the sum of the element at [0] is greater than the sum from position [1] to [n-1], you are done. If not, you call the same logic, comparing the sum from [0] to [1] versus [2] to [n-1]. Since you are looking for the smallest array, when you hit the half of the array (n/2), then you do the same starting from the end of the array.

My logic returns the index of the array. The index represents either the last element or the first element of the sub array which contains the greater sum. For example, in this case:

{ 0, 0, 0, 0, 40, 1, 2, 3 }

it will return "4". [4] is this element:

{ 0, 0, 0, 0, 40, 1, 2, 3 }
               *

Is clear here that if the index > n/2, then the sub array goes from index to n-1. If not, then the sub array goes from 0 to n/2.


问:
Column-wise average over unequal number of values in matrix
I am looking for an easy way to obtain the column-wise average of a subset of values in a matrix (indexed by a logical matrix), preferably without having to use a loop. The problem that I am experiencing is that because the number of values in each column is different, matlab collapses the values-matrix and its column-wise mean becomes the total mean (of the entire matrix). Is there a specific function or easy workaround for this problem? See below for an example.</p>

```<code>    %% define value matrix and logical indexing matrix

    values=[1 2 3 4; 5 6 7 8; 9 10 11 12];
    indices=[1 0 0 1; 0 1 0 1; 1 1 0 0];
    indices=indices==1; %convert to logical

    %% calculate column-wise average

    mean(values(indices),1)
</code>```

答:
accumarray-based approach

Use the column index as a grouping variable for accumarray:

```<code>[~, col] = find(indices);
result = accumarray(col(:), values(indices), [size(values,2) 1], @mean, NaN).';
</code>```

Note that:

The second line uses (:) to force the first input to be a column vector. This is needed because the first line may produce col as a row or column vector, depending on the size of indices.

NaN is used as fill value. This is specified as the fifth input to accumarray.

The third input to accumarray defines output size. It is necessary to specify it explicitly (as opposed to letting accumarray figure it out) in case the last columns of indices only contain false.

Hacky approach

Multiply and divide element-wise by indices. That will turn unwanted entries into NaN, which can then be ignored by mean using the 'omitnan' option:

```<code>result = mean(values.*indices./indices, 1, 'omitnan');
</code>```

Manual approach

Multiply element-wise by indices, sum each column, and divide element-wise by the sum of each column of indices:

```<code>result = sum(values.*indices, 1) ./ sum(indices, 1);
</code>```

Body:
I am looking for an easy way to obtain the column-wise average of a subset of values in a matrix (indexed by a logical matrix), preferably without having to use a loop. The problem that I am experiencing is that because the number of values in each column is different, matlab collapses the values-matrix and its column-wise mean becomes the total mean (of the entire matrix). Is there a specific function or easy workaround for this problem? See below for an example.

    %% define value matrix and logical indexing matrix

    values=[1 2 3 4; 5 6 7 8; 9 10 11 12];
    indices=[1 0 0 1; 0 1 0 1; 1 1 0 0];
    indices=indices==1; %convert to logical

    %% calculate column-wise average

    mean(values(indices),1)

Body:
accumarray-based approach

Use the column index as a grouping variable for accumarray:

[~, col] = find(indices);
result = accumarray(col(:), values(indices), [size(values,2) 1], @mean, NaN).';

Note that:

The second line uses (:) to force the first input to be a column vector. This is needed because the first line may produce col as a row or column vector, depending on the size of indices.

NaN is used as fill value. This is specified as the fifth input to accumarray.

The third input to accumarray defines output size. It is necessary to specify it explicitly (as opposed to letting accumarray figure it out) in case the last columns of indices only contain false.

Hacky approach

Multiply and divide element-wise by indices. That will turn unwanted entries into NaN, which can then be ignored by mean using the 'omitnan' option:

result = mean(values.*indices./indices, 1, 'omitnan');

Manual approach

Multiply element-wise by indices, sum each column, and divide element-wise by the sum of each column of indices:

result = sum(values.*indices, 1) ./ sum(indices, 1);


问:
Loop through entire array while excluding an item
I have an array of items that I'd like to loop through and apply some code to, excluding one item (the clicked-on item).  I've tried using splice but I don't want to remove the array item, just skip over it.  In this case, I'm trying to remove a CSS class for each item, except the excluded one.

I've tried a few methods, using splice for one which isn't what I need.  I've also tried something like if (array[i] == 3 || (i - 1) = 2) { continue; else { .... } but can't seem to get that to work.

```<code>   var array = ["item1", "item2", "item3"];
   var i;
   for (i = 0; i < items.length; i++) {
       if(array[i] is the excluded one){
               skip over}
    else { $(items[i]).removeClass('class');
    }
</code>```

No error messages, just not working as expected.

答:
I think something like this is what you need:</p>

```<code><script type="text/javascript">
    $(document).ready(function(){
        $(".click").click(function(){ //When item with class click is clicked
               var items = ["item1", "item2", "item3"];
               var i;
               var itemid = this.id;
               for (i = 0; i < items.length; i++) { //go through array
                    if(items[i]==itemid){ //check if array item is the same as id of the class click
                        // Don't do anything, this is the one you clicked
                    }else{
                        $("#"+items[i]).removeClass('removeme'); // Remove class of all other with class click
                    }
               }
        });
    });
</script>
<div class="item1 click removeme" id="item1">Test1</div>
<div class="item2 click removeme" id="item2">Test2</div>
<div class="item3 click removeme" id="item3">Test3</div>
</code>```

Body:
I have an array of items that I'd like to loop through and apply some code to, excluding one item (the clicked-on item).  I've tried using splice but I don't want to remove the array item, just skip over it.  In this case, I'm trying to remove a CSS class for each item, except the excluded one.

I've tried a few methods, using splice for one which isn't what I need.  I've also tried something like if (array[i] == 3 || (i - 1) = 2) { continue; else { .... } but can't seem to get that to work.

   var array = ["item1", "item2", "item3"];
   var i;
   for (i = 0; i < items.length; i++) {
       if(array[i] is the excluded one){
               skip over}
    else { $(items[i]).removeClass('class');
    }

No error messages, just not working as expected.

Body:
I think something like this is what you need:

<script type="text/javascript">
    $(document).ready(function(){
        $(".click").click(function(){ //When item with class click is clicked
               var items = ["item1", "item2", "item3"];
               var i;
               var itemid = this.id;
               for (i = 0; i < items.length; i++) { //go through array
                    if(items[i]==itemid){ //check if array item is the same as id of the class click
                        // Don't do anything, this is the one you clicked
                    }else{
                        $("#"+items[i]).removeClass('removeme'); // Remove class of all other with class click
                    }
               }
        });
    });
</script>
<div class="item1 click removeme" id="item1">Test1</div>
<div class="item2 click removeme" id="item2">Test2</div>
<div class="item3 click removeme" id="item3">Test3</div>


问:
Tkinter: How to grid inside of a class?
I am trying to add a variable inside of class, and also grid it with the e1.grid() command. I can create the variable inside of the class but for some reason I can't grid the variable and I can't grid text either. Is there any way to solve this problem?

```<code>import tkinter as tk
from tkinter import font  as tkfont
from tkinter import Entry

class SampleApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        self.title_font = tkfont.Font(family='Helvetica', size=18,
        weight="bold", slant="italic")

        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (StartPage, PageOne):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame

            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("StartPage")

    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame = self.frames[page_name]
        frame.tkraise()

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is the start page",
font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)

        button1 = tk.Button(self, text="Go to Page One",
                            command=lambda:
controller.show_frame("PageOne"))
        button1.pack()

class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 1",
font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda:
controller.show_frame("StartPage"))
        button.pack()

        e1 = Entry(self)
        e1.grid(row=0, column=1)

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()
</code>```

答:
you can't use pack with grid together.

'''

```<code>e1 = Entry(self).pack()
#e1.grid(row=0, column=1)
</code>```

'''

so...

```<code>import tkinter as tk
from tkinter import font  as tkfont
from tkinter import Entry

class SampleApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        self.title_font = tkfont.Font(family='Helvetica', size=18,
        weight="bold", slant="italic")

        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (StartPage, PageOne):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame

            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("StartPage")

    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame = self.frames[page_name]
        frame.tkraise()

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is the start page", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)

        button1 = tk.Button(self, text="Go to Page One",command=lambda: controller.show_frame("PageOne"))
        button1.pack()

class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 1", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to the start page",command=lambda: controller.show_frame("StartPage"))
        button.pack()

        e1 = Entry(self).pack()
        #e1.grid(row=0, column=1)

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()
</code>```

update

if you want use grid method you must grid for all widgets in the relative page

```<code>class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 1", font=controller.title_font)
        label.grid(row=0, column=0)
        button = tk.Button(self, text="Go to the start page",command=lambda: controller.show_frame("StartPage"))
        button.grid(row=0, column=1)

        e1 = Entry(self)
        e1.grid(row=1, column=0)
</code>```

Title: Tkinter: How to grid inside of a class?

Body:
I am trying to add a variable inside of class, and also grid it with the e1.grid() command. I can create the variable inside of the class but for some reason I can't grid the variable and I can't grid text either. Is there any way to solve this problem?

import tkinter as tk
from tkinter import font  as tkfont
from tkinter import Entry

class SampleApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        self.title_font = tkfont.Font(family='Helvetica', size=18,
        weight="bold", slant="italic")

        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (StartPage, PageOne):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame

            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("StartPage")

    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame = self.frames[page_name]
        frame.tkraise()

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is the start page",
font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)

        button1 = tk.Button(self, text="Go to Page One",
                            command=lambda:
controller.show_frame("PageOne"))
        button1.pack()

class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 1",
font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda:
controller.show_frame("StartPage"))
        button.pack()

        e1 = Entry(self)
        e1.grid(row=0, column=1)

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

Body:
you can't use pack with grid together.

'''

e1 = Entry(self).pack()
#e1.grid(row=0, column=1)

'''

so...

import tkinter as tk
from tkinter import font  as tkfont
from tkinter import Entry

class SampleApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        self.title_font = tkfont.Font(family='Helvetica', size=18,
        weight="bold", slant="italic")

        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (StartPage, PageOne):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame

            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("StartPage")

    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame = self.frames[page_name]
        frame.tkraise()

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is the start page", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)

        button1 = tk.Button(self, text="Go to Page One",command=lambda: controller.show_frame("PageOne"))
        button1.pack()

class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 1", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to the start page",command=lambda: controller.show_frame("StartPage"))
        button.pack()

        e1 = Entry(self).pack()
        #e1.grid(row=0, column=1)

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

update

if you want use grid method you must grid for all widgets in the relative page

class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 1", font=controller.title_font)
        label.grid(row=0, column=0)
        button = tk.Button(self, text="Go to the start page",command=lambda: controller.show_frame("StartPage"))
        button.grid(row=0, column=1)

        e1 = Entry(self)
        e1.grid(row=1, column=0)


问:
Converting 2-channel .mov file to .mp3 with ffmpeg
I use Skype Call Recorder to record Skype interviews. The app saves files in .mov format, with 2 audio channels.

When I submit these files for transcription, they always come back with just one channel transcribed.

I need to 1.) merge the tracks, and 2.) convert the .mov file to .mp3 format.

Right now the command I'm working with is:

ffmpeg -i input.mov -map 0:a output.mp3

I get the following errors:

```<code> Invalid audio stream. Exactly one MP3 audio stream is required.
 Could not write header for output file #0 (incorrect codec parameters ?): Invalid argument
</code>```

What am I missing?

Here's the full console output, if it helps:

```<code>ffmpeg version 2.6.2 Copyright (c) 2000-2015 the FFmpeg developers
  built with Apple LLVM version 6.1.0 (clang-602.0.49) (based on LLVM 3.6.0svn)
  configuration: --prefix=/usr/local/Cellar/ffmpeg/2.6.2 --enable-shared --enable-pthreads --enable-gpl --enable-version3 --enable-hardcoded-tables --enable-avresample --cc=clang --host-cflags= --host-ldflags= --enable-libx264 --enable-libmp3lame --enable-libvo-aacenc --enable-libxvid --enable-vda
  libavutil      54. 20.100 / 54. 20.100
  libavcodec     56. 26.100 / 56. 26.100
  libavformat    56. 25.101 / 56. 25.101
  libavdevice    56.  4.100 / 56.  4.100
  libavfilter     5. 11.102 /  5. 11.102
  libavresample   2.  1.  0 /  2.  1.  0
  libswscale      3.  1.101 /  3.  1.101
  libswresample   1.  1.100 /  1.  1.100
  libpostproc    53.  3.100 / 53.  3.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'input.mov':
  Metadata:
    major_brand     : qt
    minor_version   : 537199360
    compatible_brands: qt
    creation_time   : 2019-05-18 15:00:59
  Duration: 00:11:41.82, start: 0.000000, bitrate: 120 kb/s
    Stream #0:0(eng): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, mono, fltp, 58 kb/s (default)
    Metadata:
      creation_time   : 2019-05-18 15:00:59
      handler_name    : Apple Alias Data Handler
    Stream #0:1(eng): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, mono, fltp, 58 kb/s (default)
    Metadata:
      creation_time   : 2019-05-18 15:00:59
      handler_name    : Apple Alias Data Handler
[mp3 @ 0x7fd8b1003c00] Invalid audio stream. Exactly one MP3 audio stream is required.
Output #0, mp3, to 'output.mp3':
  Metadata:
    major_brand     : qt
    minor_version   : 537199360
    compatible_brands: qt
    encoder         : Lavf56.25.101
    Stream #0:0(eng): Audio: mp3 (libmp3lame), 44100 Hz, mono, fltp (default)
    Metadata:
      creation_time   : 2019-05-18 15:00:59
      handler_name    : Apple Alias Data Handler
      encoder         : Lavc56.26.100 libmp3lame
    Stream #0:1(eng): Audio: mp3 (libmp3lame), 44100 Hz, mono, fltp (default)
    Metadata:
      creation_time   : 2019-05-18 15:00:59
      handler_name    : Apple Alias Data Handler
      encoder         : Lavc56.26.100 libmp3lame
Stream mapping:
  Stream #0:0 -> #0:0 (aac (native) -> mp3 (libmp3lame))
  Stream #0:1 -> #0:1 (aac (native) -> mp3 (libmp3lame))
Could not write header for output file #0 (incorrect codec parameters ?): Invalid argument
</code>```

答:
Two mono streams to mono

Use the amix filter:

```<code>ffmpeg -i input.mov -filter_complex "[0:a]amix=inputs=2" output.mp3
</code>```

Two mono streams to stereo

Use the join or amerge filters:

```<code>ffmpeg -i input.mov -filter_complex "[0:a]join=inputs=2:channel_layout=stereo" output.mp3
</code>```

Also see FFmpeg Wiki: Audio Channel Manipulation.

Body:
I use Skype Call Recorder to record Skype interviews. The app saves files in .mov format, with 2 audio channels.

When I submit these files for transcription, they always come back with just one channel transcribed.

I need to 1.) merge the tracks, and 2.) convert the .mov file to .mp3 format.

Right now the command I'm working with is:

ffmpeg -i input.mov -map 0:a output.mp3

I get the following errors:

 Invalid audio stream. Exactly one MP3 audio stream is required.
 Could not write header for output file #0 (incorrect codec parameters ?): Invalid argument

What am I missing?

Here's the full console output, if it helps:

ffmpeg version 2.6.2 Copyright (c) 2000-2015 the FFmpeg developers
  built with Apple LLVM version 6.1.0 (clang-602.0.49) (based on LLVM 3.6.0svn)
  configuration: --prefix=/usr/local/Cellar/ffmpeg/2.6.2 --enable-shared --enable-pthreads --enable-gpl --enable-version3 --enable-hardcoded-tables --enable-avresample --cc=clang --host-cflags= --host-ldflags= --enable-libx264 --enable-libmp3lame --enable-libvo-aacenc --enable-libxvid --enable-vda
  libavutil      54. 20.100 / 54. 20.100
  libavcodec     56. 26.100 / 56. 26.100
  libavformat    56. 25.101 / 56. 25.101
  libavdevice    56.  4.100 / 56.  4.100
  libavfilter     5. 11.102 /  5. 11.102
  libavresample   2.  1.  0 /  2.  1.  0
  libswscale      3.  1.101 /  3.  1.101
  libswresample   1.  1.100 /  1.  1.100
  libpostproc    53.  3.100 / 53.  3.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'input.mov':
  Metadata:
    major_brand     : qt
    minor_version   : 537199360
    compatible_brands: qt
    creation_time   : 2019-05-18 15:00:59
  Duration: 00:11:41.82, start: 0.000000, bitrate: 120 kb/s
    Stream #0:0(eng): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, mono, fltp, 58 kb/s (default)
    Metadata:
      creation_time   : 2019-05-18 15:00:59
      handler_name    : Apple Alias Data Handler
    Stream #0:1(eng): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, mono, fltp, 58 kb/s (default)
    Metadata:
      creation_time   : 2019-05-18 15:00:59
      handler_name    : Apple Alias Data Handler
[mp3 @ 0x7fd8b1003c00] Invalid audio stream. Exactly one MP3 audio stream is required.
Output #0, mp3, to 'output.mp3':
  Metadata:
    major_brand     : qt
    minor_version   : 537199360
    compatible_brands: qt
    encoder         : Lavf56.25.101
    Stream #0:0(eng): Audio: mp3 (libmp3lame), 44100 Hz, mono, fltp (default)
    Metadata:
      creation_time   : 2019-05-18 15:00:59
      handler_name    : Apple Alias Data Handler
      encoder         : Lavc56.26.100 libmp3lame
    Stream #0:1(eng): Audio: mp3 (libmp3lame), 44100 Hz, mono, fltp (default)
    Metadata:
      creation_time   : 2019-05-18 15:00:59
      handler_name    : Apple Alias Data Handler
      encoder         : Lavc56.26.100 libmp3lame
Stream mapping:
  Stream #0:0 -> #0:0 (aac (native) -> mp3 (libmp3lame))
  Stream #0:1 -> #0:1 (aac (native) -> mp3 (libmp3lame))
Could not write header for output file #0 (incorrect codec parameters ?): Invalid argument

Body:
Two mono streams to mono

Use the amix filter:

ffmpeg -i input.mov -filter_complex "[0:a]amix=inputs=2" output.mp3

Two mono streams to stereo

Use the join or amerge filters:

ffmpeg -i input.mov -filter_complex "[0:a]join=inputs=2:channel_layout=stereo" output.mp3

Also see FFmpeg Wiki: Audio Channel Manipulation.


问:
Database backup script
i'm pretty new to Oracle and i'm trying to make a script that backups the database everytime it's ran from cronjob.

I've been looking on a lot of discussions online but i didn't really manage to find anything even tho i made some small steps.
What i need to do is run everything from 1 single script, wether it goes from creating the database directory backup location to running the backup itself

```<code>sqlplus / as SYSDBA << EOF
CREATE DIRECTORY dmpdir AS '/nfs/ora_bck/';
exit
EOF
</code>```

It should give me some positive output but instead i get some database not mounted error which doesn't make sense because it's our production database which is up and running without any issues

答: Try with <<EOF ( space removed from << EOF ), and use UpperCase directory name DMPDIR with privileges granted ( grant read, write on directory DMPDIR to <yourSchema> ), and make sure the path /nfs/ora_bck/ really exists.

Title: Database backup script

Body:
i'm pretty new to Oracle and i'm trying to make a script that backups the database everytime it's ran from cronjob.

I've been looking on a lot of discussions online but i didn't really manage to find anything even tho i made some small steps.
What i need to do is run everything from 1 single script, wether it goes from creating the database directory backup location to running the backup itself

sqlplus / as SYSDBA << EOF
CREATE DIRECTORY dmpdir AS '/nfs/ora_bck/';
exit
EOF

It should give me some positive output but instead i get some database not mounted error which doesn't make sense because it's our production database which is up and running without any issues


问:
How can I spin an object each 5 seconds in other random values?
```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RotateCamera : MonoBehaviour
{
    public GameObject objectToSpin;
    public float spinX;
    public float spinY;
    public float spinZ;
    public bool randomSpin = false;

    private void Start()
    {
        var rb = GetComponent<Rigidbody>();
        rb.angularVelocity = Random.insideUnitSphere;
    }

    private void Update()
    {
        if (randomSpin == true)
        {
            objectToSpin.transform.Rotate(Random.Range(spinX, 360), Random.Range(spinY, 360), Random.Range(spinZ, 360));
        }
        else
        {
            objectToSpin.transform.Rotate(spinX, spinY, spinZ);
        }
    }
}
</code>```

Now when changing the randomSpin flag to true it will spin random nonstop changing random angle on x y z each frame.

But I want it to spin random for 5 seconds after 5 seconds to change to random values the x y z and continue from last point and then after 5 seconds random angles and so on.

答:
For example have a simple timer using Time.deltaTime like e.g.

```<code>private float timer = 5;

private void Update()
{
    if (randomSpin == true)
    {
         timer -= Time.deltaTime;
         if(timer <= 0)
         {
            objectToSpin.transform.Rotate(Random.Range(spinX, 360), Random.Range(spinY, 360), Random.Range(spinZ, 360));

            timer = 5;
        }
    }
    else
    {
        objectToSpin.transform.Rotate(spinX, spinY, spinZ);
    }
}
</code>```

Body:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RotateCamera : MonoBehaviour
{
    public GameObject objectToSpin;
    public float spinX;
    public float spinY;
    public float spinZ;
    public bool randomSpin = false;

    private void Start()
    {
        var rb = GetComponent<Rigidbody>();
        rb.angularVelocity = Random.insideUnitSphere;
    }

    private void Update()
    {
        if (randomSpin == true)
        {
            objectToSpin.transform.Rotate(Random.Range(spinX, 360), Random.Range(spinY, 360), Random.Range(spinZ, 360));
        }
        else
        {
            objectToSpin.transform.Rotate(spinX, spinY, spinZ);
        }
    }
}

Now when changing the randomSpin flag to true it will spin random nonstop changing random angle on x y z each frame.

But I want it to spin random for 5 seconds after 5 seconds to change to random values the x y z and continue from last point and then after 5 seconds random angles and so on.

Body:
For example have a simple timer using Time.deltaTime like e.g.

private float timer = 5;

private void Update()
{
    if (randomSpin == true)
    {
         timer -= Time.deltaTime;
         if(timer <= 0)
         {
            objectToSpin.transform.Rotate(Random.Range(spinX, 360), Random.Range(spinY, 360), Random.Range(spinZ, 360));

            timer = 5;
        }
    }
    else
    {
        objectToSpin.transform.Rotate(spinX, spinY, spinZ);
    }
}


问:
Checkbox Yes/No Change on Dropbox Change
I have a Combo Box (cbo1) that list available Items. When I select an item in cbo1, I would like it change a checkbox to True (or Yes).

cbo1 gets data from tblLOG where Box (checkbox) is NO Query

I've tried using

```<code>UPDATE tblLOG
Set Box = True
WHERE Serial = cboSerial
</code>```

Actual Code.

```<code>Private Sub cbo1_Change()
    Dim strSQL As String
    Dim i As Integer
    Dim Msg As String
    Dim Assm As String

    Assm = cbo1.Value

    'Exit this sub if the combo box is cleared
    Msg = "Make Update" & vbCr & vbCr

    i = MsgBox(Msg, vbQuestion + vbYesNo, "UPDATE VALUE?")
    If i = vbYes Then
        strSQL = "UPDATE tblLOG " _
        & "SET Box= True " _
        & "WHERE Serial = Assm;"
        CurrentDb.Execute strSQL, dbFailOnError
        Response = acDataErrAdded
    End If
End Sub
</code>```

My Results are

Run-time error '3061': Too few parameters. Expected 1.

答:
The reason for your error is because you are not evaluating your VBA variable Assm, but rather concatenating the string "Assm" to your SQL query.

strSQL = "UPDATE tblLOG " _
& "SET Box= True " _
& "WHERE Serial = Assm;"
```

<p>If you were to <code>Debug.Print</code> the variable <code>strSQL</code> to the console, you would see the string:</p>

<pre class="lang-vb prettyprint-override"><code>"UPDATE tblLOG SET Box= True WHERE Serial = Assm;"
</code>```

However, since Assm is not a string in the SQL query (i.e. it is not surrounded by single or double quotes), it is interpreted as a parameter whose value hasn't been supplied when the SQL query is subsequently executed.

To solve this, you could concatenate the evaluated value of the Assm variable, e.g.:

strSQL = "UPDATE tblLOG " _
& "SET Box= True " _
& "WHERE Serial = '" & Assm & "';"
```

<p>This assumes that <code>Serial</code> is a <strong>text</strong> field - if this is not the case, remove the single quotes from the above.</p>

<p>Your entire code could be condensed somewhat to:</p>

<pre class="lang-vb prettyprint-override"><code>Private Sub cbo1_Change()
    If MsgBox("Make Update", vbQuestion + vbYesNo, "UPDATE VALUE?") = vbYes Then
        CurrentDb.Execute "update tbllog set box = true where serial = '" & cbo1 & "';", dbFailOnError
        Response = acDataErrAdded
    End If
End Sub
</code>```

Though, this is still open to SQL injection, and so a better practice is to parameterise the query, e.g.:

With CurrentDb.CreateQueryDef("", "update tbllog t set t.box = true where t.serial = myserial;")
    .Parameters!myserial = cbo1
    .Execute
End With
```

Body:
I have a Combo Box (cbo1) that list available Items. When I select an item in cbo1, I would like it change a checkbox to True (or Yes).

cbo1 gets data from tblLOG where Box (checkbox) is NO Query

I've tried using

UPDATE tblLOG
Set Box = True
WHERE Serial = cboSerial

Actual Code.

Private Sub cbo1_Change()
    Dim strSQL As String
    Dim i As Integer
    Dim Msg As String
    Dim Assm As String

    Assm = cbo1.Value

    'Exit this sub if the combo box is cleared
    Msg = "Make Update" & vbCr & vbCr

    i = MsgBox(Msg, vbQuestion + vbYesNo, "UPDATE VALUE?")
    If i = vbYes Then
        strSQL = "UPDATE tblLOG " _
        & "SET Box= True " _
        & "WHERE Serial = Assm;"
        CurrentDb.Execute strSQL, dbFailOnError
        Response = acDataErrAdded
    End If
End Sub

My Results are

Run-time error '3061': Too few parameters. Expected 1.

Body:
The reason for your error is because you are not evaluating your VBA variable Assm, but rather concatenating the string "Assm" to your SQL query.

strSQL = "UPDATE tblLOG " _
& "SET Box= True " _
& "WHERE Serial = Assm;"

If you were to Debug.Print the variable strSQL to the console, you would see the string:

"UPDATE tblLOG SET Box= True WHERE Serial = Assm;"

However, since Assm is not a string in the SQL query (i.e. it is not surrounded by single or double quotes), it is interpreted as a parameter whose value hasn't been supplied when the SQL query is subsequently executed.

To solve this, you could concatenate the evaluated value of the Assm variable, e.g.:

strSQL = "UPDATE tblLOG " _
& "SET Box= True " _
& "WHERE Serial = '" & Assm & "';"

This assumes that Serial is a text field - if this is not the case, remove the single quotes from the above.

Your entire code could be condensed somewhat to:

Private Sub cbo1_Change()
    If MsgBox("Make Update", vbQuestion + vbYesNo, "UPDATE VALUE?") = vbYes Then
        CurrentDb.Execute "update tbllog set box = true where serial = '" & cbo1 & "';", dbFailOnError
        Response = acDataErrAdded
    End If
End Sub

Though, this is still open to SQL injection, and so a better practice is to parameterise the query, e.g.:

With CurrentDb.CreateQueryDef("", "update tbllog t set t.box = true where t.serial = myserial;")
    .Parameters!myserial = cbo1
    .Execute
End With


问:
Are the "Prototype pattern" and the "Virtual constructor" the same patterns?
Does the Virtual constructor - implementing virtual function clone():

```<code>class X {
public:
     virtual X* clone() {
         return new X(*this);
     }
};
</code>```

mean the same concept as the Prototype design pattern?

答:
... mean the same concept as the Prototype design pattern?

No, it doesn't. The cloneable interface is only part of the implementation of the Prototype Design Pattern.

The point of Prototype is to have a Factory to hold instances of prototypical instances, and knows which to use as cloning source to create new instances.

Body:
Does the Virtual constructor - implementing virtual function clone():

class X {
public:
     virtual X* clone() {
         return new X(*this);
     }
};

mean the same concept as the Prototype design pattern?


问:
template parameter deduction from templated non-type template argument
I have the following typedef:

template<typename G, typename T, typename R>
using my_func_type = typename R(T::*)(G, int) const;
```

<p>It is a member function I use a lot, so I'm playing around with making different wrappers for. The premise is that I want an object that implements these functions through a common function call, so that I can combine them in different ways (currently I use the straightforward way of wrapping the call as a lambdas).</p>

<p>However, another method is to pass that function as a non-type template parameter (this improves my performance compared to the lambda solution, because I'm constantly evaluating it), viz.</p>

<pre class="lang-cpp prettyprint-override"><code>template<typename G, typename T, typename R, my_func_type<G, T, R> f>
struct MyWrapper
{
    MyWrapper(G g, T t) : g{ g }, t{ t } {}
    auto eval(int n) const
    {
        return (t.*f)(g, n);
    }

protected:
    G g;
    T t;
};

int main()
{
    AnObject g;
    TheCallingObject t;
    auto f = &TheCallingObject::callit;

    MyWrapper<AnObject, TheCallingObject, double, f> wrap(g, t)
}
</code>```

But this seems a little redundant, so is it possible for the template arguments to be deduced from f?

The halfway solution I've found is:

template<auto f, typename G, typename T>
struct MyWrapper
{
    OpFuncDerivative(G g, T t) : g{ g }, t{ t } {}
    auto eval(int n) const
    {
        return (t.*f)(g, n);
    }

protected:
    G g;
    T t;
};

int main()
{
    AnObject g;
    TheCallingObject t;
    auto f = &TheCallingObject::callit;

    // it won't automatically deduce AnObject and TheCallingObject
    // through the parameters to the constructor though!
    MyWrapper<f, AnObject, TheCallingObject> wrap(g, t)
}
```

答:
You can write a helper function:

```<code>template<typename G, typename T, auto f>
struct MyWrapper
{
    MyWrapper(G g, T t) : g{g}, t{t}
    {}

    auto eval(int n) const
    {
       return (t.*f)(g, n);
    }

protected:
    G g;
    T t;
};

template<auto f, typename G, typename T>
MyWrapper<G, T, f> make_wrapper(G g, T t)
{
    return {g, t};
}
</code>```

and then use it like this:

```<code>int main()
{
    AnObject g;
    TheCallingObject t;
    constexpr auto f = &TheCallingObject::callit;

    auto wrap = make_wrapper<f>(g, t);
}
</code>```

Body:
I have the following typedef:

template<typename G, typename T, typename R>
using my_func_type = typename R(T::*)(G, int) const;

It is a member function I use a lot, so I'm playing around with making different wrappers for. The premise is that I want an object that implements these functions through a common function call, so that I can combine them in different ways (currently I use the straightforward way of wrapping the call as a lambdas).

However, another method is to pass that function as a non-type template parameter (this improves my performance compared to the lambda solution, because I'm constantly evaluating it), viz.

template<typename G, typename T, typename R, my_func_type<G, T, R> f>
struct MyWrapper
{
    MyWrapper(G g, T t) : g{ g }, t{ t } {}
    auto eval(int n) const
    {
        return (t.*f)(g, n);
    }

protected:
    G g;
    T t;
};

int main()
{
    AnObject g;
    TheCallingObject t;
    auto f = &TheCallingObject::callit;

    MyWrapper<AnObject, TheCallingObject, double, f> wrap(g, t)
}

But this seems a little redundant, so is it possible for the template arguments to be deduced from f?

The halfway solution I've found is:

template<auto f, typename G, typename T>
struct MyWrapper
{
    OpFuncDerivative(G g, T t) : g{ g }, t{ t } {}
    auto eval(int n) const
    {
        return (t.*f)(g, n);
    }

protected:
    G g;
    T t;
};

int main()
{
    AnObject g;
    TheCallingObject t;
    auto f = &TheCallingObject::callit;

    // it won't automatically deduce AnObject and TheCallingObject
    // through the parameters to the constructor though!
    MyWrapper<f, AnObject, TheCallingObject> wrap(g, t)
}

Body:
You can write a helper function:

template<typename G, typename T, auto f>
struct MyWrapper
{
    MyWrapper(G g, T t) : g{g}, t{t}
    {}

    auto eval(int n) const
    {
       return (t.*f)(g, n);
    }

protected:
    G g;
    T t;
};

template<auto f, typename G, typename T>
MyWrapper<G, T, f> make_wrapper(G g, T t)
{
    return {g, t};
}

and then use it like this:

int main()
{
    AnObject g;
    TheCallingObject t;
    constexpr auto f = &TheCallingObject::callit;

    auto wrap = make_wrapper<f>(g, t);
}


问:
autocomplete text search
can any body tell me steps to use it, where i can get simple example for this </p>

答:
A nice solution is the jQuery UI autocomplete widget:

http://jqueryui.com/demos/autocomplete/

It can use a simple array or an ajax call as the datasource.

ContentLicense: CC BY-SA 3.0

Title: autocomplete text search


问:
In a string with just numbers and commas how do I convert that into a double
So I have a string with just numbers and commas. for example "1,233,323.32"(String) but I want to convert that to 1233323.32(double).</p>

答:
Swift 4.x:

Here is your solution with Manual Approach

```<code>var a = "1,233,323.32"
print(a.contains(","))
</code>```

check how many time does ',' occurs in a String, given below

```<code>print("occurrence of ',': \(a.characters.filter {$0 == ","}.count)")
</code>```

if ',' occurs 2times in string then remove ',' from String 2time using loop, given below

```<code>for _ in 1...(a.characters.filter {$0 == ","}.count)  {
    a.remove(at: a.index(of: ",")!)
}

print("Ans: \( Double(a)! )")
</code>```

output

```<code>true
occurrence of ',': 2
Ans: 1233323.32
</code>```

Body:
Swift 4.x:

Here is your solution with Manual Approach

var a = "1,233,323.32"
print(a.contains(","))

check how many time does ',' occurs in a String, given below

print("occurrence of ',': \(a.characters.filter {$0 == ","}.count)")

if ',' occurs 2times in string then remove ',' from String 2time using loop, given below

for _ in 1...(a.characters.filter {$0 == ","}.count)  {
    a.remove(at: a.index(of: ",")!)
}

print("Ans: \( Double(a)! )")

output

true
occurrence of ',': 2
Ans: 1233323.32


问:
Top-bar animates on scroll
I'm looking to recreate the scrolling effect found on here: As you scroll, an orange bar begins to stretch across the top of the screen, and if you scroll back up to the top, it moves back in the other direction.

Would anyone be able to help get me started?

答:
You can create a progress bar made up from 2 div elements.

the inner div will represent the value of the scroll bar.
the value will be calculated via scroll event listener and will be reset to the DOM after every change of the scroll bar.

Here is my suggestion:

LIVE DEMO

HTML:

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <!--remove comment to use jquery-->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
    <style>
    </style>
  </head>
  <body>
    <div class="progress-bar">
      <div id="pb-value">
      </div>
    </div>
    <div class="content">
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
        Quisque rutrum urna turpis, nec auctor massa scelerisque quis.
        Donec auctor erat eget ultrices luctus.
        Mauris varius, ...
      </p>
    </div>
  </body>
</html>
</code>```

CSS:

```<code>body
{
  margin:0;
}
.progress-bar
{
  position:fixed;
  display:inline-block;
  height:15px;
  width:100%;
  background-color:gray;
  z-index:999;
}
#pb-value
{
  float:left;
  display:inline-block;
  width:0;
  background-color:orange;
  height:100%;
}
.content
{
  position:absolute;
  top:10px;
}
</code>```

JS:

```<code>window.addEventListener("scroll", scrollAnim);
function scrollAnim () {
  var val = getScrollPercent();
  document.getElementById('pb-value').style.width = val + "%";
}
function getScrollPercent()
{
  var maxvalue = $(document).height() - $(window).height();
  var val = $(document).scrollTop()
  return (val / maxvalue)*100;
}
</code>```

Title: Top-bar animates on scroll

Body:
You can create a progress bar made up from 2 div elements.

the inner div will represent the value of the scroll bar.
the value will be calculated via scroll event listener and will be reset to the DOM after every change of the scroll bar.

Here is my suggestion:

LIVE DEMO

HTML:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <!--remove comment to use jquery-->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
    <style>
    </style>
  </head>
  <body>
    <div class="progress-bar">
      <div id="pb-value">
      </div>
    </div>
    <div class="content">
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
        Quisque rutrum urna turpis, nec auctor massa scelerisque quis.
        Donec auctor erat eget ultrices luctus.
        Mauris varius, ...
      </p>
    </div>
  </body>
</html>

CSS:

body
{
  margin:0;
}
.progress-bar
{
  position:fixed;
  display:inline-block;
  height:15px;
  width:100%;
  background-color:gray;
  z-index:999;
}
#pb-value
{
  float:left;
  display:inline-block;
  width:0;
  background-color:orange;
  height:100%;
}
.content
{
  position:absolute;
  top:10px;
}

JS:

window.addEventListener("scroll", scrollAnim);
function scrollAnim () {
  var val = getScrollPercent();
  document.getElementById('pb-value').style.width = val + "%";
}
function getScrollPercent()
{
  var maxvalue = $(document).height() - $(window).height();
  var val = $(document).scrollTop()
  return (val / maxvalue)*100;
}


问:
What is WAW Hazard?

Wikipedia's Hazard (computer architecture) article:

Write after write (WAW) (i2 tries to write an operand before it is
  written by i1) A write after write (WAW) data hazard may occur in a
  concurrent execution environment.

Example For example:

```<code>i1. R2 <- R4 + R7
i2. R2 <- R1 + R3
</code>```

The write back (WB) of i2 must be
  delayed until i1 finishes executing.

I haven't understood this.

What is the problem if i2 is executed before i1?

答:
It's not execution that's the problem; it's only write-back that prevents out-of-order execution of these instructions (if you didn't do register renaming).

The final result in R2 (as seen by other later instructions after this pair) has to match program order, so it has to have the result of the 2nd instruction.

This is why modern out-of-order execution CPUs use register renaming (Tomasulo's algorithm) instead of just scoreboarding: it totally negates WAW and WAR hazards.  See the first section of my answer on Why does mulss take only 3 cycles on Haswell, different from Agner's instruction tables? for another explanation in theoretical terms of how register renaming makes reuse of the same register for different results not a problem.

Also see Deoptimizing a program for the pipeline in Intel Sandybridge-family CPUs where I also explain that WAW and WAR anti-dependencies can't cause stalls on modern out-of-order execution CPUs.

For writes to memory (instead of registers), the store buffer takes care of hiding WAW and WAR hazards.

Title: What is WAW Hazard?

Body:
Wikipedia's Hazard (computer architecture) article:

Write after write (WAW) (i2 tries to write an operand before it is
  written by i1) A write after write (WAW) data hazard may occur in a
  concurrent execution environment.

Example For example:

i1. R2 <- R4 + R7
i2. R2 <- R1 + R3

The write back (WB) of i2 must be
  delayed until i1 finishes executing.

I haven't understood this.

What is the problem if i2 is executed before i1?


问:
the parameter 'body' is not defined
```<code>Compiler message:
lib/main.dart:12:11: Error: No named parameter with the name 'body'.
          body: Image(
          ^^^^
</code>```

```<code>import 'package:flutter/material.dart';

//main fuction is the starting point for all our apps.
void main() {
  runApp(
    MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.blueGrey[150],
        appBar: AppBar(
          title: Text('I Am Rich'),
          backgroundColor: Colors.deepOrange,
          body: Image(
            image:
                NetworkImage('https://www.w3schools.com/w3css/img_lights.jpg'),
          ),
        ),
      ),
    ),
  );
}
</code>```

答:
The body is a parameter ofScaffold, not AppBar

```<code>     Scaffold(
            backgroundColor: Colors.blueGrey[150],
            appBar: AppBar(
              title: Text('I Am Rich'),
              backgroundColor: Colors.deepOrange,

            ),
            body: Image(
                image:
                    NetworkImage('https://www.w3schools.com/w3css/img_lights.jpg'),
              ),
          ),
</code>```

More info here: https://api.flutter.dev/flutter/material/Scaffold-class.html

Title: the parameter 'body' is not defined

Body:
Compiler message:
lib/main.dart:12:11: Error: No named parameter with the name 'body'.
          body: Image(
          ^^^^

import 'package:flutter/material.dart';

//main fuction is the starting point for all our apps.
void main() {
  runApp(
    MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.blueGrey[150],
        appBar: AppBar(
          title: Text('I Am Rich'),
          backgroundColor: Colors.deepOrange,
          body: Image(
            image:
                NetworkImage('https://www.w3schools.com/w3css/img_lights.jpg'),
          ),
        ),
      ),
    ),
  );
}

Body:
The body is a parameter ofScaffold, not AppBar

     Scaffold(
            backgroundColor: Colors.blueGrey[150],
            appBar: AppBar(
              title: Text('I Am Rich'),
              backgroundColor: Colors.deepOrange,

            ),
            body: Image(
                image:
                    NetworkImage('https://www.w3schools.com/w3css/img_lights.jpg'),
              ),
          ),

More info here: https://api.flutter.dev/flutter/material/Scaffold-class.html


问:
Parameter value is out of range
It seems EF is padding zeros to the value that I'm trying to save and then throwing an exception.  Here is my code:  Why is the total hours field with a value of 10.17 out of range of a decimal(6,5) value type and why is it padding this value with zeros?  Saving this value directly using SQL Server Management Studio doesn't seem to be a problem, so it seems more like a problem with EF.

This is from a database first .edmx file.  I've tried setting the scale and precision and setting to none.  Neither have worked

```<code> var rVal = new Data.FactPayrollHour()
                {
                    BereavementHours = 0.0M,
                    CostCenter = "MyCostCenter",
                    Department = "MyDepartment",
                    EmergencyHours = 0.0M,
                    HomeGroupCode = "MyHomeGroup",
                    PayrollEmployeeId = employees.FirstOrDefault().Id,
                    PayType = "MyPayType",
                    PunchDateKey = dateDims.FirstOrDefault().ID,
                    Schedule = "",
                    ServiceHours = 0.0M,
                    Shift = "",
                    ShortTermHours = 0.0M,
                    TimePolicy = "",
                    TotalHours = 10.17M,
                    UnpaidHours = 0.0M,
                    VacationHours = 0.0M
                };
                db.FactPayrollHours.Add(rVal);
                db.SaveChanges();
</code>```

The exception message is: Parameter value '10.17000' is out of range.

Stack Trace:

```<code>   at System.Data.SqlClient.TdsParser.TdsExecuteRPC(SqlCommand cmd, _SqlRPC[] rpcArray, Int32 timeout, Boolean inSchema, SqlNotificationRequest notificationRequest, TdsParserStateObject stateObj, Boolean isCommandProc, Boolean sync, TaskCompletionSource`1 completion, Int32 startRpc, Int32 startParam)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
   at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
   at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext`1 c)
   at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
   at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
   at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues)
   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
</code>```

答:
If the data type is decimal(6,5) you can use up to 6 total decimal digits, 5 of which will be reserved for after the decimal point (that is why you have additional 0-es after the decimal point).

That leaves you with 1 digit before (on the left of) the decimal point. And you are using 2.
That is why you have the error.

Title: Parameter value is out of range

Body:
It seems EF is padding zeros to the value that I'm trying to save and then throwing an exception.  Here is my code:  Why is the total hours field with a value of 10.17 out of range of a decimal(6,5) value type and why is it padding this value with zeros?  Saving this value directly using SQL Server Management Studio doesn't seem to be a problem, so it seems more like a problem with EF.

This is from a database first .edmx file.  I've tried setting the scale and precision and setting to none.  Neither have worked

 var rVal = new Data.FactPayrollHour()
                {
                    BereavementHours = 0.0M,
                    CostCenter = "MyCostCenter",
                    Department = "MyDepartment",
                    EmergencyHours = 0.0M,
                    HomeGroupCode = "MyHomeGroup",
                    PayrollEmployeeId = employees.FirstOrDefault().Id,
                    PayType = "MyPayType",
                    PunchDateKey = dateDims.FirstOrDefault().ID,
                    Schedule = "",
                    ServiceHours = 0.0M,
                    Shift = "",
                    ShortTermHours = 0.0M,
                    TimePolicy = "",
                    TotalHours = 10.17M,
                    UnpaidHours = 0.0M,
                    VacationHours = 0.0M
                };
                db.FactPayrollHours.Add(rVal);
                db.SaveChanges();

The exception message is: Parameter value '10.17000' is out of range.

Stack Trace:

   at System.Data.SqlClient.TdsParser.TdsExecuteRPC(SqlCommand cmd, _SqlRPC[] rpcArray, Int32 timeout, Boolean inSchema, SqlNotificationRequest notificationRequest, TdsParserStateObject stateObj, Boolean isCommandProc, Boolean sync, TaskCompletionSource`1 completion, Int32 startRpc, Int32 startParam)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
   at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
   at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext`1 c)
   at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
   at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
   at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues)
   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()


问:
Where is kill_proc_info defined?
what is header file for the kernel API function kill_proc_info(int sig, struct siginfo *info, pid_t pid)</p>

答: You can probably found this in linux/signal.c and include/linux/sched.h

Title: Where is kill_proc_info defined?


问:
How do I hide previous slide in a simple jQuery slideshow?
I'm creating an online portfolio for my girlfriend and for that a simple slideshow of images with fade transitions. I want to be able to "hide" the previous "last-active" slide, when a new "active" one is shown.

I've modified the slideshow provided here (http://jonraasch.com/blog/a-simple-jquery-slideshow), so instead of an automatic cycle, it is controlled by 'prev / next' buttons. That all works great.
Contrary to the above example, I need to have different sized images in the slideshow.

Problem: The way the slideshow works, like a stack of images, I'm seeing the previous image behind the current "active" one. E.g. when switching between a vertical (portrait) image and a horizontal (landscape) image, i can see the landscape one behind the portrait one.

I've tried the jQuery .hide() method within the $nextSlide() function, but not sure if that's the right way to do it. I'm a complete javascript and jQuery novice.

HTML:

prev / next

```

<p>CSS:</p>

<pre class="lang-css prettyprint-override"><code>#slideshow {
    position:relative;
    height:400px;
}

#slideshow DIV {
    position:absolute;
    top:0;
    left:0;
    z-index:8;
    opacity:0.0;
    height: 400px;
    background-color: white;
}

#slideshow DIV.active {
    z-index:10;
    opacity:1.0;
}

#slideshow DIV.last-active {
    z-index:9;
}

#slideshow DIV IMG {
    height: 350px;
    display: block;
    border: 0;
    margin-bottom: 10px;
}
</code>```

JavaScript:

```<code>function nextSlide() {
    var $active = $('#slideshow DIV.active');
    if ( $active.length == 0 ) $active = $('#slideshow DIV:last');

    var $next =  $active.next().length ? $active.next()
        : $('#slideshow DIV:first');

    $active.addClass('last-active');
    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 300, function() {
            $active.removeClass('active last-active');
        });
}
$(".control-next").click(function(){
    nextSlide();
    });

´´´

The goal is to have a slideshow that doesn't show the images like a stack. I bet the solution is very simple, but I can't work it out.
</code>```

答:
After removing the active and last-active classes from your div... reset their opacity back to 0.0 so next time it will animate (fade in) again:

```<code>function nextSlide() {
    var $active = $('#slideshow DIV.active');
    if ( $active.length == 0 ) $active = $('#slideshow DIV:last');

    var $next =  $active.next().length ? $active.next()
        : $('#slideshow DIV:first');

    $active.addClass('last-active');
    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 300, function() {
            $active.css({opacity: 0.0})
                   .removeClass('active last-active');
        });
}
</code>```

If you also want it to fade-out, rather than just going to opacity 0... use the following:

```<code>$next.css({opacity: 0.0})
            .addClass('active')
            .animate({opacity: 1.0}, 300, function() {
                $active.css({opacity: 1.0})
                       .animate({opacity: 0.0}, 300, function(){
                          $active.removeClass('active last-active')
                       });
            });
</code>```

Body:
I'm creating an online portfolio for my girlfriend and for that a simple slideshow of images with fade transitions. I want to be able to "hide" the previous "last-active" slide, when a new "active" one is shown.

I've modified the slideshow provided here (http://jonraasch.com/blog/a-simple-jquery-slideshow), so instead of an automatic cycle, it is controlled by 'prev / next' buttons. That all works great.
Contrary to the above example, I need to have different sized images in the slideshow.

Problem: The way the slideshow works, like a stack of images, I'm seeing the previous image behind the current "active" one. E.g. when switching between a vertical (portrait) image and a horizontal (landscape) image, i can see the landscape one behind the portrait one.

I've tried the jQuery .hide() method within the $nextSlide() function, but not sure if that's the right way to do it. I'm a complete javascript and jQuery novice.

HTML:

prev / next

CSS:

#slideshow {
    position:relative;
    height:400px;
}

#slideshow DIV {
    position:absolute;
    top:0;
    left:0;
    z-index:8;
    opacity:0.0;
    height: 400px;
    background-color: white;
}

#slideshow DIV.active {
    z-index:10;
    opacity:1.0;
}

#slideshow DIV.last-active {
    z-index:9;
}

#slideshow DIV IMG {
    height: 350px;
    display: block;
    border: 0;
    margin-bottom: 10px;
}

JavaScript:

function nextSlide() {
    var $active = $('#slideshow DIV.active');
    if ( $active.length == 0 ) $active = $('#slideshow DIV:last');

    var $next =  $active.next().length ? $active.next()
        : $('#slideshow DIV:first');

    $active.addClass('last-active');
    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 300, function() {
            $active.removeClass('active last-active');
        });
}
$(".control-next").click(function(){
    nextSlide();
    });

´´´

The goal is to have a slideshow that doesn't show the images like a stack. I bet the solution is very simple, but I can't work it out.

Body:
After removing the active and last-active classes from your div... reset their opacity back to 0.0 so next time it will animate (fade in) again:

function nextSlide() {
    var $active = $('#slideshow DIV.active');
    if ( $active.length == 0 ) $active = $('#slideshow DIV:last');

    var $next =  $active.next().length ? $active.next()
        : $('#slideshow DIV:first');

    $active.addClass('last-active');
    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 300, function() {
            $active.css({opacity: 0.0})
                   .removeClass('active last-active');
        });
}

If you also want it to fade-out, rather than just going to opacity 0... use the following:

$next.css({opacity: 0.0})
            .addClass('active')
            .animate({opacity: 1.0}, 300, function() {
                $active.css({opacity: 1.0})
                       .animate({opacity: 0.0}, 300, function(){
                          $active.removeClass('active last-active')
                       });
            });


问:
Hitting a nullPointerExecption in my android project
Hi Iam trying to make a chat app. In this process Iam trying to retrieve messages stored in database but Iam getting a Null Object reference exception.

The code I used to add messages to database is:

```<code>    img_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String msg = text_send.getText().toString();
            if(!msg.equals(""))
                sendMessage(fuser.getUid(), currUserId, msg);
            else
                Toast.makeText(MessageActivity.this, "Enter Something",
            Toast.LENGTH_SHORT).show();
         }
       });

  private void sendMessage(String sender,String receiver,String message)
  {
    DatabaseReference reference =
    FirebaseDatabase.getInstance().getReference();
    HashMap<String,Object>hashMap = new HashMap<>();
    hashMap.put("sender",sender);
    hashMap.put("receiver",receiver);
    hashMap.put("message",message);

    reference.child("Chats").push().setValue(hashMap);

}
</code>```

NOTE:The above part of code is working fine. My database is getting updated correctly every time I send message.

After this part I tried to display messages of users, using the following code

```<code>     DatabaseReference chatref =
     FirebaseDatabase.getInstance().getReference().child("Chats");
     ArrayList<String> userchats = new ArrayList<>();

     listView = findViewById(R.id.listView);
     final ArrayAdapter <String> arrayAdapter = new ArrayAdapter<String>
     (this,android.R.layout.simple_list_item_1,userchats);
     listView.setAdapter(arrayAdapter);

     chatref.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(@NonNull DataSnapshot dataSnapshot,
        @Nullable String s) {

            String value = dataSnapshot.getValue().toString();
            try {
                JSONObject object = new JSONObject(value);
                message = object.getString("message");
            }
            catch (JSONException e) {
                e.printStackTrace();
            }
            userchats.add(message);
            arrayAdapter.notifyDataSetChanged();
        }

        @Override
        public void onChildChanged(@NonNull DataSnapshot dataSnapshot,
         @Nullable String s) {

        }

        @Override
        public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(@NonNull DataSnapshot dataSnapshot,
        @Nullable String s) {

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
        });
</code>```

When I ran the app at this moment Iam getting error and my stacktrace is as follows:

```<code>         Process: com.kcw.firebasebasics, PID: 10943
         java.lang.NullPointerException: Attempt to invoke virtual method
         'java.lang.String java.lang.Object.toString()' on a null object
         reference at android.widget.ArrayAdapter.
         createViewFromResource(ArrayAdapter.java:401)
         at android.widget.ArrayAdapter.getView(ArrayAdapter.java:369)
         at android.widget.AbsListView.obtainView(AbsListView.java:2346)
         at android.widget.ListView.makeAndAddView(ListView.java:1875)
</code>```

Finally a picture of my database:

答:
Your chatref refer to the "Chats" key witch is not a String. That´s maybe why you get the

'java.lang.String java.lang.Object.toString()' on a null object

You should parse the dataSnapshot into a class like this example

```<code>Comment comment = dataSnapshot.getValue(Comment.class);
</code>```

And the Comment class have the message receiver Sender variables

Check this Work with Lists of Data from Firebase doc

And finally here is the Firebase Android Codelab showing how to create a complete chat app called Friendly Chat

Body:
Hi Iam trying to make a chat app. In this process Iam trying to retrieve messages stored in database but Iam getting a Null Object reference exception.

The code I used to add messages to database is:

    img_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String msg = text_send.getText().toString();
            if(!msg.equals(""))
                sendMessage(fuser.getUid(), currUserId, msg);
            else
                Toast.makeText(MessageActivity.this, "Enter Something",
            Toast.LENGTH_SHORT).show();
         }
       });

  private void sendMessage(String sender,String receiver,String message)
  {
    DatabaseReference reference =
    FirebaseDatabase.getInstance().getReference();
    HashMap<String,Object>hashMap = new HashMap<>();
    hashMap.put("sender",sender);
    hashMap.put("receiver",receiver);
    hashMap.put("message",message);

    reference.child("Chats").push().setValue(hashMap);

}

NOTE:The above part of code is working fine. My database is getting updated correctly every time I send message.

After this part I tried to display messages of users, using the following code

     DatabaseReference chatref =
     FirebaseDatabase.getInstance().getReference().child("Chats");
     ArrayList<String> userchats = new ArrayList<>();

     listView = findViewById(R.id.listView);
     final ArrayAdapter <String> arrayAdapter = new ArrayAdapter<String>
     (this,android.R.layout.simple_list_item_1,userchats);
     listView.setAdapter(arrayAdapter);

     chatref.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(@NonNull DataSnapshot dataSnapshot,
        @Nullable String s) {

            String value = dataSnapshot.getValue().toString();
            try {
                JSONObject object = new JSONObject(value);
                message = object.getString("message");
            }
            catch (JSONException e) {
                e.printStackTrace();
            }
            userchats.add(message);
            arrayAdapter.notifyDataSetChanged();
        }

        @Override
        public void onChildChanged(@NonNull DataSnapshot dataSnapshot,
         @Nullable String s) {

        }

        @Override
        public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(@NonNull DataSnapshot dataSnapshot,
        @Nullable String s) {

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
        });

When I ran the app at this moment Iam getting error and my stacktrace is as follows:

         Process: com.kcw.firebasebasics, PID: 10943
         java.lang.NullPointerException: Attempt to invoke virtual method
         'java.lang.String java.lang.Object.toString()' on a null object
         reference at android.widget.ArrayAdapter.
         createViewFromResource(ArrayAdapter.java:401)
         at android.widget.ArrayAdapter.getView(ArrayAdapter.java:369)
         at android.widget.AbsListView.obtainView(AbsListView.java:2346)
         at android.widget.ListView.makeAndAddView(ListView.java:1875)

Finally a picture of my database:

Body:
Your chatref refer to the "Chats" key witch is not a String. That´s maybe why you get the

'java.lang.String java.lang.Object.toString()' on a null object

You should parse the dataSnapshot into a class like this example

Comment comment = dataSnapshot.getValue(Comment.class);

And the Comment class have the message receiver Sender variables

Check this Work with Lists of Data from Firebase doc

And finally here is the Firebase Android Codelab showing how to create a complete chat app called Friendly Chat


问:
ASP.NET Page_Load values are lagging one postback behind
I have a foreach loop in the Page_Load method of my one page to determine whether to Enable a button or not.

Code:

```<code>foreach (var class in classes)
{
    for (var i = studentsList.Count - 1; i >= 0; i--)
    {
        if (studentsList[i].Id == class.student_id)
            studenstList.Remove(studentsList[i]);
    }
}
if (studentsList.Count == 0)
{
    button1.Enabled = false;
    button1.Text = "a";
}
else
{
    button1.Enabled = true;
    button1.Text = "b";
}
if (Page.IsPostBack) { return; }
</code>```

The issue:

The value of studentsList.Count is lagging behind by a postback. If after the loop it should be 1, it only has the value of 1 at the next postback. I've debugged to confirm this is the case.

答: Does the button press edit students list?  If so, the code for the button press will be fired after the Page_Load code.</p>

Body:
I have a foreach loop in the Page_Load method of my one page to determine whether to Enable a button or not.

Code:

foreach (var class in classes)
{
    for (var i = studentsList.Count - 1; i >= 0; i--)
    {
        if (studentsList[i].Id == class.student_id)
            studenstList.Remove(studentsList[i]);
    }
}
if (studentsList.Count == 0)
{
    button1.Enabled = false;
    button1.Text = "a";
}
else
{
    button1.Enabled = true;
    button1.Text = "b";
}
if (Page.IsPostBack) { return; }

The issue:

The value of studentsList.Count is lagging behind by a postback. If after the loop it should be 1, it only has the value of 1 at the next postback. I've debugged to confirm this is the case.


问:
How to use html special special characters as normal string
How to convert HTML special characters as normal string...

For example:

```<code><h1>Copy Right Symbol 𝕔</h1>
</code>```

I want to print &copf as normal string...

答:
I will display &copf

I will display &copf

I will display "&"copf

I will display &copf

Body:
How to convert HTML special characters as normal string...

For example:

Copy Right Symbol 𝕔

I want to print &copf as normal string...