问:
How to take lag on mutliple columns as given below in R or Python
Here is the reproducible example. I have more than 800 columns. I want to take the lags as given below.

```<code>ppt <- ts(rep(c(5,6,7,8,11,13,14,15,16,15,14,17,13,12,15,13,12,12,11,10,9,8,7,6), 10)*runif(120,0.8,1.2), freq = 24)
col <- c(1:20)
data <- data.frame(lapply(col, function(x) ppt[x:(110+x)])) # create a design matrix
colnames(data) <- c(paste0("x_",as.character(c(1:19))),"y")
</code>```

答:
We can use lag in dplyr

```<code>library(dplyr)

data %>%
  mutate_all(list(lag1 = ~lag(.), lag2 = ~lag(., 2), lag3 = ~lag(., 3))) %>%
  select(gtools:: mixedorder(names(.)))
</code>```

Or if you want to only lag columns that start with "x", we can use mutate_at

```<code>data %>%
  mutate_at(vars(starts_with('x')), list(lag1 = ~lag(.), lag2 = ~lag(., 2),
                                         lag3 = ~lag(., 3))) %>%
  select(gtools:: mixedorder(names(.)))
</code>```

Body:
Here is the reproducible example. I have more than 800 columns. I want to take the lags as given below.

ppt <- ts(rep(c(5,6,7,8,11,13,14,15,16,15,14,17,13,12,15,13,12,12,11,10,9,8,7,6), 10)*runif(120,0.8,1.2), freq = 24)
col <- c(1:20)
data <- data.frame(lapply(col, function(x) ppt[x:(110+x)])) # create a design matrix
colnames(data) <- c(paste0("x_",as.character(c(1:19))),"y")

Body:
We can use lag in dplyr

library(dplyr)

data %>%
  mutate_all(list(lag1 = ~lag(.), lag2 = ~lag(., 2), lag3 = ~lag(., 3))) %>%
  select(gtools:: mixedorder(names(.)))

Or if you want to only lag columns that start with "x", we can use mutate_at

data %>%
  mutate_at(vars(starts_with('x')), list(lag1 = ~lag(.), lag2 = ~lag(., 2),
                                         lag3 = ~lag(., 3))) %>%
  select(gtools:: mixedorder(names(.)))


来源: stackexchange

问:
Issue with the logo and its position using media queries
As the title states my logo for this assignment needs to be in certain areas of the screen in different screen sizes. I have the mobile positioning correctly implemented but I can't seem to find a solution the positioning of the logo for ipad and larger screens.

For large screens the logo needs to be centered directly above the first .product element, which in my case is the A as in Apple

For ipad screens the logo needs to be halfway between the left edge of the screen and the centered h1 element

No matter what I try the logo just stays fixed the left.

I realize that in css its position is set to float:left but I've changed it to display:flex and the various flexbox properties, but it ended up creating more of a problem. I've changed the logo position in each @media query but the logo always ended up staying in place or way off from where it needs to be.

I understand that google is my best friend but I've exhausted all possible methods and have reached my last resort. The last I wanted to do was get stuck and immediately post here without at least trying for several hours. Forgive me for the newbie and probably obvious question but I'm at my wits end and really need help . Thank you.

* {
  box-sizing: border-box;
  text-align: center;
}

body {
  font-family: "Roboto", sans-serif;
  margin: 0;
  padding: 0;
}

body>i> {
  flex-grow: 0;
}

body>header> {
  flex-grow: 1;
}

.logo>img {
  width: 50px;
}

p {
  text-align: left;
  padding: 15px;
}

.navbar {
  background-color: rgb(105, 105, 105);
  padding: 10px;
  color: white;
  width: 100%;
}

.hamburger {
  display: flex;
  flex-direction: row-reverse;
}

.social {
  display: flex;
  padding-top: 20px;
  flex-direction: row;
  justify-content: space-around;
  border-top: 2px solid #e2e2e2;
}

ul {
  list-style: none;
}

li {
  line-height: 5px;
  float: right;
  padding: 0 0 50px 0;
  margin-right: 30px;
  margin-top: -10px;
}

.product {
  border: 1px solid lightgray;
  border-radius: 10px;
  margin: 10px 30px;
  padding: 10px;
}

@media screen and (max-width: 700px) {
  .logo {
    float: left;
  }
  .menu {
    display: none;
  }
  .logo {
    float: left;
  }
}

@media screen and (max-width: 500px) {
  .logo {
    float: none;
  }
  .menu {
    display: none;
  }
}

