问:
Reducing an image byte size to given value for format other than jpeg
Following this post, I successfully reduced the byte size of an image to the desired level, but the problem is that I succeeded to do that only for JPEG. When I try to perform this for, say, png, the function does not do what is expected:

```<code>def get_highest_acceptable_quality(image, filename, target):
    q_min, q_max = 1, 96
    # Highest acceptable quality found
    q_acc = -1
    while q_min <= q_max:
        m = math.floor((q_min + q_max) / 2)
        buffer = BytesIO()
        image.save(buffer, format="png", compress_level=m)
        s = buffer.getbuffer().nbytes # the s value is always the same for all values of m

        ...
</code>```

The strange thing here is that the value of s remains the same irrespective of what the value of m is. Which is not the case for JPEG (here the entire function works just fine). I am completely lost because I am not a pro in image processing stuff. Any help?

答:
JPEG is lossy. That means it is permitted to change your image pixels in order to reduce your filesize, i.e. you trade absolute accuracy for a decrease in size and transmission time. It tries to take advantage of the way we see things in order to make the quality loss less noticeable. For the technically inquisitive, I am referring to "chroma subsampling" whereby the colour information is sub-sampled because the human eye is more sensitive to brightness variation than to colour variation, and to "quantisation" whereby high frequency changes are weighted less or discarded because the human eye is better at seeing changes over a broader area than making out thousands of changes in a small, dense, confused area - see Wikipedia article on JPEG.

PNG, on the other hand, is always lossless. It cannot discard information or change pixels to make filesize smaller. Ultimately that means, with certain image types, it cannot reduce filesizes as far as JPEG.

Body:
Following this post, I successfully reduced the byte size of an image to the desired level, but the problem is that I succeeded to do that only for JPEG. When I try to perform this for, say, png, the function does not do what is expected:

def get_highest_acceptable_quality(image, filename, target):
    q_min, q_max = 1, 96
    # Highest acceptable quality found
    q_acc = -1
    while q_min <= q_max:
        m = math.floor((q_min + q_max) / 2)
        buffer = BytesIO()
        image.save(buffer, format="png", compress_level=m)
        s = buffer.getbuffer().nbytes # the s value is always the same for all values of m

        ...

The strange thing here is that the value of s remains the same irrespective of what the value of m is. Which is not the case for JPEG (here the entire function works just fine). I am completely lost because I am not a pro in image processing stuff. Any help?


来源: stackexchange

问:
Displaying the full exception stack (Nativescript)
My NS app crashes.

It displays the stack trace - but only about 20 lines or so. and then ...

That's not enough for me to figure out where it's crashing.

How can I get it to display more depth.

Thanks

答: Alternatively you can use Sidekick, Sidekick install, open debug and check its console messages, it does truncate the log but it lets you copy the full log output.</p>

ContentLicense: CC BY-SA 4.0


问:
JEST - node server having trouble during start
I have one node application which have a file called server.js where I run
node server.js env=feature port=8081 to start the node server.
I installed jest and supertest. After writing one async get call in sample.test.js file I am hitting npm test, But the result is not as expected. Because to start server.js I will pass two parameters called env and port as mentioned above. My question is, How to use it in Jest. My server importing code is present below

```<code>const app = require('../server.js')
const request = supertest(app)
describe('Sample Test', () => {
const response = await request.get("/rest/api/v1/mytools/getAvailableTools?provisioning=all");
    console.log('James bob ' + JSON.stringify(response))
    expect(response.statusCode).toEqual(401);
    done()
})
</code>```

答:
There are a couple of ways how you can approach this.

First, it's a common practice to pass such values using environment variables, you would have to update code processing those values but at the end, you can do the following:

ENV=feature PORT=8081 node server.js
ENV=feature PORT=8081 npm test
```

<p>The second option would be to decouple command line parameters from actual server and test them separately, e.g.</p>

<pre class="lang-js prettyprint-override"><code>export const createServer(env, port) {
  // Server code
}

// Command line processing code

createServer(cliEnv, cliPort)
</code>```

So in tests you can write:

const createServer = require('../server.js')
const request = supertest(createServer('feature', 8081))
describe('Sample Test', () => {
const response = await request.get("/rest/api/v1/mytools/getAvailableTools?provisioning=all");
    console.log('James bob ' + JSON.stringify(response))
    expect(response.statusCode).toEqual(401);
    done()
})
```

Body:
I have one node application which have a file called server.js where I run
node server.js env=feature port=8081 to start the node server.
I installed jest and supertest. After writing one async get call in sample.test.js file I am hitting npm test, But the result is not as expected. Because to start server.js I will pass two parameters called env and port as mentioned above. My question is, How to use it in Jest. My server importing code is present below

const app = require('../server.js')
const request = supertest(app)
describe('Sample Test', () => {
const response = await request.get("/rest/api/v1/mytools/getAvailableTools?provisioning=all");
    console.log('James bob ' + JSON.stringify(response))
    expect(response.statusCode).toEqual(401);
    done()
})

Body:
There are a couple of ways how you can approach this.

First, it's a common practice to pass such values using environment variables, you would have to update code processing those values but at the end, you can do the following:

ENV=feature PORT=8081 node server.js
ENV=feature PORT=8081 npm test

The second option would be to decouple command line parameters from actual server and test them separately, e.g.

export const createServer(env, port) {
  // Server code
}

// Command line processing code

createServer(cliEnv, cliPort)

So in tests you can write:

const createServer = require('../server.js')
const request = supertest(createServer('feature', 8081))
describe('Sample Test', () => {
const response = await request.get("/rest/api/v1/mytools/getAvailableTools?provisioning=all");
    console.log('James bob ' + JSON.stringify(response))
    expect(response.statusCode).toEqual(401);
    done()
})


问:
BeautifulSoup + For loop Zip - How to Try/Except one of them
Got the following code:

```<code>from bs4 import BeautifulSoup
import requests
import re

# Source Sites
mimo = 'https://tienda.mimo.com.ar/mimo/junior/ropa-para-ninas.html'
cheeky = ''
grisino = ''

source = requests.get(mimo).text

soup = BeautifulSoup(source, 'lxml')

for name_product, old_price, special_price in zip(soup.select('h3.titprod'),
                                                  soup.select('span[id^="old-price"]'),
                                                  soup.select('span[id^="product-price"]')):
    print(f'Name: {name_product.text.strip()} |  Old price = {old_price.text.strip()} | Discounted price = {special_price.text.strip()}')
</code>```

that outputs the information perfectly:

Name: TAPABOCAS |  Old price = $ 295 | Discounted price = $ 236
Name: REMERA JR TOWN |  Old price = $ 990 | Discounted price = $ 743
Name: CAMISOLA NENA DELFI |  Old price = $ 2.300 | Discounted price = $ 1.725
Name: CAMISOLA JR TRAFUL |  Old price = $ 1.550 | Discounted price = $ 1.163
Name: VESTIDO NENA DELFI |  Old price = $ 2.990 | Discounted price = $ 2.243
Name: SAQUITO JR DESAGUJADO |  Old price = $ 1.990 | Discounted price = $ 1.493
Name: JEGGING JR ENGOMADO |  Old price = $ 1.990 | Discounted price = $ 1.493```
</div>
</div>
</p>

<p>but...sometimes the special_price loop won't find a discounted price..so i need to make a try/except, tried to "preprocess it"..but i do not know how make it work..</p>

```special_prices_with_defaults_added = []
for sp in soup.select('span[id^="product-price"]'):
    try:
        special_prices_with_defaults_added.append(sp.text.strip())
    except:
        special_prices_with_defaults_added.append("No default price available")

for name_product, old_price, special_price in zip(
    soup.select('h3.titprod'), soup.select('span[id^="old-price"]'), special_prices_with_defaults_added):
    print(f'Name: {name_product.text.strip()} |  Old price = {old_price.text.strip()} | Discounted price = {special_prices_with_defaults_added}')
```

