问:
How to put underline under button name
I have button with name "itemname", and now I want to put underline just under character "i" in "itemname", but I don't know how I should do this. Could anyone please tell me how?</p>

答:
Do you mean you want Alt+I to click the button?

Have you tried changing the label text from itemname to &itemname?

Title: How to put underline under button name


来源: stackexchange

问:
batch backup that reads number from a text file doesn't work for values below 9
The following code works when version.txt is 9 or greater (tested for 98 to 101 and works as expected):

```<code>set /p Build=<version.txt
set /a NewBuild=%Build%+1
set TMP=backup_%Build%
if not exist "%TMP%" (
    @echo %NewBuild%> version.txt

    mkdir "%TMP%"
    cd "%TMP%"
    for /r "C:\xampp\htdocs\testzone\main" %%F in (*.*) do (
        cls
        if exist "%%F" (
            if not exist "%%~nxF" (
                xcopy /h "%%F" "%%~nxF"
                pause > nul
            )
        )
    )
)
</code>```

But it won't work for values 1, 2, 3, 4, 5, 6, 7 or 8, when I run the code with numbers from 1 to 8 the folder is created and everything is copied correctly but version.txt changes to an empty file.

答:
change

```<code>@echo %NewBuild%> version.txt
</code>```

to

```<code>> version.txt @echo %NewBuild%
</code>```

a sungle numeric directly before a redirector causes redirection of device#n (1=stdout, 2=stderr, 0=stdin, others not used.

ContentLicense: CC BY-SA 3.0

Body:
The following code works when version.txt is 9 or greater (tested for 98 to 101 and works as expected):

set /p Build=<version.txt
set /a NewBuild=%Build%+1
set TMP=backup_%Build%
if not exist "%TMP%" (
    @echo %NewBuild%> version.txt

    mkdir "%TMP%"
    cd "%TMP%"
    for /r "C:\xampp\htdocs\testzone\main" %%F in (*.*) do (
        cls
        if exist "%%F" (
            if not exist "%%~nxF" (
                xcopy /h "%%F" "%%~nxF"
                pause > nul
            )
        )
    )
)

But it won't work for values 1, 2, 3, 4, 5, 6, 7 or 8, when I run the code with numbers from 1 to 8 the folder is created and everything is copied correctly but version.txt changes to an empty file.

Body:
change

@echo %NewBuild%> version.txt

to

> version.txt @echo %NewBuild%

a sungle numeric directly before a redirector causes redirection of device#n (1=stdout, 2=stderr, 0=stdin, others not used.


问:
Find a deleted number from a list
Considering two lists (a sequence of numbers from 1 to N (arr) and the same sequence mixed but missing one number (mixed_arr)). The goal is to find the number that was deleted.

Example:

```<code>arr = [1,2,3,4,5]
mixed_arr = [3,4,1,5]
</code>```

The output should be 2.

Return 0 if no number was deleted and if there is no difference
If no number was deleted from the array and no difference with it, the function has to return 0. Note that N may be 1 or less (in the latter case, the first array will be []).

Testcases:

```<code>arr = [1,2,3,4,5,6,7,8,9]
mixed_arr = [1,9,7,4,6,2,3,8]
output = 5

arr = [1,2,3,4,5,6,7,8,9]
mixed_arr = [5,7,6,9,4,8,1,2,3]
output = 0
</code>```

Here's my code:

```<code>def find_deleted_number(arr, mixed_arr):
    arr.sort()
    mixed_arr.sort()

    for x in range(arr):
        for y in range(mixed_arr):
            if arr[x] != mixed_arr[y]:
                return arr[x]
            elif arr[x] == mixed_arr[y]:
                return 0
</code>```

The error I get is:

```<code>Traceback:
   in <module>
   in find_deleted_number
TypeError: 'list' object cannot be interpreted as an integer
</code>```

答:
You could simply use symmetric_difference(), a member of set:

set(arr).symmetric_difference(mixed_arr)
```

<p>See also sets. </p>

<p>Please note, as pointed out by DeepSpace in the comments, if it is guaranteed that both lists contain integers from 1 to N, with the exception of one missing in one of those lists, the much more efficient solution is to compute the absolute value of the difference of the sum of both lists:</p>

```abs(sum(arr) - sum(mixed_arr))
```

<hr>

<p><strong>The error you're getting:</strong></p>

<p>You're getting the error because of this line:</p>

```for x in range(arr): # arr is a list, not an int
```

<p>You surely intended to pass the length of the array:</p>

```for x in range(len(arr)):
```

The same goes for the inner loop.

Title: Find a deleted number from a list

Body:
Considering two lists (a sequence of numbers from 1 to N (arr) and the same sequence mixed but missing one number (mixed_arr)). The goal is to find the number that was deleted.

Example:

arr = [1,2,3,4,5]
mixed_arr = [3,4,1,5]

The output should be 2.

Return 0 if no number was deleted and if there is no difference
If no number was deleted from the array and no difference with it, the function has to return 0. Note that N may be 1 or less (in the latter case, the first array will be []).

Testcases:

arr = [1,2,3,4,5,6,7,8,9]
mixed_arr = [1,9,7,4,6,2,3,8]
output = 5

arr = [1,2,3,4,5,6,7,8,9]
mixed_arr = [5,7,6,9,4,8,1,2,3]
output = 0

Here's my code:

def find_deleted_number(arr, mixed_arr):
    arr.sort()
    mixed_arr.sort()

    for x in range(arr):
        for y in range(mixed_arr):
            if arr[x] != mixed_arr[y]:
                return arr[x]
            elif arr[x] == mixed_arr[y]:
                return 0

The error I get is:

Traceback:
   in <module>
   in find_deleted_number
TypeError: 'list' object cannot be interpreted as an integer

Body:
You could simply use symmetric_difference(), a member of set:

set(arr).symmetric_difference(mixed_arr)

See also sets.

Please note, as pointed out by DeepSpace in the comments, if it is guaranteed that both lists contain integers from 1 to N, with the exception of one missing in one of those lists, the much more efficient solution is to compute the absolute value of the difference of the sum of both lists:

abs(sum(arr) - sum(mixed_arr))

The error you're getting:

You're getting the error because of this line:

for x in range(arr): # arr is a list, not an int

You surely intended to pass the length of the array:

for x in range(len(arr)):

The same goes for the inner loop.


问:
convert 12-hour hh:mm AM/PM to 24-hour hh:mm
Is there any simple way to convert 12-hour hh:mm AM/PM to 24-hour hh:mm using jquery?

Note: not using any other libraries.

I have a var time = $("#starttime").val() that returns a hh:mm AM/PM.

答:
```<code>function timeConversion(s) {
  var time = s.toLowerCase().split(':');
  var hours = parseInt(time[0]);
  var _ampm = time[2];
  if (_ampm.indexOf('am') != -1 && hours == 12) {
    time[0] = '00';
  }
  if (_ampm.indexOf('pm')  != -1 && hours < 12) {
    time[0] = hours + 12;
  }
  return time.join(':').replace(/(am|pm)/, '');
}
</code>```

Call the function with string params:

```<code>timeConversion('17:05:45AM')
</code>```

or

```<code>timeConversion('07:05:45PM')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
function timeConversion(s) {
  var time = s.toLowerCase().split(':');
  var hours = parseInt(time[0]);
  var _ampm = time[2];
  if (_ampm.indexOf('am') != -1 && hours == 12) {
    time[0] = '00';
  }
  if (_ampm.indexOf('pm')  != -1 && hours < 12) {
    time[0] = hours + 12;
  }
  return time.join(':').replace(/(am|pm)/, '');
}

Call the function with string params:

timeConversion('17:05:45AM')

or

timeConversion('07:05:45PM')


问:
LDAP SearchResponse to Json C#
I am using a C# LdapConnection to get a SearchResponse at work.  I can get the SearchResponse into a Json string, but am unable to put that Json string into an object class with properties which mimic the SearchResponse.  The Json string is properly formatted.  Am I using the Newtonsoft.Json library in the wrong way?  Is there a better way to do this?  My only requirements are that I get a SearchResponse into my object class (DirectoryEntity) so I can use it from there.

My Console Application:

```<code>class Program
    {
        static void Main(string[] args)
        {
            LdapClient client = new LdapClient();
            List<LdapSearchResponseModel> list = new List<LdapSearchResponseModel>();
            string query = "(|(uupid=name1)(uupid=name2))";
            string[] attributes = new string[] { };
            string host = "id.directory.univ";
            int port = 1234;
            SearchResponse response = client.RawQuery(query, attributes, host, port);

            string json = JsonConvert.SerializeObject(response);

            var test = JsonConvert.DeserializeObject<DirectoryEntities>(json);
        }
    }
</code>```

My DirectoryEntity Class:

```<code>public class DirectoryEntity
    {
        public string EntityDN { get; set; }
        public int MailStop { get; set; }
        public List<string> UniversityAffiliation { get; set; }
        public int UniversityId { get; set; }
        public string GivenName { get; set; }
        public string Title { get; set; }
        public string PasswordState { get; set; }
        public string MiddleName { get; set; }
        public string AccountState { get; set; }
        public int Uid { get; set; }
        public string Mail { get; set; }
        public string MailPreferredAddress { get; set; }
        public DateTime DateOfBirth { get; set; }
        public List<string> GroupMembership { get; set; }
        public string DegreeType { get; set; }
        public int ClassLevelCode { get; set; }
        public string AuthId { get; set; }
        public string Major { get; set; }
        public string ClassLevel { get; set; }
        public bool SupressDisplay { get; set; }
        public string UnderGraduateLevel { get; set; }
        public string ObjectClass { get; set; }
        public int DepartmentNumber { get; set; }
        public List<string> EduPersonAffiliation { get; set; }
        public string LocalPostalAddress { get; set; }
        public string Uupid { get; set; }
        public string LocalPhone { get; set; }
        public string TelephoneNumber { get; set; }
        public string Department { get; set; }
        public string Sn { get; set; }
    }
</code>```

My DirectoryEntities Class:

```<code>public class DirectoryEntities
{
    public List<DirectoryEntity> Entities { get; set; }
    public int Count { get; set; }
}
</code>```

答:
Have you tried explicitly defining a default constructor for the DirectoryEntity class? I believe that Newtonsoft requires objects to have a default constructor before they can be deserialized. Try adding this to the DirectoryEntity class: </p>

```<code>public DirectoryEntity() { }
</code>```

Title: LDAP SearchResponse to Json C#

Body:
I am using a C# LdapConnection to get a SearchResponse at work.  I can get the SearchResponse into a Json string, but am unable to put that Json string into an object class with properties which mimic the SearchResponse.  The Json string is properly formatted.  Am I using the Newtonsoft.Json library in the wrong way?  Is there a better way to do this?  My only requirements are that I get a SearchResponse into my object class (DirectoryEntity) so I can use it from there.

My Console Application:

class Program
    {
        static void Main(string[] args)
        {
            LdapClient client = new LdapClient();
            List<LdapSearchResponseModel> list = new List<LdapSearchResponseModel>();
            string query = "(|(uupid=name1)(uupid=name2))";
            string[] attributes = new string[] { };
            string host = "id.directory.univ";
            int port = 1234;
            SearchResponse response = client.RawQuery(query, attributes, host, port);

            string json = JsonConvert.SerializeObject(response);

            var test = JsonConvert.DeserializeObject<DirectoryEntities>(json);
        }
    }

