问:
SearchWP Results showing html tags
Im using the searchWP plugin in my wordpress site but the results of the keyword is showing html tags in the description. (see picture)

Is it possible to use a filter to remove those tags from showing up but still show the text without the tags?

The tags are inside the wordpress wysiwyg editor.

Update.

The search-form uses vue.
So if it is possible to trim the html tags from the results using vue i would prefer that.

答:
I'm not tested try this.</p>

```<code>function wpse159789_posts_search( $search, $query ) {
    global $wpdb;
    if ( ! preg_match( '/' . $wpdb->posts . '\.post_content LIKE \'%(.+)%\'/', $search, $matches, PREG_OFFSET_CAPTURE ) ) {
        return $search;
    }
    $search_str = stripslashes( $matches[1][0] );
    // Cater for closed angle pairs embedded in the search string.
    for ( $i = 0, $len = mb_strlen( $search_str ); $i < $len; $i++ ) {
        $q_searches[] = '(<[^>]*>)?' . preg_quote( mb_substr( $search_str, $i, 1 ) );
    }
    $q_search = implode( '', $q_searches );
    $regexs[] = '^[^<]*' . $q_search; // Before any angle bracket.
    $regexs[] = '(<[^>]*>)[^<]*' . $q_search; // After any closed angle bracket pair.
    array_unshift( $regexs, implode( ' OR ', array_fill( 0, count( $regexs ), $wpdb->posts . '.post_content RLIKE %s' ) ) );
    $search_replace = call_user_func_array( array( $wpdb, 'prepare' ), $regexs );
    $search = substr( $search, 0, $matches[0][1] ) . $search_replace . substr( $search, $matches[0][1] + strlen( $matches[0][0] ) );
    return $search;
}
</code>```

Title: SearchWP Results showing html tags

Body:
I'm not tested try this.

function wpse159789_posts_search( $search, $query ) {
    global $wpdb;
    if ( ! preg_match( '/' . $wpdb->posts . '\.post_content LIKE \'%(.+)%\'/', $search, $matches, PREG_OFFSET_CAPTURE ) ) {
        return $search;
    }
    $search_str = stripslashes( $matches[1][0] );
    // Cater for closed angle pairs embedded in the search string.
    for ( $i = 0, $len = mb_strlen( $search_str ); $i < $len; $i++ ) {
        $q_searches[] = '(<[^>]*>)?' . preg_quote( mb_substr( $search_str, $i, 1 ) );
    }
    $q_search = implode( '', $q_searches );
    $regexs[] = '^[^<]*' . $q_search; // Before any angle bracket.
    $regexs[] = '(<[^>]*>)[^<]*' . $q_search; // After any closed angle bracket pair.
    array_unshift( $regexs, implode( ' OR ', array_fill( 0, count( $regexs ), $wpdb->posts . '.post_content RLIKE %s' ) ) );
    $search_replace = call_user_func_array( array( $wpdb, 'prepare' ), $regexs );
    $search = substr( $search, 0, $matches[0][1] ) . $search_replace . substr( $search, $matches[0][1] + strlen( $matches[0][0] ) );
    return $search;
}


来源: stackexchange

问:
Are WCF sessions secure?
I am developing a WCF service with some kind of authentication.

All users will be equal, so I am planning to require sessions and have only a method that initiates a session and doesn't terminates it. Simplifying:

```<code>[OperationContract(IsInitiating = true, IsTerminating = false)]
void Open(String user, String password);
</code>```

So, if the password is wrong (again, this is a simplification) I would raise an exception so the session would end. This way, I don't need to check credentials in every method call.

Is this a good approach? If not, why?

Update: I had to write this on a hurry so I'll try to elaborate a bit and make my question clearer.

The authentication method is a requirement, and I'm not asking about it. I want to know about session managing.

When I use the [OperationContract(IsInitiating=true, IsTerminating=false)] a session is started. I don't need to store an ID or anything; WCF manages everything. When an exception is raised or a method with IsTerminating=true is called, the session ends, and subsequent calls to the service methods fail, until a new session is initiated.

What I want to know is if it's reasonably easy for an attacker to bypass the WCF session management stuff, creating one on its own without calling Open, the only method of my service with IsInitiating=true and IsTerminating=false, so, the only way to lawfully start a session.

答:
Yes, it would be trivial for a malicious client to "hijack" an authenticated session unless you encrypt all comms that carry the session identifier using an encryption key that is not accessible to potential comms interceptors.  Then again, it would be equally simple for them to intercept the transmitted user names and passwords too without adequate encryption and anti-replay protections.

Sometimes requirements need to be revisited once implementation choices start being made.  It sounds like this might be one of those cases...

ContentLicense: CC BY-SA 3.0

Title: Are WCF sessions secure?

Body:
I am developing a WCF service with some kind of authentication.

All users will be equal, so I am planning to require sessions and have only a method that initiates a session and doesn't terminates it. Simplifying:

[OperationContract(IsInitiating = true, IsTerminating = false)]
void Open(String user, String password);

So, if the password is wrong (again, this is a simplification) I would raise an exception so the session would end. This way, I don't need to check credentials in every method call.

Is this a good approach? If not, why?

Update: I had to write this on a hurry so I'll try to elaborate a bit and make my question clearer.

The authentication method is a requirement, and I'm not asking about it. I want to know about session managing.

When I use the [OperationContract(IsInitiating=true, IsTerminating=false)] a session is started. I don't need to store an ID or anything; WCF manages everything. When an exception is raised or a method with IsTerminating=true is called, the session ends, and subsequent calls to the service methods fail, until a new session is initiated.

What I want to know is if it's reasonably easy for an attacker to bypass the WCF session management stuff, creating one on its own without calling Open, the only method of my service with IsInitiating=true and IsTerminating=false, so, the only way to lawfully start a session.


问:
How do I sort dictionary by Key in Python
I need to sort below dictionary and print first five items from sorted dictionary:

```<code>station_dict_platOne = {'6': 'Daly City', '12': 'Daly City', '19': 'Daly City', 'Leaving': 'Millbrae', '16': 'SF Airport', '28': 'Millbrae', '10': 'SF Airport', '22': 'SF Airport'}
</code>```

I am using this code:

```<code>j=0
for i in sorted(station_dict_platOne):
        if j<5:
        print(i+" "+"min", station_dict_platOne[i])
        j = j+1
</code>```

But, I am getting below output and this is not the correct output.

```<code>10 min SF Airport
12 min Daly City
16 min SF Airport
19 min Daly City
22 min SF Airport
</code>```

答:
If you remove the 'Leaving' key you can do this:

```<code>s = {6: 'Daly City', 12: 'Daly City', 19: 'Daly City',
     16: 'SF Airport', 28: 'Millbrae', 10: 'SF Airport', 22: 'SF Airport'}

for k in sorted(s):
    print(k, s[k])
</code>```

which outputs:

```<code>6 Daly City
10 SF Airport
12 Daly City
16 SF Airport
19 Daly City
22 SF Airport
28 Millbrae
</code>```

I don't know if that's what you are looking for

ContentLicense: CC BY-SA 4.0

Body:
I need to sort below dictionary and print first five items from sorted dictionary:

station_dict_platOne = {'6': 'Daly City', '12': 'Daly City', '19': 'Daly City', 'Leaving': 'Millbrae', '16': 'SF Airport', '28': 'Millbrae', '10': 'SF Airport', '22': 'SF Airport'}

I am using this code:

j=0
for i in sorted(station_dict_platOne):
        if j<5:
        print(i+" "+"min", station_dict_platOne[i])
        j = j+1

But, I am getting below output and this is not the correct output.

10 min SF Airport
12 min Daly City
16 min SF Airport
19 min Daly City
22 min SF Airport

Body:
If you remove the 'Leaving' key you can do this:

s = {6: 'Daly City', 12: 'Daly City', 19: 'Daly City',
     16: 'SF Airport', 28: 'Millbrae', 10: 'SF Airport', 22: 'SF Airport'}

for k in sorted(s):
    print(k, s[k])

which outputs:

6 Daly City
10 SF Airport
12 Daly City
16 SF Airport
19 Daly City
22 SF Airport
28 Millbrae

I don't know if that's what you are looking for


问:
Serious slowdown due to button row in React/MaterialUI
I am using material UI with react for this project.

I have my backend Load items in a mapped out series of cards with props which contain a button row. Said button row is the culprit of the slowdown from what I quickly discovered. This makes sense because its a long pile of code, and the biggest offender of the slowdown appears to be a dialogue popup I prompt to show more information that my initial card does not provide.

Here's a simplified version of my codes logic:

1. fetch database items in a json. return small card with all props mapped in a grid. Bellow is the return

```<code>  return (
    <Grid
      container
      direction="row"
      justify="space-around"
      alignItems="flex-start"
      spacing={2}
    >
      {items.map(x => {
        return (
          <Grid item sm key={`key${x._id}`}>
            <SmallCard
              key={x._id}
              // 18 other properties are assigned here and passed down.
            />
          </Grid>
        );
      })}
    </Grid>
  );
}

export default Test;
</code>```

2. in small card is the button row which i pass all my json stuff through with props.

```<code>return (
  <Card className={classes.card}>
    <CardActionArea>
      <Grid container spacing={3} style={{ position: "relative" }}>
        <Grid item xs={6} className={classes.gridItems}>
          <a href={props.GLink}>
            <CardImg imageForCard={props.GPic} />
            <p className={classes.PriceLeft}>{props.GPrice}</p>
            <p className={classes.TitleLeft}>
              {props.GTitle.substring(0, 30)}...
            </p>
          </a>
        </Grid>
        <Grid item xs={6} className={classes.gridItems}>
          <a href={props.FriftLink}>
            <CardImg imageForCard={props.FPic} />
            <p className={classes.PriceRight}>{props.FPrice}</p>
            <p className={classes.TitleRight}>
              {props.FTitle.substring(0, 30)}...
            </p>
          </a>
        </Grid>
      </Grid>
    </CardActionArea>
    <ButtonRow
      Key={props.Key}
      // 18 PROPS HERE
    />
  </Card>
</code>```

3. in button row is the more info button which passes all my props to a dialogue

```<code>return (
  <CardActions>
    <ThemeProvider theme={themeOriginal}>
      <ButtonGroup
        variant="contained"
        aria-label="text primary button group"
        type="contained"
        color="secondary"
        size="small"
        className={classes.root}
      >
        <Button/>
        <Button/>
        <Button/>
        <ButtonForInfoCard/>
        <InfoCard
          key={props.key}
          //18 PROPS HERE
        />
      </ButtonGroup>
    </ThemeProvider>
  </CardActions>
);
</code>```

4. dialogue carries all props which only display the information in smaller components.

```<code>return (
  <Dialog
    open={props.open}
    onClose={props.close}
    scroll="body"
    keepMounted
    key={x._id}
  >
    <div className={classes.dialog}>
      <TitleImgLft
        GPrice={props.GPrice}
        GPic={props.GPic}
        GTitle={props.GTitle}
      />
      <TitleImgRt
        FPrice={props.FPrice}
        FPic={props.FPic}
        FTitle={props.FTitle}
      />
      <Notes Notes={props.Notes} />
      <br />
      <VoteCount Likes={props.Likes} Dislikes={props.Dislikes} />
    </div>
  </Dialog>
);
</code>```