<p>Wrongly output:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>Name: TAPABOCAS |  Old price = $ 295 | Discounted price = ['$\xa0236', '$\xa0743', '$\xa01.725', '$\xa01.163', '$\xa02.243', '$\xa01.493', '$\xa01.493', '$\xa02.925', '$\xa0668', '$\xa0713', '$\xa01.688', '$\xa01.268', '$\xa0593', '$\xa0743', '$\xa01.125', '$\xa03.300', '$\xa02.175', '$\xa0743', '$\xa01.493', '$\xa0863', '$\xa0668', '$\xa0792', '$\xa01.520', '$\xa01.760', '$\xa0696', '$\xa03.150', '$\xa03.520', '$\xa0712', '$\xa01.352', '$\xa01.112', '$\xa01.112', '$\xa01.192', '$\xa02.800', '$\xa02.720', '$\xa03.920', '$\xa01.920']
Name: REMERA JR TOWN |  Old price = $ 990 | Discounted price = ['$\xa0236', '$\xa0743', '$\xa01.725', '$\xa01.163', '$\xa02.243', '$\xa01.493', '$\xa01.493', '$\xa02.925', '$\xa0668', '$\xa0713', '$\xa01.688', '$\xa01.268', '$\xa0593', '$\xa0743', '$\xa01.125', '$\xa03.300', '$\xa02.175', '$\xa0743', '$\xa01.493', '$\xa0863', '$\xa0668', '$\xa0792', '$\xa01.520', '$\xa01.760', '$\xa0696', '$\xa03.150', '$\xa03.520', '$\xa0712', '$\xa01.352', '$\xa01.112', '$\xa01.112', '$\xa01.192', '$\xa02.800', '$\xa02.720', '$\xa03.920', '$\xa01.920']</code>```

答:
As @furas said... it was just a small fix on the for loop call.</p>

```<code>for name_product, old_price, special_price in zip(
        soup.select('h3.titprod'), soup.select('span[id^="old-price"]'), special_prices_with_defaults_added):
    print(
        f'Name: {name_product.text.strip()} |  Old price = {old_price.text.strip()} | Discounted price = {special_price}')
</code>```

Body:
Got the following code:

from bs4 import BeautifulSoup
import requests
import re

# Source Sites
mimo = 'https://tienda.mimo.com.ar/mimo/junior/ropa-para-ninas.html'
cheeky = ''
grisino = ''

source = requests.get(mimo).text

soup = BeautifulSoup(source, 'lxml')

for name_product, old_price, special_price in zip(soup.select('h3.titprod'),
                                                  soup.select('span[id^="old-price"]'),
                                                  soup.select('span[id^="product-price"]')):
    print(f'Name: {name_product.text.strip()} |  Old price = {old_price.text.strip()} | Discounted price = {special_price.text.strip()}')

that outputs the information perfectly:

Name: TAPABOCAS |  Old price = $ 295 | Discounted price = $ 236
Name: REMERA JR TOWN |  Old price = $ 990 | Discounted price = $ 743
Name: CAMISOLA NENA DELFI |  Old price = $ 2.300 | Discounted price = $ 1.725
Name: CAMISOLA JR TRAFUL |  Old price = $ 1.550 | Discounted price = $ 1.163
Name: VESTIDO NENA DELFI |  Old price = $ 2.990 | Discounted price = $ 2.243
Name: SAQUITO JR DESAGUJADO |  Old price = $ 1.990 | Discounted price = $ 1.493
Name: JEGGING JR ENGOMADO |  Old price = $ 1.990 | Discounted price = $ 1.493

but...sometimes the special_price loop won't find a discounted price..so i need to make a try/except, tried to "preprocess it"..but i do not know how make it work..

special_prices_with_defaults_added = []
for sp in soup.select('span[id^="product-price"]'):
    try:
        special_prices_with_defaults_added.append(sp.text.strip())
    except:
        special_prices_with_defaults_added.append("No default price available")

for name_product, old_price, special_price in zip(
    soup.select('h3.titprod'), soup.select('span[id^="old-price"]'), special_prices_with_defaults_added):
    print(f'Name: {name_product.text.strip()} |  Old price = {old_price.text.strip()} | Discounted price = {special_prices_with_defaults_added}')

Wrongly output:

Name: TAPABOCAS |  Old price = $ 295 | Discounted price = ['$\xa0236', '$\xa0743', '$\xa01.725', '$\xa01.163', '$\xa02.243', '$\xa01.493', '$\xa01.493', '$\xa02.925', '$\xa0668', '$\xa0713', '$\xa01.688', '$\xa01.268', '$\xa0593', '$\xa0743', '$\xa01.125', '$\xa03.300', '$\xa02.175', '$\xa0743', '$\xa01.493', '$\xa0863', '$\xa0668', '$\xa0792', '$\xa01.520', '$\xa01.760', '$\xa0696', '$\xa03.150', '$\xa03.520', '$\xa0712', '$\xa01.352', '$\xa01.112', '$\xa01.112', '$\xa01.192', '$\xa02.800', '$\xa02.720', '$\xa03.920', '$\xa01.920']
Name: REMERA JR TOWN |  Old price = $ 990 | Discounted price = ['$\xa0236', '$\xa0743', '$\xa01.725', '$\xa01.163', '$\xa02.243', '$\xa01.493', '$\xa01.493', '$\xa02.925', '$\xa0668', '$\xa0713', '$\xa01.688', '$\xa01.268', '$\xa0593', '$\xa0743', '$\xa01.125', '$\xa03.300', '$\xa02.175', '$\xa0743', '$\xa01.493', '$\xa0863', '$\xa0668', '$\xa0792', '$\xa01.520', '$\xa01.760', '$\xa0696', '$\xa03.150', '$\xa03.520', '$\xa0712', '$\xa01.352', '$\xa01.112', '$\xa01.112', '$\xa01.192', '$\xa02.800', '$\xa02.720', '$\xa03.920', '$\xa01.920']

Body:
As @furas said... it was just a small fix on the for loop call.

for name_product, old_price, special_price in zip(
        soup.select('h3.titprod'), soup.select('span[id^="old-price"]'), special_prices_with_defaults_added):
    print(
        f'Name: {name_product.text.strip()} |  Old price = {old_price.text.strip()} | Discounted price = {special_price}')


问:
repeated logging in log 4j in java
I used log4j in a java program. I initialized it with :

```<code>BasicConfigurator.configure(); // logger configuration
try {
     logger.setLevel(Level.DEBUG);
} catch (Exception e) {
     System.out.println("Logfile not found");
}
</code>```

But, during the execution of the program i get 3 log statements instead of one. For example,

```<code>3 lines
1047 [main] INFO ibis.Preproc.Ratings  - Added AS TIMEZONE to tZones[0] = GMT-12:00
1047 [main] INFO ibis.Preproc.Ratings  - Added AS TIMEZONE to tZones[0] = GMT-12:00
1047 [main] INFO ibis.Preproc.Ratings  - Added AS TIMEZONE to tZones[0] = GMT-12:00
</code>```

instead of one line

```<code>1047 [main] INFO ibis.Preproc.Ratings  - Added AS TIMEZONE to tZones[0] = GMT-12:00
</code>```

Are there any extra configurations to be done to log4j to avoid this?

答:
Most probably you have more than one Appenders. See the log4j manual (Section: Appenders and Layouts):

Each enabled logging request for a given logger will be forwarded to all the appenders in that logger as well as the appenders higher in the hierarchy.

You can try setting the additivity flag to false.

OwnerDisplayName: BHARATH

ContentLicense: CC BY-SA 2.5

Title: repeated logging in log 4j in java

Body:
I used log4j in a java program. I initialized it with :

BasicConfigurator.configure(); // logger configuration
try {
     logger.setLevel(Level.DEBUG);
} catch (Exception e) {
     System.out.println("Logfile not found");
}

But, during the execution of the program i get 3 log statements instead of one. For example,

3 lines
1047 [main] INFO ibis.Preproc.Ratings  - Added AS TIMEZONE to tZones[0] = GMT-12:00
1047 [main] INFO ibis.Preproc.Ratings  - Added AS TIMEZONE to tZones[0] = GMT-12:00
1047 [main] INFO ibis.Preproc.Ratings  - Added AS TIMEZONE to tZones[0] = GMT-12:00

instead of one line

1047 [main] INFO ibis.Preproc.Ratings  - Added AS TIMEZONE to tZones[0] = GMT-12:00

Are there any extra configurations to be done to log4j to avoid this?

LastEditorDisplayName: Jon Skeet


问:
What are these diagrams called? (answer : railroad diagrams)
I have seen a lot of these diagrams in some help files and src documentation

What are they called? Are there any other (for same purpose) known diagrams?

Img source : http://www.sqlite.org/images/syntax/insert-stmt.gif

答: They are called syntax diagrams.</p>

ContentLicense: CC BY-SA 3.0

Body: They are called syntax diagrams.


问:
How to get the oracle dataguard log transfer and applying status?
Logs are transferred from primary db instanes to stand-by db and applied continuously.

Please advise how to get the report in the following format in browser at some frequency(say 5sec/10sec) for monitoring purposes at stand-by db(prefer to any built-in function or class in oracle dataguard):

-----------------------------------------------------------------------------------

log_name   instance   created_time   tx_start    tx_end  tx_duration  tx_success   apply_start    apply_end   apply_duration apply_success

-----------------------------------------------------------------------------------

...

...

...

-----------------------------------------------------------------------------------

答: Have a look at the V$RECOVERY.... views (e.g. look here and the following views). They have lots of info on recovery processes and stats.</p>


问:
Who is charged for Github Actions minutes?
Are GitHub Action minutes deducted from the quota of the repo owner or the user who pushes the commit to github.com?

I'm working on a free software project that uses a Github Actions workflow to automate a continuous integration pipeline. The repo is tied to my account, but I'm debating whether or not I want to grant push access to it for another developer or if I should have them fork it.

Github grants a free 2,000 "minutes" per month per user (fine print redefines "2,000 minutes" to a total of "200 minutes" per month for MacOS, but whatever).

If another github user pushes commits to my repo that trigger Github Actions, are those minutes subtracted from my quota or that user's quota? And how does this work for repos in a github organization?

答:
This is the page where you can find all information about how Github actions are billed. https://help.github.com/en/github/setting-up-and-managing-billing-and-payments-on-github/about-billing-for-github-actions

GitHub charges usage to the account that owns the repository where the workflow is run

I hope that answers your question


问:
YOLOv3 Wrong Bounding Box Prediction
I trained YOLOv3 for 1 class. When I try to predict find my object in the picture it gives me wrong bounding box coordinates and shape.

I've trained yolov3-tiny version with 70 608x608 images. It was working perfect. Even I trained it with CPU and around 100 images it detects my object accurately.

yolov3-tiny cfg settings:
batch=64
subdivisions=2
width=416
height=416

I found 70 images more. However they are 640x480 images. I resized all images to 640x480 size. Then I trained yolov3-tiny and yolov3 on Google Colab with 170 images. Although the training results show 0.08 accuracy I get terrible detection results.

yolov3.cfg settings:

batch=1
subdivisions=1
width=640
height=480

I wonder that why results got worse. How can I have accurate detection?

答:
[Updated]

I recall YOLO handles resizing for you keeping aspect ratio. Have you tried running it without changing width and height in cfg?

You should be able to run the training without rescaling your input images. Try running that previous config that worked for you but use new images?

Just noticed you also changed batch size and subdivisions. The values you provided in the second config might be too low for mode to learn anything. Have you tried going back to previous settings? (batch=64, subdivisions=2)

Title: YOLOv3 Wrong Bounding Box Prediction


问:
How to handle online captchas in WebDriver
Like: 1+ 7 =

A website has a text box and this text box will accept the input of sum of two numbers. How we capture these two number like 1 and 7. And any number can be come at this location.

Please help me out.

答:
CAPTCHA - Completely Automated Public Turing Test to tell Computers and Humans Apart.
If you automate it you are killing the sole purpose of creating Captcha on your website.
Request your devs to disable it on your QA environment and continue with your tests or use predefined cookies (hardcoded CAPTCHA). </p>


问:
How can I match and filter a dataset using another one?
I really dont know how to ask about this so let me give an example.

I have a dataset which has over 50k+ entries including adresses. Like this

```<code>streets <- c("st1","st2","st3","st4","st10000","st50000")
</code>```

I need to match this street names to cities they are belonged to. When it sees "st1" it should add CityX. I didnt have a dataset so I've created one like this.

```<code>cities <- data.table(
  city1 <- c("st1","st2","st3"),
  city2 <- c("st4","st5","st6"),
  city3 <- c("st50","st10000","st50000")
  )