My DirectoryEntity Class:

public class DirectoryEntity
    {
        public string EntityDN { get; set; }
        public int MailStop { get; set; }
        public List<string> UniversityAffiliation { get; set; }
        public int UniversityId { get; set; }
        public string GivenName { get; set; }
        public string Title { get; set; }
        public string PasswordState { get; set; }
        public string MiddleName { get; set; }
        public string AccountState { get; set; }
        public int Uid { get; set; }
        public string Mail { get; set; }
        public string MailPreferredAddress { get; set; }
        public DateTime DateOfBirth { get; set; }
        public List<string> GroupMembership { get; set; }
        public string DegreeType { get; set; }
        public int ClassLevelCode { get; set; }
        public string AuthId { get; set; }
        public string Major { get; set; }
        public string ClassLevel { get; set; }
        public bool SupressDisplay { get; set; }
        public string UnderGraduateLevel { get; set; }
        public string ObjectClass { get; set; }
        public int DepartmentNumber { get; set; }
        public List<string> EduPersonAffiliation { get; set; }
        public string LocalPostalAddress { get; set; }
        public string Uupid { get; set; }
        public string LocalPhone { get; set; }
        public string TelephoneNumber { get; set; }
        public string Department { get; set; }
        public string Sn { get; set; }
    }

My DirectoryEntities Class:

public class DirectoryEntities
{
    public List<DirectoryEntity> Entities { get; set; }
    public int Count { get; set; }
}

Body:
Have you tried explicitly defining a default constructor for the DirectoryEntity class? I believe that Newtonsoft requires objects to have a default constructor before they can be deserialized. Try adding this to the DirectoryEntity class:

public DirectoryEntity() { }


问:
Javascript check dropdown value against textbox
I need to check textbox value against dropdown list, and if that value does not exist, add to the list.

I have this script:

```<code>            <select id="drop" onchange="ChooseContact(this)">
              <option value="Volvo Red">Volvo Red</option>
              <option value="Mers Blue">Mers Blue</option>
              <option value="Ferr red">Ferr red</option>
            </select>

function execute(data) {
    var txtbox = document.getElementById ("txtServiceReportInspectedBy").value;
        if ( document.createElement('option').value != txtbox ) {
            var categories = document.getElementById("drop");
            var newOption = document.createElement('option');
            newOption.innerText = txtbox ;
            newOption.setAttribute('value', txtbox );
            categories.appendChild(newOption);
        }
    document.getElementById("drop").value = txtbox ;
}
</code>```

But the new item is still created in the dropdown list, eventhough such item already there. Thanks.

答:
You are not searching for the text among the options. Here is how you could do that:

add.addEventListener('click', execute);

function execute(data) {
    var txtbox = txtServiceReportInspectedBy.value,
        optionTexts = Array.from(document.querySelectorAll('#drop>option'),
                                 option => option.value);
    if ( !optionTexts.includes(txtbox) ) {
        var newOption = document.createElement('option');
        newOption.value = newOption.textContent = txtbox ;
        drop.appendChild(newOption);
    }
    drop.value = txtbox;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="txtServiceReportInspectedBy"><button id="add">Add</button><br>
<select id="drop">
  <option value="Volvo Red">Volvo Red</option>
  <option value="Mers Blue">Mers Blue</option>
  <option value="Ferr red">Ferr red</option>
</select></code>```

Body:
I need to check textbox value against dropdown list, and if that value does not exist, add to the list.

I have this script:

            <select id="drop" onchange="ChooseContact(this)">
              <option value="Volvo Red">Volvo Red</option>
              <option value="Mers Blue">Mers Blue</option>
              <option value="Ferr red">Ferr red</option>
            </select>

function execute(data) {
    var txtbox = document.getElementById ("txtServiceReportInspectedBy").value;
        if ( document.createElement('option').value != txtbox ) {
            var categories = document.getElementById("drop");
            var newOption = document.createElement('option');
            newOption.innerText = txtbox ;
            newOption.setAttribute('value', txtbox );
            categories.appendChild(newOption);
        }
    document.getElementById("drop").value = txtbox ;
}

But the new item is still created in the dropdown list, eventhough such item already there. Thanks.

Body:
You are not searching for the text among the options. Here is how you could do that:

add.addEventListener('click', execute);

function execute(data) {
    var txtbox = txtServiceReportInspectedBy.value,
        optionTexts = Array.from(document.querySelectorAll('#drop>option'),
                                 option => option.value);
    if ( !optionTexts.includes(txtbox) ) {
        var newOption = document.createElement('option');
        newOption.value = newOption.textContent = txtbox ;
        drop.appendChild(newOption);
    }
    drop.value = txtbox;
}

<input id="txtServiceReportInspectedBy"><button id="add">Add</button><br>
<select id="drop">
  <option value="Volvo Red">Volvo Red</option>
  <option value="Mers Blue">Mers Blue</option>
  <option value="Ferr red">Ferr red</option>
</select>


问:
Detect when a user clicks off a marker
So I am using Google Maps in my app and I am customising the onMarkerClick event to show a button.

Is it possible to detect when a user clicks "off" the marker e.g. tapping the map itself, or scrolling maybe? Anything that means the marker loses focus.

答:
In my case, when the user clicks the marker, the corresponding Info window appears. So when the user clicks in the map outside the marker, the Info Window closes and that event is detected by the map. This is useful only when the marker has an Info Window.

```<code>// Detect when Marker's Info Window is closed
    googleMap.setOnInfoWindowCloseListener(new GoogleMap.OnInfoWindowCloseListener() {
        @Override
        public void onInfoWindowClose(Marker marker) {
            // Do whatever you want to do here...
        }
    });
</code>```

Title: Detect when a user clicks off a marker

Body:
In my case, when the user clicks the marker, the corresponding Info window appears. So when the user clicks in the map outside the marker, the Info Window closes and that event is detected by the map. This is useful only when the marker has an Info Window.

// Detect when Marker's Info Window is closed
    googleMap.setOnInfoWindowCloseListener(new GoogleMap.OnInfoWindowCloseListener() {
        @Override
        public void onInfoWindowClose(Marker marker) {
            // Do whatever you want to do here...
        }
    });


答:
I tried to mock your problem.
If you are not concerned about time complexity, this is the simplest solution that I can suggest.

```<code>a = c(1,3,5)
b = c(2,4,6)

df = data.frame(a, b)
d1 = c()
d2 = c()

for(counter in 1:length(df$a))
{
  d1 = c(d1,df$a[counter],df$b[counter])
  d2 = c(d2,1,2)
}

df = data.frame(d1, d2)
print(df)
</code>```

Input:

a b

1 2

3 4

5 6

Output:

d1 d2

1  1

2  2

3  1

4  2

5  1

6  2

Title: Merge two columns, set value based upon original

Body:
I have a data.frame looking like this:

date1                  date2
2015-09-17 03:07:00    2015-09-17 11:53:00
2015-09-17 08:00:00    2015-09-18 11:48:59
2015-09-18 15:58:00    2015-09-22 12:14:00
2015-09-22 12:14:00    2015-09-24 13:58:21

I'd like to combine these two into one column, something like:

dates
2015-09-17 03:07:00
2015-09-17 11:53:00
2015-09-17 08:00:00
2015-09-18 11:48:59
2015-09-18 15:58:00
2015-09-22 12:14:00
2015-09-22 12:14:00
2015-09-24 13:58:21

Please note that dates (like the last but one and the last but two) can be equal. Now I'd like to add a column 'value'. For every date that has it's origin in date1, the value should be 1, if it's origin is in date2, it should be 2.

Adding a new column is obvious. Merging works fine. I've used:

df <- as.data.frame(df$date1)
df <- data.frame(date1 = c(df$date1, test$date2 ))

That works perfectly fine for the merging of the columns, but how to get the correct value for df$value?

The result should be:

dates                  value
2015-09-17 03:07:00    1
2015-09-17 11:53:00    2
2015-09-17 08:00:00    1
2015-09-18 11:48:59    2
2015-09-18 15:58:00    1
2015-09-22 12:14:00    1
2015-09-22 12:14:00    2
2015-09-24 13:58:21    1

Body:
I tried to mock your problem.
If you are not concerned about time complexity, this is the simplest solution that I can suggest.

a = c(1,3,5)
b = c(2,4,6)

df = data.frame(a, b)
d1 = c()
d2 = c()

for(counter in 1:length(df$a))
{
  d1 = c(d1,df$a[counter],df$b[counter])
  d2 = c(d2,1,2)
}

df = data.frame(d1, d2)
print(df)

Input:

a b

1 2

3 4

5 6

Output:

d1 d2

1  1

2  2

3  1

4  2

5  1

6  2


问:
How to combine two sql expressions into one?
I have the following issue:

It is necessary to write a query that will output 'item_id', 'price_in_byr'.

'price_in_byr' is calculated as the 'price' of the items table multiplied by the currency rate at the maximum date of the rate from the table rates.

See Schema

I apologize for my English, I'll try to explain by example:

Goods with item_id = 5 costs 20 euros, in the rates table the maximum date for the euro is January 12, at that date the exchange rate was 25.  Total our 'price_in_byr' is 25 * 20 = 500

My solution with temp table:

```<code>CREATE TABLE tempRate SELECT currency, MAX(rate) AS maxRate FROM rates GROUP
BY currency;

SELECT items.item_id,(ifnull(tempRate.maxRate,1) * items.price) AS price_in_byr
FROM items
LEFT JOIN tempRate ON items.currency = tempRate.currency;
</code>```

Tell me please, how can I do it in one query?

答:
You can just use a subquery:

```<code>SELECT
    items.item_id,(ifnull(tempRate.maxRate,1) * items.price) AS price_in_byr
FROM
    items
    LEFT JOIN
    (
    SELECT
        currency, MAX(rate) AS maxRate
    FROM
        rates
    GROUP BY
        currency
    ) AS tempRate
    ON items.currency = tempRate.currency;
</code>```

In practice, you substitute "tempRate" by (definition of tempRate) AS tempRate.

You can see an example at dbfiddle here

If you actually want the * most_recent_rate*, you'd do something completely different; insert a subquery to compute it. This subquery looks for all rates of the given currency, sorts them by their exchange_ts (meaning timestamp) in descending order, and just picks to top 1:

```<code>SELECT
    items.item_id,(ifnull(
    (
        SELECT
            rate AS most_recent_rate
        FROM
            rates
        WHERE
            rates.currency = items.currency
        ORDER BY
            exchange_ts DESC
        LIMIT 1
    )
    , 1) * items.price) AS price_in_byr
FROM
    items ;
</code>```

dbfiddle here

Body:
I have the following issue:

It is necessary to write a query that will output 'item_id', 'price_in_byr'.

'price_in_byr' is calculated as the 'price' of the items table multiplied by the currency rate at the maximum date of the rate from the table rates.

See Schema

I apologize for my English, I'll try to explain by example:

Goods with item_id = 5 costs 20 euros, in the rates table the maximum date for the euro is January 12, at that date the exchange rate was 25.  Total our 'price_in_byr' is 25 * 20 = 500

My solution with temp table:

CREATE TABLE tempRate SELECT currency, MAX(rate) AS maxRate FROM rates GROUP
BY currency;

SELECT items.item_id,(ifnull(tempRate.maxRate,1) * items.price) AS price_in_byr
FROM items
LEFT JOIN tempRate ON items.currency = tempRate.currency;

Tell me please, how can I do it in one query?

Body:
You can just use a subquery:

SELECT
    items.item_id,(ifnull(tempRate.maxRate,1) * items.price) AS price_in_byr
FROM
    items
    LEFT JOIN
    (
    SELECT
        currency, MAX(rate) AS maxRate
    FROM
        rates
    GROUP BY
        currency
    ) AS tempRate
    ON items.currency = tempRate.currency;

In practice, you substitute "tempRate" by (definition of tempRate) AS tempRate.

You can see an example at dbfiddle here

If you actually want the * most_recent_rate*, you'd do something completely different; insert a subquery to compute it. This subquery looks for all rates of the given currency, sorts them by their exchange_ts (meaning timestamp) in descending order, and just picks to top 1:

SELECT
    items.item_id,(ifnull(
    (
        SELECT
            rate AS most_recent_rate
        FROM
            rates
        WHERE
            rates.currency = items.currency
        ORDER BY
            exchange_ts DESC
        LIMIT 1
    )
    , 1) * items.price) AS price_in_byr
FROM
    items ;

dbfiddle here


问:
OpenCL: conversion from ' float* ' to ' cl_mem '
In caffe source code (branch opencl),  sometimes I can see some like these(eg. in      src/caffe/layers/base_conv_layer.cpp line 400):

```<code>void func(cl_mem a, ...)
{...}

void func2(float* a, ...)
{
    ...
    func( (cl_mem) a, ...);
    ...
}
</code>```

I think it is really strange, so I googled it, but got nothing about it.

Then I wrote a simple test code to figure out what happened, but I found this conversion is meaningless:

```<code>std::cout << long((void*)a) << " " << long((void*)(cl_mem(a))) << std::endl;
</code>```

Their value is same !

So my question is why this conversion raises no problem in caffe opencl ?
What happened in this conversion ?

答: If you look into class SyncedMemory (in include/caffe/syncedmem.hpp and src/caffe/syncedmem.cpp), you will find that a memory buffer is first created by clCreateBuffer and the handle is stored as a cl_mem object. The handle is then cast to type DType* when gpu_data() or mutable_gpu_data() is called. It can therefore be cast back to type cl_mem because it is a cl_mem object in the first place.

Body:
In caffe source code (branch opencl),  sometimes I can see some like these(eg. in      src/caffe/layers/base_conv_layer.cpp line 400):

void func(cl_mem a, ...)
{...}

void func2(float* a, ...)
{
    ...
    func( (cl_mem) a, ...);
    ...
}

I think it is really strange, so I googled it, but got nothing about it.

Then I wrote a simple test code to figure out what happened, but I found this conversion is meaningless:

std::cout << long((void*)a) << " " << long((void*)(cl_mem(a))) << std::endl;

Their value is same !

So my question is why this conversion raises no problem in caffe opencl ?
What happened in this conversion ?


答:
You can make your tempRate query into a subquery:

```<code>SELECT
    items.item_id,
    (ifnull(tempRate.maxRate,1) * items.price) AS price_in_byr
FROM
    items
    LEFT JOIN (
        SELECT currency, MAX(rate) AS maxRate
        FROM rates
        GROUP BY currency
        ) as tempRate ON items.currency = tempRate.currency;
</code>```

Title: How to combine two sql expressions into one?

Body:
You can make your tempRate query into a subquery:

SELECT
    items.item_id,
    (ifnull(tempRate.maxRate,1) * items.price) AS price_in_byr
FROM
    items
    LEFT JOIN (
        SELECT currency, MAX(rate) AS maxRate
        FROM rates
        GROUP BY currency
        ) as tempRate ON items.currency = tempRate.currency;


问:
How to make a single button appear active in android
I have been learning java for a little while and am working on an android app.  I am trying to implement a boolean logic for my image buttons nested in a linear layout whereby just one button should show active button while the others are not.
For now each button can toggle between active and inactive but i don't want two ore more buttons showing active at the same time. I want a single one showing an active button at a time. </p>

```<code> public void showAudio(View view) {
        if (!audioButtonClicked) {
            audioButtonClicked = true;
            audioWindowButton.setImageResource(R.drawable.audio_active);
        } else {
            audioWindowButton.setImageResource(R.drawable.audio_inactive);
            audioButtonClicked = false;
        }

        }

    public void showEvents(View view) {
       if(!eventButtonClicked ) {
eventWindowButton.setImageResource(R.drawable.event_active);
           eventButtonClicked = true;
       } else {
           eventWindowButton.setImageResource(R.drawable.event_inactive);
           eventButtonClicked = false;
       }
    }

    public void showMore(View view) {
        if(!moreButtonClicked) {
            moreWindowButton.setImageResource(R.drawable.event_active);
            moreButtonClicked = true;

        } else {
            moreWindowButton.setImageResource(R.drawable.event_inactive);
            moreButtonClicked = false;
        }
    }
</code>```

答:
You can use ViewSwitcher. put items in it and switch between them. only one is gonna show up. Below is an ex. with 2 view.

In layout_main.xml

```<code><ViewSwitcher
        android:id="@+id/viewSwitcher"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/text1"
            android:text="previous"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
        </TextView>

        <TextView
            android:id="@+id/text2"
            android:text="next"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
        </TextView>

</ViewSwitcher>
</code>```

In the MainActivity.java

```<code>viewSwitcher =   (ViewSwitcher)findViewById(R.id.viewSwitcher);
        text1= (TextView)findViewById(R.id.text1);
        text2 = (TextView) findViewById(R.id.text2);
        button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                if (viewSwitcher.getCurrentView() != text1){
                       viewSwitcher.showPrevious();
                } else if (viewSwitcher.getCurrentView() != text2){
                    viewSwitcher.showNext();
                }
            }
        });