I have my components in different folders to organize things But I am still not quite sure what else I can do to speed things up. I'd be happy to show code if it helps but I'm guessing I'm doing some sort of rookie movie that I don't know I am doing.

Here's my file folder layout for reference.

All of the code here is simplified and does not show my useState or hooks. All of my components are function based as I was taught to use the newsest methods. Material UI is edited in style sheets an in some cases I use a style override in favor of classes.

答: It appears the source of my slowdown is the use of themeProvider in materialUI https://material-ui.com/customization/theming/#theme-provider. This color override for some reason really boggged things down for my app. Soon as I removed it and went back to default colors is was flying. </p>

Body:
I am using material UI with react for this project.

I have my backend Load items in a mapped out series of cards with props which contain a button row. Said button row is the culprit of the slowdown from what I quickly discovered. This makes sense because its a long pile of code, and the biggest offender of the slowdown appears to be a dialogue popup I prompt to show more information that my initial card does not provide.

Here's a simplified version of my codes logic:

1. fetch database items in a json. return small card with all props mapped in a grid. Bellow is the return

  return (
    <Grid
      container
      direction="row"
      justify="space-around"
      alignItems="flex-start"
      spacing={2}
    >
      {items.map(x => {
        return (
          <Grid item sm key={`key${x._id}`}>
            <SmallCard
              key={x._id}
              // 18 other properties are assigned here and passed down.
            />
          </Grid>
        );
      })}
    </Grid>
  );
}

export default Test;

2. in small card is the button row which i pass all my json stuff through with props.

return (
  <Card className={classes.card}>
    <CardActionArea>
      <Grid container spacing={3} style={{ position: "relative" }}>
        <Grid item xs={6} className={classes.gridItems}>

            <CardImg imageForCard={props.GPic} />

{props.GPrice}

              {props.GTitle.substring(0, 30)}...

        </Grid>
        <Grid item xs={6} className={classes.gridItems}>

            <CardImg imageForCard={props.FPic} />

{props.FPrice}

              {props.FTitle.substring(0, 30)}...

        </Grid>
      </Grid>
    </CardActionArea>
    <ButtonRow
      Key={props.Key}
      // 18 PROPS HERE
    />
  </Card>

3. in button row is the more info button which passes all my props to a dialogue

return (
  <CardActions>
    <ThemeProvider theme={themeOriginal}>
      <ButtonGroup
        variant="contained"
        aria-label="text primary button group"
        type="contained"
        color="secondary"
        size="small"
        className={classes.root}
      >
        <Button/>
        <Button/>
        <Button/>
        <ButtonForInfoCard/>
        <InfoCard
          key={props.key}
          //18 PROPS HERE
        />
      </ButtonGroup>
    </ThemeProvider>
  </CardActions>
);

4. dialogue carries all props which only display the information in smaller components.

return (
  <Dialog
    open={props.open}
    onClose={props.close}
    scroll="body"
    keepMounted
    key={x._id}
  >

      <TitleImgLft
        GPrice={props.GPrice}
        GPic={props.GPic}
        GTitle={props.GTitle}
      />
      <TitleImgRt
        FPrice={props.FPrice}
        FPic={props.FPic}
        FTitle={props.FTitle}
      />
      <Notes Notes={props.Notes} />

      <VoteCount Likes={props.Likes} Dislikes={props.Dislikes} />

  </Dialog>
);

I have my components in different folders to organize things But I am still not quite sure what else I can do to speed things up. I'd be happy to show code if it helps but I'm guessing I'm doing some sort of rookie movie that I don't know I am doing.

Here's my file folder layout for reference.

All of the code here is simplified and does not show my useState or hooks. All of my components are function based as I was taught to use the newsest methods. Material UI is edited in style sheets an in some cases I use a style override in favor of classes.


问:
JSON write out with PHP
I have a JSON message, and I dont know How can I write out a part of json.

I tried:

```<code>{{$data[0]->items[0]}}

{{$data[0]->name}}

{{$data->items[0]-name}}

{{$data[0]->items}}
</code>```

ect...

```<code>JSON message:
{
   "items":[
      {
         "name":"Knight",
         "id":26000000,
         "maxLevel":13,
         "iconUrls":{
            "medium":"https:\/\/api-assets.clashroyale.com\/cards\/300\/jAj1Q5rclXxU9kVImGqSJxa4wEMfEhvwNQ_4jiGUuqg.png"
         }
      },
      {
         "name":"Archers",
         "id":26000001,
         "maxLevel":13,
         "iconUrls":{
            "medium":"https:\/\/api-assets.clashroyale.com\/cards\/300\/W4Hmp8MTSdXANN8KdblbtHwtsbt0o749BbxNqmJYfA8.png"
         }
      }
   ]
}
</code>```

EDIT:

This is the Controller

As you see $data array is decoded

It looks like your post is mostly code; please add some more details. omg

```<code>     $token = "token";

     $url = "https://api.clashroyale.com/v1/cards";

     $ch = curl_init($url);

     $headr = array();
     $headr[] = "Accept: application/json";
     $headr[] = "Authorization: Bearer ".$token;
     curl_setopt($ch, CURLOPT_HTTPHEADER, $headr);

     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     $res = curl_exec($ch);
     $data = json_decode($res, true);
     curl_close($ch);

     return view('clash', ['data' => $data]);
</code>```

答:
First you have to decode your JSON-String to a PHP-Array and then you can access it easily this way:

```<code>$json = '{
   "items":[
      {
         "name":"Knight",
         "id":26000000,
         "maxLevel":13,
         "iconUrls":{
            "medium":"https:\/\/api-assets.clashroyale.com\/cards\/300\/jAj1Q5rclXxU9kVImGqSJxa4wEMfEhvwNQ_4jiGUuqg.png"
         }
      },
      {
         "name":"Archers",
         "id":26000001,
         "maxLevel":13,
         "iconUrls":{
            "medium":"https:\/\/api-assets.clashroyale.com\/cards\/300\/W4Hmp8MTSdXANN8KdblbtHwtsbt0o749BbxNqmJYfA8.png"
         }
      },
      {
         "name":"Goblins",
         "id":26000002,
         "maxLevel":13,
         "iconUrls":{
            "medium":"https:\/\/api-assets.clashroyale.com\/cards\/300\/X_DQUye_OaS3QN6VC9CPw05Fit7wvSm3XegXIXKP--0.png"
         }
      },
      {
         "name":"Giant",
         "id":26000003,
         "maxLevel":11,
         "iconUrls":{
            "medium":"https:\/\/api-assets.clashroyale.com\/cards\/300\/Axr4ox5_b7edmLsoHxBX3vmgijAIibuF6RImTbqLlXE.png"
         }
      }
   ]
}';

$array = json_decode( $json, true ); // we receive an associative array because the second parameter is true

echo $array['items'][0]['name'];
echo $array['items'][1]['id'];
</code>```

Usage in for example:

```<code>$token = "token";
$url = "https://api.clashroyale.com/v1/cards";
$ch = curl_init($url);

$headr = array();
$headr[] = "Accept: application/json";
$headr[] = "Authorization: Bearer ".$token;

curl_setopt($ch, CURLOPT_HTTPHEADER, $headr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$res = curl_exec($ch);
$data = json_decode($res, true);
curl_close($ch);

echo $data['items'][0]['name']; // echo the value of the key 'name' of the first element in items
echo $data['items'][1]['id']; // echo the value of the key 'id' of the second element in items
// you can also store them or do whatever you want

return view('clash', ['data' => $data]);
</code>```

Or access the data in your view like this:

```<code>{{ $data['items'][0]['name'] }}
{{ $data['items'][0]['id'] }}
</code>```

Title: JSON write out with PHP

Body:
I have a JSON message, and I dont know How can I write out a part of json.

I tried:

{{$data[0]->items[0]}}

{{$data[0]->name}}

{{$data->items[0]-name}}

{{$data[0]->items}}

ect...

JSON message:
{
   "items":[
      {
         "name":"Knight",
         "id":26000000,
         "maxLevel":13,
         "iconUrls":{
            "medium":"https:\/\/api-assets.clashroyale.com\/cards\/300\/jAj1Q5rclXxU9kVImGqSJxa4wEMfEhvwNQ_4jiGUuqg.png"
         }
      },
      {
         "name":"Archers",
         "id":26000001,
         "maxLevel":13,
         "iconUrls":{
            "medium":"https:\/\/api-assets.clashroyale.com\/cards\/300\/W4Hmp8MTSdXANN8KdblbtHwtsbt0o749BbxNqmJYfA8.png"
         }
      }
   ]
}

EDIT:

This is the Controller

As you see $data array is decoded

It looks like your post is mostly code; please add some more details. omg

     $token = "token";

     $url = "https://api.clashroyale.com/v1/cards";

     $ch = curl_init($url);

     $headr = array();
     $headr[] = "Accept: application/json";
     $headr[] = "Authorization: Bearer ".$token;
     curl_setopt($ch, CURLOPT_HTTPHEADER, $headr);

     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     $res = curl_exec($ch);
     $data = json_decode($res, true);
     curl_close($ch);

     return view('clash', ['data' => $data]);

Body:
First you have to decode your JSON-String to a PHP-Array and then you can access it easily this way:

$json = '{
   "items":[
      {
         "name":"Knight",
         "id":26000000,
         "maxLevel":13,
         "iconUrls":{
            "medium":"https:\/\/api-assets.clashroyale.com\/cards\/300\/jAj1Q5rclXxU9kVImGqSJxa4wEMfEhvwNQ_4jiGUuqg.png"
         }
      },
      {
         "name":"Archers",
         "id":26000001,
         "maxLevel":13,
         "iconUrls":{
            "medium":"https:\/\/api-assets.clashroyale.com\/cards\/300\/W4Hmp8MTSdXANN8KdblbtHwtsbt0o749BbxNqmJYfA8.png"
         }
      },
      {
         "name":"Goblins",
         "id":26000002,
         "maxLevel":13,
         "iconUrls":{
            "medium":"https:\/\/api-assets.clashroyale.com\/cards\/300\/X_DQUye_OaS3QN6VC9CPw05Fit7wvSm3XegXIXKP--0.png"
         }
      },
      {
         "name":"Giant",
         "id":26000003,
         "maxLevel":11,
         "iconUrls":{
            "medium":"https:\/\/api-assets.clashroyale.com\/cards\/300\/Axr4ox5_b7edmLsoHxBX3vmgijAIibuF6RImTbqLlXE.png"
         }
      }
   ]
}';

$array = json_decode( $json, true ); // we receive an associative array because the second parameter is true

echo $array['items'][0]['name'];
echo $array['items'][1]['id'];

Usage in for example:

$token = "token";
$url = "https://api.clashroyale.com/v1/cards";
$ch = curl_init($url);