setnames(cities,"V1","NY")
setnames(cities,"V2","LA")
setnames(cities,"V3","DC")
</code>```

Now I want to match this datasets if cities include street names it should create a new column in "streets" and add city name to there. Should be seen like this:

```<code>streets2 <- data.table(streets <- c("st1","st2","st3","st4","st10000","st50000"),
c("NY","NY","NY", "LA","DC","DC"))
</code>```

I should mention that I cant use dpylr for this only data.table is allowed. I think I need to use for loop and lapply but idk how. Thank you.

答:
Here is an option:

```<code>teams <- c("barcelona","rmadrid","liverpool")
DT <- rbindlist(lapply(mget(teams), function(x) data.table(Player=trimws(strsplit(x,",")[[1L]]))),
    idcol="Team")

data.table(Player=strsplit(players, ",")[[1L]])[DT, on=.(Player), Team := Team][]
</code>```

output:

```<code>     Player      Team
 1:    Xavi barcelona
 2:   Puyol barcelona
 3: Iniesta barcelona
 4:   Messi barcelona
 5: Gerrard liverpool
 6:   Salah liverpool
 7:    Mane liverpool
 8: Ronaldo   rmadrid
 9:   Ramos   rmadrid
10:  Hazard   rmadrid
</code>```

Hasn't Xavi, Puyol and Gerrard retired? And Ronaldo is still at Real Madrid?

data:

```<code>players <- "Xavi,Puyol,Iniesta,Messi,Gerrard,Salah,Mane,Ronaldo,Ramos, Hazard"
barcelona <- "Xavi,Puyol,Iniesta,Messi"
rmadrid <- "Ronaldo,Ramos,Hazard"
liverpool <- "Gerrard,Salah,Mane"
</code>```

Body:
I really dont know how to ask about this so let me give an example.

I have a dataset which has over 50k+ entries including adresses. Like this

streets <- c("st1","st2","st3","st4","st10000","st50000")

I need to match this street names to cities they are belonged to. When it sees "st1" it should add CityX. I didnt have a dataset so I've created one like this.

cities <- data.table(
  city1 <- c("st1","st2","st3"),
  city2 <- c("st4","st5","st6"),
  city3 <- c("st50","st10000","st50000")
  )

setnames(cities,"V1","NY")
setnames(cities,"V2","LA")
setnames(cities,"V3","DC")

Now I want to match this datasets if cities include street names it should create a new column in "streets" and add city name to there. Should be seen like this:

streets2 <- data.table(streets <- c("st1","st2","st3","st4","st10000","st50000"),
c("NY","NY","NY", "LA","DC","DC"))

I should mention that I cant use dpylr for this only data.table is allowed. I think I need to use for loop and lapply but idk how. Thank you.

Body:
Here is an option:

teams <- c("barcelona","rmadrid","liverpool")
DT <- rbindlist(lapply(mget(teams), function(x) data.table(Player=trimws(strsplit(x,",")[[1L]]))),
    idcol="Team")

data.table(Player=strsplit(players, ",")[[1L]])[DT, on=.(Player), Team := Team][]

output:

     Player      Team
 1:    Xavi barcelona
 2:   Puyol barcelona
 3: Iniesta barcelona
 4:   Messi barcelona
 5: Gerrard liverpool
 6:   Salah liverpool
 7:    Mane liverpool
 8: Ronaldo   rmadrid
 9:   Ramos   rmadrid
10:  Hazard   rmadrid

Hasn't Xavi, Puyol and Gerrard retired? And Ronaldo is still at Real Madrid?

data:

players <- "Xavi,Puyol,Iniesta,Messi,Gerrard,Salah,Mane,Ronaldo,Ramos, Hazard"
barcelona <- "Xavi,Puyol,Iniesta,Messi"
rmadrid <- "Ronaldo,Ramos,Hazard"
liverpool <- "Gerrard,Salah,Mane"


答: They are called  "railroad diagrams", because of their resemblance to a railroad track. They were often used to describe the grammar of older languages, before more formal grammars became routinely used. The problem with them is you can't easily feed them into tools like parser generators, or grammar checkers, so they are not used so much these days.</p>

Title: What are these diagrams called? (answer : railroad diagrams)

Body:
I have seen a lot of these diagrams in some help files and src documentation

What are they called? Are there any other (for same purpose) known diagrams?

Img source : http://www.sqlite.org/images/syntax/insert-stmt.gif


问:
How do I make this embedded video 100% wide?
I have the code below with one row and two columns. In the first column I would like to display an embedded video from Vimeo. What I want is that the video would fill out its column without having any paddings. The two columns should have no space between them either.

.video iframe {
    width: 100%;
}
.lesson-pager {
    background-color: #00000081;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
                <div class="row video-row no-gutters">
                    <div class="col-lg-8">
                        <div class="video">
                            <iframe src="https://player.vimeo.com/video/42582007" width="640" height="360" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe>
                        </div>
                    </div>
                    <div class="col-lg-4 lesson-pager">
                        <div class="lesson-title">
                            <h4>Lesson title</h4>
                        </div>
                    </div>
                </div>
            </div></code>```