</code>```

Body:
I have been learning java for a little while and am working on an android app.  I am trying to implement a boolean logic for my image buttons nested in a linear layout whereby just one button should show active button while the others are not.
For now each button can toggle between active and inactive but i don't want two ore more buttons showing active at the same time. I want a single one showing an active button at a time.

 public void showAudio(View view) {
        if (!audioButtonClicked) {
            audioButtonClicked = true;
            audioWindowButton.setImageResource(R.drawable.audio_active);
        } else {
            audioWindowButton.setImageResource(R.drawable.audio_inactive);
            audioButtonClicked = false;
        }

        }

    public void showEvents(View view) {
       if(!eventButtonClicked ) {
eventWindowButton.setImageResource(R.drawable.event_active);
           eventButtonClicked = true;
       } else {
           eventWindowButton.setImageResource(R.drawable.event_inactive);
           eventButtonClicked = false;
       }
    }

    public void showMore(View view) {
        if(!moreButtonClicked) {
            moreWindowButton.setImageResource(R.drawable.event_active);
            moreButtonClicked = true;

        } else {
            moreWindowButton.setImageResource(R.drawable.event_inactive);
            moreButtonClicked = false;
        }
    }

Body:
You can use ViewSwitcher. put items in it and switch between them. only one is gonna show up. Below is an ex. with 2 view.

In layout_main.xml

<ViewSwitcher
        android:id="@+id/viewSwitcher"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/text1"
            android:text="previous"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
        </TextView>

        <TextView
            android:id="@+id/text2"
            android:text="next"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
        </TextView>

</ViewSwitcher>

In the MainActivity.java

viewSwitcher =   (ViewSwitcher)findViewById(R.id.viewSwitcher);
        text1= (TextView)findViewById(R.id.text1);
        text2 = (TextView) findViewById(R.id.text2);
        button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                if (viewSwitcher.getCurrentView() != text1){
                       viewSwitcher.showPrevious();
                } else if (viewSwitcher.getCurrentView() != text2){
                    viewSwitcher.showNext();
                }
            }
        });


问:
filter out nodes with certain id expression using xpath
Currently I've got following example xpaths of the nodes I want:

```<code>/html
 /body
  /div[@id='wp']
   /div[@id='ct']
    /div
     /div[@id='threadlist']
      /div[2]
       /form
        /table
         /tbody[@id='normalthread_1174131']
          /tr
           /th
            /a
</code>```

And something I don't need:

```<code>/html
 /body
  /div[@id='wp']
   /div[@id='ct']
    /div
     /div[@id='threadlist']
      /div[2]
       /form
        /table
         /tbody[@id='stickthread_1174132']
          /tr
           /th
            /a
</code>```

Of course, I could select them all using:

```<code>/html/body/div[@id='wp']/div[@id='ct']/div/div[@id='threadlist']
                                           /div[2]/form/table/tbody[@id]/tr/th/a
</code>```

But I only want to select nodes with id normalthread_xxx. As each node has different id. In other words, the target page may have following nodes:

```<code>/html/body/div[@id='wp']
           /div[@id='ct']
            /div/div[@id='threadlist']
                 /div[2]/form/table/tbody[@id='normalthread_1174133']
                                    /tr/th/a

/html/body/div[@id='wp']
           /div[@id='ct']
            /div/div[@id='threadlist']
                 /div[2]/form/table/tbody[@id='normalthread_1174134']
                                    /tr/th/a
</code>```

Can we have something similar to

```<code>/html/body/div[@id='wp']
           /div[@id='ct']
            /div/div[@id='threadlist']
                 /div[2]/form/table/tbody[@id='normalthread_XXX']
                                    /tr/th/a
</code>```

, in order to filter all the nodes here?

答:
You should be able to use starts-with() (part of XPath 1.0):

```<code>/html/body/(...)/form/table/tbody[starts-with(@id,'normalthread_')]/tr/th/a
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Currently I've got following example xpaths of the nodes I want:

/html
 /body
  /div[@id='wp']
   /div[@id='ct']
    /div
     /div[@id='threadlist']
      /div[2]
       /form
        /table
         /tbody[@id='normalthread_1174131']
          /tr
           /th
            /a

And something I don't need:

/html
 /body
  /div[@id='wp']
   /div[@id='ct']
    /div
     /div[@id='threadlist']
      /div[2]
       /form
        /table
         /tbody[@id='stickthread_1174132']
          /tr
           /th
            /a

Of course, I could select them all using:

/html/body/div[@id='wp']/div[@id='ct']/div/div[@id='threadlist']
                                           /div[2]/form/table/tbody[@id]/tr/th/a

But I only want to select nodes with id normalthread_xxx. As each node has different id. In other words, the target page may have following nodes:

/html/body/div[@id='wp']
           /div[@id='ct']
            /div/div[@id='threadlist']
                 /div[2]/form/table/tbody[@id='normalthread_1174133']
                                    /tr/th/a

/html/body/div[@id='wp']
           /div[@id='ct']
            /div/div[@id='threadlist']
                 /div[2]/form/table/tbody[@id='normalthread_1174134']
                                    /tr/th/a

Can we have something similar to