$headr = array();
$headr[] = "Accept: application/json";
$headr[] = "Authorization: Bearer ".$token;

curl_setopt($ch, CURLOPT_HTTPHEADER, $headr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$res = curl_exec($ch);
$data = json_decode($res, true);
curl_close($ch);

echo $data['items'][0]['name']; // echo the value of the key 'name' of the first element in items
echo $data['items'][1]['id']; // echo the value of the key 'id' of the second element in items
// you can also store them or do whatever you want

return view('clash', ['data' => $data]);

Or access the data in your view like this:

{{ $data['items'][0]['name'] }}
{{ $data['items'][0]['id'] }}


问:
Why does cudaMemGetInfo report a change in the total amount of device memory?
When I run the following piece of code the reported total amount of memory on my GPU changes (according to cudaMemGetInfo anyway). This behavior is not mentioned in the documentation for cudaMemGetInfo, which says that total should contain the total amount of memory on my device that can be allocated (which cannot change without putting a different GPU in my system right?). Can somebody explain why this is happening? It does not seem to happen when I don't call cudaMallocManaged.

#include <iostream>

void printStats()
{
    size_t free, total;
    cudaMemGetInfo(&free, &total);
    std::cout << "free:  " << free << "\ntotal: " << total << std::endl;
}

int main(void)
{
    // Before memory allocation
    printStats();

    int N = 1;
    float *x, *y;
    cudaMallocManaged(&x, N*sizeof(float));
    cudaMallocManaged(&y, N*sizeof(float));

    // After memory allocation.
    printStats();

    cudaFree(x);
    cudaFree(y);

    // After freeing the memory.
    printStats();

    return 0;
}
```

<p>result:</p>

```free:  94383273356630
total: 20
free:  5661994326
total: 4
free:  140729276827856
total: 94383273355680
```

答:
It turns out that when your CUDA driver version is insufficient for CUDA runtime version this sort of undefined behavior happens. For anyone else running into this problem I recommend checking the output of cudaGetLastError() that's how I discovered what the problem was.

I fixed it by downgrading my CUDA version to 10.1 since that was the newest version my driver supports. (You can check your CUDA and driver version using the nvidia-smi tool).

Body:
When I run the following piece of code the reported total amount of memory on my GPU changes (according to cudaMemGetInfo anyway). This behavior is not mentioned in the documentation for cudaMemGetInfo, which says that total should contain the total amount of memory on my device that can be allocated (which cannot change without putting a different GPU in my system right?). Can somebody explain why this is happening? It does not seem to happen when I don't call cudaMallocManaged.

#include <iostream>

void printStats()
{
    size_t free, total;
    cudaMemGetInfo(&free, &total);
    std::cout << "free:  " << free << "\ntotal: " << total << std::endl;
}

int main(void)
{
    // Before memory allocation
    printStats();

    int N = 1;
    float *x, *y;
    cudaMallocManaged(&x, N*sizeof(float));
    cudaMallocManaged(&y, N*sizeof(float));

    // After memory allocation.
    printStats();

    cudaFree(x);
    cudaFree(y);

    // After freeing the memory.
    printStats();

    return 0;
}

result:

free:  94383273356630
total: 20
free:  5661994326
total: 4
free:  140729276827856
total: 94383273355680


问:
How to convert a List< Long> into a double[] in Java
I am trying to convert a List<Long> to a double[] in Java,

I did in the following way,

```<code>  List<Long> longList = ........;

  int len = longList.size();

  double[] doubleArray = new double[len];

  for (int i = 0; i < len; i++)
     doubleArray[i] = (double) longList.get(i);
</code>```

I am wondering if I can do it in a smarter way (and how) since I'm using Java-8, I saw some conversion using the stream method. But couldn't find anything that can solve my problem.

答:
Just use:</p>

```<code>double[] doubleArray = longList.stream().mapToDouble(v -> v).toArray();
</code>```

Body:
I am trying to convert a List<Long> to a double[] in Java,

I did in the following way,

  List<Long> longList = ........;

  int len = longList.size();

  double[] doubleArray = new double[len];

  for (int i = 0; i < len; i++)
     doubleArray[i] = (double) longList.get(i);

I am wondering if I can do it in a smarter way (and how) since I'm using Java-8, I saw some conversion using the stream method. But couldn't find anything that can solve my problem.

Body:
Just use:

double[] doubleArray = longList.stream().mapToDouble(v -> v).toArray();


问:
Integrate Kibana Dashboard in .Net MVC Application?
Is it possible to integrate Kibana dashboard in my application instead of my application dashboard, that means when you click on dashboard tab it should open Kibana dashboard without login dialogue(direct dashboard).</p>

答:
Sure, but you will have to proxy the connection (that is, some component will have to actually login, retrieve the view and send it to the user).

There has been some discussion about it on the elastic discussion groups and there is a related issue still open in the project that would allow doing that without login.


问:
How to make generic function to delete data in two Realm tables?
Code:

```<code>  class Realm_manager {

        private init() {}

        static let shared = Realm_manager()

        let realm = try! Realm()

         func deleteObjects<T: Object,T2: Object>(id: String,obj1: T,obj2: T2) {
             try! realm.write {
            realm.delete(realm.objects(T2.self).filter("set_id=%@", id))
            realm.delete(realm.objects(T.self).filter("id=%@", id))
        }
    }
    }
</code>```

function call in VC:

```<code>Realm_manager.shared.deleteObjects(id: array[indexPath.row].id, obj1: className1, obj2: className2)
</code>```

Error in VC:

Cannot convert value of type 'className1.Type' to expected argument type 'Object'

How can I solve this error?

答:
How you're getting/setting className1 and className2?
Should work like:

```<code>let object = Object()
deleteObjects(id: "1234", obj1: object, obj2: object)
</code>```

Actually, your deleteObjects don't need to know anything about real objects.
Could:

```<code>func deleteObjects<T: Object,T2: Object>(id: String, obj1: T.Type, obj2: T2.Type) {
    try! realm.write {
        realm.delete(realm.objects(T2.self).filter("set_id=%@", id))
        realm.delete(realm.objects(T.self).filter("id=%@", id))
    }
}
</code>```

And call:

```<code>deleteObjects(id: "1234", obj1: Object.self, obj2: Object.self)
</code>```

Or more convinient would be:

```<code>func deleteObjectsWith(id: String, withTypes types: [Object.Type]) {
    try! realm.write {
        types.forEach { objectType in
            let objects = realm.objects(objectType).filter("set_id=%@", id)
            realm.delete(objects)
        }
    }
}
</code>```

And call:

```<code>deleteObjectsWith(id: "1234", withTypes: [Object.self, Object.self])
</code>```

Body:
Code:

  class Realm_manager {

        private init() {}

        static let shared = Realm_manager()

        let realm = try! Realm()

         func deleteObjects<T: Object,T2: Object>(id: String,obj1: T,obj2: T2) {
             try! realm.write {
            realm.delete(realm.objects(T2.self).filter("set_id=%@", id))
            realm.delete(realm.objects(T.self).filter("id=%@", id))
        }
    }
    }

function call in VC:

Realm_manager.shared.deleteObjects(id: array[indexPath.row].id, obj1: className1, obj2: className2)

Error in VC:

Cannot convert value of type 'className1.Type' to expected argument type 'Object'

How can I solve this error?

Body:
How you're getting/setting className1 and className2?
Should work like:

let object = Object()
deleteObjects(id: "1234", obj1: object, obj2: object)

Actually, your deleteObjects don't need to know anything about real objects.
Could:

func deleteObjects<T: Object,T2: Object>(id: String, obj1: T.Type, obj2: T2.Type) {
    try! realm.write {
        realm.delete(realm.objects(T2.self).filter("set_id=%@", id))
        realm.delete(realm.objects(T.self).filter("id=%@", id))
    }
}

And call:

deleteObjects(id: "1234", obj1: Object.self, obj2: Object.self)

Or more convinient would be:

func deleteObjectsWith(id: String, withTypes types: [Object.Type]) {
    try! realm.write {
        types.forEach { objectType in
            let objects = realm.objects(objectType).filter("set_id=%@", id)
            realm.delete(objects)
        }
    }
}

And call:

deleteObjectsWith(id: "1234", withTypes: [Object.self, Object.self])


答:
less complex

```<code>awk 'BEGIN {FS=OFS="|"}
     NF>43 {for(i=43;i<=NF;i+=42) {t=$i; $i=substr(t,1,1) ORS substr(t,2)}}1' file

931096|376601|1|ART|AT-2151780724|2151780724|2|102809198|I|CGM44I|MIL3VF03|52576377.3600|PENDING|MO|PEND-INFO|Pend ACS4R|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|52576377.3600|1317720|system|2020-02-13 02:00:42|0
931097|375789|1|AYT|AT-2151509210|2151509210|7|102614605|A|CTHGMI|OZF19|444006.6400|APPROVED|NULL|APPROVED|Approved|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|kg17718|NULL|NULL|0.0000|1317722|system|2020-02-13 02:00:43|0
931098|375979|1|AHT|AT-2151780726|2151780726|2|102809199|I|CGMI|MILaesLF11|26312.0000|PENDING|MO|PEND-INFO|Pend ACRES|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|26312.0000|1317721|system|2020-02-13 02:00:43|0
931099|376572|1|AT|AT-2151399812|2151399812|5|102673999|I|CG2rMI|WEL44LF15|60991.6956|PENDING|MO|PEND-INFO|Pend ACERS|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|0.0000|1317723|system|2020-02-13 02:00:45|0
</code>```

following your spec

If cols > 43 Split 44th 43th column to add
  \n and print the remaining. Repeat process until cols=43 the end.

Title: Bash command/script to split line on a certain character

Body:
I would like to split the below data to the expected output:

Raw Data:

931096|376601|1|ART|AT-2151780724|2151780724|2|102809198|I|CGM44I|MIL3VF03|52576377.3600|PENDING|MO|PEND-INFO|Pend ACS4R|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|52576377.3600|1317720|system|2020-02-13 02:00:42|0
931097|375789|1|AYT|AT-2151509210|2151509210|7|102614605|A|CTHGMI|OZF19|444006.6400|APPROVED|NULL|APPROVED|Approved|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|kg17718|NULL|NULL|0.0000|1317722|system|2020-02-13 02:00:43|0931098|375979|1|AHT|AT-2151780726|2151780726|2|102809199|I|CGMI|MILaesLF11|26312.0000|PENDING|MO|PEND-INFO|Pend ACRES|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|26312.0000|1317721|system|2020-02-13 02:00:43|0
931099|376572|1|AT|AT-2151399812|2151399812|5|102673999|I|CG2rMI|WEL44LF15|60991.6956|PENDING|MO|PEND-INFO|Pend ACERS|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|0.0000|1317723|system|2020-02-13 02:00:45|0

Expected Output:

931096|376601|1|ART|AT-2151780724|2151780724|2|102809198|I|CGM44I|MIL3VF03|52576377.3600|PENDING|MO|PEND-INFO|Pend ACS4R|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|52576377.3600|1317720|system|2020-02-13 02:00:42|0
931097|375789|1|AYT|AT-2151509210|2151509210|7|102614605|A|CTHGMI|OZF19|444006.6400|APPROVED|NULL|APPROVED|Approved|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|kg17718|NULL|NULL|0.0000|1317722|system|2020-02-13 02:00:43|0
931098|375979|1|AHT|AT-2151780726|2151780726|2|102809199|I|CGMI|MILaesLF11|26312.0000|PENDING|MO|PEND-INFO|Pend ACRES|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|26312.0000|1317721|system|2020-02-13 02:00:43|0
931099|376572|1|AT|AT-2151399812|2151399812|5|102673999|I|CG2rMI|WEL44LF15|60991.6956|PENDING|MO|PEND-INFO|Pend ACERS|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|0.0000|1317723|system|2020-02-13 02:00:45|0

Basically the \n character is getting lost sometimes in the data and the lines are getting merged. Sometimes more than 1 line gets merged as well (even the opposite happens but we can get to that later).

The data always has 43 columns | separated. The last but one column(42nd) always is a timestamp and the last column is usually 0 or 1.

Trying for the below approach:
If cols > 43
Split 44th column to add \n and print the remaining.
Repeat process until cols=43

echo "${curr}" | awk -F\| ' { if(NF > 43) {for(i=43;i<NF;i++) "sed '${NR}s/\(^0\)/\1\n/p' $i" }}' filename

Body:
less complex

awk 'BEGIN {FS=OFS="|"}
     NF>43 {for(i=43;i<=NF;i+=42) {t=$i; $i=substr(t,1,1) ORS substr(t,2)}}1' file

931096|376601|1|ART|AT-2151780724|2151780724|2|102809198|I|CGM44I|MIL3VF03|52576377.3600|PENDING|MO|PEND-INFO|Pend ACS4R|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|52576377.3600|1317720|system|2020-02-13 02:00:42|0
931097|375789|1|AYT|AT-2151509210|2151509210|7|102614605|A|CTHGMI|OZF19|444006.6400|APPROVED|NULL|APPROVED|Approved|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|kg17718|NULL|NULL|0.0000|1317722|system|2020-02-13 02:00:43|0
931098|375979|1|AHT|AT-2151780726|2151780726|2|102809199|I|CGMI|MILaesLF11|26312.0000|PENDING|MO|PEND-INFO|Pend ACRES|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|26312.0000|1317721|system|2020-02-13 02:00:43|0
931099|376572|1|AT|AT-2151399812|2151399812|5|102673999|I|CG2rMI|WEL44LF15|60991.6956|PENDING|MO|PEND-INFO|Pend ACERS|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|0.0000|1317723|system|2020-02-13 02:00:45|0

following your spec

If cols > 43 Split 44th 43th column to add
  \n and print the remaining. Repeat process until cols=43 the end.


问:
What's is "this" refer to in Phaser 3?
I'm new to Javascript and want to make simple games with Phaser 3, and I found that Javascript seems to be a little different from other OOP languages like C++ or Java. I checked out the tutorial in the official website and some other tutorial page, most of the code is like:

```<code>var config = {
    ...
    scene: {
        preload: preload,
        create: create,
        update: update
    }
}
var game = new Phaser.Game(config)

function preload(){
    this.load.img(...)
}
</code>```

My question is what is the "this" in the preload() indicate to? Is it means the "game" we defined before?

And how to check the object's class in console? typeof() only tells "object".

答:
this is an instance of Phaser.Scene and not Phaser.Game.

The other answers are incorrect. The code is running the browser.

To see the docs for a Scene you can look here

Title: What's is "this" refer to in Phaser 3?

Body:
I'm new to Javascript and want to make simple games with Phaser 3, and I found that Javascript seems to be a little different from other OOP languages like C++ or Java. I checked out the tutorial in the official website and some other tutorial page, most of the code is like:

var config = {
    ...
    scene: {
        preload: preload,
        create: create,
        update: update
    }
}
var game = new Phaser.Game(config)

function preload(){
    this.load.img(...)
}

My question is what is the "this" in the preload() indicate to? Is it means the "game" we defined before?

And how to check the object's class in console? typeof() only tells "object".


问:
CoreMotion framework
I recently was doing a compass, to involve CoreMotion framework, but I checked for a long time did not find information on how to implement this framework the effect of the compass, hoping to get everyone's help.</p>

答:
Apple's Core Motion Framework Reference

Apple's Event Handling Guide for iOS: Core Motion

Apple's CoreMotionTeaPot from WWDC ’10 Sample Code

Get Moving with Core Motion — Jonathan Blocksom

Getting you started with CoreMotion — Ludwig Schubert

A similar question: make a compass application in iPad

ContentLicense: CC BY-SA 2.5

Title: CoreMotion framework


问:
How to list all registered events of a DOM node using JavaScript?
I can add or remove an event handler for a DOM node. Is it possible to find out all the registered events handlers of a given DOM node? I am referring to straight Javascript meaning no frameworks or toolkits like jQuery, dojo, Prototype, GWT, etc. If the answer is no, any reason why? Security issues?</p>

答:
I faced the same problem, landed here, and didn't find an useful answer.

In case you can execute script before addEventListener calls from other parties, you might do something really dirty like:

```<code>var obj = something; // Your DOM element you want to watch

var beforeAddEvent = obj.addEventListener;
obj.addEventListener = function() {
  // Do something with arguments here (like storing in an array)
  // arguments[0]: event name
  // arguments[1]: Listener function
  // arguments[3]: eventual options passed

  // If you don't call this, the event listener won't even be attached, it might be also useful in some case
  beforeAddEvent.apply(obj, arguments);
};
</code>```

Body:
I faced the same problem, landed here, and didn't find an useful answer.

In case you can execute script before addEventListener calls from other parties, you might do something really dirty like:

var obj = something; // Your DOM element you want to watch

var beforeAddEvent = obj.addEventListener;
obj.addEventListener = function() {
  // Do something with arguments here (like storing in an array)
  // arguments[0]: event name
  // arguments[1]: Listener function
  // arguments[3]: eventual options passed

  // If you don't call this, the event listener won't even be attached, it might be also useful in some case
  beforeAddEvent.apply(obj, arguments);
};


问:
Skip Git commit hooks
I'm looking at a Git hook which looks for print statements in Python code.  If a print statement is found, it prevents the Git commit.

I want to override this hook and I was told that there is a command to do so.  I haven't been able to find it.  Any thoughts?

答:
With both comment and no verify without any further issue:

```<code>git commit -m "Some comments" --no-verify
</code>```

Title: Skip Git commit hooks

Body:
With both comment and no verify without any further issue:

git commit -m "Some comments" --no-verify


问:
EnityManagerFactory Singleton. Please just check out?
I am just cruious if this looks solid. It gives no errors but I just want to double check as I am having a pooling issue with c3p0. Just checking to see if anything here is the cause. Thank you in advance!

```<code>import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class EntityManagerFactorySingleton {
    private static EntityManagerFactorySingleton singleton;
    private EntityManagerFactory emf;

public EntityManagerFactorySingleton(){
    emf = Persistence.createEntityManagerFactory(ConfigList.getProperty(Config.PERSISTENCE_UNIT), System.getProperties());
}

public synchronized static EntityManagerFactorySingleton getInstance() {
   if(singleton == null) {
    singleton = new EntityManagerFactorySingleton();
   }
   return singleton;
}

public EntityManagerFactory getEntityManagerFactory(){
    return emf;
}
</code>```

}

答:
<s>The code is not thread safe.</s> (Sorry, missed the synchronized)

You should not use singletons.

Instead, use a DI framework like Spring, guice or maybe your deployment envionment already offers one.

This will make your code much more robust and much more simple to test.

Body:
I am just cruious if this looks solid. It gives no errors but I just want to double check as I am having a pooling issue with c3p0. Just checking to see if anything here is the cause. Thank you in advance!

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class EntityManagerFactorySingleton {
    private static EntityManagerFactorySingleton singleton;
    private EntityManagerFactory emf;

public EntityManagerFactorySingleton(){
    emf = Persistence.createEntityManagerFactory(ConfigList.getProperty(Config.PERSISTENCE_UNIT), System.getProperties());
}

public synchronized static EntityManagerFactorySingleton getInstance() {
   if(singleton == null) {
    singleton = new EntityManagerFactorySingleton();
   }
   return singleton;
}

public EntityManagerFactory getEntityManagerFactory(){
    return emf;
}

}


问:
How to lock thread correctly with ReentrantLock or Mutex?
I have an acync method with callback:

```<code>myAsyncMethod(params) {
    handleResult(it)
}
</code>```

I need to convert it to sync method (block and return result) like this:

```<code>val result = mySyncMethod(params)
handleResult(result)
</code>```

I can't re-implement it by another way because this method provided by third-party library.

I am trying to use ReentrantLock:

```<code>fun mySyncMethod(params:Type) {
    Log.d("tag", "1")
    val result = null
    val mutex = ReentrantLock()
    myAsyncMethod(params) {
        Log.d("tag", "3")
        result = it
        mutex.unlock()
    }
    Log.d("tag", "2")
    mutex.lock()
    Log.d("tag", "4")
    return result
}

handleResult(mySyncMethod(params))
</code>```

I wait that I should see 1, 2, 3, 4. But I get 1, 2, 4, 3 and null in handleResult. I am trying the same with mutex but with the same result. How to make it works?

P.S. Sure I can use synchronized, but in this case I have to use Object-variable additionally.

答:
I expect that I should see 1, 2, 3, 4.

Then you misunderstood what ReentrantLock is actually for.

If mySyncMethod can be called from different threads, then after mutex.lock() is called, only one thread at a time can execute the code following mutex.lock() - the other threads executing this method have to wait. Once mutex.unlock() is called, one of the waiting threads will execute the code too and so on.

So, the thread owning the mutex forces the other threads to wait but its own flow isn't blocked. myAsyncMethod starts running after the outer method has completed already and hence result is still null.

I need to convert it to sync method (block and return result) like this:

According to your requirements, you need to block the current thread until the async task is complete. To achieve this, you could use Semaphore or CountDownLatch. For example, with Semaphore, your method could look as follows:

```<code>fun mySyncMethod(params:Type) {
    Log.d("tag", "1")
    val result = null
    val semaphore = Semaphore(0)
    myAsyncMethod(params) {
        Log.d("tag", "3")
        result = it
        semaphore.release()
    }
    Log.d("tag", "2")
    semaphore.acquireUninterruptibly()
    Log.d("tag", "4")
    return result
}
</code>```

Body:
I have an acync method with callback:

myAsyncMethod(params) {
    handleResult(it)
}

I need to convert it to sync method (block and return result) like this:

val result = mySyncMethod(params)
handleResult(result)

I can't re-implement it by another way because this method provided by third-party library.

I am trying to use ReentrantLock:

fun mySyncMethod(params:Type) {
    Log.d("tag", "1")
    val result = null
    val mutex = ReentrantLock()
    myAsyncMethod(params) {
        Log.d("tag", "3")
        result = it
        mutex.unlock()
    }
    Log.d("tag", "2")
    mutex.lock()
    Log.d("tag", "4")
    return result
}

handleResult(mySyncMethod(params))

I wait that I should see 1, 2, 3, 4. But I get 1, 2, 4, 3 and null in handleResult. I am trying the same with mutex but with the same result. How to make it works?

P.S. Sure I can use synchronized, but in this case I have to use Object-variable additionally.

Body:
I expect that I should see 1, 2, 3, 4.

Then you misunderstood what ReentrantLock is actually for.

If mySyncMethod can be called from different threads, then after mutex.lock() is called, only one thread at a time can execute the code following mutex.lock() - the other threads executing this method have to wait. Once mutex.unlock() is called, one of the waiting threads will execute the code too and so on.

So, the thread owning the mutex forces the other threads to wait but its own flow isn't blocked. myAsyncMethod starts running after the outer method has completed already and hence result is still null.

I need to convert it to sync method (block and return result) like this:

According to your requirements, you need to block the current thread until the async task is complete. To achieve this, you could use Semaphore or CountDownLatch. For example, with Semaphore, your method could look as follows:

fun mySyncMethod(params:Type) {
    Log.d("tag", "1")
    val result = null
    val semaphore = Semaphore(0)
    myAsyncMethod(params) {
        Log.d("tag", "3")
        result = it
        semaphore.release()
    }
    Log.d("tag", "2")
    semaphore.acquireUninterruptibly()
    Log.d("tag", "4")
    return result
}


问:
Python best practice import submodule in submodule
I'm currently reading about Python's submodule in submodule imports and somehow I can't find a proper answer. Here is an example:

```<code>root/
     main.py
     moduleA/
             __init__.py
             log.py
     moduleB/
             __init__.py
             worker.py
</code>```

I'd like to import log in worker by using import moduleA.log. And I'd like to import worker in main and use it there.

So far I've found the following solutions:

Append sys.path with ../ (sys.path.append('../'))

I read something about using pip -e to install my module into the environment.

Avoiding scripts which import from submodules.

I've read that the sys.path hack is considered the best practice. But somehow it feels wrong.

So I'd like to know what is considered best practice by you.

答:
You can use relative imports to solve this issue:

In main.py write

```<code>from .moduleB import worker
</code>```

In worker.py:

```<code>from ..moduleA import log
</code>```

One dot takes the current directory as beginning of the path, so .moduleB digs into the folder moduleB below the current dir.

Two dots moves one dir upwards, so ..moduleA in goes up to the root directory and then down to moduleA. Each additional dot is one directory up.

F.i. from . import ab would import ab.py from the same directory.

Packaging/installing a module is not necessary to do relative imports. But you have to import with from ..moduleA import log. Importing with import ..moduleA.log won't work with relative imports.

Body:
I'm currently reading about Python's submodule in submodule imports and somehow I can't find a proper answer. Here is an example:

root/
     main.py
     moduleA/
             __init__.py
             log.py
     moduleB/
             __init__.py
             worker.py

I'd like to import log in worker by using import moduleA.log. And I'd like to import worker in main and use it there.

So far I've found the following solutions:

Append sys.path with ../ (sys.path.append('../'))

I read something about using pip -e to install my module into the environment.

Avoiding scripts which import from submodules.

I've read that the sys.path hack is considered the best practice. But somehow it feels wrong.

So I'd like to know what is considered best practice by you.

Body:
You can use relative imports to solve this issue:

In main.py write

from .moduleB import worker

In worker.py:

from ..moduleA import log

One dot takes the current directory as beginning of the path, so .moduleB digs into the folder moduleB below the current dir.

Two dots moves one dir upwards, so ..moduleA in goes up to the root directory and then down to moduleA. Each additional dot is one directory up.

F.i. from . import ab would import ab.py from the same directory.

Packaging/installing a module is not necessary to do relative imports. But you have to import with from ..moduleA import log. Importing with import ..moduleA.log won't work with relative imports.


问:
Java regex does not match multiline string
I am sorry I am new in Java. I need to match multiline string in Java which looks like:

```<code>meno je povinné pole
priezvisko je povinné pole
heslo je povinné pole
email je povinné pole
email nemá platný formát
musíte súhlasiť s podmienkami
</code>```

And here is the Pattern to match this string.

```<code>Pattern p = Pattern.compile("meno.+heslo", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.MULTILINE);
Matcher m = p.matcher(alert.getText().toLowerCase());  // text from the example
</code>```

What is wrong with that? If I test only the first line it works. So I think problem is in the lines.

答:
The . will not match the newlines, to fix this use the DOTALL flag when compiling your pattern.

```<code> Pattern.DOTALL
</code>```

The MULTILINE flag will only do the following:

"In multiline mode the expressions ^ and $ match just after or just before, respectively, a line terminator or the end of the input sequence."

Body:
I am sorry I am new in Java. I need to match multiline string in Java which looks like:

meno je povinné pole
priezvisko je povinné pole
heslo je povinné pole
email je povinné pole
email nemá platný formát
musíte súhlasiť s podmienkami

And here is the Pattern to match this string.

Pattern p = Pattern.compile("meno.+heslo", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.MULTILINE);
Matcher m = p.matcher(alert.getText().toLowerCase());  // text from the example

What is wrong with that? If I test only the first line it works. So I think problem is in the lines.

Body:
The . will not match the newlines, to fix this use the DOTALL flag when compiling your pattern.

 Pattern.DOTALL

The MULTILINE flag will only do the following:

"In multiline mode the expressions ^ and $ match just after or just before, respectively, a line terminator or the end of the input sequence."


问:
Custom sequence in Hibernate that should reset yearly
I'm working on simple application that uses Spring MVC 3 and hibernate 3.

I have a requirement to generate ID in the following format.

```<code>Month/Year/number(number will increase).
</code>```

Month and year values do change based on the current Date.
Once the year completed, let say after the completion of one financial year the sequence again start from the beginning, like month/Year/number. Hope I'm clear.

Example:

```<code>1st Financial Year:
Mar/2011/001
Jun/2011/002
Dec/2011/003
Feb/2011/004
...
...

2nd Financial Year:
Mar/2012/001
Mar/2012/002
Aug/2012/003
..
..
..
</code>```

How can I approach this problem?
Please help me.

答:
Look at various options provided here in the hibernate docs.

Here is a related stackoverflow thread.

Finally, your implementation will have to derive from this hibernate interface and then you can implement your custom logic in the generate method.

Body:
I'm working on simple application that uses Spring MVC 3 and hibernate 3.

I have a requirement to generate ID in the following format.

Month/Year/number(number will increase).

Month and year values do change based on the current Date.
Once the year completed, let say after the completion of one financial year the sequence again start from the beginning, like month/Year/number. Hope I'm clear.

Example:

1st Financial Year:
Mar/2011/001
Jun/2011/002
Dec/2011/003
Feb/2011/004
...
...

2nd Financial Year:
Mar/2012/001
Mar/2012/002
Aug/2012/003
..
..
..

How can I approach this problem?
Please help me.


问:
Collapsing rows using two vectors as indicators
This is my first time posting; please let me know if I'm doing any beginner mistakes. In my specific case I have a vector of strings, and I want to collapse some adjacent rows. I have one vector indicating the starting position and one indicating the last element. How can I do this?

Here is some sample code and my approach that does not work:

```<code>text <- c("cat", "dog", "house", "mouse", "street")
x <- c(1,3)
y <- c(2,5)
result <- as.data.frame(paste(text[x:y],sep = " ",collapse = ""))
</code>```

In case it's not clear, the result I want is a data frame consisting of two strings: "cat dog" and "house mouse street".

答:
Another base R solution, using parse + eval

```<code>result <- data.frame(new = sapply(paste0(x,":",y),function(v) paste0(text[eval(parse(text = v))],collapse = " ")),
                     row.names = NULL)
</code>```

such that

```<code>> result
                 new
1            cat dog
2 house mouse street
</code>```

Body:
This is my first time posting; please let me know if I'm doing any beginner mistakes. In my specific case I have a vector of strings, and I want to collapse some adjacent rows. I have one vector indicating the starting position and one indicating the last element. How can I do this?

Here is some sample code and my approach that does not work:

text <- c("cat", "dog", "house", "mouse", "street")
x <- c(1,3)
y <- c(2,5)
result <- as.data.frame(paste(text[x:y],sep = " ",collapse = ""))

In case it's not clear, the result I want is a data frame consisting of two strings: "cat dog" and "house mouse street".

Body:
Another base R solution, using parse + eval

result <- data.frame(new = sapply(paste0(x,":",y),function(v) paste0(text[eval(parse(text = v))],collapse = " ")),
                     row.names = NULL)

such that

> result
                 new
1            cat dog
2 house mouse street


问:
ContiguousPagedList onPageError while I'm not using ContiguousPagedList
I have implementation of PositionalDataSource that defines loadInitial and loadRange. Paging works fine however under some boundary condition (likely related with loading next page in progress while exiting the screen) app crashes with androidx.paging.ContiguousPagedList$1.onPageError (ContiguousPagedList.java:153). However a per https://developer.android.com/reference/android/arch/paging/PositionalDataSource my source is not contiguous?

Crash occurs under ContiguousPagedList's onPageError, line with "todo":

```<code>public void onPageError(@PageResult.ResultType int resultType,
        @NonNull Throwable error, boolean retryable) {

   LoadState errorState = retryable ? LoadState.RETRYABLE_ERROR : LoadState.ERROR;

    if (resultType == PageResult.PREPEND) {
        mLoadStateManager.setState(LoadType.START, errorState, error);
    } else if (resultType == PageResult.APPEND) {
        mLoadStateManager.setState(LoadType.END, errorState, error);
    } else {
        // TODO: pass init signal through to *previous* list
        throw new IllegalStateException("TODO");
    }
}
</code>```

My configuration is not using placeholders, and I'm not passing total count into onResult of LoadInitialCallback. Version of paging library is 2.1.1

答:
There is no good and clean solution at least for now(version 2.1.1).

ContiguousPagedList doesn't support error handling for initialization.
You have to implement parallel streams for loading statuses and custom retry.

See the example in the official architecture components samples library.
Yigit Boyar implemented few streams by returning custom Listing object from the repository.

data class Listing<T>(
        // the LiveData of paged lists for the UI to observe
        val pagedList: LiveData<PagedList<T>>,
        // represents the network request status to show to the user
        val networkState: LiveData<NetworkState>,
        // represents the refresh status to show to the user. Separate from networkState, this
        // value is importantly only when refresh is requested.
        val refreshState: LiveData<NetworkState>,
        // refreshes the whole data and fetches it from scratch.
        val refresh: () -> Unit,
        // retries any failed requests.
        val retry: () -> Unit)
```

See the implementation of data source here

Update

After many different tries, I end-up removing Jetpack from the core part of the architecture, and leave it only in view model, looks much cleaner for me now. You can read about it here

Body:
I have implementation of PositionalDataSource that defines loadInitial and loadRange. Paging works fine however under some boundary condition (likely related with loading next page in progress while exiting the screen) app crashes with androidx.paging.ContiguousPagedList$1.onPageError (ContiguousPagedList.java:153). However a per https://developer.android.com/reference/android/arch/paging/PositionalDataSource my source is not contiguous?

Crash occurs under ContiguousPagedList's onPageError, line with "todo":

public void onPageError(@PageResult.ResultType int resultType,
        @NonNull Throwable error, boolean retryable) {

   LoadState errorState = retryable ? LoadState.RETRYABLE_ERROR : LoadState.ERROR;

    if (resultType == PageResult.PREPEND) {
        mLoadStateManager.setState(LoadType.START, errorState, error);
    } else if (resultType == PageResult.APPEND) {
        mLoadStateManager.setState(LoadType.END, errorState, error);
    } else {
        // TODO: pass init signal through to *previous* list
        throw new IllegalStateException("TODO");
    }
}

My configuration is not using placeholders, and I'm not passing total count into onResult of LoadInitialCallback. Version of paging library is 2.1.1

Body:
There is no good and clean solution at least for now(version 2.1.1).

ContiguousPagedList doesn't support error handling for initialization.
You have to implement parallel streams for loading statuses and custom retry.

See the example in the official architecture components samples library.
Yigit Boyar implemented few streams by returning custom Listing object from the repository.

data class Listing<T>(
        // the LiveData of paged lists for the UI to observe
        val pagedList: LiveData<PagedList<T>>,
        // represents the network request status to show to the user
        val networkState: LiveData<NetworkState>,
        // represents the refresh status to show to the user. Separate from networkState, this
        // value is importantly only when refresh is requested.
        val refreshState: LiveData<NetworkState>,
        // refreshes the whole data and fetches it from scratch.
        val refresh: () -> Unit,
        // retries any failed requests.
        val retry: () -> Unit)

See the implementation of data source here

Update

After many different tries, I end-up removing Jetpack from the core part of the architecture, and leave it only in view model, looks much cleaner for me now. You can read about it here


问:
How to sum float numbers in the format hours and minutes?
How to sum float numbers in the format hours and minutes?

Those. if  calculate two such numbers 0.35+3.45 then it should be = 4.20, not 3.80

var arr = [0.15, 0.2, 3.45, 0.4, 2, 0.3, 5.2, 1, 1.4, 1.1, 2.4, 1, 3.4]

var sum = 0.0;

arr.forEach(function(item) {
  console.log(sum);
  sum += parseFloat(item);
});```
</div>
</div>
</p>

<p>The result should be like this:</p>

```0
0.15
0.35
4.20
5.0
7.0
7.30
12.50
13.50
15.30
16.40
19.20
20.20
```

答:
The best way to deal with "crazy" data formats like that is to first convert them into a sane and easily processable format, do whatever you need to do using the converted data and finally (if you absolutely have to) convert the results back to the original format.

(Of course, the real solution is to stop using such crazy time representations entirely.  But that's not always practical, e.g. because you need to interface with a legacy system that you cannot change.)

In your case, a suitable sane format for your data would be e.g. an integral number of minutes.  Once you've converted your data to this format, you can then do ordinary arithmetic on it.

// converts a pseudo-float of the form hh.mm into an integer number of minutes
// robust against floating-point roundoff errors, also works for negative numbers
function hhMmToMinutes(x) {
  const hhmm = Math.round(100 * x)  // convert hh.mm -> hhmm
  return 60 * Math.trunc(hhmm / 100) + (hhmm % 100)
}

// convert minutes back to hh.mm pseudo-float format
// use minutesToHhMm(minutes).toFixed(2) if you want trailing zeros
function minutesToHhMm(minutes) {
  return Math.trunc(minutes / 60) + (minutes % 60) / 100
}

const arr = [0.15, 0.2, 3.45, 0.4, 2, 0.3, 5.2, 1, 1.4, 1.1, 2.4, 1, 3.4]

let sum = 0
console.log( arr.map(hhMmToMinutes).map(x => sum += x).map(minutesToHhMm) )```
</div>
</div>
</p>

<p>Note that the conversion code above first multiplies the input float by 100 and rounds it to an integer before separating the hour and minute parts.  This should robustly handle inputs with possible rounding errors while avoiding the need to stringify the inputs.</p>

<p>The reason for taking extra care here is because the number 0.01 = 1/100 (and most of its multiples) is not actually exactly representable in the binary floating-point format used by JavaScript.  Thus you can't actually have a JS number that would be <em>exactly</em> equal 0.01 — the best you can have is a number that's so close that converting it to a string will automatically hide the error.  But the rounding error is still there, and can bite you if you try to do things like comparing such numbers to a exact threshold.  Here's a nice and simple demonstration:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>console.log(Math.trunc(100 * 0.29))  // you'd think this would be 29...</code>```

Body:
How to sum float numbers in the format hours and minutes?

Those. if  calculate two such numbers 0.35+3.45 then it should be = 4.20, not 3.80

var arr = [0.15, 0.2, 3.45, 0.4, 2, 0.3, 5.2, 1, 1.4, 1.1, 2.4, 1, 3.4]

var sum = 0.0;

arr.forEach(function(item) {
  console.log(sum);
  sum += parseFloat(item);
});

The result should be like this:

0
0.15
0.35
4.20
5.0
7.0
7.30
12.50
13.50
15.30
16.40
19.20
20.20

Body:
The best way to deal with "crazy" data formats like that is to first convert them into a sane and easily processable format, do whatever you need to do using the converted data and finally (if you absolutely have to) convert the results back to the original format.

(Of course, the real solution is to stop using such crazy time representations entirely.  But that's not always practical, e.g. because you need to interface with a legacy system that you cannot change.)

In your case, a suitable sane format for your data would be e.g. an integral number of minutes.  Once you've converted your data to this format, you can then do ordinary arithmetic on it.

// converts a pseudo-float of the form hh.mm into an integer number of minutes
// robust against floating-point roundoff errors, also works for negative numbers
function hhMmToMinutes(x) {
  const hhmm = Math.round(100 * x)  // convert hh.mm -> hhmm
  return 60 * Math.trunc(hhmm / 100) + (hhmm % 100)
}

// convert minutes back to hh.mm pseudo-float format
// use minutesToHhMm(minutes).toFixed(2) if you want trailing zeros
function minutesToHhMm(minutes) {
  return Math.trunc(minutes / 60) + (minutes % 60) / 100
}

const arr = [0.15, 0.2, 3.45, 0.4, 2, 0.3, 5.2, 1, 1.4, 1.1, 2.4, 1, 3.4]

let sum = 0
console.log( arr.map(hhMmToMinutes).map(x => sum += x).map(minutesToHhMm) )

Note that the conversion code above first multiplies the input float by 100 and rounds it to an integer before separating the hour and minute parts.  This should robustly handle inputs with possible rounding errors while avoiding the need to stringify the inputs.

The reason for taking extra care here is because the number 0.01 = 1/100 (and most of its multiples) is not actually exactly representable in the binary floating-point format used by JavaScript.  Thus you can't actually have a JS number that would be exactly equal 0.01 — the best you can have is a number that's so close that converting it to a string will automatically hide the error.  But the rounding error is still there, and can bite you if you try to do things like comparing such numbers to a exact threshold.  Here's a nice and simple demonstration:

console.log(Math.trunc(100 * 0.29))  // you'd think this would be 29...


问:
Why I can sometimes use functions from nested modules without importing the whole path?
I was wondering what's the difference between these two cases? Is the inner structure of the modules somehow different?

So why this one works:

```<code>>>> import numpy
>>> numpy.random.RandomState
<class 'numpy.random.mtrand.RandomState'>
</code>```

But this one doesn't work until I import the nested module also:

```<code>>>> import tkinter
>>> tkinter.ttk.Spinbox
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'tkinter' has no attribute 'ttk'
>>> import tkinter.ttk
>>> tkinter.ttk.Spinbox
<class 'tkinter.ttk.Spinbox'>
</code>```

I think that this must be something to do with the __init__.py files in each module, but a concrete example of an implementation would be helpful.

答:
By default, when you load a "package" (which is really just a directory with a __init__.py file, Python loads just the __init__.py file.

In that file, if you want, you can automatically load other things, such as modules (other .py files) and even other packages (dirs with __init__.py)

So the reason that those libraries differ is most likely due to a difference in how the __init__.py files are set up.

For instance, I've created a package with a single module. I have the module imported by the __init__.py file so that it loads automatically.

Body:
I was wondering what's the difference between these two cases? Is the inner structure of the modules somehow different?

So why this one works:

>>> import numpy
>>> numpy.random.RandomState
<class 'numpy.random.mtrand.RandomState'>

But this one doesn't work until I import the nested module also:

>>> import tkinter
>>> tkinter.ttk.Spinbox
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'tkinter' has no attribute 'ttk'
>>> import tkinter.ttk
>>> tkinter.ttk.Spinbox
<class 'tkinter.ttk.Spinbox'>

I think that this must be something to do with the __init__.py files in each module, but a concrete example of an implementation would be helpful.


问:
Sort array of objects by date property
Hello guys I want to sort array by "New_date" but in some cases there is another object inside of main object with key "New_date". Do you know how could I sort array in this case?

```<code>  arr.sort(function(a, b) {

        a = new Date(a.New_date);
        b = new Date(b.New_date);
        return a>b ? -1 : a<b ? 1 : 0;
    });

arr=
[0: {name:"Angel", data "random data", New_date: "2020-12-10"},
 1: [0: {name:"Tom", data "random data"},
     1: {name:"Tom", data "random data"},
     New_date:"2020-11-10"],
 2:name:"Angel", data "random data", New_date: "2020-09-10"}]
</code>```

答:
Here is a solution with a correctly formatted array.

let arr = [
  { name: "Angel", data: "random data", New_date: "2020-12-10" },
  { name: "Tom", data: "random data", New_date: "2019-11-10" },
  { name: "Tom", data: "random data", New_date: "2020-11-10" },
  { name: "Angel", data: "random data", New_date: "2020-09-10" },
]
console.log('ascending', arr.sort((a, b) => new Date(a.New_date) - new Date(b.New_date)))
console.log('descending', arr.sort((a, b) => new Date(b.New_date) - new Date(a.New_date)))```

Title: Sort array of objects by date property

Body:
Hello guys I want to sort array by "New_date" but in some cases there is another object inside of main object with key "New_date". Do you know how could I sort array in this case?

  arr.sort(function(a, b) {

        a = new Date(a.New_date);
        b = new Date(b.New_date);
        return a>b ? -1 : a<b ? 1 : 0;
    });

arr=
[0: {name:"Angel", data "random data", New_date: "2020-12-10"},
 1: [0: {name:"Tom", data "random data"},
     1: {name:"Tom", data "random data"},
     New_date:"2020-11-10"],
 2:name:"Angel", data "random data", New_date: "2020-09-10"}]