@media screen and (min-width: 900px) {
  .hamburger {
    display: none;
  }
  .product {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    border: 1px solid lightgray;
    border-radius: 10px;
    margin-left: 30px;
    margin-right: 30px;
    width: 50%;
    text-align: center;
    margin-top: -20px;
    margin-bottom: 0px;
  }
  main {
    display: inline-flex;
  }
  .logo {
    position: absolute;
    left: 0;
    top: 25;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <title>Parcel Sandbox</title>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css" integrity="sha384-5sAR7xN1Nv6T6+dT2mhtzEpVJvfS3NScPQTrOxhwjIuvcA67KV2R5Jz6kr4abQsz" crossorigin="anonymous">
  <link rel="stylesheet" href="style.css" />
</head>

<body>
  <header>
    <div class="logo"><img src="https://uploads.codesandbox.io/uploads/user/6eb75550-4d51-47fd-8ec1-d216b5da5e5c/M4sq-logo.jpeg" /></div>
    <h1>The ABC Company</h1>
  </header>
  <nav class="navbar">
    <div class="hamburger">☰</div>
    <ul class="menu">
      <li>Help</li>
      <li>Products</li>
      <li>About</li>
      <li>Home</li>
    </ul>
  </nav>
  <main>
    <section class="product">
      <i class="fas fa-apple-alt fa-5x"></i>
      <h2>A as in Apple</h2>
      <p>
        We take out fruit very seriously at ABC, that is why the A in ABC is for Apple. Try our new AppleBook App, the coolest new technology disrupting the fruit industry. This is the Uber of Apples!
      </p>
    </section>
    <section class="product">
      <i class="fas fa-money-bill-wave fa-5x"></i>
      <h2>B as in Bail</h2>
      <p>
        Do you need Bail! Our new BailFace app will provide you with lawyers and bail money at the push of a button. Its the Facebook of bail bonds!
      </p>
    </section>
    <section class="product">
      <i class="fas fa-utensils fa-5x"></i>
      <h2>C as in Curry</h2>

      <p>
        Fancy some curry! Our new HurryCurry app will provide curry cooked by Italian chefs right to your door. Its the AirBnB of curry!
      </p>
    </section>
  </main>
  <footer>
    <ul class="social">
      <li class="social_icon"><i class="fab fa-twitter"></i></li>
      <li class="social_icon"><i class="fab fa-facebook"></i></li>
      <li class="social_icon"><i class="fab fa-instagram"></i></li>
    </ul>
  </footer>
</body>

</html></code>```

答:
First sorry my English, I am not fluent, my solution proposal, I took the liberty to change some things in your css.

    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css" integrity="sha384-5sAR7xN1Nv6T6+dT2mhtzEpVJvfS3NScPQTrOxhwjIuvcA67KV2R5Jz6kr4abQsz"
     crossorigin="anonymous">
    <link rel="stylesheet" href="style.css" />

The ABC Company

☰

Help

Products

About

Home

A as in Apple

            We take out fruit very seriously at ABC, that is why
            the A in ABC is for Apple. Try our new AppleBook App,
            the coolest new technology disrupting the fruit industry.
            This is the Uber of Apples!

B as in Bail

                Do you need Bail! Our new BailFace app will provide you
                with lawyers and bail money at the push of a button. Its the
                Facebook of bail bonds!

C as in Curry

                Fancy some curry! Our new HurryCurry app will provide curry
                cooked by Italian chefs right to your door. Its the AirBnB of curry!

```

ContentLicense: CC BY-SA 4.0

Body:
As the title states my logo for this assignment needs to be in certain areas of the screen in different screen sizes. I have the mobile positioning correctly implemented but I can't seem to find a solution the positioning of the logo for ipad and larger screens.

For large screens the logo needs to be centered directly above the first .product element, which in my case is the A as in Apple

For ipad screens the logo needs to be halfway between the left edge of the screen and the centered h1 element

No matter what I try the logo just stays fixed the left.

I realize that in css its position is set to float:left but I've changed it to display:flex and the various flexbox properties, but it ended up creating more of a problem. I've changed the logo position in each @media query but the logo always ended up staying in place or way off from where it needs to be.

I understand that google is my best friend but I've exhausted all possible methods and have reached my last resort. The last I wanted to do was get stuck and immediately post here without at least trying for several hours. Forgive me for the newbie and probably obvious question but I'm at my wits end and really need help . Thank you.

* {
  box-sizing: border-box;
  text-align: center;
}

body {
  font-family: "Roboto", sans-serif;
  margin: 0;
  padding: 0;
}

body>i> {
  flex-grow: 0;
}

body>header> {
  flex-grow: 1;
}

.logo>img {
  width: 50px;
}

p {
  text-align: left;
  padding: 15px;
}

.navbar {
  background-color: rgb(105, 105, 105);
  padding: 10px;
  color: white;
  width: 100%;
}

.hamburger {
  display: flex;
  flex-direction: row-reverse;
}

.social {
  display: flex;
  padding-top: 20px;
  flex-direction: row;
  justify-content: space-around;
  border-top: 2px solid #e2e2e2;
}

ul {
  list-style: none;
}

li {
  line-height: 5px;
  float: right;
  padding: 0 0 50px 0;
  margin-right: 30px;
  margin-top: -10px;
}

.product {
  border: 1px solid lightgray;
  border-radius: 10px;
  margin: 10px 30px;
  padding: 10px;
}

@media screen and (max-width: 700px) {
  .logo {
    float: left;
  }
  .menu {
    display: none;
  }
  .logo {
    float: left;
  }
}

@media screen and (max-width: 500px) {
  .logo {
    float: none;
  }
  .menu {
    display: none;
  }
}

@media screen and (min-width: 900px) {
  .hamburger {
    display: none;
  }
  .product {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    border: 1px solid lightgray;
    border-radius: 10px;
    margin-left: 30px;
    margin-right: 30px;
    width: 50%;
    text-align: center;
    margin-top: -20px;
    margin-bottom: 0px;
  }
  main {
    display: inline-flex;
  }
  .logo {
    position: absolute;
    left: 0;
    top: 25;
  }
}

<!DOCTYPE html>

  <title>Parcel Sandbox</title>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css" integrity="sha384-5sAR7xN1Nv6T6+dT2mhtzEpVJvfS3NScPQTrOxhwjIuvcA67KV2R5Jz6kr4abQsz" crossorigin="anonymous">
  <link rel="stylesheet" href="style.css" />

The ABC Company

☰

Help

Products

About

Home

A as in Apple

        We take out fruit very seriously at ABC, that is why the A in ABC is for Apple. Try our new AppleBook App, the coolest new technology disrupting the fruit industry. This is the Uber of Apples!

B as in Bail

        Do you need Bail! Our new BailFace app will provide you with lawyers and bail money at the push of a button. Its the Facebook of bail bonds!

C as in Curry

        Fancy some curry! Our new HurryCurry app will provide curry cooked by Italian chefs right to your door. Its the AirBnB of curry!

Body:
First sorry my English, I am not fluent, my solution proposal, I took the liberty to change some things in your css.

<html lang="en">
<head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css" integrity="sha384-5sAR7xN1Nv6T6+dT2mhtzEpVJvfS3NScPQTrOxhwjIuvcA67KV2R5Jz6kr4abQsz"
     crossorigin="anonymous">
    <link rel="stylesheet" href="style.css" />
</head>
<style>
    *{
    box-sizing: border-box;
}
body{
    margin: 0;
    padding: 0;
}
.navbar {
    display: flex;
    flex-direction: row-reverse;
    width: 100vw;
    background-color: rgb(105, 105, 105);
    color: white;
}

.hamburger {
    display: flex;
    flex-direction: row-reverse;
    align-content: center;
    align-self: center;
    justify-content: flex-start;
    margin-right: 10px;
    display: none;
}

.social {
    display: flex;
    padding-top: 20px;
    flex-direction:row;
    justify-content:space-around;
    border-top: 2px solid #e2e2e2;
    }
.menu{
    display: inherit;
    list-style: none;
}

.navbar ul li {
    display: inline;
    padding: 0 15px;
}

.product {
    border: 1px solid lightgray;
    border-radius: 10px;
    margin: 10px 30px;
    padding:10px;
}

header{
    display: flex;
    flex-direction: row;

}

header h1 {
    display: inherit;
    flex-grow: 1;
    align-content: center;
    align-self: center;
    align-items: center;
    justify-content: flex-start;
}

.logo{
    display: inherit;
    align-content: center;
    align-self: center;
    align-items: center;
    flex-grow: 1;
    justify-content: center;

}

.logo > img{
    width: 50px;
    height: 50px;
}

@media (max-width: 900px) {
    .hamburger {
      display: none;
    }
    main{
    display: flex;
    flex-direction: column;
    justify-content: center;
}

    .product {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      align-items: center;
      align-self: center;
      align-content: center;
      border: 1px solid lightgray;
      border-radius: 10px;
      width: 50vw;
      text-align: center;
    }
}

@media (max-width:700px){
    .navbar ul li{
        display: none;
    }
    .hamburger{
        display: block;
    }
}

@media (max-width: 400px){
    header h1 {
        display: inherit;
        flex-grow: 1;
        align-content: center;
        align-self: center;
        align-items: center;
        justify-content: flex-start;
        font-size: 1.5rem;
    }
}
</style>
<body>
  <header>
        <div class="logo"><img src="https://uploads.codesandbox.io/uploads/user/6eb75550-4d51-47fd-8ec1-d216b5da5e5c/M4sq-logo.jpeg"/></div>
        <h1>The ABC Company</h1>
    </header>
    <nav class="navbar">
        <div class="hamburger">&#9776;</div>
        <ul class="menu">
            <li>Help</li>
            <li>Products</li>
            <li>About</li>
            <li>Home</li>
        </ul>
    </nav>
    <main>
    <section class="product">
         <i class="fas fa-apple-alt fa-5x"></i>
            <h2>A as in Apple</h2>
            <p>
            We take out fruit very seriously at ABC, that is why
            the A in ABC is for Apple. Try our new AppleBook App,
            the coolest new technology disrupting the fruit industry.
            This is the Uber of Apples!
            </p>
        </section>
        <section class="product">
            <i class="fas fa-money-bill-wave fa-5x"></i>
            <h2>B as in Bail</h2>
            <p>
                Do you need Bail! Our new BailFace app will provide you
                with lawyers and bail money at the push of a button. Its the
                Facebook of bail bonds!
            </p>
        </section>
        <section class="product">
            <i class="fas fa-utensils fa-5x"></i>
            <h2>C as in Curry</h2>

            <p>
                Fancy some curry! Our new HurryCurry app will provide curry
                cooked by Italian chefs right to your door. Its the AirBnB of curry!
            </p>
        </section>
    </main>
  <footer>
        <ul class="social">
            <li class="social_icon"><i class="fab fa-twitter"></i></li>
            <li class="social_icon"><i class="fab fa-facebook"></i></li>
            <li class="social_icon"><i class="fab fa-instagram"></i></li>
        </ul>
    </footer>
</body>
</html>


问:
Powershell- How to identify via variable, the matched string index on a array
```<code>$array = @('blue','red','purple','pink')
$array2 = @('brown','red','black','yellow')

$array | ForEach-Object {
    if ($array2 -contains $_) {
        Write-Host "`$array2 contains the `$array1 string [$_]"
    }
}
</code>```

how to get the index of the match string?

答:
You can try something with an index counter you can use. If $array2.ToLower() contains that element.ToLower(), then loop through that second array to find out where that element actually is.

Note that this is not going to work for large amount of arrays as the time it will take to go through would get larger and larger. But, for small samples like this one, it works fine.

```<code>$array = 'blue','Red','purple','pink', 'browN'
$array2 = 'brown','rEd','black','yellow'

$array | ForEach-Object {
    if ($array2.ToLower() -contains $_.ToLower()) {
        $index = 0
        foreach($arrElement in $array2) {
            #$index++ # based on index starting with 1
            if ($arrElement -eq $_) {
                Write-Host "`$array2 contains the `$array1 string [$_] at index: $index"
            }
            $index++ # based on index starting with 0
        }
    }
}

# produces output
$array2 contains the $array1 string [Red] at index: 1
$array2 contains the $array1 string [browN] at index: 0
</code>```

If there are duplicates in the $array2, you'll get two separate lines that would show each index entry.

```<code>$array = 'blue','Red','purple','pink', 'browN'
$array2 = 'brown','rEd','black','yellow', 'red'

#Output would be with above code:
$array2 contains the $array1 string [Red] at index: 1
$array2 contains the $array1 string [Red] at index: 4
$array2 contains the $array1 string [browN] at index: 0

</code>```

Body:
$array = @('blue','red','purple','pink')
$array2 = @('brown','red','black','yellow')

$array | ForEach-Object {
    if ($array2 -contains $_) {
        Write-Host "`$array2 contains the `$array1 string [$_]"
    }
}

how to get the index of the match string?

Body:
You can try something with an index counter you can use. If $array2.ToLower() contains that element.ToLower(), then loop through that second array to find out where that element actually is.

Note that this is not going to work for large amount of arrays as the time it will take to go through would get larger and larger. But, for small samples like this one, it works fine.

$array = 'blue','Red','purple','pink', 'browN'
$array2 = 'brown','rEd','black','yellow'

$array | ForEach-Object {
    if ($array2.ToLower() -contains $_.ToLower()) {
        $index = 0
        foreach($arrElement in $array2) {
            #$index++ # based on index starting with 1
            if ($arrElement -eq $_) {
                Write-Host "`$array2 contains the `$array1 string [$_] at index: $index"
            }
            $index++ # based on index starting with 0
        }
    }
}

# produces output
$array2 contains the $array1 string [Red] at index: 1
$array2 contains the $array1 string [browN] at index: 0

If there are duplicates in the $array2, you'll get two separate lines that would show each index entry.

$array = 'blue','Red','purple','pink', 'browN'
$array2 = 'brown','rEd','black','yellow', 'red'

#Output would be with above code:
$array2 contains the $array1 string [Red] at index: 1
$array2 contains the $array1 string [Red] at index: 4
$array2 contains the $array1 string [browN] at index: 0


问:
WhatApp click to chat links do not work with OSX native client and WhatsApp Web
Whatsapp Link Issue

WhatsApp native OSX app is installed or web-app is opened but links can’t open in native app on OSX and always tries to lunch a new web app if try to open in web app.

REGION: US-SOUTH

BROWSER: Google Chrome

We use WhatsApp links - Click to chat feature - to message customers quickly from our admin panel.

In the last days as it seems WhatsApp has updated something and broke the links overnight.

Neither of the formats we used previously seem to work:

```<code>https://wa.me/<number>
https://api.whatsapp.com/send?phone=<number>
</code>```

If we try to open links with WhatsApp client OSX:

Says OSX is not installed

If we try to open links with WhatsApp Web client:

Will launch other instance in a new tab/window and loads for seconds

答:
As it is extremely annoying for those who use this feature (like us), I'm going to leave my findings here:

Opening up the console revealed that there is a problem with the format as it does not request permission to open the native app, since it brakes something in content security policy when trying to redirect to the following link: whatsapp://send/?phone=

SOLUTION:

USE THE CUSTOM URL SCHEME FORMAT -
  whatsapp://send/?phone=&text&source&data

With this the browser will be able to request permission to open the native app. If you accept all works smooth.

Body:
Whatsapp Link Issue

WhatsApp native OSX app is installed or web-app is opened but links can’t open in native app on OSX and always tries to lunch a new web app if try to open in web app.

REGION: US-SOUTH

BROWSER: Google Chrome

We use WhatsApp links - Click to chat feature - to message customers quickly from our admin panel.

In the last days as it seems WhatsApp has updated something and broke the links overnight.

Neither of the formats we used previously seem to work:

https://wa.me/<number>
https://api.whatsapp.com/send?phone=<number>

If we try to open links with WhatsApp client OSX:

Says OSX is not installed

If we try to open links with WhatsApp Web client:

Will launch other instance in a new tab/window and loads for seconds


问:
Tizen.NET NfcCardEmulation throws UnsupportedException (with added privileges)
I had a issue with a Tizen.NET Api v4. Generally i need cardemulation in the watch, but while executing static method

NfcManager.GetCardEmulationAdapter()

i am gettings logs

tizen-manifest.xml looks like (and he was generating by vs2019 with Tizen ext)
<?xml version="1.0" encoding="utf-8"?>
<manifest package="tizenapp" version="1.0.1" api-version="4" xmlns="http://tizen.org/ns/packages">
    <profile name="wearable" />
    <ui-application appid="tizenapp" exec="tizenapp.dll" multiple="false" nodisplay="false" taskmanage="true" type="dotnet" launch_mode="single">
        tizenapp
        <icon>tizenapp.png</icon>
        <metadata key="http://tizen.org/metadata/prefer_dotnet_aot" value="true" />
        <splash-screens />
    </ui-application>
    <shortcut-list />
    <privileges>
        <privilege>http://tizen.org/privilege/secureelement</privilege>
        <privilege>http://tizen.org/privilege/nfc</privilege>
        <privilege>http://tizen.org/privilege/nfc.cardemulation</privilege>
        <privilege>http://tizen.org/feature/network.nfc.card_emulation</privilege>
        <privilege>http://tizen.org/feature/network.nfc</privilege>
    </privileges>
    <dependencies />
    <provides-appdefined-privileges />
    <feature name="http://tizen.org/feature/network.nfc">true</feature>
    <feature name="http://tizen.org/feature/network.nfc.card_emulation">true</feature>
    <feature name="http://tizen.org/feature/network.secure_element">true</feature>
    <feature name="http://tizen.org/feature/network.secure_element.ese">true</feature>
    <feature name="http://tizen.org/feature/network.secure_element.uicc">true</feature>
</manifest>

I dont know what i need to fix this problems.

答:
It looks like a simple typo in the implementation. It's fixed in API5 and later.

https://github.com/Samsung/TizenFX/pull/578/files

I'm not sure if there's any workaround for this when targetting for API4, because it's not about a privilege but a feature.


问:
Need GestureColor as transparent
I am implementing Gesture in my Activity in Android.
Every time I am performing a Gesture, a yellow line is being drawn on the screen.

How would I set the GestureColor to transparent?

答: Try setting .setGestureVisible to false.</p>

ContentLicense: CC BY-SA 3.0

Title: Need GestureColor as transparent


问:
Threads are freezing main form
I want to run multiple thread. Each thread should convert JPEG to Bitmap. Conversion works but my whole application is always using 12%-13% of CPU. I have an 8 core CPU so it seems the whole application uses just a single core. Also while the threads are working the main form is frozen and doesn't respond.</p>

```<code>unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics,
  Controls, Forms, Jpeg, Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
    Str: TMemoryStream;
    procedure OnTerminate(Sender: TObject);
  end;

  TMakeThumbThread= class(TThread)
  private
    FStream: TStream;
  public
    FBmp: TBitmap;
    constructor Create(Str: TStream);
    procedure Execute; override;
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

constructor TMakeThumbThread.Create(Str: TStream);
begin
  inherited Create(True);
  FStream := Str;
  FreeOnTerminate := True;
end;

procedure TMakeThumbThread.Execute;
var Jpg: TJpegImage;
begin
  FBmp := TBitmap.Create;
  FBmp.PixelFormat := pf32bit;
  FBmp.Width := 300;
  FBmp.Height := 200;

  Jpg := TJpegImage.Create;
  FStream.Position := 0;
  Jpg.LoadFromStream(FStream);
  FBmp.Canvas.Draw(0,0, Jpg);
  Jpg.Free;

  DoTerminate;
  FBmp.Free;
end;

procedure TForm1.Button1Click(Sender: TObject);
var F: TFileStream;
    i: Integer;
    MT: TMakeThumbThread;
begin
  Str := TMemoryStream.Create;
  F := TFileStream.Create('test.jpg', fmOpenRead or fmShareDenyWrite);
  Str.CopyFrom(F, F.Size);
  F.Free;

  for i:=0 to 500 do begin
    MT := TMakeThumbThread.Create(Str);
    MT.OnTerminate := OnTerminate;
    MT.Execute;
  end;
end;

procedure TForm1.OnTerminate(Sender: TObject);
var Bmp: TBitmap;
begin
  Bmp := TMakeThumbThread(Sender).FBmp;
  Form1.Canvas.Draw(1,1, Bmp );
end;

end.
</code>```

答:
You are manually calling the thread's Execute() method in the context of the main thread. DON'T DO THAT! That is why your UI is freezing. You are creating your threads in a suspended state and never resuming them.

You need to change this line:

```<code>MT.Execute;
</code>```

To either this:

```<code>MT.Resume;
</code>```

Or this:

```<code>MT.Start;
</code>```

Depending on which version of Delphi you are using.

There are several other problems with your code, too.

The VCL's TBitmap class is not entirely thread-safe. You MUST Lock() the TBitmap.Canvas when working with a TBitmap in a worker thread, to prevent the main thread from ripping GDI resources away from the TBitmap unexpectedly.

You are sharing a single TMemoryStream with multiple threads to have them all load the same JPG image simultaneously. That will not work unless you wrap access to the TMemoryStream with a synchronization object, like a TCriticalSection or TMutex. Or, another option would be to use TCustomMemoryStream to create multiple streams that share a single memory block. Otherwise, you would be better off simply passing the JPG filename to each thread and let Execute() call TJpegImage.LoadFromFile() instead of TJpegImage.LoadFromStream().

You are calling FBmp.Free() at the end of Execute(), but then you are accessing FBmp afterwards in the OnTerminate event handler. You need to delay the call to FBmp.Free() until after the OnTerminate event handler exits, such as in the thread's destructor.

You are drawing the bitmaps directly on the TForm.Canvas from outside of the Form's OnPaint event. As such, as soon as your Form need to redraw itself for any reason, your drawn images will be lost. If you want the images to be persistent for the Form's lifetime, you need to save them and draw them whenever the OnPaint event fires. Or, you can simply assign them to TImage components and let them handle the drawing for you.

Title: Threads are freezing main form

Body:
I want to run multiple thread. Each thread should convert JPEG to Bitmap. Conversion works but my whole application is always using 12%-13% of CPU. I have an 8 core CPU so it seems the whole application uses just a single core. Also while the threads are working the main form is frozen and doesn't respond.

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics,
  Controls, Forms, Jpeg, Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
    Str: TMemoryStream;
    procedure OnTerminate(Sender: TObject);
  end;

  TMakeThumbThread= class(TThread)
  private
    FStream: TStream;
  public
    FBmp: TBitmap;
    constructor Create(Str: TStream);
    procedure Execute; override;
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

constructor TMakeThumbThread.Create(Str: TStream);
begin
  inherited Create(True);
  FStream := Str;
  FreeOnTerminate := True;
end;

procedure TMakeThumbThread.Execute;
var Jpg: TJpegImage;
begin
  FBmp := TBitmap.Create;
  FBmp.PixelFormat := pf32bit;
  FBmp.Width := 300;
  FBmp.Height := 200;

  Jpg := TJpegImage.Create;
  FStream.Position := 0;
  Jpg.LoadFromStream(FStream);
  FBmp.Canvas.Draw(0,0, Jpg);
  Jpg.Free;

  DoTerminate;
  FBmp.Free;
end;

procedure TForm1.Button1Click(Sender: TObject);
var F: TFileStream;
    i: Integer;
    MT: TMakeThumbThread;
begin
  Str := TMemoryStream.Create;
  F := TFileStream.Create('test.jpg', fmOpenRead or fmShareDenyWrite);
  Str.CopyFrom(F, F.Size);
  F.Free;

  for i:=0 to 500 do begin
    MT := TMakeThumbThread.Create(Str);
    MT.OnTerminate := OnTerminate;
    MT.Execute;
  end;
end;

procedure TForm1.OnTerminate(Sender: TObject);
var Bmp: TBitmap;
begin
  Bmp := TMakeThumbThread(Sender).FBmp;
  Form1.Canvas.Draw(1,1, Bmp );
end;

end.

Body:
You are manually calling the thread's Execute() method in the context of the main thread. DON'T DO THAT! That is why your UI is freezing. You are creating your threads in a suspended state and never resuming them.

You need to change this line:

MT.Execute;

To either this:

MT.Resume;

Or this:

MT.Start;

Depending on which version of Delphi you are using.

There are several other problems with your code, too.

The VCL's TBitmap class is not entirely thread-safe. You MUST Lock() the TBitmap.Canvas when working with a TBitmap in a worker thread, to prevent the main thread from ripping GDI resources away from the TBitmap unexpectedly.

You are sharing a single TMemoryStream with multiple threads to have them all load the same JPG image simultaneously. That will not work unless you wrap access to the TMemoryStream with a synchronization object, like a TCriticalSection or TMutex. Or, another option would be to use TCustomMemoryStream to create multiple streams that share a single memory block. Otherwise, you would be better off simply passing the JPG filename to each thread and let Execute() call TJpegImage.LoadFromFile() instead of TJpegImage.LoadFromStream().

You are calling FBmp.Free() at the end of Execute(), but then you are accessing FBmp afterwards in the OnTerminate event handler. You need to delay the call to FBmp.Free() until after the OnTerminate event handler exits, such as in the thread's destructor.

You are drawing the bitmaps directly on the TForm.Canvas from outside of the Form's OnPaint event. As such, as soon as your Form need to redraw itself for any reason, your drawn images will be lost. If you want the images to be persistent for the Form's lifetime, you need to save them and draw them whenever the OnPaint event fires. Or, you can simply assign them to TImage components and let them handle the drawing for you.


问:
Pipenv creation using python
Is there a way to create virtual environment using python code. It would be great help if anyone can help. I need to automate creating virtual environment.As in using subprocesses or something similar

pip3 install pipenv
cd /root_directory_of_project
pipenv shell

答:
```<code>sudo apt install python3-pip
pip3 install pipenv
cd /root_directory_of_project
pipenv shell
</code>```

if you want to see what modules are installed do,

```<code>pip3 freeze
</code>```

do this inside the pipenv shell.

use exit to exit the pipenv shell.
Anytime you want to use the virtual environment just do, pipenv shell in that directory to enter the shell again.

Title: Pipenv creation using python

Body:
sudo apt install python3-pip
pip3 install pipenv
cd /root_directory_of_project
pipenv shell

if you want to see what modules are installed do,

pip3 freeze

do this inside the pipenv shell.

use exit to exit the pipenv shell.
Anytime you want to use the virtual environment just do, pipenv shell in that directory to enter the shell again.


问:
How do I calculate the difference
I have data in two columns. I need to write a query that only shows the customers that have gone over their credit limit and by how much:</p>

```<code>customer balance         credit limit
418.75                   500
10.75                    200
200.1                    100
</code>```

答:
Of course this doesn't take customer information into account since you didn't mention any customer tables, but this should get you the customer balance and overage:

```<code>SELECT customer_balance, credit_limit, customer_balance - credit_limit as overage
FROM your_table
WHERE customer_balance > credit_limit
</code>```

It's pretty straight-forward; you select customers with a balance over their limit, and just select the difference as a third column.

Title: How do I calculate the difference

Body:
I have data in two columns. I need to write a query that only shows the customers that have gone over their credit limit and by how much:

customer balance         credit limit
418.75                   500
10.75                    200
200.1                    100

Body:
Of course this doesn't take customer information into account since you didn't mention any customer tables, but this should get you the customer balance and overage:

SELECT customer_balance, credit_limit, customer_balance - credit_limit as overage
FROM your_table
WHERE customer_balance > credit_limit

It's pretty straight-forward; you select customers with a balance over their limit, and just select the difference as a third column.


问:
How to delete a row from DOM on button click in JavaScript?
I have an HTML code as shown below. I have copied this from DOM and it is generated through php.

```<code><div class="house-senate-committee" style="text-align:center; margin-top:15px;">
    <button type="button" onclick="removeRow()" name="delete_row[]" style="margin-right:10px;" value="">Delete</button>
    <input type="text" name="code[]" style="margin-right:10px;" value="AEFA">
    <input type="text" name="en_desc[]" value="Foreign Affairs and International Trade">
</div>

<div class="house-senate-committee" style="text-align:center; margin-top:15px;">
    <button type="button" onclick="removeRow()" name="delete_row[]" style="margin-right:10px;" value="">Delete</button>
    <input type="text" name="code[]" style="margin-right:10px;" value="AGFO">
    <input type="text" name="en_desc[]" value="Agriculture and Forestry">
</div>
</code>```

The above HTML code belongs to the following screenshot:

Problem Statement:

I am wondering what JS code I need to add so that on clicking Delete button it deletes a row containing that button.

For example: If I click the 2nd row Delete button, it should delete the complete 2nd row and if I click the 1st row Delete
button, it should delete the complete 1st row.

This is what I have tried:

```<code>function removeRow() {
 document.queryselector(".house-senate-committee").remove();
}
</code>```

答:
If you change your buttons to have onclick="removeRow(this)", you can then rewrite removeRow as below to remove that button's div when it is clicked.

function removeRow(el) {
  el.parentNode.remove();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="house-senate-committee" style="text-align:center; margin-top:15px;">
  <button type="button" onclick="removeRow(this)" name="delete_row[]" style="margin-right:10px;" value="">Delete</button>
  <input type="text" name="code[]" style="margin-right:10px;" value="AEFA">
  <input type="text" name="en_desc[]" value="Foreign Affairs and International Trade">
</div>

<div class="house-senate-committee" style="text-align:center; margin-top:15px;">
  <button type="button" onclick="removeRow(this)" name="delete_row[]" style="margin-right:10px;" value="">Delete</button>
  <input type="text" name="code[]" style="margin-right:10px;" value="AGFO">
  <input type="text" name="en_desc[]" value="Agriculture and Forestry">
</div></code>```

Body:
I have an HTML code as shown below. I have copied this from DOM and it is generated through php.

    <button type="button" onclick="removeRow()" name="delete_row[]" style="margin-right:10px;" value="">Delete</button>
    <input type="text" name="code[]" style="margin-right:10px;" value="AEFA">
    <input type="text" name="en_desc[]" value="Foreign Affairs and International Trade">

    <button type="button" onclick="removeRow()" name="delete_row[]" style="margin-right:10px;" value="">Delete</button>
    <input type="text" name="code[]" style="margin-right:10px;" value="AGFO">
    <input type="text" name="en_desc[]" value="Agriculture and Forestry">

The above HTML code belongs to the following screenshot:

Problem Statement:

I am wondering what JS code I need to add so that on clicking Delete button it deletes a row containing that button.

For example: If I click the 2nd row Delete button, it should delete the complete 2nd row and if I click the 1st row Delete
button, it should delete the complete 1st row.

This is what I have tried:

function removeRow() {
 document.queryselector(".house-senate-committee").remove();
}

Body:
If you change your buttons to have onclick="removeRow(this)", you can then rewrite removeRow as below to remove that button's div when it is clicked.

function removeRow(el) {
  el.parentNode.remove();
}

<div class="house-senate-committee" style="text-align:center; margin-top:15px;">
  <button type="button" onclick="removeRow(this)" name="delete_row[]" style="margin-right:10px;" value="">Delete</button>
  <input type="text" name="code[]" style="margin-right:10px;" value="AEFA">
  <input type="text" name="en_desc[]" value="Foreign Affairs and International Trade">
</div>

<div class="house-senate-committee" style="text-align:center; margin-top:15px;">
  <button type="button" onclick="removeRow(this)" name="delete_row[]" style="margin-right:10px;" value="">Delete</button>
  <input type="text" name="code[]" style="margin-right:10px;" value="AGFO">
  <input type="text" name="en_desc[]" value="Agriculture and Forestry">
</div>


问:
How to calculate percentages of poker hands when the program knows all hands?
I am looking to calculate the percentages that you see on tv when watching poker in my java program. The difference between this question and many others, if unclear, is that the program DOES know all players hands and can therefore determine an accurate percentage. There are many websites such as this one: https://www.pokerlistings.com/online-poker-odds-calculator
where you can input the players cards and it will give you the percentages. I was wondering if there were any all ready set algorithms for this or any java API that i could use in my program. I understand that my question may be a bit unrealistic. So if there is no algorithms or APIs, perhaps someone knows how it is calculated, so that i can try to construct my own algorithm?

In case there is still confusion:
If there are 3 players and their hands are

player 1: As kh

player 2: 2d 3c

player 3: AH AD

I would like to know the percentage that each player has to win preflop, pre-turn and pre-river
Thanks in advance.

答: its inefficient, but you can loop through all of the cards left to be played and see how many each player wins in each scenario. Various speed ups can be made by eliminating possibilities ( IE no flushes if suits havent lined up )</p>


问:
Is destructuring this possible?
I am new to destructuring and need help finding the best solution. I have a pretty complicated object coming back as a response and would like to clean it up. Without doing anything, it looks like this:

```<code>
const homeTeam = {

totalPlaysFor: res.data.stats.home.teamStats[0].miscellaneous.offensePlays,

totalPlaysAgainst: res.data.stats.away.teamStats[0].miscellaneous.offensePlays

}

</code>```

I know I can do something like:

```<code>
const { offensePlays } = res.data.stats.home.teamStats[0].miscellaneous;

</code>```

but that only solves my problem for one of them and would leave the other still long and tough to read.

答:
You can destructure the stats property in advance, then make a helper function that takes the .home or .away object and navigates to the nested .offensePlays:

```<code>const { stats } = res.data;
const getOffPlays = obj => obj.teamStats[0].miscellaneous.offensePlays;
const homeTeam = {
  totalPlaysFor: getOffPlays(stats.home),
  totalPlaysAgainst: getOffPlays(stats.away)
};
</code>```

Without having a standalone helper function, you could also create the object by .mapping an array of properties (eg [['totalPlaysFor', 'home'], ['totalPlaysAgainst', 'away']]) and pass it to Object.fromEntries, but that would be significantly less readable IMO.

Title: Is destructuring this possible?

Body:
I am new to destructuring and need help finding the best solution. I have a pretty complicated object coming back as a response and would like to clean it up. Without doing anything, it looks like this:

const homeTeam = {

totalPlaysFor: res.data.stats.home.teamStats[0].miscellaneous.offensePlays,

totalPlaysAgainst: res.data.stats.away.teamStats[0].miscellaneous.offensePlays

}

I know I can do something like:

const { offensePlays } = res.data.stats.home.teamStats[0].miscellaneous;

but that only solves my problem for one of them and would leave the other still long and tough to read.

Body:
You can destructure the stats property in advance, then make a helper function that takes the .home or .away object and navigates to the nested .offensePlays:

const { stats } = res.data;
const getOffPlays = obj => obj.teamStats[0].miscellaneous.offensePlays;
const homeTeam = {
  totalPlaysFor: getOffPlays(stats.home),
  totalPlaysAgainst: getOffPlays(stats.away)
};

Without having a standalone helper function, you could also create the object by .mapping an array of properties (eg [['totalPlaysFor', 'home'], ['totalPlaysAgainst', 'away']]) and pass it to Object.fromEntries, but that would be significantly less readable IMO.


问:
Showing Morning, afternoon, evening, night message based on Time in java

What i am trying to do::

Show message based on

Good morning  (12am-12pm)

Good after noon (12pm -4pm)

Good evening (4pm to 9pm)

Good night ( 9pm to 6am)

CODE::

I used 24-hr format to get this logic

```<code>private void getTimeFromAndroid() {
        Date dt = new Date();
        int hours = dt.getHours();
        int min = dt.getMinutes();

        if(hours>=1 || hours<=12){
            Toast.makeText(this, "Good Morning", Toast.LENGTH_SHORT).show();
        }else if(hours>=12 || hours<=16){
            Toast.makeText(this, "Good Afternoon", Toast.LENGTH_SHORT).show();
        }else if(hours>=16 || hours<=21){
            Toast.makeText(this, "Good Evening", Toast.LENGTH_SHORT).show();
        }else if(hours>=21 || hours<=24){
            Toast.makeText(this, "Good Night", Toast.LENGTH_SHORT).show();
        }
    }
</code>```

Question:

Is this this best way of doing it, If no which is the best way

答:
A cleaner method for detecting date would be.</p>

```<code>//the time cannot go below zero, so if this case is true, it must be between 0 and 12
   if(time <= 12)
   {
       return "Good Morning";
       //it will only fall into this case if the time is greater than 12.
   }else if(time < 16)
   {
       return "Good Afternoon";
   }else if(time < 21)
   {
       return "Good Evening";
   }else //it is guaranteed that the time will not exceed 24
       //, and if the previous case are all false, it must be within 21 and 24
   {
       return "Good Night";
   }
</code>```

Body:
What i am trying to do::

Show message based on

Good morning  (12am-12pm)

Good after noon (12pm -4pm)

Good evening (4pm to 9pm)

Good night ( 9pm to 6am)

CODE::

I used 24-hr format to get this logic

private void getTimeFromAndroid() {
        Date dt = new Date();
        int hours = dt.getHours();
        int min = dt.getMinutes();

        if(hours>=1 || hours<=12){
            Toast.makeText(this, "Good Morning", Toast.LENGTH_SHORT).show();
        }else if(hours>=12 || hours<=16){
            Toast.makeText(this, "Good Afternoon", Toast.LENGTH_SHORT).show();
        }else if(hours>=16 || hours<=21){
            Toast.makeText(this, "Good Evening", Toast.LENGTH_SHORT).show();
        }else if(hours>=21 || hours<=24){
            Toast.makeText(this, "Good Night", Toast.LENGTH_SHORT).show();
        }
    }

Question:

Is this this best way of doing it, If no which is the best way

Body:
A cleaner method for detecting date would be.

//the time cannot go below zero, so if this case is true, it must be between 0 and 12
   if(time <= 12)
   {
       return "Good Morning";
       //it will only fall into this case if the time is greater than 12.
   }else if(time < 16)
   {
       return "Good Afternoon";
   }else if(time < 21)
   {
       return "Good Evening";
   }else //it is guaranteed that the time will not exceed 24
       //, and if the previous case are all false, it must be within 21 and 24
   {
       return "Good Night";
   }


问:
Display Woocommerce Categories on page
Im using woocommerce but Im not building an ecommerce site, its a site that will have a series of marketing images, starting with categories and then working towards a product.

So I have a page for instance called 'Wood Stoves', I have made that a main category and this is a page, but then inside that page I need the 'Brands' that will be associated with this category, but they still categories, so for instance 'Brand 1' its parent is 'Wood Stoves' and again it needs to have an image. So these then become clickable categories.

Then inside that brand there will be products, but I only again want an image to show with a bit of text.

So the first page is the categories (brnads) within the main category, and then inside there is the products within the brand.

My site is https://www.accend4web.co.uk/little-stove-company/ and am using the TwentyTwenty theme, which also doesnt seem to work that well with woocommerce.

答:
Manual:

If you are not planning to fully use Woocommerce, then you can just edit the home page and add the categories one by one as images linked to the category page with you can get from the categories page under "Products" (go to the  https://www.accend4web.co.uk//wp-admin/edit-tags.php?taxonomy=product_cat&post_type=product , then click on "View" on the category, that will send you to a page that contains all products with that category.

Then do the same for every category you have, you will get a home page with categories titles with pictures linked to the categories pages.

Automated:

Insted of using the category as Brands there are some nice plugins that add the "Brands" features to  Woocommerce, and they even add the brand under the product short description and they will be linked to the brands' page which contains the product of that brand
https://wordpress.org/plugins/yith-woocommerce-brands-add-on/
https://wordpress.org/plugins/premmerce-woocommerce-brands/

Title: Display Woocommerce Categories on page


问:
Kafka Consumer Poll runs indefinitely and doesn't return anything
I am facing difficulty with KafkaConsumer.poll(duration timeout), wherein it runs indefinitely and never come out of the method. Understand that this could be related to connection and I have seen it a bit inconsistent sometimes. How do I handle this should poll stops responding? Given below is the snippet from KafkaConsumer.poll()

```<code>public ConsumerRecords<K, V> poll(final Duration timeout) {
    return poll(time.timer(timeout), true);
}
</code>```

and I am calling the above from here :

```<code>Duration timeout = Duration.ofSeconds(30);
    while (true) {
        final ConsumerRecords<recordID, topicName> records = consumer.poll(timeout);
        System.out.println("record count is" + records.count());
}
</code>```

I am getting the below error:

org.apache.kafka.common.errors.SerializationException: Error
  deserializing key/value for partition  at offset 2. If
  needed, please seek past the record to continue consumption.

答:
I stumbled upon some useful information while trying to fix the problem I was facing above. I will provide the piece of code which should be able to handle this, but before that it is important to know what causes this.

While producing or consuming message or data to Apache Kafka, we need schema structure to that message or data, in my case Avro schema. If there is a conflict of message being produced to Kafka that conflict with that message schema, it will have an effect on consumption.

Add below code in your consumer topic in the method where it consume records --

do remember to import below packages:

import org.apache.kafka.common.TopicPartition;

  import org.jsoup.SerializationException;

```<code>try {
        while (true) {
            ConsumerRecords<String, GenericRecord> records = null;
            try {
                records = consumer.poll(10000);
            } catch (SerializationException e) {
                String s = e.getMessage().split("Error deserializing key/value
for partition ")[1].split(". If needed, please seek past the record to
continue consumption.")[0];
                String topics = s.split("-")[0];
                int offset = Integer.valueOf(s.split("offset ")[1]);
                int partition = Integer.valueOf(s.split("-")[1].split(" at") .
   [0]);

                TopicPartition topicPartition = new TopicPartition(topics,
 partition);
                //log.info("Skipping " + topic + "-" + partition + " offset "
 + offset);
                consumer.seek(topicPartition, offset + 1);
            }

            for (ConsumerRecord<String, GenericRecord> record : records) {

                System.out.printf("value = %s \n", record.value());

            }

        }

    } finally {
        consumer.close();
    }
</code>```

Body:
I am facing difficulty with KafkaConsumer.poll(duration timeout), wherein it runs indefinitely and never come out of the method. Understand that this could be related to connection and I have seen it a bit inconsistent sometimes. How do I handle this should poll stops responding? Given below is the snippet from KafkaConsumer.poll()

public ConsumerRecords<K, V> poll(final Duration timeout) {
    return poll(time.timer(timeout), true);
}

and I am calling the above from here :

Duration timeout = Duration.ofSeconds(30);
    while (true) {
        final ConsumerRecords<recordID, topicName> records = consumer.poll(timeout);
        System.out.println("record count is" + records.count());
}

I am getting the below error:

org.apache.kafka.common.errors.SerializationException: Error
  deserializing key/value for partition  at offset 2. If
  needed, please seek past the record to continue consumption.

Body:
I stumbled upon some useful information while trying to fix the problem I was facing above. I will provide the piece of code which should be able to handle this, but before that it is important to know what causes this.

While producing or consuming message or data to Apache Kafka, we need schema structure to that message or data, in my case Avro schema. If there is a conflict of message being produced to Kafka that conflict with that message schema, it will have an effect on consumption.

Add below code in your consumer topic in the method where it consume records --

do remember to import below packages:

import org.apache.kafka.common.TopicPartition;

  import org.jsoup.SerializationException;

try {
        while (true) {
            ConsumerRecords<String, GenericRecord> records = null;
            try {
                records = consumer.poll(10000);
            } catch (SerializationException e) {
                String s = e.getMessage().split("Error deserializing key/value
for partition ")[1].split(". If needed, please seek past the record to
continue consumption.")[0];
                String topics = s.split("-")[0];
                int offset = Integer.valueOf(s.split("offset ")[1]);
                int partition = Integer.valueOf(s.split("-")[1].split(" at") .
   [0]);

                TopicPartition topicPartition = new TopicPartition(topics,
 partition);
                //log.info("Skipping " + topic + "-" + partition + " offset "
 + offset);
                consumer.seek(topicPartition, offset + 1);
            }

            for (ConsumerRecord<String, GenericRecord> record : records) {

                System.out.printf("value = %s \n", record.value());

            }

        }

    } finally {
        consumer.close();
    }


问:
Unable to get time difference between to pandas dataframe columns
I have a pandas dataframe that contains a couple of columns. Two of which are start_time and end_time. In those columns the values look like - 2020-01-04 01:38:33 +0000 UTC

I am not able to create a datetime object from these strings because I am not able to get the format right -

```<code>df['start_time'] = pd.to_datetime(df['start_time'], format="yyyy-MM-dd HH:mm:ss +0000 UTC")
</code>```

I also tried using yyyy-MM-dd HH:mm:ss %z UTC as a format

This gives the error -

```<code>ValueError: time data '2020-01-04 01:38:33 +0000 UTC' does not match format 'yyyy-MM-dd HH:mm:ss +0000 UTC' (match)
</code>```

答:
There are some notes below about this problem:

1. About your error

This gives the error -

You have parsed a wrong datetime format that will cause the error. For correct format check this one https://strftime.org/. Correct format for this problem would be: "%Y-%m-%d %H:%M:%S %z UTC"

2. Pandas limitation with timezone

Parsing UTC timezone as %z doesn't working on pd.Series (it only works on index value). So if you use this, it will not work:

```<code>df['startTime'] = pd.to_datetime(df.startTime, format="%Y-%m-%d %H:%M:%S %z UTC", utc=True)
</code>```

Solution for this is using python built-in library for inferring the datetime data:

```<code>from datetime import datetime
f = lambda x: datetime.strptime(x, "%Y-%m-%d %H:%M:%S %z UTC")
df['startTime'] = pd.to_datetime(df.startTime.apply(f), utc=True)
</code>```

@fmarm answer only help you dealing with date and hour data, not UTC timezone.

Body:
I have a pandas dataframe that contains a couple of columns. Two of which are start_time and end_time. In those columns the values look like - 2020-01-04 01:38:33 +0000 UTC

I am not able to create a datetime object from these strings because I am not able to get the format right -

df['start_time'] = pd.to_datetime(df['start_time'], format="yyyy-MM-dd HH:mm:ss +0000 UTC")

I also tried using yyyy-MM-dd HH:mm:ss %z UTC as a format

This gives the error -

ValueError: time data '2020-01-04 01:38:33 +0000 UTC' does not match format 'yyyy-MM-dd HH:mm:ss +0000 UTC' (match)

Body:
There are some notes below about this problem:

1. About your error

This gives the error -

You have parsed a wrong datetime format that will cause the error. For correct format check this one https://strftime.org/. Correct format for this problem would be: "%Y-%m-%d %H:%M:%S %z UTC"

2. Pandas limitation with timezone

Parsing UTC timezone as %z doesn't working on pd.Series (it only works on index value). So if you use this, it will not work:

df['startTime'] = pd.to_datetime(df.startTime, format="%Y-%m-%d %H:%M:%S %z UTC", utc=True)

Solution for this is using python built-in library for inferring the datetime data:

from datetime import datetime
f = lambda x: datetime.strptime(x, "%Y-%m-%d %H:%M:%S %z UTC")
df['startTime'] = pd.to_datetime(df.startTime.apply(f), utc=True)

@fmarm answer only help you dealing with date and hour data, not UTC timezone.


问:
How to make this image effect, any library that can help with it
Do you know if an emboss effect like this can be done with a programming package. Can someone suggest something

答:
With GD:

create a new transparent image with the size of the original one - imagecreatetruecolor()

draw the text in that image - imagettftext() / imagettfbbox() - hint: IMG_COLOR_TRANSPARENT

apply the IMG_FILTER_EMBOSS filter - imagefilter()

copy the embossed text over the original image - imagecopymerge()


问:
Scroll view with an embedded stack view programmatically failing
I want to get the following structure programmatically (and am currently failing...):

View

Scroll View

Vertical Stack View

I was able to get what I wanted in Interface Builder, but cannot seem to figure out how to achieve this in code. In IB, it looks like this (please click on the picture to see it fully):

The settings of the stack view look like this:

Now, this is my attempt to mirror that in code:

```<code>import UIKit

class ScrollViewController: UIViewController {

    lazy var scrollView: UIScrollView = {
        let s = UIScrollView()
        s.contentMode = .scaleToFill
        s.backgroundColor = .gray
        s.accessibilityIdentifier = "scroll_view"
        s.translatesAutoresizingMaskIntoConstraints = false
        return s
    }()

    lazy var stackView: UIStackView = {
        let s = UIStackView()
        s.axis = .vertical
        s.alignment = .fill
        s.distribution = .equalSpacing
        s.spacing = 10
        s.contentMode = .scaleToFill
        s.accessibilityIdentifier = "stack_view"
        return s
    }()

    // See helper method at bottom
    lazy var textField1 = self.createTextField(placeholder: "Textfield 1")
    lazy var textField2 = self.createTextField(placeholder: "Textfield 2")
    lazy var textField3 = self.createTextField(placeholder: "Textfield 3")
    lazy var textField4 = self.createTextField(placeholder: "Textfield 4")
    lazy var textField5 = self.createTextField(placeholder: "Textfield 5")
    lazy var textField6 = self.createTextField(placeholder: "Textfield 6")

    override func loadView() {
        view = UIView()
        view.backgroundColor = .white

        view.addSubview(scrollView)
        scrollView.addSubview(stackView)

        stackView.addArrangedSubview(textField1)
        stackView.addArrangedSubview(textField2)
        stackView.addArrangedSubview(textField3)
        stackView.addArrangedSubview(textField4)
        stackView.addArrangedSubview(textField5)
        stackView.addArrangedSubview(textField6)

        NSLayoutConstraint.activate([
            scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20),
            scrollView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 20),
            scrollView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -20),
            scrollView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -20),

            stackView.widthAnchor.constraint(equalTo: scrollView.contentLayoutGuide.widthAnchor),
            stackView.trailingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.trailingAnchor),
            stackView.topAnchor.constraint(equalTo: scrollView.contentLayoutGuide.topAnchor),
            stackView.leadingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.leadingAnchor),
            stackView.bottomAnchor.constraint(equalTo: scrollView.contentLayoutGuide.bottomAnchor)
        ])
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        scrollView.contentSize = stackView.frame.size
    }

    func createTextField(placeholder: String) -> UITextField {
        let t = UITextField()
        t.translatesAutoresizingMaskIntoConstraints = false
        t.borderStyle = .roundedRect
        t.clearButtonMode = .whileEditing
        t.text = placeholder
        t.placeholder = placeholder
        t.accessibilityIdentifier = placeholder
        return t
    }
}
</code>```

I am quite obviously missing something, but even after spending several hours of trying and googling, I still haven't found a solution...

What I do realize is that all the text fields' and the stack view's frames are (0, 0, 0, 0), so quite obviously, I am missing some constraints, right?

答: for stackView, you are not defining stackView.translatesAutoresizingMaskIntoConstraints = false

Body:
I want to get the following structure programmatically (and am currently failing...):

View

Scroll View

Vertical Stack View

I was able to get what I wanted in Interface Builder, but cannot seem to figure out how to achieve this in code. In IB, it looks like this (please click on the picture to see it fully):

The settings of the stack view look like this:

Now, this is my attempt to mirror that in code:

import UIKit

class ScrollViewController: UIViewController {

    lazy var scrollView: UIScrollView = {
        let s = UIScrollView()
        s.contentMode = .scaleToFill
        s.backgroundColor = .gray
        s.accessibilityIdentifier = "scroll_view"
        s.translatesAutoresizingMaskIntoConstraints = false
        return s
    }()

    lazy var stackView: UIStackView = {
        let s = UIStackView()
        s.axis = .vertical
        s.alignment = .fill
        s.distribution = .equalSpacing
        s.spacing = 10
        s.contentMode = .scaleToFill
        s.accessibilityIdentifier = "stack_view"
        return s
    }()

    // See helper method at bottom
    lazy var textField1 = self.createTextField(placeholder: "Textfield 1")
    lazy var textField2 = self.createTextField(placeholder: "Textfield 2")
    lazy var textField3 = self.createTextField(placeholder: "Textfield 3")
    lazy var textField4 = self.createTextField(placeholder: "Textfield 4")
    lazy var textField5 = self.createTextField(placeholder: "Textfield 5")
    lazy var textField6 = self.createTextField(placeholder: "Textfield 6")

    override func loadView() {
        view = UIView()
        view.backgroundColor = .white

        view.addSubview(scrollView)
        scrollView.addSubview(stackView)

        stackView.addArrangedSubview(textField1)
        stackView.addArrangedSubview(textField2)
        stackView.addArrangedSubview(textField3)
        stackView.addArrangedSubview(textField4)
        stackView.addArrangedSubview(textField5)
        stackView.addArrangedSubview(textField6)

        NSLayoutConstraint.activate([
            scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20),
            scrollView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 20),
            scrollView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -20),
            scrollView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -20),

            stackView.widthAnchor.constraint(equalTo: scrollView.contentLayoutGuide.widthAnchor),
            stackView.trailingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.trailingAnchor),
            stackView.topAnchor.constraint(equalTo: scrollView.contentLayoutGuide.topAnchor),
            stackView.leadingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.leadingAnchor),
            stackView.bottomAnchor.constraint(equalTo: scrollView.contentLayoutGuide.bottomAnchor)
        ])
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        scrollView.contentSize = stackView.frame.size
    }

    func createTextField(placeholder: String) -> UITextField {
        let t = UITextField()
        t.translatesAutoresizingMaskIntoConstraints = false
        t.borderStyle = .roundedRect
        t.clearButtonMode = .whileEditing
        t.text = placeholder
        t.placeholder = placeholder
        t.accessibilityIdentifier = placeholder
        return t
    }
}

I am quite obviously missing something, but even after spending several hours of trying and googling, I still haven't found a solution...

What I do realize is that all the text fields' and the stack view's frames are (0, 0, 0, 0), so quite obviously, I am missing some constraints, right?


问:
How to add onfocus event listener to input field to change the style of the labels
I am trying to make my input labels change style to the .fancyclass style when I use onfocus on the input field. I was wondering how I would do this using event listeners in Javascript?

```<code>            <fieldset name="in-fields">

                <section>
                    <label for ="inputname" class="name">Name*</label>
                    First: <br><input type="text" name="info" required><br/>
                    Last: <br><input type="text" name="info" required><br/>
                </section>

                <section>
                    <label for="inputnumber" class ="name">Phone Number*</label>
                    <input type="text" name="info" required>
                </section>

                <section>
                    <label for="inputemploy" class ="name">Current Employer</label>
                    <input type="text" name="info">
                </section>

                <section>
                    <label for="inputemail" class= "name">Email*</label>
                    <input type="email" name="info" required>
                </section>

           </fieldset>

           .fancyclass {
           font-weight:bold;
           text-transform:uppercase;
           }

        document.querySelectorAll('input[name="info"]').forEach(item=> {
            item.addEventListener('focus', event => {
            console.log("add fancy class");
            })
        })