答:
You can use this css trick to make it covering full area

.lesson-pager {
    background-color: #00000081;
}
.video{
  position: relative;
    padding-top: 56.25%;
}
.video iframe{
  width: 100%;
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>

<div class="container">
  <div class="row video-row no-gutters">
      <div class="col-lg-8">
          <div class="video">
              <iframe src="https://player.vimeo.com/video/42582007" width="640" height="360" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe>
          </div>
      </div>
      <div class="col-lg-4 lesson-pager">
          <div class="lesson-title">
              <h4>Lesson title</h4>
          </div>
      </div>
  </div>
</div></code>```

Body:
I have the code below with one row and two columns. In the first column I would like to display an embedded video from Vimeo. What I want is that the video would fill out its column without having any paddings. The two columns should have no space between them either.

.video iframe {
    width: 100%;
}
.lesson-pager {
    background-color: #00000081;
}

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>

Lesson title

Body:
You can use this css trick to make it covering full area

.lesson-pager {
    background-color: #00000081;
}
.video{
  position: relative;
    padding-top: 56.25%;
}
.video iframe{
  width: 100%;
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
}

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>

<div class="container">
  <div class="row video-row no-gutters">
      <div class="col-lg-8">
          <div class="video">
              <iframe src="https://player.vimeo.com/video/42582007" width="640" height="360" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe>
          </div>
      </div>
      <div class="col-lg-4 lesson-pager">
          <div class="lesson-title">
              <h4>Lesson title</h4>
          </div>
      </div>
  </div>
</div>


问:
Testing suspending functions for exception with JUnit5 assertThrows and MockWebServer
How can we test a suspending function with MockWebServer that supposed to throw exception?

```<code>fun `Given Server down, should return 500 error`()= testCoroutineScope.runBlockingTest {

    // GIVEN
    mockWebServer.enqueue(MockResponse().setResponseCode(500))

    // WHEN
    val exception = assertThrows<RuntimeException> {
        testCoroutineScope.async {
            postApi.getPosts()
        }

    }

    // THEN
    Truth.assertThat(exception.message)
        .isEqualTo("com.jakewharton.retrofit2.adapter.rxjava2.HttpException: HTTP 500 Server Error")
}
</code>```

Calling  postApi.getPosts() directly inside assertThrows is not possible since it's not a suspending function, i tried using async, launch and

```<code> val exception = testCoroutineScope.async {
            assertThrows<RuntimeException> {
                launch {
                    postApi.getPosts()
                }
            }
        }.await()
</code>```

but test fails with org.opentest4j.AssertionFailedError: Expected java.lang.RuntimeException to be thrown, but nothing was thrown. for each variation.

答:
You could just remove the assertThrows, using something like this: </p>

```<code>fun `Given Server down, should return 500 error`()= testCoroutineScope.runBlockingTest {

    // GIVEN
    mockWebServer.enqueue(MockResponse().setResponseCode(500))

    // WHEN
    val exception = try {
        postApi.getPosts()
        null
    } catch (exception: RuntimeException){
        exception
    }

    // THEN
    Truth.assertThat(exception?.message)
        .isEqualTo("com.jakewharton.retrofit2.adapter.rxjava2.HttpException: HTTP 500 Server Error")
}
</code>```

Body:
How can we test a suspending function with MockWebServer that supposed to throw exception?

fun `Given Server down, should return 500 error`()= testCoroutineScope.runBlockingTest {

    // GIVEN
    mockWebServer.enqueue(MockResponse().setResponseCode(500))

    // WHEN
    val exception = assertThrows<RuntimeException> {
        testCoroutineScope.async {
            postApi.getPosts()
        }

    }

    // THEN
    Truth.assertThat(exception.message)
        .isEqualTo("com.jakewharton.retrofit2.adapter.rxjava2.HttpException: HTTP 500 Server Error")
}

Calling  postApi.getPosts() directly inside assertThrows is not possible since it's not a suspending function, i tried using async, launch and

 val exception = testCoroutineScope.async {
            assertThrows<RuntimeException> {
                launch {
                    postApi.getPosts()
                }
            }
        }.await()

but test fails with org.opentest4j.AssertionFailedError: Expected java.lang.RuntimeException to be thrown, but nothing was thrown. for each variation.

Body:
You could just remove the assertThrows, using something like this:

fun `Given Server down, should return 500 error`()= testCoroutineScope.runBlockingTest {

    // GIVEN
    mockWebServer.enqueue(MockResponse().setResponseCode(500))

    // WHEN
    val exception = try {
        postApi.getPosts()
        null
    } catch (exception: RuntimeException){
        exception
    }

    // THEN
    Truth.assertThat(exception?.message)
        .isEqualTo("com.jakewharton.retrofit2.adapter.rxjava2.HttpException: HTTP 500 Server Error")
}


问:
Cannot archive blog post in Wordpress
I am new to wordpress v5, as I see there is no archive menu for current version. How to make archieve post without delete them? Thanks

答:
Full docs can be found here https://wordpress.org/support/article/post-status/

To remove a post from the frontend, choose Draft from the Status dropdown. It will hide on frontend but still be saved in backend.

If you want to make it a private post so that no one but you can see it on the frontend, choose visibility and select Private.

Title: Cannot archive blog post in Wordpress


问:
How to know if the user is on mobile in css?
How to know if the user is on mobile in CSS?
I am making a mobile detector, but I don't know how to know the user on mobile. can you help me?</p>

答:
If I understand this correctly, you need to make that p tag disappear on mobiles and that is fairly simple.
Simply add another media query above the previous one but with a max-width of 767px like so:

```<code>    @media only screen and (max-width: 767px) {
        p {
            display: none;
        }
    }
    @media only screen and (min-width: 768px) {
        p {
            display:block;
        }
    }
</code>```

Now, the p tag will be invisible in mobile view but visible on screens above 767px.

Body:
If I understand this correctly, you need to make that p tag disappear on mobiles and that is fairly simple.
Simply add another media query above the previous one but with a max-width of 767px like so:

    @media only screen and (max-width: 767px) {
        p {
            display: none;
        }
    }
    @media only screen and (min-width: 768px) {
        p {
            display:block;
        }
    }

Now, the p tag will be invisible in mobile view but visible on screens above 767px.


问:
R loop for creating data frame
I have a list of samples in the object my.ID:

```<code>head(my.ID)
</code>```

returns:

```<code>[1] PATL1 PATL2 PATL9 PCAN1 PCAN2 PCAN3
117 Levels: PATL1 PATL2 PATL9...
</code>```

For each sample, I have a file, called like that:

Pi_Win5kb_JudDP_2020.04.29.vcf_PATL1.windowed.pi

With the name of the sample in the middle (here PATL1)

I want to create a data frame for each sample where first column is the name of the  sample (PATL1 for instance, which is listed in my.ID), and the second column is the column called PI from its associated data frame (in my example: Pi_Win5kb_JudDP_2020.04.29.vcf_PATL1.windowed.pi$PI.

I tried multiple loops, changes a few stuff but never worked.
I think that it's because I don't manage to properly define the value in the data.frame command.

Can someone show me how to change the loop so that it works?

```<code>for (i in 1:(length(my.ID))){
  my.value <- noquote(paste0("Pi_Win5kb_JudDP_2020.04.29.vcf_",my.ID[i],".windowed.pi$PI"))
  cur.file <- data.frame(group=my.ID[i], value=as.name(my.value))
  my.name <- my.ID[i]
  assign(paste(my.name), cur.file)
}
</code>```

答:
I may misunderstand your question but is it as simple as this?

```<code>library(dplyr)
library(tibble)

cur.file <- tibble(
  group = as.factor(c("PATL1", "PATL2", "PATL9", "PCAN1", "PCAN2", "PCAN3"))
)
</code>```

dplyr

```<code>cur.file <- cur.file %>%
  mutate(value = paste0("Pi_Win5kb_JudDP_2020.04.29.vcf_", group,".windowed.pi$PI"))
</code>```

baseR

```<code>cur.file$value <- paste0("Pi_Win5kb_JudDP_2020.04.29.vcf_", cur.file$group, ".windowed.pi$PI")
</code>```

With this result:

```<code>> cur.file
# A tibble: 6 x 2
  group value
  <fct> <chr>
1 PATL1 Pi_Win5kb_JudDP_2020.04.29.vcf_PATL1.windowed.pi$PI
2 PATL2 Pi_Win5kb_JudDP_2020.04.29.vcf_PATL2.windowed.pi$PI
3 PATL9 Pi_Win5kb_JudDP_2020.04.29.vcf_PATL9.windowed.pi$PI
4 PCAN1 Pi_Win5kb_JudDP_2020.04.29.vcf_PCAN1.windowed.pi$PI
5 PCAN2 Pi_Win5kb_JudDP_2020.04.29.vcf_PCAN2.windowed.pi$PI
6 PCAN3 Pi_Win5kb_JudDP_2020.04.29.vcf_PCAN3.windowed.pi$PI
</code>```

Title: R loop for creating data frame

Body:
I have a list of samples in the object my.ID:

head(my.ID)

returns:

[1] PATL1 PATL2 PATL9 PCAN1 PCAN2 PCAN3
117 Levels: PATL1 PATL2 PATL9...

For each sample, I have a file, called like that:

Pi_Win5kb_JudDP_2020.04.29.vcf_PATL1.windowed.pi

With the name of the sample in the middle (here PATL1)

I want to create a data frame for each sample where first column is the name of the  sample (PATL1 for instance, which is listed in my.ID), and the second column is the column called PI from its associated data frame (in my example: Pi_Win5kb_JudDP_2020.04.29.vcf_PATL1.windowed.pi$PI.

I tried multiple loops, changes a few stuff but never worked.
I think that it's because I don't manage to properly define the value in the data.frame command.

Can someone show me how to change the loop so that it works?

for (i in 1:(length(my.ID))){
  my.value <- noquote(paste0("Pi_Win5kb_JudDP_2020.04.29.vcf_",my.ID[i],".windowed.pi$PI"))
  cur.file <- data.frame(group=my.ID[i], value=as.name(my.value))
  my.name <- my.ID[i]
  assign(paste(my.name), cur.file)
}

Body:
I may misunderstand your question but is it as simple as this?

library(dplyr)
library(tibble)

cur.file <- tibble(
  group = as.factor(c("PATL1", "PATL2", "PATL9", "PCAN1", "PCAN2", "PCAN3"))
)

dplyr

cur.file <- cur.file %>%
  mutate(value = paste0("Pi_Win5kb_JudDP_2020.04.29.vcf_", group,".windowed.pi$PI"))

baseR

cur.file$value <- paste0("Pi_Win5kb_JudDP_2020.04.29.vcf_", cur.file$group, ".windowed.pi$PI")

With this result:

> cur.file
# A tibble: 6 x 2
  group value
  <fct> <chr>
1 PATL1 Pi_Win5kb_JudDP_2020.04.29.vcf_PATL1.windowed.pi$PI
2 PATL2 Pi_Win5kb_JudDP_2020.04.29.vcf_PATL2.windowed.pi$PI
3 PATL9 Pi_Win5kb_JudDP_2020.04.29.vcf_PATL9.windowed.pi$PI
4 PCAN1 Pi_Win5kb_JudDP_2020.04.29.vcf_PCAN1.windowed.pi$PI
5 PCAN2 Pi_Win5kb_JudDP_2020.04.29.vcf_PCAN2.windowed.pi$PI
6 PCAN3 Pi_Win5kb_JudDP_2020.04.29.vcf_PCAN3.windowed.pi$PI


问:
Power Query: how can I make power query tolerate columns with the same name?
I have a table with several column having the same name.
This columns is updated and provided regularly to power bi.

The columns has several columns with the same name such as "Result", "Result" and do so on...

However, Power BI adds each time in an automated way a number after my columns.

When I try to "force" power bi not to have a number, I get the following message
"The name "Result" is already used for a column..."

How could I change this?

The only way would be for the people using my file to extract the data and correct the name manually in excel...which is not great

答:
You cannot edit this behavior, PowerBI needs an unique identifier to reference the data, therefore the column name must be unique within a table (the complete identifier is given by table + column), otherwise the tool won't be able to reference the data.

This rule usually applies to any tool that manages data and sometimes to the data themselves (that's up to the format though). How can the tool get data from "Result" if more than one column has this identifier? which is the right one? The tool does not know and based on the context can give you an error or will fix this issue itself by making the names unique.

Note that also excel will append numbers to the columns (with the same name names) if you put the data in a proper table (insert-> table), in fact, an excel sheet can be considered unstructured free data, meanwhile, an excel table will enforce the data structure.
Most tools (like PowerBI) will also enforce data types.


问:
How to convert "Index" to type "Int" in Swift?
I want to convert the index of a letter contained within a string to an integer value. Attempted to read the header files but I cannot find the type for Index, although it appears to conform to protocol ForwardIndexType with methods (e.g. distanceTo).

```<code>var letters = "abcdefg"
let index = letters.characters.indexOf("c")!

// ERROR: Cannot invoke initializer for type 'Int' with an argument list of type '(String.CharacterView.Index)'
let intValue = Int(index)  // I want the integer value of the index (e.g. 2)
</code>```

Any help is appreciated.

答:
encodedOffset has deprecated from Swift 4.2.

Deprecation message:
encodedOffset has been deprecated as most common usage is incorrect. Use utf16Offset(in:) to achieve the same behavior.

So we can use utf16Offset(in:) like this:

```<code>var str = "abcdefgc"
let index = str.index(of: "c")?.utf16Offset(in: str) // Result: 2
</code>```

Body:
I want to convert the index of a letter contained within a string to an integer value. Attempted to read the header files but I cannot find the type for Index, although it appears to conform to protocol ForwardIndexType with methods (e.g. distanceTo).

var letters = "abcdefg"
let index = letters.characters.indexOf("c")!

// ERROR: Cannot invoke initializer for type 'Int' with an argument list of type '(String.CharacterView.Index)'
let intValue = Int(index)  // I want the integer value of the index (e.g. 2)

Any help is appreciated.

Body:
encodedOffset has deprecated from Swift 4.2.

Deprecation message:
encodedOffset has been deprecated as most common usage is incorrect. Use utf16Offset(in:) to achieve the same behavior.

So we can use utf16Offset(in:) like this:

var str = "abcdefgc"
let index = str.index(of: "c")?.utf16Offset(in: str) // Result: 2


问:
Jquery Each Problem
So the server is giving me a block of html within a hidden input. I need to take this block (which contains multiple divs) and move those divs, but with some logic.

My approach is to take the value of the hidden input (html block) and append it into a newly created hidden div:

```<code>  var history = $("input[name=history]").val();
  $("#global_wrapper").after("<div id='history_temp' style='display:none;'></div>");
  $("#history_temp").html(history);
</code>```

Here is an example of what the HTML block looks like:

```<code><div class="off 1"></div>
<div class="off 1"></div>
<div class="off 2"></div>
<div class="off 3"></div>
</code>```

The .off will always be there and the number class will range from 1-9

Based on the number class, I need to move each of these divs into an existing html block that looks like this:

```<code><div class="on 1"></div>
<div class="on 2"></div>
<div class="on 3"></div>
</code>```

The logic is that each .off div needs to be appended after the .on div with the same number class so that the end result would look like this:

```<code><div class="on 1"></div>
<div class="off 1"></div>
<div class="off 1"></div>
<div class="on 2"></div>
<div class="off 2"></div>
<div class="on 3"></div>
<div class="off 3"></div>
</code>```

My attempt was to run an each function for each .off div and then set up an if this.hasClass for each number div, but it was duplicating the .off divs and there were like 12 .off divs when there should have been just 3. Here is my code:

```<code>   $("#history_temp .off").each(function(){
    if ($(this).hasClass("1")) {
      $(this).clone().insertAfter(".on.1");
    }
    else if ($(this).hasClass("2")) {
      $(this).clone().insertAfter(".on.2");
    }
    else if ($(this).hasClass("3")) {
      $(this).clone().insertAfter(".on.3");
    }
    else if ($(this).hasClass("4")) {
      $(this).clone().insertAfter(".on.4");
    }
    else if ($(this).hasClass("5")) {
      $(this).clone().insertAfter(".on.5");
    }
    else if ($(this).hasClass("6")) {
      $(this).clone().insertAfter(".on.6");
    }
    else if ($(this).hasClass("7")) {
      $(this).clone().insertAfter(".on.7");
    }
    else if ($(this).hasClass("8")) {
      $(this).clone().insertAfter(".on.8");
    }
    else if ($(this).hasClass("9")) {
      $(this).clone().insertAfter(".on.9");
    }
    else {
      return false;
    }
  });
</code>```

Could anyone point me in the right direction? I'm curious as to what the most efficient solution would be.

Thanks,
Brian

EDIT: Fixed an error in my example code (was missing the "." before each on class)

答:
FWIW, your code works fine: http://jsfiddle.net/7XWuN/2/

I assume there is something else going on in the code you did not post.

Without any more context, I would suggest something like this:

```<code>$("#history_temp .off").each(function(){
    var n = this.className.match(/\d+/)[0];
    $(this).insertAfter('.on.' + n);
});
</code>```

DEMO

This works under the assumption that the elements have only one class that contains a number. It could also be that using numbers as classes does not play well with the selector, as classes are not allowed to start with a number afaik. If it does not work, prepend some other character.

Title: Jquery Each Problem

Body:
So the server is giving me a block of html within a hidden input. I need to take this block (which contains multiple divs) and move those divs, but with some logic.

My approach is to take the value of the hidden input (html block) and append it into a newly created hidden div:

  var history = $("input[name=history]").val();
  $("#global_wrapper").after("

");
  $("#history_temp").html(history);

Here is an example of what the HTML block looks like:

The .off will always be there and the number class will range from 1-9

Based on the number class, I need to move each of these divs into an existing html block that looks like this:

The logic is that each .off div needs to be appended after the .on div with the same number class so that the end result would look like this:

My attempt was to run an each function for each .off div and then set up an if this.hasClass for each number div, but it was duplicating the .off divs and there were like 12 .off divs when there should have been just 3. Here is my code:

   $("#history_temp .off").each(function(){
    if ($(this).hasClass("1")) {
      $(this).clone().insertAfter(".on.1");
    }
    else if ($(this).hasClass("2")) {
      $(this).clone().insertAfter(".on.2");
    }
    else if ($(this).hasClass("3")) {
      $(this).clone().insertAfter(".on.3");
    }
    else if ($(this).hasClass("4")) {
      $(this).clone().insertAfter(".on.4");
    }
    else if ($(this).hasClass("5")) {
      $(this).clone().insertAfter(".on.5");
    }
    else if ($(this).hasClass("6")) {
      $(this).clone().insertAfter(".on.6");
    }
    else if ($(this).hasClass("7")) {
      $(this).clone().insertAfter(".on.7");
    }
    else if ($(this).hasClass("8")) {
      $(this).clone().insertAfter(".on.8");
    }
    else if ($(this).hasClass("9")) {
      $(this).clone().insertAfter(".on.9");
    }
    else {
      return false;
    }
  });

Could anyone point me in the right direction? I'm curious as to what the most efficient solution would be.

Thanks,
Brian

EDIT: Fixed an error in my example code (was missing the "." before each on class)

Body:
FWIW, your code works fine: http://jsfiddle.net/7XWuN/2/

I assume there is something else going on in the code you did not post.

Without any more context, I would suggest something like this:

$("#history_temp .off").each(function(){
    var n = this.className.match(/\d+/)[0];
    $(this).insertAfter('.on.' + n);
});

DEMO

This works under the assumption that the elements have only one class that contains a number. It could also be that using numbers as classes does not play well with the selector, as classes are not allowed to start with a number afaik. If it does not work, prepend some other character.


问:
Do i keep the child theme or move/use parent theme only?
Not sure its the right place to ask this question,

I have a website that we use mainly for marketing our services, online service bookings and selling bit of products. the site hasn’t been updated since 2017, both the Avada parent and child theme need an update to version 6.2, remove products/WooCommerce and replace the booking system to a new app.

I would like to start managed/update/customise my site but I have no knowledge in coding such as CSS, functions...Etc however I prefer at this point to start with Avada fusion builder as I can easily learn quickly and get results to get my website up and running and then learn coding as I go.

I have installed wordpress on my local ubuntu server using 5.4.1 wordpress/php7.4/apache docker image and MariaDB database Image. i have imported the live site database, content and updates all the plugins and fixed all the small issues.

the site is now up and running on my local server however few things are broken due to the customisation, theme and wordpress version updates. i’m just trying to have a plan what is the best way for me and how to do it.

Before I start update the website, I would like plan how to structure it so it will be easier for me to manage the site in the future. I did some research and it seems that now days for most customisation, you don’t need a child theme as it can do most of CSS customisation and functions by using the WordPress/Avada parent theme and plugin. as explain above the website will have standard pages for the services with style customisation and an online booking system.

The Avada Theme/fusion builder and wordpress has a section to do the custom CSS locally on the page and globally. for the functions codes you can use snippets or similar plugin. if i understand, the customisation are store in the database when you move to a new version of wordpress/theme as well as the plugin store in the content files, meaning when you do your backup you don’t loose it.

if all the customisation are backed up and i don’t need the child theme any more is there a way to copy or use migration plugin to move the customisation from the child theme back to the parent theme? it looks like child theme is not necessary for most websites at it use to be.

My questions are:

Per above scope, future update/upgrades and easy management do I need a child theme or better use parent theme/plugin to do the customisation?

How do I move the child theme configuration back to latest version parent theme?

If keeping the child theme structure, how do I update/migrate/move the old child theme to the new version child theme?

Can i use the old child theme with the new parent theme? or its better/recommended to use the new child theme version.

please check this video, that explain the above, about not using child theme https://youtu.be/30JdAarTAFU

Thank you for your help in advance.

答:
glad to see you actually make an effort to understand this. I will try to answer your questions best I can. I have been working with Avada for last 3 years.

Per above scope, future update/upgrades and easy management do I need
  a child theme or better use parent theme/plugin to do the
  customisation?

I will always have a child theme. The reason for this is very simple - every site needs to be customised in some way. Yes, page builders help but don't have every option for everything. I use Elementor these days and I believe this is the best builder on the market today, yet I still find myself writing small bits of code to change things that are not supplied with it.

Since you are looking to update your site. You should not remove the child theme because there might be some functions or templates that are used.

How do I move the child theme configuration back to latest version
  parent theme?

If there were any custom css you will need to copy it and paste it into the theme 'Custom CSS' option page in the backend of your website.
Any template or functions.php file will need to be moved back to parent theme. However, if you have these files and you moved it back to parent you will overwrite these with any updates to the theme.
I really don't recommend removing child-theme.

If keeping the child theme structure, how do I update/migrate/move the
  old child theme to the new version child theme?

You need to update the parent and not the child theme. The whole idea is to never update child theme so none of your files will be overwritten. Also, the core child theme will consist (in most cases) of functions.php and style.css - and both are empty. So if you update the child theme you will be basically removing whats there already.

Can i use the old child theme with the new parent theme? or its
  better/recommended to use the new child theme version.

Yes, this is the main reason for having child themes.

Updating Avada

I will assume the version of Avada is 4.0.3 and the newest one is 6.*. The process is very easy:
1. Update WordPress (5.4.1 is the newest today).
2. Download new files from the theme website.
3. Upload the files to parent theme.
4. Login to your admin account on your website. There you should see the installation.
5. Once completed, check all the pages (especially where the builder is present) for any errors.

There might need to make some small changes to the header.php and footer.php

Let me know how it went.


答:
Since you are using bootstrap-4, you may use the embed utility to make it 100% wide.

.video iframe {
  width: 100%;
}

.lesson-pager {
  background-color: #00000081;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
  <div class="row video-row no-gutters">
    <div class="col-lg-8">
      <div class="video embed-responsive embed-responsive-16by9">
        <iframe class="embed-responsive-item" src="https://player.vimeo.com/video/42582007" width="640" height="360" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe>
      </div>
    </div>
    <div class="col-lg-4 lesson-pager">
      <div class="lesson-title">
        <h4>Lesson title</h4>
      </div>
    </div>
  </div>
</div></code>```

Title: How do I make this embedded video 100% wide?

Body:
Since you are using bootstrap-4, you may use the embed utility to make it 100% wide.

.video iframe {
  width: 100%;
}

.lesson-pager {
  background-color: #00000081;
}

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
  <div class="row video-row no-gutters">
    <div class="col-lg-8">
      <div class="video embed-responsive embed-responsive-16by9">
        <iframe class="embed-responsive-item" src="https://player.vimeo.com/video/42582007" width="640" height="360" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe>
      </div>
    </div>
    <div class="col-lg-4 lesson-pager">
      <div class="lesson-title">
        <h4>Lesson title</h4>
      </div>
    </div>
  </div>
</div>


问:
Jhipster - Creating a relationship between JHI_User and another Entity ERROR
I generated a Jhipster configured hereafter (Spring boot / React ).

In order to add some additional information to User Registration, I tried to follow this Tip published on Jhipster website : https://www.jhipster.tech/tips/022_tip_registering_user_with_additional_information.html

I already have an entity called "Client" that I want to use it as extra for User registration.

I started by creating a Relationship between Client and JHI_User, and here i'm stuck.

The command to edit an entity : Jhipster entity client

then, this was my entries to the inquiries

But, this error about JHI_User reducer i couldn't figure out :

Any idea ? Someone succeeded such thing ?

Thank You

答:
Try using User instead of JHI_User. For example, if you were to use JDL instead of the console to generate your entities you would do something like this:

relationship OneToOne {
    Client{registerUser} to User{clientUser}
}
```


问:
Update/set state dynamically in reactjs
I am new to reactjs and used to load/update data through javascript/jquery.

In my example I've got 3 buttons. Whenever I click one one button, I would like to update the text above. Right now, I am using same state for the counter. Can't you somehow get the current divs ID - and update the state inside it?

I could just change the state to 3 different states.
But the reason why I am not doing this is if I ever want to load something dynamically they probably have the same state?

jsfiddle:
https://jsfiddle.net/t9am76fs/1/

```<code>constructor(props) {
    super(props);

    this.state = {
        count: 0,
    };
}
incrementCounter = (value) => {
    this.setState({ count: this.state.count + value })
};

render() {
    return (
        <div>
            <div id='div1'>
                  <p>You clicked {this.state.count} times</p>
                  <button onClick={() => this.incrementCounter(1)}>+1</button>
            </div>

            <div id='div2'>
                  <p>You clicked {this.state.count} times</p>
                  <button onClick={() => this.incrementCounter(1)}>+1</button>
            </div>

            <div id='div3'>
                  <p>You clicked {this.state.count} times</p>
                  <button onClick={() => this.incrementCounter(1)}>+1</button>
            </div>
        </div>
    );
}
</code>```

Thanks

答:
It looks like you want to render dynamic elements, like you would do if you gather data from an API from example.

What I would do is to group the data you need dynamically into an array of objects, and you can keep the counter for each of those objects inside the object itself.

In the example below. You map the array and each onClick will update its own object counter. This way you don't need to explicitly write the state for every single element.

This is just a sample and you can improve it later:

```<code>const dynamicDivsInfo = [
  { name: "Example", id: "div1", count: 0 },
  { name: "Example 2", id: "div2", count: 0 }
];

class Example extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      divs: [...dynamicDivsInfo]
    };
  }
  incrementCounter = (value, index) => {
    const divs = [...this.state.divs];
    divs[index].count += value;
    this.setState({ divs });
  };

  render() {
    return (
      <div>
        {this.state.divs.map((element, index) => {
          return (
            <div id={element.id}>
              <p>
                You clicked {element.name}: {element.count} times
              </p>
              <button onClick={() => this.incrementCounter(1, index)}>
                +1
              </button>
            </div>
          );
        })}
      </div>
    );
  }
}
</code>```

Here is a code sandbox example: https://codesandbox.io/s/goofy-night-1hfoc?file=/src/App.js:244-1086

Title: Update/set state dynamically in reactjs

Body:
I am new to reactjs and used to load/update data through javascript/jquery.

In my example I've got 3 buttons. Whenever I click one one button, I would like to update the text above. Right now, I am using same state for the counter. Can't you somehow get the current divs ID - and update the state inside it?

I could just change the state to 3 different states.
But the reason why I am not doing this is if I ever want to load something dynamically they probably have the same state?

jsfiddle:
https://jsfiddle.net/t9am76fs/1/

constructor(props) {
    super(props);

    this.state = {
        count: 0,
    };
}
incrementCounter = (value) => {
    this.setState({ count: this.state.count + value })
};

render() {
    return (

You clicked {this.state.count} times

                  <button onClick={() => this.incrementCounter(1)}>+1</button>

You clicked {this.state.count} times

                  <button onClick={() => this.incrementCounter(1)}>+1</button>

You clicked {this.state.count} times

                  <button onClick={() => this.incrementCounter(1)}>+1</button>

    );
}

Thanks

Body:
It looks like you want to render dynamic elements, like you would do if you gather data from an API from example.

What I would do is to group the data you need dynamically into an array of objects, and you can keep the counter for each of those objects inside the object itself.

In the example below. You map the array and each onClick will update its own object counter. This way you don't need to explicitly write the state for every single element.

This is just a sample and you can improve it later:

const dynamicDivsInfo = [
  { name: "Example", id: "div1", count: 0 },
  { name: "Example 2", id: "div2", count: 0 }
];

class Example extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      divs: [...dynamicDivsInfo]
    };
  }
  incrementCounter = (value, index) => {
    const divs = [...this.state.divs];
    divs[index].count += value;
    this.setState({ divs });
  };

  render() {
    return (
      <div>
        {this.state.divs.map((element, index) => {
          return (
            <div id={element.id}>
              <p>
                You clicked {element.name}: {element.count} times
              </p>
              <button onClick={() => this.incrementCounter(1, index)}>
                +1
              </button>
            </div>
          );
        })}
      </div>
    );
  }
}

Here is a code sandbox example: https://codesandbox.io/s/goofy-night-1hfoc?file=/src/App.js:244-1086


问:
How to convert this for loop C# code to Linq or make the process time faster?
Convert this for loop C# code to Linq or make the process time faster

```<code>List<List<Array_Group>> array_Group = new List<List<Array_Group>>();
array_Group.Add(new List<Array_Group>());
object previosSelecter = null;