问:
Bulk create a primary object and objects referencing the primary object at the same time?
```<code>class Profile(models.Model):
    pass

class Experience(models.Model):
    profile = models.ForeignKey(Profile)
</code>```

How would I save a a Profile along with a list of Experiences with a single transaction?

Right now I'm doing the following

```<code>p = Profile()
p.save()

e_list = [Experience(profile=p), Experience(profile=p)]
Education.objects.bulk_create(e_list)
</code>```

Which is two database hits, can I do it in one?

答:
Use transaction.atomic in order to have multiple queries in the same transaction:

```<code>from django.db import transaction

with transaction.atomic():
    p = Profile()
    p.save()

    e_list = [Experience(profile=p), Experience(profile=p)]
    Education.objects.bulk_create(e_list)
</code>```

Body:
class Profile(models.Model):
    pass

class Experience(models.Model):
    profile = models.ForeignKey(Profile)

How would I save a a Profile along with a list of Experiences with a single transaction?

Right now I'm doing the following

p = Profile()
p.save()

e_list = [Experience(profile=p), Experience(profile=p)]
Education.objects.bulk_create(e_list)

Which is two database hits, can I do it in one?

Body:
Use transaction.atomic in order to have multiple queries in the same transaction:

from django.db import transaction

with transaction.atomic():
    p = Profile()
    p.save()

    e_list = [Experience(profile=p), Experience(profile=p)]
    Education.objects.bulk_create(e_list)