/html/body/div[@id='wp']
           /div[@id='ct']
            /div/div[@id='threadlist']
                 /div[2]/form/table/tbody[@id='normalthread_XXX']
                                    /tr/th/a

, in order to filter all the nodes here?

Body:
You should be able to use starts-with() (part of XPath 1.0):

/html/body/(...)/form/table/tbody[starts-with(@id,'normalthread_')]/tr/th/a


问:
Javascript loop through array asynchronous
I'm making a bot code for a game running on NodeJS and what this function is supposed to do is to loop through an array of vectors and then make the bot go to each vector.

However, what it's actually doing is telling the bot to run to all the vectors at the same time so it spazzes out and then runs to the last vector in the array:

```<code>function digSchedule() {
    var arrayLength = blocksToMine.length;
    for (var i = 0; i < blocksToMine.length; i++) {
        console.log(i);
        scaffoldTo(blocksToMine[i]);
    }
    ...
}
</code>```

The function scaffoldTo() needs to be ran and then wait for the bot to do said function then run it for the next element in the array, but I can't figure out how to do it.

答:
There's several ways to achieve this.  The first is probably to pass a callback with the "next function to be called" (probably scaffoldTo()).  You can use .bind() to create a reference with the iterator index i.

Alternatively, you could set up a loop of Promises, which by definition have a .then() method which executes once the promise is resolved.

Finally, the async/await pattern is similar to Promises, but some find it clearer and it seems to be winning the Hype Wars: https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec10518dd9.

Callbacks (solution 1) will be available in any version of JS.  Promises  generally available with a library and have native support in ES6. Async/await is a proposal (?) in ES2017 and is generally well supported.

Body:
I'm making a bot code for a game running on NodeJS and what this function is supposed to do is to loop through an array of vectors and then make the bot go to each vector.

However, what it's actually doing is telling the bot to run to all the vectors at the same time so it spazzes out and then runs to the last vector in the array:

function digSchedule() {
    var arrayLength = blocksToMine.length;
    for (var i = 0; i < blocksToMine.length; i++) {
        console.log(i);
        scaffoldTo(blocksToMine[i]);
    }
    ...
}

The function scaffoldTo() needs to be ran and then wait for the bot to do said function then run it for the next element in the array, but I can't figure out how to do it.


问:
How to create nested group in ssrs
Sorry if this is a basic question, but I just started with SSRS and wasn't able to find something on google.
Let's say I have a data that is returned in the form (Column1, Column2, Column3, Column4). I am trying to build a report that would group first on Column1 and then on Column2. For example if my query returns a result:

```<code>Column1 Column2 Column3 Column 4
Type A  Item A  Name 1  1
Type A  Item A  Name 2  2
Type A  Item B  Name 3  3
Type B  Item A  Name 4  4
</code>```

I would like to see something like

```<code>Column1 Column2 Column3 Column 4
Type A  Item A  Name 1  1
Type A  Item A  Name 2  2
Type A  Item B  Name 3  3
Type B  Item A  Name 4  4

    Type A
    Item A
Name 1  1
Name 2  2
Total:  3
    Item B
Name 3  3
Total:  3
    Type B
    Item B
Name 4  4
Total:  4
</code>```

答:
Right click on your Tablix and select Add Group -> Parent Group. Group on Column 1. Next, select the same row and do it again but this time select Child Group. Set the grouping to Column 2.

The tablix will automagically group your data based on Column 1 first, then Column 2, and this will be reflected in your totals. To add a total the way you specified in your question, you're going to want to total based on the outer group, so you'd right click on the row and select Add Total. Sometimes it does not allow you to do this (depending on how your report is set up) so you could simply do Sum(Column4) in a textbox below - inside the outer group and outside the inner group - to achieve this result.

Title: How to create nested group in ssrs

Body:
Sorry if this is a basic question, but I just started with SSRS and wasn't able to find something on google.
Let's say I have a data that is returned in the form (Column1, Column2, Column3, Column4). I am trying to build a report that would group first on Column1 and then on Column2. For example if my query returns a result:

Column1 Column2 Column3 Column 4
Type A  Item A  Name 1  1
Type A  Item A  Name 2  2
Type A  Item B  Name 3  3
Type B  Item A  Name 4  4

I would like to see something like

Column1 Column2 Column3 Column 4
Type A  Item A  Name 1  1
Type A  Item A  Name 2  2
Type A  Item B  Name 3  3
Type B  Item A  Name 4  4

    Type A
    Item A
Name 1  1
Name 2  2
Total:  3
    Item B
Name 3  3
Total:  3
    Type B
    Item B
Name 4  4
Total:  4


问:
Application Insights tracking only failed ASP.NET MVC Web API requests
I have a ASP.NET Web API controller that provides a saveAndNew operation.

This class is derived from System.Web.Http.ApiController as expected.

Application Insights is correctly configured using version 2.1.0 of the SDK and the default settings in ApplicationInsights.config.

If a request to the mentioned operation fails - for example with status code 400 - the request is recorded correctly in App Insights.

The problem is that if the operation SUCCEEDS (status code 200) nothing is recorded in Application Insights.

I've used Fiddler to see if the request is made to the App Insights track service and it is not. So the problem is not in the configuration of Application Insights on the Azure portal.

I can't figure out what is preventing ALL requests to my Web API controllers operations from being recorded.

Can anyone help?

答:
You might want to try removing/commenting out TransferRequestHandler in ApplicationInsights.config file.

GitHub issue "REST API app can have all requests filtered out" here states that: "commenting out the one line in the ApplicationInsights.config caused successful requests to start getting logged. Web API 2 project.

```<code><!--<Add>System.Web.Handlers.TransferRequestHandler</Add>-->
</code>```

Body:
You might want to try removing/commenting out TransferRequestHandler in ApplicationInsights.config file.

GitHub issue "REST API app can have all requests filtered out" here states that: "commenting out the one line in the ApplicationInsights.config caused successful requests to start getting logged. Web API 2 project.

<!--<Add>System.Web.Handlers.TransferRequestHandler</Add>-->


问:
NSDate Swift 3 - EVReflection
I'm using EVReflection and Date does not work. And with NSDate I don't know how to format to string like 'dd-MM-yyyy HH:mm'. </p>

答:
Two things:

First:
You need to ask a specific question, always with Code similar to, or the actual code that shows what you're trying to acomplish.. None of these are here.

Second:
What you are trying to do is not possible unfortunately. Looking at EVReflection, it's property setter .setObjectForKey doesn't work with structs, and if you look at the Title of the page of Date in the apple docs.. it is a struct. Do your research!

EVReflection suggests :

Instead of using a struct, create your own object model for that
  struct

So you'll have to try that, and see if it works.

As for your NSDate format, use an extension like this one found in this post here:

```<code>extension Date {

    var currentUTCTimeZoneDate: String {
        let formatter = DateFormatter()
        formatter.timeZone = TimeZone(identifier: "UTC")
        formatter.amSymbol = "AM"
        formatter.pmSymbol = "PM"
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

        return formatter.string(from: self)
    }
}
</code>```

Which you can use on NSDate:

```<code>extension NSDate {

    var currentUTCTimeZoneDate: String {
        return (self as Date).currentUTCTimeZoneDate
    }
}

let d = NSDate().currentUTCTimeZoneDate
print(d) // prints 2017-07-07 22:19:22
</code>```

Title: NSDate Swift 3 - EVReflection

Body:
Two things:

First:
You need to ask a specific question, always with Code similar to, or the actual code that shows what you're trying to acomplish.. None of these are here.

Second:
What you are trying to do is not possible unfortunately. Looking at EVReflection, it's property setter .setObjectForKey doesn't work with structs, and if you look at the Title of the page of Date in the apple docs.. it is a struct. Do your research!

EVReflection suggests :

Instead of using a struct, create your own object model for that
  struct

So you'll have to try that, and see if it works.

As for your NSDate format, use an extension like this one found in this post here:

extension Date {

    var currentUTCTimeZoneDate: String {
        let formatter = DateFormatter()
        formatter.timeZone = TimeZone(identifier: "UTC")
        formatter.amSymbol = "AM"
        formatter.pmSymbol = "PM"
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

        return formatter.string(from: self)
    }
}

Which you can use on NSDate:

extension NSDate {

    var currentUTCTimeZoneDate: String {
        return (self as Date).currentUTCTimeZoneDate
    }
}

let d = NSDate().currentUTCTimeZoneDate
print(d) // prints 2017-07-07 22:19:22


问:
In C++, is there a defined order of operations when assigning an expression into an object when the expression involves that object?
Consider the following C++ code that uses Qt's container class QMap:

```<code>#include <QMap>
#include <iostream>

QMap<int, int> myMap;

int count() {
    return myMap.size();
}

int main() {
    myMap[0] = count();
    std::cout << myMap[0] << std::endl;
    return 0;
}
</code>```

Depending on whether myMap has a new entry created in it before or after count() is executed, this code's output will be either 1 or 0 respectively.

Does the output of this code depend on the implementation of QMap? Or does the C++ specification make any guarantees about when count() will be executed in relation to QMap::operator[]? Or could the result be undefined and this is a situation that's best avoided?

I ask because I had an essentially identical situation in a program I was working on. When I compiled the program in Windows and ran it using the stock Qt 5.5.1 DLLs, the result was 0. However, when I ran it using a different set of Qt 5.5.1 DLLs that had been compiled from source, the result was 1. It was an awfully confusing bug that took me a little while to track down, particularly since I got different results depending on where I ran the executable!

I'm hoping that I can understand how there was two different behaviors for the same program so that I might be able to avoid bugs like this in the future.

答:
Your problem here:

```<code>myMap[0] = count();
</code>```

is that the whole assignment is an expression and the call to count() is a sub-expression. There is no sequence point between expressions and sub-expressions.

This is not about evaluation order but about the ordering of side effects. An assignment has a side effect, in this case, it adds a new element to your QMap. Only at a sequence point, you have the guarantee that all side effects resulting from code before the sequence point are completed.

A function call is a sequence point, but it's between the evaluation of the function arguments and the actual calls -- not related to the return value. As you don't have any arguments here, it doesn't apply in this case.

So yes, this is undefined behavior and you should avoid it. For reference, here's a quite exhaustive answer on the topic of sequence points.

The solution of course is simple: Use two separate statements. The end of a statement (;) is always a sequence point.

Body:
Consider the following C++ code that uses Qt's container class QMap:

#include <QMap>
#include <iostream>

QMap<int, int> myMap;

int count() {
    return myMap.size();
}

int main() {
    myMap[0] = count();
    std::cout << myMap[0] << std::endl;
    return 0;
}

Depending on whether myMap has a new entry created in it before or after count() is executed, this code's output will be either 1 or 0 respectively.

Does the output of this code depend on the implementation of QMap? Or does the C++ specification make any guarantees about when count() will be executed in relation to QMap::operator[]? Or could the result be undefined and this is a situation that's best avoided?

I ask because I had an essentially identical situation in a program I was working on. When I compiled the program in Windows and ran it using the stock Qt 5.5.1 DLLs, the result was 0. However, when I ran it using a different set of Qt 5.5.1 DLLs that had been compiled from source, the result was 1. It was an awfully confusing bug that took me a little while to track down, particularly since I got different results depending on where I ran the executable!