for (int i = 0; i < array_count; i++)
{
    Type Group = typeof(Array_Group);
    var current = after_Rounded.ElementAt(i);

    Type type = current.GetType();

    PropertyInfo prop = Group.GetProperty("FD_T_Act_");

    object currentSelector = prop.GetValue(current);
    if (previosSelecter == null)
    {
        array_Group.LastOrDefault().Add(current);
    }
    else
        if (currentSelector.Equals(previosSelecter))
        {
            array_Group.LastOrDefault().Add(current);
        }
        else
        {
            array_Group.Add(new List<Array_Group>() { current });
        }
    previosSelecter = currentSelector;
}
</code>```

The execution time takes very long time due to the huge data that needs to be processed.
How can I make it more simpler and faster execution?

答:
These two lines

```<code>Type Group = typeof(Array_Group);

PropertyInfo prop = Group.GetProperty("FD_T_Act_");
</code>```

You can definitly move before your loop. This is a constant expression, will result in always the same value, but it's a very expensive time consuming expression also.

Accessing a property via 'GetProperty' is also quiet time consuming.

You can create a delegate to improve this (also before your loop)

```<code> Func<Array_Group, propType> getter = (Func<Array_Group, propType>)
        Delegate.CreateDelegate(typeof(Func<Array_Group, propType>), null,
            prop.GetGetMethod());