问:
How to change the last value in a pandas dataframe which conditioned out by loc?
I would like to change the value of the last row of conditioned out by loc

I tried the following and it did not work...

```<code>df.loc({condition}, {column}).iloc[-1] = {some_value}
</code>```

Body:
I would like to change the value of the last row of conditioned out by loc

I tried the following and it did not work...

df.loc({condition}, {column}).iloc[-1] = {some_value}

Body:
Say I have this DF:

   Stake  Odds Ftr  Ind
0   0.25  2.50   H    1
1   0.15  4.00   D    2
2   0.26  1.75   A    2
3   0.30  2.20   H    1
4   0.10  1.85   H    3
5   0.40  3.20   A    3
6   0.32  1.50   D    3
7   0.11  1.20   H    1
8   0.20  2.15   H    2
9   0.25  1.65   A    2

When I run:

a = df[df['Ftr']=='H'].tail(1).index.values[0]
df.iloc[a,int(df.columns.get_indexer(['Odds']))] = 10

I get:

   Stake   Odds Ftr  Ind
0   0.25   2.50   H    1
1   0.15   4.00   D    2
2   0.26   1.75   A    2
3   0.30   2.20   H    1
4   0.10   1.85   H    3
5   0.40   3.20   A    3
6   0.32   1.50   D    3
7   0.11   1.20   H    1
8   0.20  10.00   H    2
9   0.25   1.65   A    2