</code>```

This is what I have so far... I am pretty sure this is wrong. I don't know how to add the fancy class to the label when I focus on the input field.

答:
don't forget to remove your fancy class on blur too

const myForm     = document.getElementById('my-form')
  ,   All_Labels = myForm['in-fields'].querySelectorAll('label')
  ;
myForm['in-fields'].querySelectorAll('input').forEach(inElm=>
  {
  inElm.onfocus=focusOn;
  inElm.onblur=focusOff;
  })
function focusOn(e)
  {
  let label_elm = e.target.parentNode.querySelector('label')
  All_Labels.forEach(lbl=>
    {
    if (lbl===label_elm)  { lbl.classList.add('fancyclass')    }
    else                  { lbl.classList.remove('fancyclass') }
    })
  }
function focusOff(e)
  {
  All_Labels.forEach(lbl=> lbl.classList.remove('fancyclass') )
  }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.fancyclass {
  font-weight:bold;
  text-transform:uppercase;
}</code>```

<form id="my-form">
  <fieldset name="in-fields">

      Name*

      First:
<input type="text" name="First-Name" required>

      Last:
<input type="text" name="Last-Name"  required>

      Phone Number*
      <input type="text" name="Phone-Number" required>

      Current Employer
      <input type="text" name="Current-Employer">

      Email*
      <input type="email" name="Email" required>

  </fieldset>