</code>```

It's also typesafe, it returns your real datatype, not just an object, in case of it is a value type, you avoid the boxing with such a delegate.

So instead of

```<code> object currentSelector = prop.GetValue(current);
</code>```

You do

```<code> propType currentSelector = getter(current);
</code>```

Body:
Convert this for loop C# code to Linq or make the process time faster

List<List<Array_Group>> array_Group = new List<List<Array_Group>>();
array_Group.Add(new List<Array_Group>());
object previosSelecter = null;

for (int i = 0; i < array_count; i++)
{
    Type Group = typeof(Array_Group);
    var current = after_Rounded.ElementAt(i);

    Type type = current.GetType();

    PropertyInfo prop = Group.GetProperty("FD_T_Act_");

    object currentSelector = prop.GetValue(current);
    if (previosSelecter == null)
    {
        array_Group.LastOrDefault().Add(current);
    }
    else
        if (currentSelector.Equals(previosSelecter))
        {
            array_Group.LastOrDefault().Add(current);
        }
        else
        {
            array_Group.Add(new List<Array_Group>() { current });
        }
    previosSelecter = currentSelector;
}

The execution time takes very long time due to the huge data that needs to be processed.
How can I make it more simpler and faster execution?

Body:
These two lines

Type Group = typeof(Array_Group);

PropertyInfo prop = Group.GetProperty("FD_T_Act_");

You can definitly move before your loop. This is a constant expression, will result in always the same value, but it's a very expensive time consuming expression also.

Accessing a property via 'GetProperty' is also quiet time consuming.

You can create a delegate to improve this (also before your loop)

 Func<Array_Group, propType> getter = (Func<Array_Group, propType>)
        Delegate.CreateDelegate(typeof(Func<Array_Group, propType>), null,
            prop.GetGetMethod());

It's also typesafe, it returns your real datatype, not just an object, in case of it is a value type, you avoid the boxing with such a delegate.

So instead of

 object currentSelector = prop.GetValue(current);

You do

 propType currentSelector = getter(current);


问:
machine learning problem:i made a new column in test data but instead of median value it is filled with NaN
Here i am trying to predict the sales price by taking median of price with respect to area and mzzone
here are the values:

```<code>combo=pd.pivot_table(train,values=['SALES_PRICE'],index=['MZZONE','AREA'],aggfunc='median')
combo
</code>```

output:

```<code>                        SALES_PRICE
 MZZONE  AREA
    A   Adyar           7144042.5
        Karapakkam      5468500.0
        Velachery       8428745.0
    C   Adyar           7877645.0
        Karapakkam      6443000.0
        Velachery       9170660.0
    I   Adyar           8785350.0