Is this what you are looking for?


问:
SQL: How to construct a time series from irregular data and then subsequently calculate a rolling average over it
I am trying to calculate a rolling average of data from incident reports. The exact quantity I'm looking for is the 30-day-mean-time-to-resolution (mttr) which means the average of the time it takes to resolve incidents in the last 30 days.

My incidents table looks something like this:

```<code>| incident_id | start_datetime        | end_datetime          |
|-------------|-----------------------|-----------------------|
| 1           | '2020-02-01T10:13:00' | '2020-02-01T10:59:33' |
| 2           | '2020-02-01T17:55:13' | '2020-02-02T00:35:28' |
| 3           | '2020-02-03T13:33:01' | '2020-02-03T15:54:01' |
</code>```

What I want is something like this (the numbers are made up so don't try to actually calculate-- just note that the datetime intervals are every hour):

```<code>| datetime              | mttr_last30days_in_hours |
|-----------------------|--------------------------|
| '2020-02-01T10:00:00' | 5.7                      |
| '2020-02-01T11:00:00' | 5.6                      |
| '2020-02-02T12:00:00' | 5.8                      |
</code>```

I can calculate the mttr in the last 30 days really easily if I'm doing it just for one point in time:

SELECT avg(end_datetime - start_datetime) mttr_last30days_in_hours
FROM incidents
WHERE datetime_diff(current_datetime(), start_datetime, DAY) <= 30
```

The problem is this just gives me ONE number. How do I create a time series spanning the range of say, the first incident's start_datetime (min(start_datetime)) to the current time, and then get a rolling 30 day average with evenly spaced, hourly intervals (like the example table above)?

答:
If you have an unique field in your table, you can try doing that:

```<code>WITH

t_filter AS(
  SELECT
     *
  FROM
    incidents
  WHERE datetime_diff(current_datetime(), start_datetime, DAY) <= 30
),

t_dates AS (
  SELECT
    unique_key,
    GENERATE_DATE_ARRAY(DATE(start_datetime), CURRENT_DATE(), INTERVAL 1 DAY) AS date_array
  FROM
    t_filter
),

t_hour AS (
  SELECT *
  FROM
  UNNEST(["00:00:00",
    "01:00:00",
    "02:00:00",
    "03:00:00",
    "04:00:00",
    "05:00:00",
    "06:00:00",
    "07:00:00",
    "08:00:00",
    "09:00:00",
    "10:00:00",
    "11:00:00",
    "12:00:00",
    "13:00:00",
    "14:00:00",
    "15:00:00",
    "16:00:00",
    "17:00:00",
    "18:00:00",
    "19:00:00",
    "20:00:00",
    "21:00:00",
    "22:00:00",
    "23:00:00"]) h
),

sequence AS(
  SELECT
    unique_key,
    CONCAT(CAST(arr AS string),"T", h) date_hour
  FROM
    t_dates,
    UNNEST(date_array) arr,
    t_hour
)

SELECT
  date_hour,
  AVG(end_datetime - start_datetime)
FROM
  sequence
LEFT JOIN
  t_filter
ON
incidents.unique_key = sequence.unique_key
GROUP BY
  date_hour
</code>```

I hope it helps

Body:
I am trying to calculate a rolling average of data from incident reports. The exact quantity I'm looking for is the 30-day-mean-time-to-resolution (mttr) which means the average of the time it takes to resolve incidents in the last 30 days.

My incidents table looks something like this:

| incident_id | start_datetime        | end_datetime          |
|-------------|-----------------------|-----------------------|
| 1           | '2020-02-01T10:13:00' | '2020-02-01T10:59:33' |
| 2           | '2020-02-01T17:55:13' | '2020-02-02T00:35:28' |
| 3           | '2020-02-03T13:33:01' | '2020-02-03T15:54:01' |

What I want is something like this (the numbers are made up so don't try to actually calculate-- just note that the datetime intervals are every hour):

| datetime              | mttr_last30days_in_hours |
|-----------------------|--------------------------|
| '2020-02-01T10:00:00' | 5.7                      |
| '2020-02-01T11:00:00' | 5.6                      |
| '2020-02-02T12:00:00' | 5.8                      |

I can calculate the mttr in the last 30 days really easily if I'm doing it just for one point in time:

SELECT avg(end_datetime - start_datetime) mttr_last30days_in_hours
FROM incidents
WHERE datetime_diff(current_datetime(), start_datetime, DAY) <= 30

The problem is this just gives me ONE number. How do I create a time series spanning the range of say, the first incident's start_datetime (min(start_datetime)) to the current time, and then get a rolling 30 day average with evenly spaced, hourly intervals (like the example table above)?

Body:
If you have an unique field in your table, you can try doing that:

WITH

t_filter AS(
  SELECT
     *
  FROM
    incidents
  WHERE datetime_diff(current_datetime(), start_datetime, DAY) <= 30
),

t_dates AS (
  SELECT
    unique_key,
    GENERATE_DATE_ARRAY(DATE(start_datetime), CURRENT_DATE(), INTERVAL 1 DAY) AS date_array
  FROM
    t_filter
),

t_hour AS (
  SELECT *
  FROM
  UNNEST(["00:00:00",
    "01:00:00",
    "02:00:00",
    "03:00:00",
    "04:00:00",
    "05:00:00",
    "06:00:00",
    "07:00:00",
    "08:00:00",
    "09:00:00",
    "10:00:00",
    "11:00:00",
    "12:00:00",
    "13:00:00",
    "14:00:00",
    "15:00:00",
    "16:00:00",
    "17:00:00",
    "18:00:00",
    "19:00:00",
    "20:00:00",
    "21:00:00",
    "22:00:00",
    "23:00:00"]) h
),

sequence AS(
  SELECT
    unique_key,
    CONCAT(CAST(arr AS string),"T", h) date_hour
  FROM
    t_dates,
    UNNEST(date_array) arr,
    t_hour
)

SELECT
  date_hour,
  AVG(end_datetime - start_datetime)
FROM
  sequence
LEFT JOIN
  t_filter
ON
incidents.unique_key = sequence.unique_key
GROUP BY
  date_hour

I hope it helps


问:
Swift perform action when become first responder
Is there a default method that is called when a UITextField or similar becomes the first responder, in order to have actions occur at that point?</p>

答:
You can check the UItextfield delegate methods in this link
and choose the one that fits your need.

Just don't forget to make assign the UItextfield.delegate to the class using it.


问:
React Navigation V5 Hide Bottom Tabs
I would like to be able to hide the tabs on a screen using React Native Navigation v5.

I've been reading the documentation but it doesn't seem like they've updated this for v5 and it refers to the < v4 way of doing things.

here is my code:

```<code>import Home from './components/Home';
import SettingsScreen from './components/Settings';
import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { createStackNavigator } from '@react-navigation/stack';

const SettingsStack = createStackNavigator();
const ProfileStack  = createStackNavigator();

function SettingsStackScreen() {
    return (
        <SettingsStack.Navigator>
            <SettingsStack.Screen name="Settings" component={SettingsScreen} />
        </SettingsStack.Navigator>
    )
}

function ProfileStackScreen() {
    return (
        <ProfileStack.Navigator>
            <ProfileStack.Screen name="Home" component={Home} />
        </ProfileStack.Navigator>
    )
}

const Tab = createBottomTabNavigator();

export default function App() {
  return (
    <NavigationContainer>
      <Tab.Navigator>
        <Tab.Screen name="Home" component={ProfileStackScreen} />
        <Tab.Screen name="Settings" component={SettingsStackScreen} />
      </Tab.Navigator>
    </NavigationContainer>
  );
}
</code>```

Things I have tried:

Accessing the options of the function and hiding that way.

Passing tabBarVisible as a prop to the Screen.

What I am asking for is, what is the correct way of hiding tabs on screens in React Navigation v5.

答:
The above answer will help you to remove the bottom tabs from the root navigation.If you want to remove bottom tabs from a specific screen like Home Screen or Settings Screen you need to change navigation options dynamically.

For changing navigation options dynamically you will need the concept of:

React.Context

useNavigationState

Context - will dynamically change the navigationOption value i.e. either to hide the bottom Tabs or not. We can choose MobX or Redux to do the same.

UseNavigationState - will help context to know at which screen the user is.

We need to create Context in a separate .js file so that Home.js and Settings.js can access it in all the other screens.

```<code>import * as React from 'react';
import { View, Text } from 'react-native'
import { NavigationContainer, useNavigationState, useRoute } from '@react-navigation/native';
const Tab = createBottomTabNavigator();
const Context = React.createContext();

import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { createStackNavigator } from '@react-navigation/stack';
import { TouchableOpacity } from 'react-native-gesture-handler';

const SettingsStack = createStackNavigator();
const ProfileStack = createStackNavigator();

function SettingsScreen({ navigation }) {
  return (
    <View>
      <Text>
        Setting
      </Text>
    </View>
  );
}

function Home({ navigation }) {
  const rout = useNavigationState(state => state);
  const { screen, setScreen } = React.useContext(Context);
  setScreen(rout.index);
  return (
    <View>
      <TouchableOpacity
        onPress={() => {
          navigation.navigate("Settings");
        }}
      >
        <Text>
          Home
        </Text>
      </TouchableOpacity>
    </View>
  );
}

function SettingsStackScreen({ navigation }) {
  return (
    <SettingsStack.Navigator>
      <SettingsStack.Screen name="Settings" component={SettingsScreen} />
    </SettingsStack.Navigator>
  )
}

function ProfileStackScreen({ navigation }) {
  const { screen, setScreen } = React.useContext(Context)
  if (screen == 0) {
    navigation.setOptions({ tabBarVisible: true })
  } else {
    navigation.setOptions({ tabBarVisible: false })
  }
  return (
    <ProfileStack.Navigator>
      <ProfileStack.Screen name="Home" component={Home} />
      <ProfileStack.Screen name="Settings" component={SettingsScreen} />
    </ProfileStack.Navigator>
  )
}

function BottomNav({ navigation }) {
  return (
    <Tab.Navigator>
      <Tab.Screen name="Home" component={ProfileStackScreen} />
      <Tab.Screen name="Settings" component={SettingsStackScreen} />
    </Tab.Navigator>
  );
}

export default function App() {
  const [screen, setScreen] = React.useState(0);

  return (
    <Context.Provider value={{ screen, setScreen }}>
      <NavigationContainer>
        <BottomNav />
      </NavigationContainer>
    </Context.Provider>
  );
}
</code>```

Here the screen is a flag that checks the index of the navigation and removes the bottom navigation for all the screen stacked in ProfileStackScreen.

Title: React Navigation V5 Hide Bottom Tabs

Body:
I would like to be able to hide the tabs on a screen using React Native Navigation v5.

I've been reading the documentation but it doesn't seem like they've updated this for v5 and it refers to the < v4 way of doing things.

here is my code:

import Home from './components/Home';
import SettingsScreen from './components/Settings';
import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { createStackNavigator } from '@react-navigation/stack';

const SettingsStack = createStackNavigator();
const ProfileStack  = createStackNavigator();

function SettingsStackScreen() {
    return (
        <SettingsStack.Navigator>
            <SettingsStack.Screen name="Settings" component={SettingsScreen} />
        </SettingsStack.Navigator>
    )
}

function ProfileStackScreen() {
    return (
        <ProfileStack.Navigator>
            <ProfileStack.Screen name="Home" component={Home} />
        </ProfileStack.Navigator>
    )
}

const Tab = createBottomTabNavigator();

export default function App() {
  return (
    <NavigationContainer>
      <Tab.Navigator>
        <Tab.Screen name="Home" component={ProfileStackScreen} />
        <Tab.Screen name="Settings" component={SettingsStackScreen} />
      </Tab.Navigator>
    </NavigationContainer>
  );
}

Things I have tried:

Accessing the options of the function and hiding that way.

Passing tabBarVisible as a prop to the Screen.

What I am asking for is, what is the correct way of hiding tabs on screens in React Navigation v5.

Body:
The above answer will help you to remove the bottom tabs from the root navigation.If you want to remove bottom tabs from a specific screen like Home Screen or Settings Screen you need to change navigation options dynamically.

For changing navigation options dynamically you will need the concept of:

React.Context

useNavigationState

Context - will dynamically change the navigationOption value i.e. either to hide the bottom Tabs or not. We can choose MobX or Redux to do the same.

UseNavigationState - will help context to know at which screen the user is.

We need to create Context in a separate .js file so that Home.js and Settings.js can access it in all the other screens.

import * as React from 'react';
import { View, Text } from 'react-native'
import { NavigationContainer, useNavigationState, useRoute } from '@react-navigation/native';
const Tab = createBottomTabNavigator();
const Context = React.createContext();

import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { createStackNavigator } from '@react-navigation/stack';
import { TouchableOpacity } from 'react-native-gesture-handler';

const SettingsStack = createStackNavigator();
const ProfileStack = createStackNavigator();

function SettingsScreen({ navigation }) {
  return (
    <View>
      <Text>
        Setting
      </Text>
    </View>
  );
}

function Home({ navigation }) {
  const rout = useNavigationState(state => state);
  const { screen, setScreen } = React.useContext(Context);
  setScreen(rout.index);
  return (
    <View>
      <TouchableOpacity
        onPress={() => {
          navigation.navigate("Settings");
        }}
      >
        <Text>
          Home
        </Text>
      </TouchableOpacity>
    </View>
  );
}

function SettingsStackScreen({ navigation }) {
  return (
    <SettingsStack.Navigator>
      <SettingsStack.Screen name="Settings" component={SettingsScreen} />
    </SettingsStack.Navigator>
  )
}

function ProfileStackScreen({ navigation }) {
  const { screen, setScreen } = React.useContext(Context)
  if (screen == 0) {
    navigation.setOptions({ tabBarVisible: true })
  } else {
    navigation.setOptions({ tabBarVisible: false })
  }
  return (
    <ProfileStack.Navigator>
      <ProfileStack.Screen name="Home" component={Home} />
      <ProfileStack.Screen name="Settings" component={SettingsScreen} />
    </ProfileStack.Navigator>
  )
}

function BottomNav({ navigation }) {
  return (
    <Tab.Navigator>
      <Tab.Screen name="Home" component={ProfileStackScreen} />
      <Tab.Screen name="Settings" component={SettingsStackScreen} />
    </Tab.Navigator>
  );
}

export default function App() {
  const [screen, setScreen] = React.useState(0);

  return (
    <Context.Provider value={{ screen, setScreen }}>
      <NavigationContainer>
        <BottomNav />
      </NavigationContainer>
    </Context.Provider>
  );
}

Here the screen is a flag that checks the index of the navigation and removes the bottom navigation for all the screen stacked in ProfileStackScreen.


问:
Send a mail using Javascript without going through Outlook
Is it possible to Send a mail using Javascript without going through Outlook</p>

答:
Short answer: no.
Long answer: if you use a server-side component that you access asynchronously, yes.</p>


问:
Stage changes in file below a certain line number
I made two sets of changes in a single file.
They are conceptually different so I would like to keep them in seperate commits.

Can I stage the changes in a certain range or everything above or a below a line from the command line?

I.e. something like the following:

```<code>git add file -lines 124:421
</code>```

答:
You can use git add -p and then select the hunks ou wish to add.

These are the options you can do within add -p:

```<code>y - stage this hunk
n - do not stage this hunk
q - quit, do not stage this hunk nor any of the remaining ones
a - stage this and all the remaining hunks in the file
d - do not stage this hunk nor any of the remaining hunks in the file
g - select a hunk to go to
/ - search for a hunk matching the given regex
j - leave this hunk undecided, see next undecided hunk
J - leave this hunk undecided, see next hunk
k - leave this hunk undecided, see previous undecided hunk
K - leave this hunk undecided, see previous hunk
s - split the current hunk into smaller hunks
e - manually edit the current hunk
? - print help
</code>```

Once you use the s it will pick the chunk of code which can be considered as a standalone change. If you want to split it even more you will have to use the e to edit the hunk and then add it back to the stage area.

Summary:

To split hunks you use the s flag.

If you need to split it into even smaller chunks you will need to manually edit it using the e option.

Body:
I made two sets of changes in a single file.
They are conceptually different so I would like to keep them in seperate commits.

Can I stage the changes in a certain range or everything above or a below a line from the command line?

I.e. something like the following:

git add file -lines 124:421

Body:
You can use git add -p and then select the hunks ou wish to add.

These are the options you can do within add -p:

y - stage this hunk
n - do not stage this hunk
q - quit, do not stage this hunk nor any of the remaining ones
a - stage this and all the remaining hunks in the file
d - do not stage this hunk nor any of the remaining hunks in the file
g - select a hunk to go to
/ - search for a hunk matching the given regex
j - leave this hunk undecided, see next undecided hunk
J - leave this hunk undecided, see next hunk
k - leave this hunk undecided, see previous undecided hunk
K - leave this hunk undecided, see previous hunk
s - split the current hunk into smaller hunks
e - manually edit the current hunk
? - print help

Once you use the s it will pick the chunk of code which can be considered as a standalone change. If you want to split it even more you will have to use the e to edit the hunk and then add it back to the stage area.

Summary:

To split hunks you use the s flag.

If you need to split it into even smaller chunks you will need to manually edit it using the e option.


问:
Drop column from SQLite table
I have a problem: I need to delete a column from my SQLite database. I wrote this query

```<code>alter table table_name drop column column_name
</code>```

but it does not work. Please help me.

答:
I've made a Python function where you enter the table and column to remove as arguments:

```<code>def removeColumn(table, column):
    columns = []
    for row in c.execute('PRAGMA table_info(' + table + ')'):
        columns.append(row[1])
    columns.remove(column)
    columns = str(columns)
    columns = columns.replace("[", "(")
    columns = columns.replace("]", ")")
    for i in ["\'", "(", ")"]:
        columns = columns.replace(i, "")
    c.execute('CREATE TABLE temptable AS SELECT ' + columns + ' FROM ' + table)
    c.execute('DROP TABLE ' + table)
    c.execute('ALTER TABLE temptable RENAME TO ' + table)
    conn.commit()
</code>```

As per the info on Duda's and MeBigFatGuy's answers this won't work if there is a foreign key on the table, but this can be fixed with 2 lines of code (creating a new table and not just renaming the temporary table)

Title: Drop column from SQLite table

Body:
I have a problem: I need to delete a column from my SQLite database. I wrote this query

alter table table_name drop column column_name

but it does not work. Please help me.

Body:
I've made a Python function where you enter the table and column to remove as arguments:

def removeColumn(table, column):
    columns = []
    for row in c.execute('PRAGMA table_info(' + table + ')'):
        columns.append(row[1])
    columns.remove(column)
    columns = str(columns)
    columns = columns.replace("[", "(")
    columns = columns.replace("]", ")")
    for i in ["\'", "(", ")"]:
        columns = columns.replace(i, "")
    c.execute('CREATE TABLE temptable AS SELECT ' + columns + ' FROM ' + table)
    c.execute('DROP TABLE ' + table)
    c.execute('ALTER TABLE temptable RENAME TO ' + table)
    conn.commit()

As per the info on Duda's and MeBigFatGuy's answers this won't work if there is a foreign key on the table, but this can be fixed with 2 lines of code (creating a new table and not just renaming the temporary table)