I'm hoping that I can understand how there was two different behaviors for the same program so that I might be able to avoid bugs like this in the future.

Body:
Your problem here:

myMap[0] = count();

is that the whole assignment is an expression and the call to count() is a sub-expression. There is no sequence point between expressions and sub-expressions.

This is not about evaluation order but about the ordering of side effects. An assignment has a side effect, in this case, it adds a new element to your QMap. Only at a sequence point, you have the guarantee that all side effects resulting from code before the sequence point are completed.

A function call is a sequence point, but it's between the evaluation of the function arguments and the actual calls -- not related to the return value. As you don't have any arguments here, it doesn't apply in this case.

So yes, this is undefined behavior and you should avoid it. For reference, here's a quite exhaustive answer on the topic of sequence points.

The solution of course is simple: Use two separate statements. The end of a statement (;) is always a sequence point.


问:
Prevent error_log() messages to be printed to the terminal during tests
As the title states, I'm looking forward to finding a way to prevent the error_log() message to be printed in the terminal during my PHPUnit tests.

In the example above, the method under test passes through an error_log('Don\'t show up'), printing its message between the tests.

Is there any way to prevent this behavior, to keep my test log fancy? Also, is there any way to catch the message and test its output? (for the cases where the message isn't a simple string).

答:
Is there any way to prevent this behavior, to keep my test log fancy? Also, is there any way to catch the message and test its output? (for the cases where the message isn't a simple string).

First of all what you see is not the test log. The error message that is displayed is actually on the standard error stream and not the standard output stream. For what you see this makes not much of a difference as the terminal shows both intermixed, logging to file would not log that error message.

This is b/c error_log() writes the error message to the configured logfile (PHP's error_log ini directive). As Phpunit runs with the CLI version of PHP (on the command-line), this by default is the said standard error stream.

This also contains all needed information to not output to the standard error stream but to capture it, e.g. temporarily for a test:

```<code>$capture = tmpfile();
$saved = ini_set('error_log', stream_get_meta_data($capture)['uri']);
error_log("Test for this message");
ini_set('error_log', $saved);
var_dump(stream_get_contents($capture));
</code>```

This will provide the contents output via error_log() and via a temporary file:

```<code>string(59) "[06-Jul-2017 12:14:45 Europe/Amsterdam] Test for this message
"
</code>```

The temporary file is removed automatically when the test-case ends.

Body:
Is there any way to prevent this behavior, to keep my test log fancy? Also, is there any way to catch the message and test its output? (for the cases where the message isn't a simple string).

First of all what you see is not the test log. The error message that is displayed is actually on the standard error stream and not the standard output stream. For what you see this makes not much of a difference as the terminal shows both intermixed, logging to file would not log that error message.

This is b/c error_log() writes the error message to the configured logfile (PHP's error_log ini directive). As Phpunit runs with the CLI version of PHP (on the command-line), this by default is the said standard error stream.

This also contains all needed information to not output to the standard error stream but to capture it, e.g. temporarily for a test:

$capture = tmpfile();
$saved = ini_set('error_log', stream_get_meta_data($capture)['uri']);
error_log("Test for this message");
ini_set('error_log', $saved);
var_dump(stream_get_contents($capture));

This will provide the contents output via error_log() and via a temporary file:

string(59) "[06-Jul-2017 12:14:45 Europe/Amsterdam] Test for this message
"

The temporary file is removed automatically when the test-case ends.


问:
Extracting string of dates in a big query
I have used the below code  </p>

```<code>select --split( INDIVIDUAL_NAMES, '->') as Assigned_to_individual,

regexp_extract( split( INDIVIDUAL_NAMES, '->'),r'(\d\d/\d\d/\d\d\d\d \d\d:\d\d:\d\d)') from [table name ]where _ID  in('071632')
</code>```

<p>Here we need to extract date and i have given it a try by using d so it gives me numeric fields but this is not giving me complete date. </p>

答:
Since I do not have access to your table, I used WITH clause to emulate your input table, using the provided input sample. With that, the following query produces the desired output dates. Note that this is a StandardSQL query:

```<code>#standardSQL
WITH
  input AS (
  SELECT
    "Start -> (11/11/2016 08:24:24 AM) -> Akumar (11/11/2016 11:15:33 AM) -> Akumar (01/06/2017 08:08:44 PM) -> Akumar (01/30/2017 10:34:33 AM) -> Akumar (03/15/2017 02:10:12 PM) -> Akumar (03/23/2017 12:42:52 PM) -> Akumar (06/20/2017 12:52:27 PM) -> (06/27/2017 05:30:48 PM) -> Sneha Singh (06/28/2017 03:11:34 AM)" AS input_group),
  split_output AS (
  SELECT
    SPLIT(input_group, "->") AS output
  FROM
    input)
SELECT
  REGEXP_EXTRACT(output,r"(\d\d/\d\d/\d\d\d\d \d\d:\d\d:\d\d)") AS date
FROM
  split_output so,
  so.output
</code>```

Output (null is for the "Start" entry - note that sql output is not ordered):

```<code>Row date
1   03/15/2017 02:10:12
2   01/06/2017 08:08:44
3   11/11/2016 08:24:24
4   06/20/2017 12:52:27
5   06/28/2017 03:11:34
6   01/30/2017 10:34:33
7   06/27/2017 05:30:48
8   null
9   11/11/2016 11:15:33
10  03/23/2017 12:42:52
</code>```

Body:
I have used the below code

select --split( INDIVIDUAL_NAMES, '->') as Assigned_to_individual,

regexp_extract( split( INDIVIDUAL_NAMES, '->'),r'(\d\d/\d\d/\d\d\d\d \d\d:\d\d:\d\d)') from [table name ]where _ID  in('071632')

Here we need to extract date and i have given it a try by using d so it gives me numeric fields but this is not giving me complete date.

Body:
Since I do not have access to your table, I used WITH clause to emulate your input table, using the provided input sample. With that, the following query produces the desired output dates. Note that this is a StandardSQL query:

#standardSQL
WITH
  input AS (
  SELECT
    "Start -> (11/11/2016 08:24:24 AM) -> Akumar (11/11/2016 11:15:33 AM) -> Akumar (01/06/2017 08:08:44 PM) -> Akumar (01/30/2017 10:34:33 AM) -> Akumar (03/15/2017 02:10:12 PM) -> Akumar (03/23/2017 12:42:52 PM) -> Akumar (06/20/2017 12:52:27 PM) -> (06/27/2017 05:30:48 PM) -> Sneha Singh (06/28/2017 03:11:34 AM)" AS input_group),
  split_output AS (
  SELECT
    SPLIT(input_group, "->") AS output
  FROM
    input)
SELECT
  REGEXP_EXTRACT(output,r"(\d\d/\d\d/\d\d\d\d \d\d:\d\d:\d\d)") AS date
FROM
  split_output so,
  so.output

Output (null is for the "Start" entry - note that sql output is not ordered):

Row date
1   03/15/2017 02:10:12
2   01/06/2017 08:08:44
3   11/11/2016 08:24:24
4   06/20/2017 12:52:27
5   06/28/2017 03:11:34
6   01/30/2017 10:34:33
7   06/27/2017 05:30:48
8   null
9   11/11/2016 11:15:33
10  03/23/2017 12:42:52


问:
What is the equivalent of Java's Stream#Peek method in Linq C#?
I have been used to using Java's Stream#Peek method so much as it's a useful method to debug intermediate stream operation. For those of you who are not familiar with the Stream#Peek method, below shows the definition of it:

Stream<T> peek(Consumer<? super T> action)

Returns a stream consisting of the elements of this stream,
  additionally performing the provided action on each element as
  elements are consumed from the resulting stream. This is an
  intermediate operation.

Consider this simple example below:

```<code>List<Integer> integerList = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
List<Integer> result = integerList.stream()
                                  .filter(i -> i % 2 == 0)
                                  .peek(System.out::println)
                                  .collect(Collectors.toList());
</code>```

With the Stream#Peek method, this should basically allow me to print all the even numbers to the console so that I can test to see if that's what I would expect.

I have tried to find an answer to the question at hand but can't seem to find a similar method in C#, does anyone know the equivalent of Java's Stream#Peek or some other method with similar behavior?

答:
There is no equivalent of Peek in LINQ - i.e. there is no method which performs some action and returns source elements. There is a ForEach method in List class which performs an operation on each element, but it does not return source elements, and as already said, it's not an IEnumerable extension.

But you can easily write your own extension

```<code>public static IEnumerable<T> Peek<T>(this IEnumerable<T> source, Action<T> action)
{
    if (source == null) throw new ArgumentNullException(nameof(source));
    if (action == null) throw new ArgumentNullException(nameof(action));

    return Iterator();

    IEnumerable<T> Iterator() // C# 7 Local Function
    {
       foreach(var item in source)
       {
           action(item);
           yield return item;
       }
    }
}
</code>```

Body:
I have been used to using Java's Stream#Peek method so much as it's a useful method to debug intermediate stream operation. For those of you who are not familiar with the Stream#Peek method, below shows the definition of it:

Stream<T> peek(Consumer<? super T> action)

Returns a stream consisting of the elements of this stream,
  additionally performing the provided action on each element as
  elements are consumed from the resulting stream. This is an
  intermediate operation.

Consider this simple example below:

List<Integer> integerList = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
List<Integer> result = integerList.stream()
                                  .filter(i -> i % 2 == 0)
                                  .peek(System.out::println)
                                  .collect(Collectors.toList());

With the Stream#Peek method, this should basically allow me to print all the even numbers to the console so that I can test to see if that's what I would expect.

I have tried to find an answer to the question at hand but can't seem to find a similar method in C#, does anyone know the equivalent of Java's Stream#Peek or some other method with similar behavior?

Body:
There is no equivalent of Peek in LINQ - i.e. there is no method which performs some action and returns source elements. There is a ForEach method in List class which performs an operation on each element, but it does not return source elements, and as already said, it's not an IEnumerable extension.

But you can easily write your own extension

public static IEnumerable<T> Peek<T>(this IEnumerable<T> source, Action<T> action)
{
    if (source == null) throw new ArgumentNullException(nameof(source));
    if (action == null) throw new ArgumentNullException(nameof(action));

    return Iterator();

    IEnumerable<T> Iterator() // C# 7 Local Function
    {
       foreach(var item in source)
       {
           action(item);
           yield return item;
       }
    }
}


问:
Visual Python using a for loop to track a changing axis?
I have a giant array that I am importing from a text file holding 200,000 values which all describe how an arrow should be traversing along the x axis.  Mx is the name of the array that I have imported from this text file.  I am using visual python to try and simulate this movement across the axes.

```<code>    arrow = arrow(length = 1.0,pos = (0,0,0),axis=(0,0,0),color=color.blue)
    for i in range(len(Mx)):
     rate(60)
     arrow.axis.x = Mx[i]
</code>```

When I run my code the arrow remains stationary, and "QObject::killTimers: timers cannot be stopped from another thread" this error message pops up.  I am not sure why.  Any advice would be really helpful.

答:
What I found is that this fixed it for some reason.

```<code>arrow = arrow(length = 1.0,pos = (0,0,0),axis=(0,0,0),color=color.blue)
for i in range(len(Mx)):
 rate(60)
 x = Mx[i]
 arrow.axis.x = x
</code>```

Not 100 percent sure why, but I am guessing it has something to do with how python handles the array that I imported from the text file.

Body:
I have a giant array that I am importing from a text file holding 200,000 values which all describe how an arrow should be traversing along the x axis.  Mx is the name of the array that I have imported from this text file.  I am using visual python to try and simulate this movement across the axes.

    arrow = arrow(length = 1.0,pos = (0,0,0),axis=(0,0,0),color=color.blue)
    for i in range(len(Mx)):
     rate(60)
     arrow.axis.x = Mx[i]

When I run my code the arrow remains stationary, and "QObject::killTimers: timers cannot be stopped from another thread" this error message pops up.  I am not sure why.  Any advice would be really helpful.

Body:
What I found is that this fixed it for some reason.

arrow = arrow(length = 1.0,pos = (0,0,0),axis=(0,0,0),color=color.blue)
for i in range(len(Mx)):
 rate(60)
 x = Mx[i]
 arrow.axis.x = x

Not 100 percent sure why, but I am guessing it has something to do with how python handles the array that I imported from the text file.


问:
Autoplaying embedded Facebook videos in Qualtrics
I have created a qualtrics survey containing an assortment of embedded videos from Facebook. The videos appear in the survey and work perfectly, but I need them to autoplay - currently, the participant has to manually click play.

I am using the embedded code from Facebook and copying into the 'HTML View' textbox on the questions in the survey.

```<code><iframe src="https://www.facebook.com/plugins/video.php href=https%3A%2F%2Fwww.facebook.com%2Fcapitalismbethechange%2Fvideos%2F1825771414355523%2F&show_text=0&width=560" width="560" height="315" style="border:none;overflow:hidden" scrolling="no" frameborder="0" allowTransparency="true" allowFullScreen="true"></iframe>
</code>```

答:
Add &autoplay=1 at the end of the URL. </p>

```<code><iframe src="https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2FDSouzaDinesh%2Fvideos%2F1650157581677557%2F&show_text=0&width=560&autoplay=1" width="560" height="315" style="border:none;overflow:hidden" scrolling="no" frameborder="0" allowTransparency="true" allowFullScreen="true"></iframe>
</code>```

Body:
Add &autoplay=1 at the end of the URL.

<iframe src="https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2FDSouzaDinesh%2Fvideos%2F1650157581677557%2F&show_text=0&width=560&autoplay=1" width="560" height="315" style="border:none;overflow:hidden" scrolling="no" frameborder="0" allowTransparency="true" allowFullScreen="true"></iframe>


问:
Assigning Figures to a Variable with an operator
i'm fairly new to Python (using 2.7) and have run into an issue with assigning to variables.

I'm trying to assign a number to a variable and then use that variable to create a new variable and assign a list (or a value) to it. For example:

```<code>x = 15
"MA"+str(x) = [12,54]
print MA15
</code>```

The print MA15 should return the list [12,54]. The error I get is 'SyntaxError: can't assign to operator'.

I've tried other methods such as {"%s%s" % ("MA", str(Days))}, {exec()}, and {setattr()} functions.

答:
try using exec:</p>

```<code>x=15
string="MA%d=[12,54]"%(x)
exec(string)
</code>```

Body:
i'm fairly new to Python (using 2.7) and have run into an issue with assigning to variables.

I'm trying to assign a number to a variable and then use that variable to create a new variable and assign a list (or a value) to it. For example:

x = 15
"MA"+str(x) = [12,54]
print MA15

The print MA15 should return the list [12,54]. The error I get is 'SyntaxError: can't assign to operator'.

I've tried other methods such as {"%s%s" % ("MA", str(Days))}, {exec()}, and {setattr()} functions.

Body:
try using exec:

x=15
string="MA%d=[12,54]"%(x)
exec(string)


问:
Make phonecall through application
I am pretty sure the answer to this is no, but I want to be absolutely certain before I tell my boss. What I would like is to make a phone call through an application so that when the call is made, the user is taken to another screen of the application so I can have my own custom background or whatever for the call screen, and then when they have finished pop back to the original screen.

I did a few searches around and I know it was not possible prior to IOS 4, but I just want to check if IOS 5 added this functionality? Or is it still not possible to create something like this.

Thanks in advance!

答:
Try with this!</p>

```<code>let phoneNumber =  txtNum.text!;
        let called: NSURL = NSURL(string: "tel://\(phoneNumber)")!
        let options = [UIApplicationOpenURLOptionUniversalLinksOnly : false]

        UIApplication.shared.open(called as URL, options: options, completionHandler: { (success) in
            print("Open url : \(success)")
        })
</code>```

Title: Make phonecall through application

Body:
Try with this!

let phoneNumber =  txtNum.text!;
        let called: NSURL = NSURL(string: "tel://\(phoneNumber)")!
        let options = [UIApplicationOpenURLOptionUniversalLinksOnly : false]

        UIApplication.shared.open(called as URL, options: options, completionHandler: { (success) in
            print("Open url : \(success)")
        })


问:
JS returning a value gives "undefined"
i'm currently working with electron and I need to get some data from a mysql database, what is working good.

But there is a problem with sending values between functions. I'm kinda new to JS and electron, so maybe i just missed something:

```<code>function getUserData(user, data){

// connect
var connection = connect();

// Perform a query
$query = 'SELECT ' + data + ' FROM `users` WHERE user_id = ' + user;

// Query ausführen
connection.query($query, function(err, rows, fields) {
    if(err){
        console.log("There was an error with executing the query.");
        console.log(err);
        return;
    }

    return rows;
});

// End function
return;
}
</code>```

So basically i want to return "rows", but it says it's undefined.
Right above

```<code>return rows;
</code>```

if i check with

```<code>console.log(rows);
</code>```

it has data in it

Am i missing something?

Thanks in advance!

答:
Well, you actually return undefined with return;.

If it (connection.query) is synchronous then just do return connection.query(/*smth*/).
If it is asynchronous you won't be able to do that this easily and the best you can do is, in the function provided as argument, change the value of a variable that is globally defined (or return the Promise/"asynchronous handling" object if there's one).

Title: JS returning a value gives "undefined"

Body:
i'm currently working with electron and I need to get some data from a mysql database, what is working good.

But there is a problem with sending values between functions. I'm kinda new to JS and electron, so maybe i just missed something:

function getUserData(user, data){

// connect
var connection = connect();

// Perform a query
$query = 'SELECT ' + data + ' FROM `users` WHERE user_id = ' + user;

// Query ausführen
connection.query($query, function(err, rows, fields) {
    if(err){
        console.log("There was an error with executing the query.");
        console.log(err);
        return;
    }

    return rows;
});

// End function
return;
}

So basically i want to return "rows", but it says it's undefined.
Right above

return rows;

if i check with

console.log(rows);

it has data in it

Am i missing something?

Thanks in advance!


问:
How can I split a URL string up into separate parts in Python?
I decided that I'll learn Python tonight :)
I know C pretty well (wrote an OS in it), so I'm not a noob in programming, so everything in Python seems pretty easy, but I don't know how to solve this problem:
let's say I have this address:

http://example.com/random/folder/path.html

Now how can I create two strings from this, one containing the "base" name of the server, so in this example it would be

http://example.com/

and another containing the thing without the last filename, so in this example it would be

http://example.com/random/folder/

Also I of course know the possibility to just find the third and last slash respectively, but is there a better way?

Also it would be cool to have the trailing slash in both cases, but I don't care since it can be added easily.
So is there a good, fast, effective solution for this? Or is there only "my" solution, finding the slashes?

答:
If this is the extent of your URL parsing, Python's inbuilt rpartition will do the job:

```<code>>>> URL = "http://example.com/random/folder/path.html"
>>> Segments = URL.rpartition('/')
>>> Segments[0]
'http://example.com/random/folder'
>>> Segments[2]
'path.html'
</code>```

From Pydoc, str.rpartition:

Splits the string at the last occurrence of sep, and returns a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself

What this means is that rpartition does the searching for you, and splits the string at the last (right most) occurrence of the character you specify (in this case / ). It returns a tuple containing:

```<code>(everything to the left of char , the character itself , everything to the right of char)
</code>```

OwnerDisplayName: Language

LastEditorDisplayName: Simucal

Body:
If this is the extent of your URL parsing, Python's inbuilt rpartition will do the job:

>>> URL = "http://example.com/random/folder/path.html"
>>> Segments = URL.rpartition('/')
>>> Segments[0]
'http://example.com/random/folder'
>>> Segments[2]
'path.html'

From Pydoc, str.rpartition:

Splits the string at the last occurrence of sep, and returns a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself

What this means is that rpartition does the searching for you, and splits the string at the last (right most) occurrence of the character you specify (in this case / ). It returns a tuple containing:

(everything to the left of char , the character itself , everything to the right of char)

OwnerDisplayName: Mike Hamer

LastEditorDisplayName: Mike Hamer


问:
Is it a solvable problem to generate a regular expression that matches some input set?
I provide some input set which contains known separated number of text blocks.

I want to make a program that automatically generate 1 or more regular expressions each of which matches every text block in the input set.

I see some relatively easy ways to implement a brute-force search. But I'm not an expert in compilers theory. That's why I'm curious:

1) is this problem solvable? or there are some principle impossibility to make such algorithm?

2) is it possible to achieve polynomial complexity for this algorithm and avoid brute forcing?

答: ".*" is one-or-more regexp that will match every text block in the input set. ;-)</p>


问:
Big Query Analytic Functions Improve Query Performance
Pretty new to big query and hitting timeouts on a 100M point dataset.  I'm trying to find the points at which we reach a consistent series of values around 0 (stops) and points at which we consistently get above 0 (starts).

I saved the subquery that's being joined that determines the start file times to it's own dataset, but that didn't help. (seconds increments through multiple "files."

The part causing the problem is the initial aggregation of previous pts and next pts.

```<code>WITH test AS
 (SELECT 'A' as ACM, CAST('2017-01-01' AS DATE) as file_date, CAST('10:10:10' AS TIME) as file_time , 0.0 as value, 0.1 as seconds
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', 0, 0.2 #start
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', 2000, 0.3
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', 1000, 0.4
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', 0, 0.5
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', -1000, 0.6
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', -2000, 0.7
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', 0, 0.8 #stop
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', 0, 0.9
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 0, 1.0 #start
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 1000, 1.1
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 1000, 1.2
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 2000, 1.3
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 0, 1.4
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 0, 1.5
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', -1000, 1.6
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', -2000, 1.7
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 0, 1.8
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 1000, 1.9
  UNION ALL SELECT 'A', '2017-01-01', '10:10:12', 2000, 2.0
  UNION ALL SELECT 'A', '2017-01-01', '10:10:12', 1000, 2.1
  UNION ALL SELECT 'A', '2017-01-01', '10:10:12', 0, 2.2 #stop
  UNION ALL SELECT 'A', '2017-01-01', '10:10:12', 20, 2.3
  UNION ALL SELECT 'A', '2017-01-01', '10:10:12', 0, 2.4
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', 0, 0.1
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', 0, 0.2 #start
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', 2000, 0.3
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', 1000, 0.4
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', 0, 0.5
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', -1000, 0.6
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', -2000, 0.7
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', 0, 0.8 #stop
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', 0, 0.9
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 0, 1.0 #start
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 1000, 1.1
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 1000, 1.2
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 2000, 1.3
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 0, 1.4
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 0, 1.5
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', -1000, 1.6
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', -2000, 1.7
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 0, 1.8
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 1000, 1.9
  UNION ALL SELECT 'B', '2017-01-01', '10:10:12', 2000, 2.0
  UNION ALL SELECT 'B', '2017-01-01', '10:10:12', 1000, 2.1
  UNION ALL SELECT 'B', '2017-01-01', '10:10:12', 0, 2.2 #stop
  UNION ALL SELECT 'B', '2017-01-01', '10:10:12', 20, 2.3
  UNION ALL SELECT 'B', '2017-01-01', '10:10:12', 0, 2.4 )
SELECT
  acm,
  file_date,
  start_file_time,
  file_times,
  agg_sec as start_stop
FROM (
  SELECT
    acm,
    file_date,
    start_file_time,
    file_times,
    ARRAY_AGG(kind) OVER w AS agg_kind,
    ARRAY_AGG(seconds)  OVER w AS agg_sec
  FROM (
    SELECT
      acm,
      file_date,
      start_file_time,
      ARRAY(SELECT DISTINCT x FROM UNNEST(file_times) as x) AS file_times,
      seconds,
      CASE
      WHEN (ABS(prev_val) < 50 and ABS(next_val) >= 50 and next_avg >= 50 and prev_avg < 50 ) THEN 'start'
      WHEN (ABS(next_val) < 50 and ABS(prev_val) >= 50 and prev_avg >= 50 and next_avg < 50 ) THEN 'stop'
      END as kind,
      prev_val, next_val, prev_avg, next_avg
    FROM (
      SELECT
        s.acm as acm,
        s.file_date as file_date,
        s.start_file_time as start_file_time,
        seconds,
        value,
        ARRAY_AGG(s.file_time) OVER (PARTITION BY s.acm, s.file_date, s.start_file_time) as file_times,
        AVG(ABS(value)) OVER prev as prev_avg,
        NTH_VALUE(value, 2) OVER prev as prev_val,
        AVG(ABS(value)) OVER next as next_avg,
        NTH_VALUE(value, 2) OVER next as next_val
      FROM test v
      JOIN (
        SELECT
          acm,
          file_date,
          file_time,
          TIME_SUB(file_time, INTERVAL CAST(FLOOR(MIN(seconds)) AS INT64) SECOND) as start_file_time
        FROM test
        GROUP BY acm, file_date, file_time
      ) s ON s.acm = v.acm AND s.file_date = v.file_date AND s.file_time = v.file_time
      WINDOW prev AS (PARTITION BY s.acm, s.file_date, s.start_file_time ORDER BY seconds ROWS 2 PRECEDING), next AS (PARTITION BY s.acm, s.file_date, s.start_file_time ORDER BY seconds ROWS BETWEEN CURRENT ROW AND 2 FOLLOWING)
      )
    WHERE value = 0)
  WHERE kind IN ('start', 'stop')
  WINDOW w AS (PARTITION BY acm, file_date, start_file_time ORDER BY seconds ROWS 1 PRECEDING))
WHERE ARRAY_LENGTH(agg_kind) = 2 AND agg_kind[ORDINAL(1)] = 'start' AND agg_kind[ORDINAL(2)] = 'stop'
;
</code>```

Body:
Pretty new to big query and hitting timeouts on a 100M point dataset.  I'm trying to find the points at which we reach a consistent series of values around 0 (stops) and points at which we consistently get above 0 (starts).

I saved the subquery that's being joined that determines the start file times to it's own dataset, but that didn't help. (seconds increments through multiple "files."

The part causing the problem is the initial aggregation of previous pts and next pts.

WITH test AS
 (SELECT 'A' as ACM, CAST('2017-01-01' AS DATE) as file_date, CAST('10:10:10' AS TIME) as file_time , 0.0 as value, 0.1 as seconds
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', 0, 0.2 #start
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', 2000, 0.3
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', 1000, 0.4
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', 0, 0.5
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', -1000, 0.6
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', -2000, 0.7
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', 0, 0.8 #stop
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', 0, 0.9
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 0, 1.0 #start
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 1000, 1.1
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 1000, 1.2
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 2000, 1.3
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 0, 1.4
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 0, 1.5
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', -1000, 1.6
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', -2000, 1.7
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 0, 1.8
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 1000, 1.9
  UNION ALL SELECT 'A', '2017-01-01', '10:10:12', 2000, 2.0
  UNION ALL SELECT 'A', '2017-01-01', '10:10:12', 1000, 2.1
  UNION ALL SELECT 'A', '2017-01-01', '10:10:12', 0, 2.2 #stop
  UNION ALL SELECT 'A', '2017-01-01', '10:10:12', 20, 2.3
  UNION ALL SELECT 'A', '2017-01-01', '10:10:12', 0, 2.4
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', 0, 0.1
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', 0, 0.2 #start
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', 2000, 0.3
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', 1000, 0.4
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', 0, 0.5
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', -1000, 0.6
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', -2000, 0.7
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', 0, 0.8 #stop
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', 0, 0.9
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 0, 1.0 #start
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 1000, 1.1
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 1000, 1.2
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 2000, 1.3
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 0, 1.4
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 0, 1.5
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', -1000, 1.6
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', -2000, 1.7
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 0, 1.8
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 1000, 1.9
  UNION ALL SELECT 'B', '2017-01-01', '10:10:12', 2000, 2.0
  UNION ALL SELECT 'B', '2017-01-01', '10:10:12', 1000, 2.1
  UNION ALL SELECT 'B', '2017-01-01', '10:10:12', 0, 2.2 #stop
  UNION ALL SELECT 'B', '2017-01-01', '10:10:12', 20, 2.3
  UNION ALL SELECT 'B', '2017-01-01', '10:10:12', 0, 2.4 )
SELECT
  acm,
  file_date,
  start_file_time,
  file_times,
  agg_sec as start_stop
FROM (
  SELECT
    acm,
    file_date,
    start_file_time,
    file_times,
    ARRAY_AGG(kind) OVER w AS agg_kind,
    ARRAY_AGG(seconds)  OVER w AS agg_sec
  FROM (
    SELECT
      acm,
      file_date,
      start_file_time,
      ARRAY(SELECT DISTINCT x FROM UNNEST(file_times) as x) AS file_times,
      seconds,
      CASE
      WHEN (ABS(prev_val) < 50 and ABS(next_val) >= 50 and next_avg >= 50 and prev_avg < 50 ) THEN 'start'
      WHEN (ABS(next_val) < 50 and ABS(prev_val) >= 50 and prev_avg >= 50 and next_avg < 50 ) THEN 'stop'
      END as kind,
      prev_val, next_val, prev_avg, next_avg
    FROM (
      SELECT
        s.acm as acm,
        s.file_date as file_date,
        s.start_file_time as start_file_time,
        seconds,
        value,
        ARRAY_AGG(s.file_time) OVER (PARTITION BY s.acm, s.file_date, s.start_file_time) as file_times,
        AVG(ABS(value)) OVER prev as prev_avg,
        NTH_VALUE(value, 2) OVER prev as prev_val,
        AVG(ABS(value)) OVER next as next_avg,
        NTH_VALUE(value, 2) OVER next as next_val
      FROM test v
      JOIN (
        SELECT
          acm,
          file_date,
          file_time,
          TIME_SUB(file_time, INTERVAL CAST(FLOOR(MIN(seconds)) AS INT64) SECOND) as start_file_time
        FROM test
        GROUP BY acm, file_date, file_time
      ) s ON s.acm = v.acm AND s.file_date = v.file_date AND s.file_time = v.file_time
      WINDOW prev AS (PARTITION BY s.acm, s.file_date, s.start_file_time ORDER BY seconds ROWS 2 PRECEDING), next AS (PARTITION BY s.acm, s.file_date, s.start_file_time ORDER BY seconds ROWS BETWEEN CURRENT ROW AND 2 FOLLOWING)
      )
    WHERE value = 0)
  WHERE kind IN ('start', 'stop')
  WINDOW w AS (PARTITION BY acm, file_date, start_file_time ORDER BY seconds ROWS 1 PRECEDING))
WHERE ARRAY_LENGTH(agg_kind) = 2 AND agg_kind[ORDINAL(1)] = 'start' AND agg_kind[ORDINAL(2)] = 'stop'
;

Body:
Check if below version will make a difference

I tried to preserve your original code as much as possible

#standardSQL
WITH test AS
 (SELECT 'A' AS ACM, CAST('2017-01-01' AS DATE) AS file_date, CAST('10:10:10' AS TIME) AS file_time , 0.0 AS value, 0.1 AS seconds
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', 0, 0.2 #start
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', 2000, 0.3
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', 1000, 0.4
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', 0, 0.5
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', -1000, 0.6
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', -2000, 0.7
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', 0, 0.8 #stop
  UNION ALL SELECT 'A', '2017-01-01', '10:10:10', 0, 0.9
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 0, 1.0 #start
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 1000, 1.1
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 1000, 1.2
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 2000, 1.3
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 0, 1.4
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 0, 1.5
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', -1000, 1.6
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', -2000, 1.7
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 0, 1.8
  UNION ALL SELECT 'A', '2017-01-01', '10:10:11', 1000, 1.9
  UNION ALL SELECT 'A', '2017-01-01', '10:10:12', 2000, 2.0
  UNION ALL SELECT 'A', '2017-01-01', '10:10:12', 1000, 2.1
  UNION ALL SELECT 'A', '2017-01-01', '10:10:12', 0, 2.2 #stop
  UNION ALL SELECT 'A', '2017-01-01', '10:10:12', 20, 2.3
  UNION ALL SELECT 'A', '2017-01-01', '10:10:12', 0, 2.4
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', 0, 0.1
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', 0, 0.2 #start
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', 2000, 0.3
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', 1000, 0.4
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', 0, 0.5
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', -1000, 0.6
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', -2000, 0.7
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', 0, 0.8 #stop
  UNION ALL SELECT 'B', '2017-01-01', '10:10:10', 0, 0.9
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 0, 1.0 #start
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 1000, 1.1
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 1000, 1.2
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 2000, 1.3
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 0, 1.4
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 0, 1.5
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', -1000, 1.6
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', -2000, 1.7
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 0, 1.8
  UNION ALL SELECT 'B', '2017-01-01', '10:10:11', 1000, 1.9
  UNION ALL SELECT 'B', '2017-01-01', '10:10:12', 2000, 2.0
  UNION ALL SELECT 'B', '2017-01-01', '10:10:12', 1000, 2.1
  UNION ALL SELECT 'B', '2017-01-01', '10:10:12', 0, 2.2 #stop
  UNION ALL SELECT 'B', '2017-01-01', '10:10:12', 20, 2.3
  UNION ALL SELECT 'B', '2017-01-01', '10:10:12', 0, 2.4
), temp1 AS (
  SELECT acm, file_date, value, seconds,
   TIME_SUB(file_time, INTERVAL CAST(FLOOR(seconds) AS INT64) SECOND) AS start_file_time
  FROM test
), temp2 AS (
  SELECT
    acm, file_date, start_file_time, seconds,
    AVG(ABS(value)) OVER prev AS prev_avg,
    NTH_VALUE(value, 2) OVER prev AS prev_val,
    AVG(ABS(value)) OVER next AS next_avg,
    NTH_VALUE(value, 2) OVER next AS next_val
  FROM temp1 WINDOW
    prev AS (PARTITION BY acm, file_date, start_file_time ORDER BY seconds ROWS 2 PRECEDING),
    next AS (PARTITION BY acm, file_date, start_file_time ORDER BY seconds ROWS BETWEEN CURRENT ROW AND 2 FOLLOWING)
), temp3 AS (
  SELECT
    acm, file_date, start_file_time, seconds,
    CASE
      WHEN (ABS(prev_val) < 50 AND ABS(next_val) >= 50 AND next_avg >= 50 AND prev_avg < 50 ) THEN 'start'
      WHEN (ABS(next_val) < 50 AND ABS(prev_val) >= 50 AND prev_avg >= 50 AND next_avg < 50 ) THEN 'stop'
    END AS kind
  FROM temp2
), temp4 AS (
  SELECT *,
    COUNTIF(kind = 'start') OVER (PARTITION BY acm, file_date, start_file_time ORDER BY seconds) +
    COUNTIF(kind = 'stop') OVER (PARTITION BY acm, file_date, start_file_time ORDER BY seconds ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS grp
  FROM temp3
)
SELECT
  acm, file_date, start_file_time,
  MIN(seconds) AS start_seconds,
  MAX(seconds) AS stop_seconds
FROM temp4
GROUP BY acm, file_date, start_file_time, grp
HAVING MIN(kind) != MAX(kind)
-- ORDER BY 1, 2, 3, 4


问:
Can I use constructor logic with object initializer syntax?
i.e.

```<code>MyClass myClass = new MyClass() { Value = 5 };
</code>```

I have a bunch of constructor calls like the one above, but now I've realized I need to add logic to the constructor, which was a massive oversight. Currently I have no constructor, so just a blank implicit default constructor.

The below code should explain my problem.

Edit: I'm not actually doing validation, that's just a simple example of constructor logic

```<code>class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(new Test(1) + " should be true");
        Console.WriteLine(new Test(0) + " should be false");
        Test test = new Test(0) { Value = 1 }; // It allows this syntax, oddly, but the value that's used is the one passed as a parameter
        Console.WriteLine("I wish " + test + " was true");
        // This is what I have currently, but I'd like to add logic like that which exists in the parameterized constructor
        //Test test = new Test() { Value = 1 } // Would ideally function just like Test(1), otherwise I have to go and change every call

        // OUTPUT
        // True should be true
        // False should be false
        // I wish False was true

        Console.ReadLine();
    }
}

class Test
{
    public bool? IsGood { get; }
    public int Value { get; set; }

    // This doesn't currently exist in my class, but I'd like to add it
    public Test(int value)
    {
        if (value == 1)
            IsGood = true;
        else
            IsGood = false;
    }

    public override string ToString()
    {
        return IsGood.ToString();
    }
}
</code>```

答:
Don't write code like this in the first place.

I'd write your code like this:

```<code>class Test
{
  public static bool IsValid(int value)
  {
     return whatever; // test for validity here
  }
  public int Value { get; private set; } // Don't let anyone change it.
  public Test(int value) {
    if (!IsValid(value)) throw new InvalidArgumentException("value");
    this.Value = value;
  }
}
</code>```

There, now Value is always valid; the user can know ahead of time whether it is valid or not; an attempt to set an invalid value produces an exception.  This assumes that Value cannot change.

If Value can change then write it like this:

```<code>class Test
{
  public static bool IsValid(int value)
  {
     return whatever; // test for validity here
  }
  private int value;
  public int Value { get { return value; }
    set
    {
      if (!IsValid(value)) throw new InvalidArgumentException("value");
      this.value = value;
    }
  }
  public Test(int value) {
    this.Value = value;
  }
}
</code>```

Now the value is again always legal.

If it is legal for value to be invalid, then:

```<code>class Test
{
  public bool IsValid
  {
     get
     {
       return whatever; // test for validity here
     } // read-only property
  }
  public int Value { get; set; }
  public Test(int value) {
    this.Value = value;
  }
}
</code>```

Now the value can be any integer and whether it is valid or not can be tested dynamically.

Body:
i.e.

MyClass myClass = new MyClass() { Value = 5 };

I have a bunch of constructor calls like the one above, but now I've realized I need to add logic to the constructor, which was a massive oversight. Currently I have no constructor, so just a blank implicit default constructor.

The below code should explain my problem.

Edit: I'm not actually doing validation, that's just a simple example of constructor logic

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(new Test(1) + " should be true");
        Console.WriteLine(new Test(0) + " should be false");
        Test test = new Test(0) { Value = 1 }; // It allows this syntax, oddly, but the value that's used is the one passed as a parameter
        Console.WriteLine("I wish " + test + " was true");
        // This is what I have currently, but I'd like to add logic like that which exists in the parameterized constructor
        //Test test = new Test() { Value = 1 } // Would ideally function just like Test(1), otherwise I have to go and change every call

        // OUTPUT
        // True should be true
        // False should be false
        // I wish False was true

        Console.ReadLine();
    }
}