</code>```

but when i try to put it in test data by making a new column, it is filling NaN in full column
here is the code i used to put the median values in test data:

```<code>test['super_mean']=0
s2 = 'MZZONE'
s1 = 'AREA'
for i in test[s1].unique():
  for j in test[s2].unique():
    test['super_mean'][ (test[s1]==str(i)) & (test[s2]==str(j)) ] = train['SALES_PRICE'][ (train[s1]==str(i)) & (train[s2]==str(i)) ].median()
</code>```

why this is happening so??

答:
You have a mistake in the code within the 'j' for loop. You have an 'i' where should be a 'j'. This is the correct for loop:</p>

```<code>test['super_mean']=0
s2 = 'MZZONE'
s1 = 'AREA'
for i in test[s1].unique():
  for j in test[s2].unique():
    test['super_mean'][ (test[s1]==str(i)) & (test[s2]==str(j)) ] = train['SALES_PRICE'][ (train[s1]==str(i)) & (train[s2]==str(j)) ].median()
</code>```

Body:
Here i am trying to predict the sales price by taking median of price with respect to area and mzzone
here are the values:

combo=pd.pivot_table(train,values=['SALES_PRICE'],index=['MZZONE','AREA'],aggfunc='median')
combo

output:

                        SALES_PRICE
 MZZONE  AREA
    A   Adyar           7144042.5
        Karapakkam      5468500.0
        Velachery       8428745.0
    C   Adyar           7877645.0
        Karapakkam      6443000.0
        Velachery       9170660.0
    I   Adyar           8785350.0

but when i try to put it in test data by making a new column, it is filling NaN in full column
here is the code i used to put the median values in test data:

test['super_mean']=0
s2 = 'MZZONE'
s1 = 'AREA'
for i in test[s1].unique():
  for j in test[s2].unique():
    test['super_mean'][ (test[s1]==str(i)) & (test[s2]==str(j)) ] = train['SALES_PRICE'][ (train[s1]==str(i)) & (train[s2]==str(i)) ].median()

why this is happening so??

Body:
You have a mistake in the code within the 'j' for loop. You have an 'i' where should be a 'j'. This is the correct for loop:

test['super_mean']=0
s2 = 'MZZONE'
s1 = 'AREA'
for i in test[s1].unique():
  for j in test[s2].unique():
    test['super_mean'][ (test[s1]==str(i)) & (test[s2]==str(j)) ] = train['SALES_PRICE'][ (train[s1]==str(i)) & (train[s2]==str(j)) ].median()


问:
Are arrays being transformed when using an enhanced for loop?
Does Java 5 or higher apply some of form of "boxing" to arrays? This question came to mind as the following code goes through an array as if it's an Iterable.</p>

```<code>for( String : args ){
// Do stuff
}
</code>```

答:
Arrays are not primitives. Primitives are things that are not objects. Only boolean, char, byte, short, int, long, float, and double are primitives. Arraysare objects with special syntax. If you can call toString() on type in Java < 5 it is not primitive.

All autoboxing does is convert primitives to/from objects that expect objects such as ArrayList. It allows code like:

```<code>List<Integer> l = new ArrayList<Integer>();
l.add( 7 );
int i = l.get(0);
</code>```

To be short hand for:

```<code>List<Integer> l = new ArrayList<Integer>();
Integer ii = Integer.valueOf( 7 )
l.add( ii );
int i = l.get(0).getIntValue();
</code>```

This is all autoboxing does. Since String is already an object (and is not equivalent to char[] unlike in C) there is nothing to box/unbox String to.

Edit: added boolean as mentioned

Body:
Does Java 5 or higher apply some of form of "boxing" to arrays? This question came to mind as the following code goes through an array as if it's an Iterable.

for( String : args ){
// Do stuff
}

Body:
Arrays are not primitives. Primitives are things that are not objects. Only boolean, char, byte, short, int, long, float, and double are primitives. Arraysare objects with special syntax. If you can call toString() on type in Java < 5 it is not primitive.

All autoboxing does is convert primitives to/from objects that expect objects such as ArrayList. It allows code like:

List<Integer> l = new ArrayList<Integer>();
l.add( 7 );
int i = l.get(0);

To be short hand for:

List<Integer> l = new ArrayList<Integer>();
Integer ii = Integer.valueOf( 7 )
l.add( ii );
int i = l.get(0).getIntValue();

This is all autoboxing does. Since String is already an object (and is not equivalent to char[] unlike in C) there is nothing to box/unbox String to.

Edit: added boolean as mentioned