</form>```

Body:
I am trying to make my input labels change style to the .fancyclass style when I use onfocus on the input field. I was wondering how I would do this using event listeners in Javascript?

            <fieldset name="in-fields">

                    Name*
                    First:
<input type="text" name="info" required>

                    Last:
<input type="text" name="info" required>

                    Phone Number*
                    <input type="text" name="info" required>

                    Current Employer
                    <input type="text" name="info">

                    Email*
                    <input type="email" name="info" required>

           </fieldset>

           .fancyclass {
           font-weight:bold;
           text-transform:uppercase;
           }

        document.querySelectorAll('input[name="info"]').forEach(item=> {
            item.addEventListener('focus', event => {
            console.log("add fancy class");
            })
        })

This is what I have so far... I am pretty sure this is wrong. I don't know how to add the fancy class to the label when I focus on the input field.

Body:
don't forget to remove your fancy class on blur too

const myForm     = document.getElementById('my-form')
  ,   All_Labels = myForm['in-fields'].querySelectorAll('label')
  ;
myForm['in-fields'].querySelectorAll('input').forEach(inElm=>
  {
  inElm.onfocus=focusOn;
  inElm.onblur=focusOff;
  })
function focusOn(e)
  {
  let label_elm = e.target.parentNode.querySelector('label')
  All_Labels.forEach(lbl=>
    {
    if (lbl===label_elm)  { lbl.classList.add('fancyclass')    }
    else                  { lbl.classList.remove('fancyclass') }
    })
  }
function focusOff(e)
  {
  All_Labels.forEach(lbl=> lbl.classList.remove('fancyclass') )
  }

.fancyclass {
  font-weight:bold;
  text-transform:uppercase;
}

<form id="my-form">
  <fieldset name="in-fields">
    <section>
      <label class="name">Name*</label><br>
      First: <br><input type="text" name="First-Name" required><br>
      Last:  <br><input type="text" name="Last-Name"  required><br>
    </section>

    <section>
      <label class="name">Phone Number*</label>
      <input type="text" name="Phone-Number" required>
    </section>

    <section>
      <label class="name">Current Employer</label>
      <input type="text" name="Current-Employer">
    </section>

    <section>
      <label class="name">Email*</label>
      <input type="email" name="Email" required>
    </section>

  </fieldset>
</form>


问:
How to get Word Level Timestamps using Azure Speech to Text and the Python SDK?
My code currently is able to read an audio file and transcribe it using Azure Speech to Text, with help from an example that I found on GitHub. However, I need to include the timestamps for all the words in the transcription. According to the documentation, this functionality was added in version 1.5.0, and is accessed through the method request_word_level_timestamps(). But even when I have called it, I get the same response as before. I cannot figure out how to use it from the documentation. Does anyone know how it works?

I'm using Python SDK version 1.5.1.

```<code>import azure.cognitiveservices.speech as speechsdk
import time
from allennlp.predictors.predictor import Predictor
import json