class Test
{
    public bool? IsGood { get; }
    public int Value { get; set; }

    // This doesn't currently exist in my class, but I'd like to add it
    public Test(int value)
    {
        if (value == 1)
            IsGood = true;
        else
            IsGood = false;
    }

    public override string ToString()
    {
        return IsGood.ToString();
    }
}

Body:
Don't write code like this in the first place.

I'd write your code like this:

class Test
{
  public static bool IsValid(int value)
  {
     return whatever; // test for validity here
  }
  public int Value { get; private set; } // Don't let anyone change it.
  public Test(int value) {
    if (!IsValid(value)) throw new InvalidArgumentException("value");
    this.Value = value;
  }
}

There, now Value is always valid; the user can know ahead of time whether it is valid or not; an attempt to set an invalid value produces an exception.  This assumes that Value cannot change.

If Value can change then write it like this:

class Test
{
  public static bool IsValid(int value)
  {
     return whatever; // test for validity here
  }
  private int value;
  public int Value { get { return value; }
    set
    {
      if (!IsValid(value)) throw new InvalidArgumentException("value");
      this.value = value;
    }
  }
  public Test(int value) {
    this.Value = value;
  }
}

Now the value is again always legal.

If it is legal for value to be invalid, then:

class Test
{
  public bool IsValid
  {
     get
     {
       return whatever; // test for validity here
     } // read-only property
  }
  public int Value { get; set; }
  public Test(int value) {
    this.Value = value;
  }
}

Now the value can be any integer and whether it is valid or not can be tested dynamically.


问:
Build React Components Incrementally based on conditions
I have an array of objects prjLvlData. This array contains information that I use to conditionally render a component.

In my .jsx file I have

```<code>{
  prjLvlData.map(ele => {

    if (ele.fields.level_exp === 'portfolio' && ele.fields.has_experience) {
      return <div className="btn btnAddBadge button noCursor projectLevelBtn active" id={`btnPortfolio${id}`}>Portfolio</div>
    } else {
      return <div className="btn btnAddBadge button noCursor projectLevelBtn" id={`btnPortfolio${id}`}>Portfolio</div>
    }
    if (ele.fields.level_exp === 'program' && ele.fields.has_experience) {
      return <div className="btn btnAddBadge button noCursor projectLevelBtn active" id={`btnProgram{id}`}>Program</div>
    } else {
      return <div className="btn btnAddBadge button noCursor projectLevelBtn " id={`btnProgram{id}`}>Program</div>
    }
    if (ele.fields.level_exp === 'project' && ele.fields.has_experience) {
      return <div className="btn btnAddBadge button noCursor projectLevelBtn active" id={`btnProject${id}`}>Project</div>
    } else {
      return <div className="btn btnAddBadge button noCursor projectLevelBtn" id={`btnProject${id}`}>Project</div>
    }
  })
}
</code>```