inputPath = "(inputlocation)"
outputPath = "(outputlocation)"

# Creates an instance of a speech config with specified subscription     key and service region.
# Replace with your own subscription key and service region (e.g., "westus").
speech_key, service_region = "apikey", "region"
speech_config = speechsdk.SpeechConfig(subscription=speech_key,     region=service_region)
speech_config.request_word_level_timestamps()
speech_config.output_format=speechsdk.OutputFormat.Detailed
#print("VALUE: " +     speech_config.get_property(property_id=speechsdk.PropertyId.SpeechServic    eResponse_RequestWordLevelTimestamps))
filename = input("Enter filename: ")

print(speech_config)

try:
    audio_config = speechsdk.audio.AudioConfig(filename= inputPath +     filename)

    # Creates a recognizer with the given settings
    speech_recognizer =     speechsdk.SpeechRecognizer(speech_config=speech_config,     audio_config=audio_config)

def start():
    done = False
    #output = ""
    fileOpened = open(outputPath+ filename[0: len(filename) - 4] + "_MS_recognized.txt", "w+")
    fileOpened.truncate(0)
    fileOpened.close()

    def stop_callback(evt):
        print("Closing on {}".format(evt))
        speech_recognizer.stop_continuous_recognition()
        nonlocal done
        done = True

    def add_to_res(evt):
        #nonlocal output
        #print("Recognized: {}".format(evt.result.text))
        #output = output + evt.result.text + "\n"
        fileOpened = open( outputPath + filename[0: len(filename) - 4] + "_MS_recognized.txt", "a")
        fileOpened.write(evt.result.text + "\n")
        fileOpened.close()
        #print(output)

    # Connect callbacks to the events fired by the speech recognizer
    speech_recognizer.recognizing.connect(lambda evt: print('RECOGNIZING: {}'.format(evt)))
    speech_recognizer.recognized.connect(lambda evt: print('RECOGNIZED: {}'.format(evt)))
    speech_recognizer.recognized.connect(add_to_res)
    speech_recognizer.session_started.connect(lambda evt: print('SESSION STARTED: {}'.format(evt)))
    speech_recognizer.session_stopped.connect(lambda evt: print('SESSION STOPPED {}'.format(evt)))
    speech_recognizer.canceled.connect(lambda evt: print('CANCELED {}'.format(evt)))
    # stop continuous recognition on either session stopped or canceled events
    speech_recognizer.session_stopped.connect(stop_callback)
    speech_recognizer.canceled.connect(stop_callback)

    # Start continuous speech recognition
    speech_recognizer.start_continuous_recognition()
    while not done:
        time.sleep(.5)
    # </SpeechContinuousRecognitionWithFile>

    # Starts speech recognition, and returns after a single utterance is recognized. The end of a
    # single utterance is determined by listening for silence at the end or until a maximum of 15
    # seconds of audio is processed.  The task returns the recognition text as result.
    # Note: Since recognize_once() returns only a single utterance, it is suitable only for single
    # shot recognition like command or query.
    # For long-running multi-utterance recognition, use start_continuous_recognition() instead.