How can I build them so that by the end of the 3 if statements, I return the built-up component, instead of returning inside every if statement?

I want something like this, in pseudo code

```<code>var component = <div>

if (...)
  component += thing1
if (...)
  component += thing2

return component + <div>
</code>```

答:
You could return an Array of elements:

```<code> {prjLvlData.map(ele => {
   const elements = [];

   if (ele.fields.level_exp === 'portfolio' && ele.fields.has_experience) {
     elements.push(<div className="btn btnAddBadge button noCursor projectLevelBtn active" id={`btnPortfolio${id}`}>Portfolio</div>)
   }

   // etc...

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

This happens inside a map, so you'll need to flatten the Array to a single level of nesting to embed it in another component. A utility library like lodash or a short JavaScript function can do that:

Here's an example:

```<code>const nestedElements = prjLvlData.map(/* function from above */);
const flatElements = flatten(nestedElements);

const rendered = <p>
  {flatElements)
</p>
</code>```

Body:
I have an array of objects prjLvlData. This array contains information that I use to conditionally render a component.

In my .jsx file I have

{
  prjLvlData.map(ele => {

    if (ele.fields.level_exp === 'portfolio' && ele.fields.has_experience) {
      return <div className="btn btnAddBadge button noCursor projectLevelBtn active" id={`btnPortfolio${id}`}>Portfolio

    } else {
      return <div className="btn btnAddBadge button noCursor projectLevelBtn" id={`btnPortfolio${id}`}>Portfolio

    }
    if (ele.fields.level_exp === 'program' && ele.fields.has_experience) {
      return <div className="btn btnAddBadge button noCursor projectLevelBtn active" id={`btnProgram{id}`}>Program

    } else {
      return <div className="btn btnAddBadge button noCursor projectLevelBtn " id={`btnProgram{id}`}>Program

    }
    if (ele.fields.level_exp === 'project' && ele.fields.has_experience) {
      return <div className="btn btnAddBadge button noCursor projectLevelBtn active" id={`btnProject${id}`}>Project

    } else {
      return <div className="btn btnAddBadge button noCursor projectLevelBtn" id={`btnProject${id}`}>Project

    }
  })
}

How can I build them so that by the end of the 3 if statements, I return the built-up component, instead of returning inside every if statement?

I want something like this, in pseudo code

var component =

if (...)
  component += thing1
if (...)
  component += thing2

return component +

Body:
You could return an Array of elements:

 {prjLvlData.map(ele => {
   const elements = [];

   if (ele.fields.level_exp === 'portfolio' && ele.fields.has_experience) {
     elements.push(<div className="btn btnAddBadge button noCursor projectLevelBtn active" id={`btnPortfolio${id}`}>Portfolio</div>)
   }

   // etc...

   return elements;
)}

This happens inside a map, so you'll need to flatten the Array to a single level of nesting to embed it in another component. A utility library like lodash or a short JavaScript function can do that:

Here's an example:

const nestedElements = prjLvlData.map(/* function from above */);
const flatElements = flatten(nestedElements);

const rendered = <p>
  {flatElements)
</p>