start()

except Exception as e:
    print("File does not exist")
    #print(e)
</code>```

The results only contain session_id and a result object which includes result_id, text and reason.

答:
Per a comment on how will it help for continuous recognition, if you set up the SpeechConfig with request_word_level_timestamps(), you can run this as continuous recognition. You can inspect the json results with evt.result.json.

For example,

```<code>speech_config = speechsdk.SpeechConfig(subscription=speech_key, region=service_region)
speech_config.request_word_level_timestamps()
</code>```

then your speech recognizer:

```<code>speech_recognizer = speechsdk.SpeechRecognizer(speech_config=speech_config, audio_config=audio_config)
</code>```

When you're connecting callbacks to the events fired by the speech_recognizer, you can see word-level timestamps with:

```<code>speech_recognizer.recognized.connect(lambda evt: print('JSON: {}'.format(evt.result.json)))
</code>```

My issue is that the Translation object doesn't contain word-level as it doesn't accept a speech_config.

Body:
My code currently is able to read an audio file and transcribe it using Azure Speech to Text, with help from an example that I found on GitHub. However, I need to include the timestamps for all the words in the transcription. According to the documentation, this functionality was added in version 1.5.0, and is accessed through the method request_word_level_timestamps(). But even when I have called it, I get the same response as before. I cannot figure out how to use it from the documentation. Does anyone know how it works?

I'm using Python SDK version 1.5.1.

import azure.cognitiveservices.speech as speechsdk
import time
from allennlp.predictors.predictor import Predictor
import json

inputPath = "(inputlocation)"
outputPath = "(outputlocation)"

# Creates an instance of a speech config with specified subscription     key and service region.
# Replace with your own subscription key and service region (e.g., "westus").
speech_key, service_region = "apikey", "region"
speech_config = speechsdk.SpeechConfig(subscription=speech_key,     region=service_region)
speech_config.request_word_level_timestamps()
speech_config.output_format=speechsdk.OutputFormat.Detailed
#print("VALUE: " +     speech_config.get_property(property_id=speechsdk.PropertyId.SpeechServic    eResponse_RequestWordLevelTimestamps))
filename = input("Enter filename: ")

print(speech_config)

try:
    audio_config = speechsdk.audio.AudioConfig(filename= inputPath +     filename)

    # Creates a recognizer with the given settings
    speech_recognizer =     speechsdk.SpeechRecognizer(speech_config=speech_config,     audio_config=audio_config)

def start():
    done = False
    #output = ""
    fileOpened = open(outputPath+ filename[0: len(filename) - 4] + "_MS_recognized.txt", "w+")
    fileOpened.truncate(0)
    fileOpened.close()

    def stop_callback(evt):
        print("Closing on {}".format(evt))
        speech_recognizer.stop_continuous_recognition()
        nonlocal done
        done = True

    def add_to_res(evt):
        #nonlocal output
        #print("Recognized: {}".format(evt.result.text))
        #output = output + evt.result.text + "\n"
        fileOpened = open( outputPath + filename[0: len(filename) - 4] + "_MS_recognized.txt", "a")
        fileOpened.write(evt.result.text + "\n")
        fileOpened.close()
        #print(output)

    # Connect callbacks to the events fired by the speech recognizer
    speech_recognizer.recognizing.connect(lambda evt: print('RECOGNIZING: {}'.format(evt)))
    speech_recognizer.recognized.connect(lambda evt: print('RECOGNIZED: {}'.format(evt)))
    speech_recognizer.recognized.connect(add_to_res)
    speech_recognizer.session_started.connect(lambda evt: print('SESSION STARTED: {}'.format(evt)))
    speech_recognizer.session_stopped.connect(lambda evt: print('SESSION STOPPED {}'.format(evt)))
    speech_recognizer.canceled.connect(lambda evt: print('CANCELED {}'.format(evt)))
    # stop continuous recognition on either session stopped or canceled events
    speech_recognizer.session_stopped.connect(stop_callback)
    speech_recognizer.canceled.connect(stop_callback)

    # Start continuous speech recognition
    speech_recognizer.start_continuous_recognition()
    while not done:
        time.sleep(.5)
    # </SpeechContinuousRecognitionWithFile>

    # Starts speech recognition, and returns after a single utterance is recognized. The end of a
    # single utterance is determined by listening for silence at the end or until a maximum of 15
    # seconds of audio is processed.  The task returns the recognition text as result.
    # Note: Since recognize_once() returns only a single utterance, it is suitable only for single
    # shot recognition like command or query.
    # For long-running multi-utterance recognition, use start_continuous_recognition() instead.

start()

except Exception as e:
    print("File does not exist")
    #print(e)

The results only contain session_id and a result object which includes result_id, text and reason.

Body:
Per a comment on how will it help for continuous recognition, if you set up the SpeechConfig with request_word_level_timestamps(), you can run this as continuous recognition. You can inspect the json results with evt.result.json.

For example,

speech_config = speechsdk.SpeechConfig(subscription=speech_key, region=service_region)
speech_config.request_word_level_timestamps()

then your speech recognizer:

speech_recognizer = speechsdk.SpeechRecognizer(speech_config=speech_config, audio_config=audio_config)

When you're connecting callbacks to the events fired by the speech_recognizer, you can see word-level timestamps with:

speech_recognizer.recognized.connect(lambda evt: print('JSON: {}'.format(evt.result.json)))

My issue is that the Translation object doesn't contain word-level as it doesn't accept a speech_config.


问:
Combinig output of 2 function in javascript
I am relatively new to Javascript (biopython background) and I am trying to add a simple feature to a website.

In essence, I need to accept user input for 4 types of menus (check boxes) and then multiply the sum of the values ($) of selected menus by the number of days and number of people (user inputs using text fields).

Below are HTML and Javascript parts of the code

function multiply() {
  var n_ppl = document.getElementsByName('people')[0].value;
  var n_days = document.getElementsByName('days')[0].value;
  return var out = n_ppl * n_days;
}

function totalIt() {
  var n_ppl = document.getElementsByName('people')[0].value;
  var n_days = document.getElementsByName('days')[0].value;
  var input = document.getElementsByName("product");
  var total = 0;
  for (var i = 0; i < input.length; i++) {
    if (input[i].checked) {
      total += parseInt(input[i].value);
    }
  return var price = total
}

  // not sure how can I get - var final = total * out
  // after I get it I can finally do - document.getElementsByName("total")[0].value = "$" + final.toFixed(2);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><br> Breakfast <input name="product" value="12" type="checkbox" onclick="totalIt()" /> <br>
<br> First Meal <input name="product" value="20" type="checkbox" onclick="totalIt()" /> <br>
<br> Second Meal <input name="product" value="15" type="checkbox" onclick="totalIt()" /> <br>
<br> Craft Service <input name="product" value="10" type="checkbox" onclick="totalIt()" /> <br>
<br> Number of People <input type="text" name="people"> <br>
<br> Number of Days <input type="text" name="days"> <br>
<br> Total: <input value="$0.00" readonly="readonly" type="text" name="total" /></code>```

I apologize to all web developers for my pythonic style in advance.

I should also mention that both functions work perfectly fine separately but even without trying to multiply their outputs (i.e. even if their code is present next to each other), nothing works.
I will be really grateful for your help!

Body:
I am relatively new to Javascript (biopython background) and I am trying to add a simple feature to a website.

In essence, I need to accept user input for 4 types of menus (check boxes) and then multiply the sum of the values ($) of selected menus by the number of days and number of people (user inputs using text fields).

Below are HTML and Javascript parts of the code

function multiply() {
  var n_ppl = document.getElementsByName('people')[0].value;
  var n_days = document.getElementsByName('days')[0].value;
  return var out = n_ppl * n_days;
}

function totalIt() {
  var n_ppl = document.getElementsByName('people')[0].value;
  var n_days = document.getElementsByName('days')[0].value;
  var input = document.getElementsByName("product");
  var total = 0;
  for (var i = 0; i < input.length; i++) {
    if (input[i].checked) {
      total += parseInt(input[i].value);
    }
  return var price = total
}

  // not sure how can I get - var final = total * out
  // after I get it I can finally do - document.getElementsByName("total")[0].value = "$" + final.toFixed(2);

 Breakfast <input name="product" value="12" type="checkbox" onclick="totalIt()" />

 First Meal <input name="product" value="20" type="checkbox" onclick="totalIt()" />

 Second Meal <input name="product" value="15" type="checkbox" onclick="totalIt()" />

 Craft Service <input name="product" value="10" type="checkbox" onclick="totalIt()" />

 Number of People <input type="text" name="people">

 Number of Days <input type="text" name="days">

 Total: <input value="$0.00" readonly="readonly" type="text" name="total" />

I apologize to all web developers for my pythonic style in advance.

I should also mention that both functions work perfectly fine separately but even without trying to multiply their outputs (i.e. even if their code is present next to each other), nothing works.
I will be really grateful for your help!

Body:
You need only one function to iterate over your inputs.

Do not use inline JavaScript it's sign of bad coding habits, and makes the application hard to debug. Keep your JS in one place and make use of Element.addEventListener()

Use Node.querySelector() and Node.querySelectorAll()

Use name="product[]" syntax when handling similar names. This will be submitted to the backend as an array of values.

You can use Array.prototype.reduce() to reduce (accumulate) all your '[name="product[]"]:checked' chechboxes values to a single integer

Place your <script> code  right before the closing </body> tag

const EL_menu  = document.querySelector("#menu");

const calcPrice = evt => {

  const price = [...EL_menu.querySelectorAll('[name="product[]"]:checked')]
    .reduce((n, el) => (n += +el.value, n), 0);

  const nPers = +EL_menu.querySelector('[name="people"]').value || 1;
  const nDays = +EL_menu.querySelector('[name="days"]').value || 1;
  const total = price * nPers * nDays;

  EL_menu.querySelector("[name=total]").value = `\$${total.toFixed(2)}`;
}

EL_menu.querySelectorAll("input").forEach(el => el.addEventListener('input', calcPrice));

#menu label { display: block; }

<div id="menu">
  <label><input type="checkbox" name="product[]" value="12"> Breakfast</label>
  <label><input type="checkbox" name="product[]" value="20"> First Meal</label>
  <label><input type="checkbox" name="product[]" value="15"> Second Meal</label>
  <label><input type="checkbox" name="product[]" value="10"> Craft Service</label>
  <label><input type="number" name="people" value="1" min="1"> Number of People</label>
  <label><input type="number" name="days" value="1" min="1"> Number of Days</label><br>
  Total: <input type="text" name="total" value="$0.00" readonly="readonly">
</div>


问:
Google Maps Marker Set Opacity With Transition
Based on this SO post I see it is possible to set opacity to a marker. Does anyone know if one can add a transition property as well so that the transition to, let's say opacity 0.7, happens at a duration of 350ms? I have tried adding the following css keys to the method setOptions:

```<code>marker.setOptions({'opacity': 0.7, 'transition-property': 'opacity', 'transition-duration': '350ms'})
</code>```

But the transition duration does not seem to be working. The marker's opacity just changes immediately.

答:
You can use setTimeout at 350 ms to set the marker's opacity to 0.7 .

```<code>  setTimeout(function(){
  marker.setOpacity(0.7);
  }, 350);
</code>```

Here is a sample code.

Body:
Based on this SO post I see it is possible to set opacity to a marker. Does anyone know if one can add a transition property as well so that the transition to, let's say opacity 0.7, happens at a duration of 350ms? I have tried adding the following css keys to the method setOptions:

marker.setOptions({'opacity': 0.7, 'transition-property': 'opacity', 'transition-duration': '350ms'})

But the transition duration does not seem to be working. The marker's opacity just changes immediately.

Body:
You can use setTimeout at 350 ms to set the marker's opacity to 0.7 .

  setTimeout(function(){
  marker.setOpacity(0.7);
  }, 350);

Here is a sample code.


问:
Invalid initialization of reference of type error
A million thanks to anyone, who is willing to help me with this.

First, the code:

```<code>#include <iostream>
#include <string>
#include <fstream>
#include <vector>

using namespace std;

void Beolvas (vector<vector<int> > mat);
bool VanNemNull (const vector<vector<int> > &mat);

int main()
{
cout << "Van-e a mátrixnak olyan oszlopa, hogy a főátló alatt csak 0-át tartalmaz, és ha igen, akkor melyik az?\n" <<endl;

    char ch;
    do{
        // Adatbevitel
        vector<vector<int> > mat;
        Beolvas(mat);

        //Kiértékelés
        int i;
       if (VanNemNull(&mat[i])) cout<<"szupiiiiii";

        cout<< endl << "Futtassam újra?   (I/N)";cin>>ch;
        }while (ch!='n' && ch!='N');
    return 0;
}

void Beolvas(vector<vector<int> > mat)
{
    ifstream fajl;
    bool hiba;
    string str;

    do{
        cout << "Fajl neve:";
        cin >> str;
        fajl.open(str.c_str());
        if (hiba = fajl.fail())
        {
            cout << "Nincs ilyen nevű fájl" << endl;
            fajl.clear();
        }
    }while (hiba);

    int n;
    fajl >> n;
    if (n<1)
    {
        cout<<"Helytelen a mátrix mérete\n Kérem ellenőrizze a forrásfájlt!\n";
        cout<<"E megnyomásával kilép"<<endl;

    char ex;
    do{
        cin>>ex;
        }while (ex!='e' && ex!='E');exit(0);
    }

    mat.resize(n);
    for(int i=0; i<n; ++i)
        {
            mat[i].resize(n);
            for (int j=0; j<n; ++j)
            {
                fajl >> mat[i][j];
            }
        }
    fajl.close();
    cout<<"A mátrix a következöképpen néz ki:"<<"\n";
    cout<<"Elemszáma: "; cout<<n*n<<"\n";
    for (int i=0; i<n; ++i)
        {
            for (int j=0; j<n; ++j)
            {
                cout<<mat[i][j]<<"\t";
            }
            cout<<"\n";

        }

}

/*void Vansor (const vector<vector<int> > mat)
{
    //bool l = false;
}*/

bool VanNemNull (const vector<vector<int> > mat)
{
    bool l = false;
    int i=0;
    cout<<(int)mat.size();
    for (int j=i+1; !l && j<(int)mat.size(); ++j)
    {
        cout<<mat[j][i]<<"\n";
        if (l) cout<<"hej\n";
        l = (mat[j][i]!=0);
        if (l= true) cout<<"22"; else cout<<"11";

    }
    return (l);
}
</code>```

The main problem (I think) is the last part. Also, I get these error messages:

```<code>||In function `int main()':|
|23|error: invalid initialization of reference of type 'const std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > >&' from expression of type 'std::vector<int, std::allocator<int> >*'|
|9|error: in passing argument 1 of `bool VanNemNull(const std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > >&)'|
||=== Build finished: 2 errors, 0 warnings ===|
</code>```

答: &mat[i] has type vector<int>*, and you're passing it to a function that takes a reference to avector<vector<int> >.  I don't understand what your code is doing well enough to tell you how to fix it, but now you know what the error means.

Body:
A million thanks to anyone, who is willing to help me with this.

First, the code:

#include <iostream>
#include <string>
#include <fstream>
#include <vector>

using namespace std;

void Beolvas (vector<vector<int> > mat);
bool VanNemNull (const vector<vector<int> > &mat);

int main()
{
cout << "Van-e a mátrixnak olyan oszlopa, hogy a főátló alatt csak 0-át tartalmaz, és ha igen, akkor melyik az?\n" <<endl;

    char ch;
    do{
        // Adatbevitel
        vector<vector<int> > mat;
        Beolvas(mat);

        //Kiértékelés
        int i;
       if (VanNemNull(&mat[i])) cout<<"szupiiiiii";

        cout<< endl << "Futtassam újra?   (I/N)";cin>>ch;
        }while (ch!='n' && ch!='N');
    return 0;
}

void Beolvas(vector<vector<int> > mat)
{
    ifstream fajl;
    bool hiba;
    string str;

    do{
        cout << "Fajl neve:";
        cin >> str;
        fajl.open(str.c_str());
        if (hiba = fajl.fail())
        {
            cout << "Nincs ilyen nevű fájl" << endl;
            fajl.clear();
        }
    }while (hiba);

    int n;
    fajl >> n;
    if (n<1)
    {
        cout<<"Helytelen a mátrix mérete\n Kérem ellenőrizze a forrásfájlt!\n";
        cout<<"E megnyomásával kilép"<<endl;

    char ex;
    do{
        cin>>ex;
        }while (ex!='e' && ex!='E');exit(0);
    }

    mat.resize(n);
    for(int i=0; i<n; ++i)
        {
            mat[i].resize(n);
            for (int j=0; j<n; ++j)
            {
                fajl >> mat[i][j];
            }
        }
    fajl.close();
    cout<<"A mátrix a következöképpen néz ki:"<<"\n";
    cout<<"Elemszáma: "; cout<<n*n<<"\n";
    for (int i=0; i<n; ++i)
        {
            for (int j=0; j<n; ++j)
            {
                cout<<mat[i][j]<<"\t";
            }
            cout<<"\n";

        }

}

/*void Vansor (const vector<vector<int> > mat)
{
    //bool l = false;
}*/

bool VanNemNull (const vector<vector<int> > mat)
{
    bool l = false;
    int i=0;
    cout<<(int)mat.size();
    for (int j=i+1; !l && j<(int)mat.size(); ++j)
    {
        cout<<mat[j][i]<<"\n";
        if (l) cout<<"hej\n";
        l = (mat[j][i]!=0);
        if (l= true) cout<<"22"; else cout<<"11";

    }
    return (l);
}

The main problem (I think) is the last part. Also, I get these error messages:

||In function `int main()':|
|23|error: invalid initialization of reference of type 'const std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > >&' from expression of type 'std::vector<int, std::allocator<int> >*'|
|9|error: in passing argument 1 of `bool VanNemNull(const std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > >&)'|
||=== Build finished: 2 errors, 0 warnings ===|


问:
Check nested JSON in Javascript/Typescript to see if Data is null before operation
Is there an easier way in Typescript/Javascript to check if nested JSON object is null, and then set a value? Right now, we have to peruse through 4 data layers to check if they are null, and then we can conduct operation to set value. Curious if there is any easier syntax?

```<code>if (this.addressEntryConfig
    && this.addressEntryConfig.addressModel
    && this.addressEntryConfig.addressModel.partyMailingAddress
    && this.addressEntryConfig.addressModel.partyMailingAddress.address) {

    this.addressMailingInputData = this.addressEntryConfig.addressModel.partyMailingAddress.address;
}
</code>```

Resource:  Test for existence of nested JavaScript object key

答:
In Typescript, you can use optional chaining...

```<code>this.addressEntryConfig?.addressModel?.partyMailingAddress?.address
</code>```

It will only return the value of address if the rest of the properties are not null or undefined. If any are null or undefined, it will stop processing and just return undefined.

If other words you can do:

```<code>if (this.addressEntryConfig?.addressModel?.partyMailingAddress?.address)
    this.addressMailingInputData = this.addressEntryConfig.addressModel.partyMailingAddress.address;
</code>```

More on the TypeScript 3.7 release notes page here: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#optional-chaining

Body:
Is there an easier way in Typescript/Javascript to check if nested JSON object is null, and then set a value? Right now, we have to peruse through 4 data layers to check if they are null, and then we can conduct operation to set value. Curious if there is any easier syntax?

if (this.addressEntryConfig
    && this.addressEntryConfig.addressModel
    && this.addressEntryConfig.addressModel.partyMailingAddress
    && this.addressEntryConfig.addressModel.partyMailingAddress.address) {

    this.addressMailingInputData = this.addressEntryConfig.addressModel.partyMailingAddress.address;
}

Resource:  Test for existence of nested JavaScript object key

Body:
In Typescript, you can use optional chaining...

this.addressEntryConfig?.addressModel?.partyMailingAddress?.address

It will only return the value of address if the rest of the properties are not null or undefined. If any are null or undefined, it will stop processing and just return undefined.

If other words you can do:

if (this.addressEntryConfig?.addressModel?.partyMailingAddress?.address)
    this.addressMailingInputData = this.addressEntryConfig.addressModel.partyMailingAddress.address;

More on the TypeScript 3.7 release notes page here: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#optional-chaining