问:
Draw a line of certain length in Pine Script
I'm trying to develop a Pivot Points indicator on Trading View v4.0 and an issue I'm facing is that the pivot lines are drawn only up to the current bar. The behavior I want is that I want the line to extend for the duration of the period. For example, the weekly pivot line should extend from Monday to Sunday even if today is Monday.

Below is the code I'm using as well as the result:

```<code>// Function outputs 1 when it's the first bar of the D/W/M/Y
is_newbar(res) =>
    ch = 0
    if(res == 'Y')
        t  = year(time('D'))
        ch := change(t) != 0 ? 1 : 0
    else
        t = time(res)
        ch := change(t) != 0 ? 1 : 0
    ch

bars_since_week = 0
bars_since_week := is_newbar(pp_res_week) ? 0 : bars_since_week[1] + 1

vpp_p_week = line.new(bar_index[min(bars_since_week, 300)], PP_week, bar_index, PP_week, color=color.black, width = 2, style =  line.style_solid, extend = extend.none)
vs1_p_week = line.new(bar_index[min(bars_since_week, 300)], S1_week, bar_index, S1_week, color=color.black, width = 2, style =  line.style_solid, extend = extend.none)
vs2_p_week = line.new(bar_index[min(bars_since_week, 300)], S2_week, bar_index, S2_week, color=color.black, width = 2, style =  line.style_solid, extend = extend.none)
vs3_p_week = line.new(bar_index[min(bars_since_week, 300)], S3_week, bar_index, S3_week, color=color.black, width = 2, style =  line.style_solid, extend = extend.none)
vr1_p_week = line.new(bar_index[min(bars_since_week, 300)], R1_week, bar_index, R1_week, color=color.black, width = 2, style =  line.style_solid, extend = extend.none)
vr2_p_week = line.new(bar_index[min(bars_since_week, 300)], R2_week, bar_index, R2_week, color=color.black, width = 2, style =  line.style_solid, extend = extend.none)
vr3_p_week = line.new(bar_index[min(bars_since_week, 300)], R3_week, bar_index, R3_week, color=color.black, width = 2, style =  line.style_solid, extend = extend.none)
</code>```

Also, below is the behavior I would expect - notice the longer lines:

答:
It's not a simple matter, at least not the way it's done here ) There is perhaps a better way, but haven't figured out any:

You'll need to work with xloc = xloc.bar_time to be able to draw a line in the future when you need to.

Use the f_avgDilationOf() from the PineCoders MTF Selection Framework to know the average number of chart bars in the dilation of the higher TF (on a 24/7 market, this would be 7 on a daily chart if HTF=1W).

Figure out if current chart bars (current being the one the script is executing on) are included in the last dilation of the HTF. We need this info because when that is true, we will project the line in the future.

```<code>//@version=4
study("Periodic lines", "", true)
htf = input("W", type = input.resolution)

// Returns the average number of current chart bars in the given target HTF resolution (this reflects the dataset's history).
f_avgDilationOf(_res) =>
    // _res: resolution of any TF (in "timeframe.period" string format).
    b = barssince(change(time(_res)))
    cumTotal = cum(b == 0 ? b[1] + 1 : 0)
    cumCount = cum(b == 0 ? 1 : 0)
    cumTotal / cumCount

// Period change detection.
pChange(res) =>
    change(time(res == 'Y' ? 'D' : res))

// Get some previous value from last HTF period.
pHi = security(syminfo.tickerid, htf, high[1], lookahead = barmerge.lookahead_on)
// Verify if current charts bars are part of the last dilation of HTF.
lastPBar = security(syminfo.tickerid, htf, barstate.islast, lookahead = barmerge.lookahead_on)
// Get avg no of chart bars in one dilation of HTF.
dilation = round(f_avgDilationOf(htf))
timeDelta = time - time[1]

var line pHiLine = na
// Holds bar index where a new line is created.
var pHiBar = 0
if pChange(htf)
    // Extend old line for the last bar before creating a new one.
    line.set_xy2(pHiLine, time, pHi[1])
    // Save bar index on transition.
    pHiBar := bar_index
    // Create new line.
    pHiLine := line.new(time, pHi, time + timeDelta, pHi, xloc.bar_time, color = color.black, width = 2)
    // Make type of the 2 `if` blocks the same.
    float(na)
else
    // We are not on a transition; prolong line until next transition.
    line.set_xy2(pHiLine, time, pHi)
    float(na)

// If we are in the last bars of the HTF resolution's dilation, project line into the future with remaining bars in average no of bars in dilation.
if lastPBar
    line.set_xy2(pHiLine, time + (timeDelta * (dilation - (bar_index - pHiBar))), pHi)
</code>```

Caveat: Haven't forward-tested this, so unsure how it'll perform in those conditions.

Body:
I'm trying to develop a Pivot Points indicator on Trading View v4.0 and an issue I'm facing is that the pivot lines are drawn only up to the current bar. The behavior I want is that I want the line to extend for the duration of the period. For example, the weekly pivot line should extend from Monday to Sunday even if today is Monday.

Below is the code I'm using as well as the result:

// Function outputs 1 when it's the first bar of the D/W/M/Y
is_newbar(res) =>
    ch = 0
    if(res == 'Y')
        t  = year(time('D'))
        ch := change(t) != 0 ? 1 : 0
    else
        t = time(res)
        ch := change(t) != 0 ? 1 : 0
    ch

bars_since_week = 0
bars_since_week := is_newbar(pp_res_week) ? 0 : bars_since_week[1] + 1

vpp_p_week = line.new(bar_index[min(bars_since_week, 300)], PP_week, bar_index, PP_week, color=color.black, width = 2, style =  line.style_solid, extend = extend.none)
vs1_p_week = line.new(bar_index[min(bars_since_week, 300)], S1_week, bar_index, S1_week, color=color.black, width = 2, style =  line.style_solid, extend = extend.none)
vs2_p_week = line.new(bar_index[min(bars_since_week, 300)], S2_week, bar_index, S2_week, color=color.black, width = 2, style =  line.style_solid, extend = extend.none)
vs3_p_week = line.new(bar_index[min(bars_since_week, 300)], S3_week, bar_index, S3_week, color=color.black, width = 2, style =  line.style_solid, extend = extend.none)
vr1_p_week = line.new(bar_index[min(bars_since_week, 300)], R1_week, bar_index, R1_week, color=color.black, width = 2, style =  line.style_solid, extend = extend.none)
vr2_p_week = line.new(bar_index[min(bars_since_week, 300)], R2_week, bar_index, R2_week, color=color.black, width = 2, style =  line.style_solid, extend = extend.none)
vr3_p_week = line.new(bar_index[min(bars_since_week, 300)], R3_week, bar_index, R3_week, color=color.black, width = 2, style =  line.style_solid, extend = extend.none)

Also, below is the behavior I would expect - notice the longer lines:

Body:
It's not a simple matter, at least not the way it's done here ) There is perhaps a better way, but haven't figured out any:

You'll need to work with xloc = xloc.bar_time to be able to draw a line in the future when you need to.

Use the f_avgDilationOf() from the PineCoders MTF Selection Framework to know the average number of chart bars in the dilation of the higher TF (on a 24/7 market, this would be 7 on a daily chart if HTF=1W).

Figure out if current chart bars (current being the one the script is executing on) are included in the last dilation of the HTF. We need this info because when that is true, we will project the line in the future.

//@version=4
study("Periodic lines", "", true)
htf = input("W", type = input.resolution)

// Returns the average number of current chart bars in the given target HTF resolution (this reflects the dataset's history).
f_avgDilationOf(_res) =>
    // _res: resolution of any TF (in "timeframe.period" string format).
    b = barssince(change(time(_res)))
    cumTotal = cum(b == 0 ? b[1] + 1 : 0)
    cumCount = cum(b == 0 ? 1 : 0)
    cumTotal / cumCount

// Period change detection.
pChange(res) =>
    change(time(res == 'Y' ? 'D' : res))

// Get some previous value from last HTF period.
pHi = security(syminfo.tickerid, htf, high[1], lookahead = barmerge.lookahead_on)
// Verify if current charts bars are part of the last dilation of HTF.
lastPBar = security(syminfo.tickerid, htf, barstate.islast, lookahead = barmerge.lookahead_on)
// Get avg no of chart bars in one dilation of HTF.
dilation = round(f_avgDilationOf(htf))
timeDelta = time - time[1]

var line pHiLine = na
// Holds bar index where a new line is created.
var pHiBar = 0
if pChange(htf)
    // Extend old line for the last bar before creating a new one.
    line.set_xy2(pHiLine, time, pHi[1])
    // Save bar index on transition.
    pHiBar := bar_index
    // Create new line.
    pHiLine := line.new(time, pHi, time + timeDelta, pHi, xloc.bar_time, color = color.black, width = 2)
    // Make type of the 2 `if` blocks the same.
    float(na)
else
    // We are not on a transition; prolong line until next transition.
    line.set_xy2(pHiLine, time, pHi)
    float(na)

// If we are in the last bars of the HTF resolution's dilation, project line into the future with remaining bars in average no of bars in dilation.
if lastPBar
    line.set_xy2(pHiLine, time + (timeDelta * (dilation - (bar_index - pHiBar))), pHi)

Caveat: Haven't forward-tested this, so unsure how it'll perform in those conditions.


来源: stackexchange

问:
sudo: npm: command not found
I'm trying to upgrade to the latest version of node. I'm following the instructions at http://davidwalsh.name/upgrade-nodejs

But when I do:

```<code>sudo npm install -g n
</code>```

I get the error:

```<code>sudo: npm: command not found
</code>```

npm works without sudo. When I do:

```<code>whereis node
</code>```

I see:

```<code>node: /usr/bin/node /usr/lib/node /usr/bin/X11/node /usr/local/node
</code>```

Running:

```<code>which npm
</code>```

Shows:

```<code>/usr/local/node/bin/npm
</code>```

I tried the solution at https://stackoverflow.com/a/5062718/1246159

But I'm still getting the same error. I also looked at the /etc/sudoers file and the relevant line is:

```<code>Defaults        secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
</code>```

This looks fine to me. How can I possibly get NPM working with sudo command?

答:
Work for me Resolving EACCES permissions errors when installing packages globally

To minimize the chance of permissions errors, you can configure npm to use a different directory. In this example, you will create and use hidden directory in your home directory.

Back up your computer.
On the command line, in your home directory, create a directory for global installations:

 mkdir ~/.npm-global
```

<p>Configure npm to use the new directory path:</p>

<pre class="lang-sh prettyprint-override"><code> npm config set prefix '~/.npm-global'
</code>```

In your preferred text editor, open or create a ~/.profile file and add this line:

 export PATH=~/.npm-global/bin:$PATH
```

<p>On the command line, update your system variables:</p>

<pre class="lang-sh prettyprint-override"><code> source ~/.profile
</code>```

To test your new configuration, install a package globally without using sudo:

 npm install -g jshint
```

ContentLicense: CC BY-SA 4.0

Title: sudo: npm: command not found

Body:
I'm trying to upgrade to the latest version of node. I'm following the instructions at http://davidwalsh.name/upgrade-nodejs

But when I do:

sudo npm install -g n

I get the error:

sudo: npm: command not found

npm works without sudo. When I do:

whereis node

I see:

node: /usr/bin/node /usr/lib/node /usr/bin/X11/node /usr/local/node

Running:

which npm

Shows:

/usr/local/node/bin/npm

I tried the solution at https://stackoverflow.com/a/5062718/1246159

But I'm still getting the same error. I also looked at the /etc/sudoers file and the relevant line is:

Defaults        secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

This looks fine to me. How can I possibly get NPM working with sudo command?

Body:
Work for me Resolving EACCES permissions errors when installing packages globally

To minimize the chance of permissions errors, you can configure npm to use a different directory. In this example, you will create and use hidden directory in your home directory.

Back up your computer.
On the command line, in your home directory, create a directory for global installations:

 mkdir ~/.npm-global

Configure npm to use the new directory path:

 npm config set prefix '~/.npm-global'

In your preferred text editor, open or create a ~/.profile file and add this line:

 export PATH=~/.npm-global/bin:$PATH

On the command line, update your system variables:

 source ~/.profile

To test your new configuration, install a package globally without using sudo:

 npm install -g jshint


问:
How to merge states from two composition functions?
How to merge states from two composition functions?
I've read docs and didn't find any examples?</p>

```<code>function useFeature1() {
  let state = reactive({
    todo: '',
    todolist: [],
  })
  return {
    state
  }
}

function useFeature2() {
  let state = reactive({
    items: []
  })
  return {
    state
  }
}
</code>```

答: I've just understood there is no point to merge states. Probably it's better to just name states consistently. Like mainStat, stateWithFeature and so on.</p>

Body:
How to merge states from two composition functions?
I've read docs and didn't find any examples?

function useFeature1() {
  let state = reactive({
    todo: '',
    todolist: [],
  })
  return {
    state
  }
}

function useFeature2() {
  let state = reactive({
    items: []
  })
  return {
    state
  }
}


问:
tidyverse - delete a column within a nested column/list
I have the following data:

(Note: I'm using the current github version of dplyr within tidyverse which offerse some new experimental functions, like condense - which I'm using below, but I think that's not relevant for my problem/question).

```<code>library(tidyverse)
library(corrr)

dat <- data.frame(grp = rep(1:4, each = 25),
                  Q1 = sample(c(1:5, NA), 100, replace = TRUE),
                  Q2 = sample(c(1:5, NA), 100, replace = TRUE),
                  Q3 = sample(c(1:5, NA), 100, replace = TRUE),
                  Q4 = sample(c(1:5, NA), 100, replace = TRUE),
                  Q5 = sample(c(1:5, NA), 100, replace = TRUE),
                  Q6 = sample(c(1:5, NA), 100, replace = TRUE))
</code>```

I now want to calculate the correlation between Q1 to Q6 within each group, and I'm using:

```<code>cor_dat <- dat %>%
  group_by(grp) %>%
  condense(cor = correlate(cur_data()))
</code>```

Which gives me the correlations as a list-column (?). Within each list, the first column is called rowname and I want to simply delete this column from each list in a tidyverse way. How can I do this?

I already tried something naive like select (-rowname), but this doesn't work.

答:
The suggestion by @r2evans would work if we remove the group attribute

```<code>library(dplyr)
library(purrr)
cor_dat %>%
     ungroup %>%
     mutate(cor = map(cor, ~ select(.x, -rowname)))
# A tibble: 4 x 2
#    grp cor
#  <int> <list>
#1     1 <tibble [6 × 6]>
#2     2 <tibble [6 × 6]>
#3     3 <tibble [6 × 6]>
#4     4 <tibble [6 × 6]>
</code>```

When there is a group attribute, it results in error

```<code>cor_dat %>%
    mutate(cor = map(cor, ~ select(.x, -rowname)))
</code>```

Error: mutate() argument cor errored.
      ℹ cor is map(cor, ~select(.x, -rowname)).
      ℹ The error occured in row 1.
      ✖ no applicable method for 'select_' applied to an object of class "character"
      Run rlang::last_error() to see where the error occurred.

which is consistent with the same behavior if we extract as a column

```<code>cor_dat$cor %>%
           map(~ .x %>% select(-rowname))
</code>```

Or if we want to make it shorter, it can be done within condense itself because correlate adds a rowname column as per the documentation

```<code>dat %>%
  group_by(grp) %>%
  condense(cor = correlate(cur_data()) %>%
                              select(-rowname))
# A tibble: 4 x 2
# Rowwise:  grp
#    grp cor
#  <int> <list>
#1     1 <tibble [6 × 6]>
#2     2 <tibble [6 × 6]>
#3     3 <tibble [6 × 6]>
#4     4 <tibble [6 × 6]>
</code>```

Body:
I have the following data:

(Note: I'm using the current github version of dplyr within tidyverse which offerse some new experimental functions, like condense - which I'm using below, but I think that's not relevant for my problem/question).

library(tidyverse)
library(corrr)

dat <- data.frame(grp = rep(1:4, each = 25),
                  Q1 = sample(c(1:5, NA), 100, replace = TRUE),
                  Q2 = sample(c(1:5, NA), 100, replace = TRUE),
                  Q3 = sample(c(1:5, NA), 100, replace = TRUE),
                  Q4 = sample(c(1:5, NA), 100, replace = TRUE),
                  Q5 = sample(c(1:5, NA), 100, replace = TRUE),
                  Q6 = sample(c(1:5, NA), 100, replace = TRUE))

I now want to calculate the correlation between Q1 to Q6 within each group, and I'm using:

cor_dat <- dat %>%
  group_by(grp) %>%
  condense(cor = correlate(cur_data()))

Which gives me the correlations as a list-column (?). Within each list, the first column is called rowname and I want to simply delete this column from each list in a tidyverse way. How can I do this?

I already tried something naive like select (-rowname), but this doesn't work.

Body:
The suggestion by @r2evans would work if we remove the group attribute

library(dplyr)
library(purrr)
cor_dat %>%
     ungroup %>%
     mutate(cor = map(cor, ~ select(.x, -rowname)))
# A tibble: 4 x 2
#    grp cor
#  <int> <list>
#1     1 <tibble [6 × 6]>
#2     2 <tibble [6 × 6]>
#3     3 <tibble [6 × 6]>
#4     4 <tibble [6 × 6]>

When there is a group attribute, it results in error

cor_dat %>%
    mutate(cor = map(cor, ~ select(.x, -rowname)))

Error: mutate() argument cor errored.
      ℹ cor is map(cor, ~select(.x, -rowname)).
      ℹ The error occured in row 1.
      ✖ no applicable method for 'select_' applied to an object of class "character"
      Run rlang::last_error() to see where the error occurred.

which is consistent with the same behavior if we extract as a column

cor_dat$cor %>%
           map(~ .x %>% select(-rowname))

Or if we want to make it shorter, it can be done within condense itself because correlate adds a rowname column as per the documentation

dat %>%
  group_by(grp) %>%
  condense(cor = correlate(cur_data()) %>%
                              select(-rowname))
# A tibble: 4 x 2
# Rowwise:  grp
#    grp cor
#  <int> <list>
#1     1 <tibble [6 × 6]>
#2     2 <tibble [6 × 6]>
#3     3 <tibble [6 × 6]>
#4     4 <tibble [6 × 6]>


问:
Flutter: Execution failed for task ':app:compileDebugKotlin'
I tried running the default flutter app from flutter create on my android device but it throws me an error. Can someone help?

Launching lib\main.dart on SM G610F in debug mode... Running Gradle
  task 'assembleDebug'...

FAILURE: Build failed with an exception.

What went wrong: Execution failed for task ':app:compileDebugKotlin'.

Could not resolve all artifacts for configuration ':app:debugCompileClasspath'. . . .

Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 14s Finished with error: Gradle task assembleDebug
  failed with exit code 1

This is my flutter doctor:

[√] Flutter (Channel stable, v1.12.13+hotfix.5, on Microsoft Windows
  [Version 10.0.10586], locale en-US)
      • Flutter version 1.12.13+hotfix.5 at E:\flutter\flutter
      • Framework revision 27321ebbad (6 weeks ago), 2019-12-10 18:15:01 -0800
      • Engine revision 2994f7e1e6
      • Dart version 2.7.0

[√] Android toolchain - develop for Android devices (Android SDK
  version 29.0.2)
      • Android SDK at C:\Users\208046\AppData\Local\Android\sdk
      • Android NDK location not configured (optional; useful for native profiling support)
      • Platform android-29, build-tools 29.0.2
      • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
      • Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b03)
      • All Android licenses accepted.

[√] Android Studio (version 3.5)
      • Android Studio at C:\Program Files\Android\Android Studio
      • Flutter plugin version 42.1.1
      • Dart plugin version 191.8593
      • Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b03)

[√] VS Code, 64-bit edition (version 1.41.1)
      • VS Code at C:\Program Files\Microsoft VS Code
      • Flutter extension version 3.7.1

[√] Connected device (1 available)
      • SM G610F • 33005566b2b5c3df • android-arm • Android 8.1.0 (API 27)

• No issues found!

edit: for my complete logs you can see here:

Flutter github issues

答: For me, I found that when building that 2 different MainActivity.kt files were in andriod/app/src/main/kotlin. One had a default MainActivity.kt file with the package name that was originally generated for my project. Something like 'example.project_name' . The other one had what I changed my project name into. I went ahead and deleted the folder with the MainActivity.kt containing the import starting with 'example.project_name' and that resolved the issue for me.


问:
Google Translate API Pricing and Language auto-detect Effeciency
I have the following three questions

I want to use Google's API to translate text. I know that Google charges separately for translation and detection. Google translate also supports translation two ways to translate

i) By specifying both source and target, as in
https://www.googleapis.com/language/translate/v2?key=INSERT-YOUR-KEY&source=en&target=de&q=Hello%20world&q=My%20name%20is%20Jeff

ii) By specifying just the target, where the source us auto-detected,
like this https://www.googleapis.com/language/translate/v2?key=INSERT-YOUR-KEY&target=de&q=Hello%20world

My question is, if i call the API as in the second example, will I be charged for both detection and translation or just translation?

Is it more efficient when you specify both source and target than when you just the target, or, are there any downsides of using the second way above?

How many words should be sent to Google Translate API to detect a language reliably?

Thanks

答:
I pretty much translate using the second approach most of the time (not informing to google the source language) and they only charge for the translation, not for the detection.

However, you must be aware of the fact that, in case your source text is of the same language as your target language, google will attempt to translate it anyways, and sometimes it leads to confused results, or at least a translation which was not necessary, since you already had the text in the desired language.

ContentLicense: CC BY-SA 3.0


问:
Selenium looking at a class and determine how many elements are in the class, finally executes an action on all elements found
I need to interact with elements under a class but the number of elements in that class is changing every time I run the script.

To give you context the website is a calendar, where I need to pick a day that I'll use as a template for my work. Every time I run the script (Monthly) the webpage with the calendar is updated to show the current month, thus Selenium picks the same day it did in the previous month. But every month the day Selenium picks has different contents and number of elements change every month. Currently, for example, the script is written to interact with 5 elements, but for next month it won't work because the day picked will have a different number of elements. So every month I have to manually change the script to interact with the correct number of elements.

Here's an example of the element structure of the website:

```<code><ul class="list-unstyled tags-list grid_9">
     <li><!-- react-text: 185 -->Text<!-- /react-text --><i data-id="0" class="icon-cancel pointer icon12
      ml5px error"></i></li>
     <li><!-- react-text: 188 -->Text<!-- /react-text --><i data-id="1" class="icon-cancel pointer icon12
      ml5px error"></i></li>
     <li><!-- react-text: 191 -->Text<!-- /react-text --><i data-id="2" class="icon-cancel pointer icon12
      ml5px error"></i></li>
</ul>
</code>```

So the number of elements that I need to interact within the class 'list-unstyled tags-list grid_9' is always changing. The elements with the id's "0", "1" and "2". Sometimes there might be 4 elements with ID's "0", "1", "2", "3" and sometimes there's 2 elements etc.

I've been trying to figure out how to write a script where Selenium looks inside that class ''list-unstyled tags-list grid_9', see's how many elements are in there and executes a -

```<code>driver.find_element_by_(xpath,class,id whatever).click()
</code>```

on all of the elements found in there.

UPDATE:
So I tried this code:

```<code>tab = driver.find_element_by_css_selector('#postForm > div:nth-child(3) > ul.list-unstyled.tags-list.grid_9')
    hashs = tab.find_elements_by_tag_name('li')
    for element in hashs:
        element.find_element_by_tag_name('i').click()
</code>```

And it gave me this error:

```<code>stale element reference: element is not attached to the page document
</code>```

答:
I think you are very close to acheive your objective. Just try to click with JS.

```<code>tab = driver.find_element_by_css_selector('#postForm > div:nth-child(3) > ul.list-unstyled.tags-list.grid_9')
hashs = tab.find_elements_by_tag_name('li')
for element in hashs:
    x_element=element.find_element_by_tag_name('i')
driver.execute_script("arguments[0].click();", x_element)
</code>```

OR

Wait for element to be clickable and then click.

```<code>from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

tab = driver.find_element_by_css_selector('#postForm > div:nth-child(3) > ul.list-unstyled.tags-list.grid_9')
hashs = tab.find_elements_by_tag_name('li')

number_of_buttons = len(hashs)
for x in range(number_of_buttons):

   button = WebDriverWait(driver, 50).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#postForm > div:nth-child(3) > ul.list-unstyled.tags-list.grid_9 > li:nth-child(" + str(x+1) + ") > i")))
    button.click()
</code>```

Body:
I need to interact with elements under a class but the number of elements in that class is changing every time I run the script.

To give you context the website is a calendar, where I need to pick a day that I'll use as a template for my work. Every time I run the script (Monthly) the webpage with the calendar is updated to show the current month, thus Selenium picks the same day it did in the previous month. But every month the day Selenium picks has different contents and number of elements change every month. Currently, for example, the script is written to interact with 5 elements, but for next month it won't work because the day picked will have a different number of elements. So every month I have to manually change the script to interact with the correct number of elements.

Here's an example of the element structure of the website:

Text

Text

Text

So the number of elements that I need to interact within the class 'list-unstyled tags-list grid_9' is always changing. The elements with the id's "0", "1" and "2". Sometimes there might be 4 elements with ID's "0", "1", "2", "3" and sometimes there's 2 elements etc.

I've been trying to figure out how to write a script where Selenium looks inside that class ''list-unstyled tags-list grid_9', see's how many elements are in there and executes a -

driver.find_element_by_(xpath,class,id whatever).click()

on all of the elements found in there.

UPDATE:
So I tried this code:

tab = driver.find_element_by_css_selector('#postForm > div:nth-child(3) > ul.list-unstyled.tags-list.grid_9')
    hashs = tab.find_elements_by_tag_name('li')
    for element in hashs:
        element.find_element_by_tag_name('i').click()

And it gave me this error:

stale element reference: element is not attached to the page document

Body:
I think you are very close to acheive your objective. Just try to click with JS.

tab = driver.find_element_by_css_selector('#postForm > div:nth-child(3) > ul.list-unstyled.tags-list.grid_9')
hashs = tab.find_elements_by_tag_name('li')
for element in hashs:
    x_element=element.find_element_by_tag_name('i')
driver.execute_script("arguments[0].click();", x_element)

OR

Wait for element to be clickable and then click.

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

tab = driver.find_element_by_css_selector('#postForm > div:nth-child(3) > ul.list-unstyled.tags-list.grid_9')
hashs = tab.find_elements_by_tag_name('li')

number_of_buttons = len(hashs)
for x in range(number_of_buttons):

   button = WebDriverWait(driver, 50).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#postForm > div:nth-child(3) > ul.list-unstyled.tags-list.grid_9 > li:nth-child(" + str(x+1) + ") > i")))
    button.click()


问:
How to get the index of the current ItemsControl item?
Is there any way to get the index of the current ItemsControl item in WPF?

For example, I want to do something like:

```<code><ItemsControl>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBox Text="{Binding current_index}">
            </TextBox>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
</code>```

so that after this, the first TextBox will show text "0", second "1", third "2" ....

答:
If your goal is to have a button in the ItemTemplate work properly, I would use the DataContext. You should also be able to find the index from the DataContext and ItemsSource using LINQ.

If using commands

```<code>Command="{Binding DataContext.TestCmd, ElementName=Parent_UC}"
CommandParameter="{Binding DataContext, RelativeSource={RelativeSource Mode=Self}}"
</code>```

If using events, use the sender.

```<code>private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
{
   if(sender is Button b)
   {
      if(b.DataContext is ClassType t)
      { enter code here }
   }
}
</code>```

Body:
Is there any way to get the index of the current ItemsControl item in WPF?

For example, I want to do something like:

<ItemsControl>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBox Text="{Binding current_index}">
            </TextBox>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

so that after this, the first TextBox will show text "0", second "1", third "2" ....

Body:
If your goal is to have a button in the ItemTemplate work properly, I would use the DataContext. You should also be able to find the index from the DataContext and ItemsSource using LINQ.

If using commands

Command="{Binding DataContext.TestCmd, ElementName=Parent_UC}"
CommandParameter="{Binding DataContext, RelativeSource={RelativeSource Mode=Self}}"

If using events, use the sender.

private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
{
   if(sender is Button b)
   {
      if(b.DataContext is ClassType t)
      { enter code here }
   }
}


问:
context is disposed when using "two levels" of context
When doing:

```<code>    using (IUnitOfWork uow = UnitOfWork.Current)
    {
        LocationRepository rep = new LocationRepository();
        Location loc = new Location()
        {
            CompanyId = m_User.UserCompany.CompanyId,
            Name = locationName
        };
        rep.Insert(loc);
        uow.Commit();
    }
</code>```

I get the exception:

```<code>The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
</code>```

The reason I get this exception is that m_User.UserCompany is implemented like:

```<code>public _Company UserCompany
{
    get
    {
                using (IUnitOfWork uow = UnitOfWork.Current)
                {
                    CompanyRepository rep = new CompanyRepository();
                    m_Company = rep.Get(companyId.Value);
                }
        return m_Company;
    }
}
</code>```

So actually inside the first using statement I create another using statement which dispose my context when done and I get the exception in the outer using statement.

I am using the entity framework the way described here.

What is the common solution for such case?

答:
The simple solution would be to remove the using statement from the 'UserCompany' property. This would ensure that the UnitOfWork.Current isnt being disposed of prematurely.

Another idea would be to re-factor the property to a function that takes a IUnitOfWork as a parameter. e.g.

```<code>public _Company GetUserCompany(IUnitOfWork uow)
{
    CompanyRepository rep = new CompanyRepository();
    m_Company = rep.Get(companyId.Value);
    return m_Company;
}
</code>```

this then allows you to manage the life of the IUnitOfWork outside the scope of the function. e.g.

```<code>using (IUnitOfWork uow = UnitOfWork.Current)
{
    /* Snip...*/

        CompanyId = m_User.GetUserCompany(uow).CompanyId,

    /* Snip...*/
}
</code>```

This has the added benefit of allowing an external caller to the GetUserCompany() to always be able to manage the lifespan of the IUnitOfWork regardless of how its used within the GetUserCompany function.

Body:
When doing:

    using (IUnitOfWork uow = UnitOfWork.Current)
    {
        LocationRepository rep = new LocationRepository();
        Location loc = new Location()
        {
            CompanyId = m_User.UserCompany.CompanyId,
            Name = locationName
        };
        rep.Insert(loc);
        uow.Commit();
    }

I get the exception:

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

The reason I get this exception is that m_User.UserCompany is implemented like:

public _Company UserCompany
{
    get
    {
                using (IUnitOfWork uow = UnitOfWork.Current)
                {
                    CompanyRepository rep = new CompanyRepository();
                    m_Company = rep.Get(companyId.Value);
                }
        return m_Company;
    }
}

So actually inside the first using statement I create another using statement which dispose my context when done and I get the exception in the outer using statement.

I am using the entity framework the way described here.

What is the common solution for such case?

Body:
The simple solution would be to remove the using statement from the 'UserCompany' property. This would ensure that the UnitOfWork.Current isnt being disposed of prematurely.

Another idea would be to re-factor the property to a function that takes a IUnitOfWork as a parameter. e.g.

public _Company GetUserCompany(IUnitOfWork uow)
{
    CompanyRepository rep = new CompanyRepository();
    m_Company = rep.Get(companyId.Value);
    return m_Company;
}

this then allows you to manage the life of the IUnitOfWork outside the scope of the function. e.g.

using (IUnitOfWork uow = UnitOfWork.Current)
{
    /* Snip...*/

        CompanyId = m_User.GetUserCompany(uow).CompanyId,

    /* Snip...*/
}

This has the added benefit of allowing an external caller to the GetUserCompany() to always be able to manage the lifespan of the IUnitOfWork regardless of how its used within the GetUserCompany function.


问:
Rank and unrank combinations to distribute k balls into n bins of different capacities
I want to distribute k balls into n bins of different capacities. How can I rank and unrank the distributions given n, k, and the bin capacities?

Example:

n := 3

k := 4

bin capacities := 3,2,1

Balls in bins:

1,2,1, 2,1,1, 2,2,0, 3,0,1, 3,1,0 := 5

Is there a formula?

答:
Here's a way (in pseudocode), though it doesn't look very efficient. It would probably be smart to add some short-circuiting in places where the number of balls won't fit in the total remaining capacity. Perhaps some clever caching could help, if a given list of capacities will be used many times.

All numbers are non-negative integers. Function ArrayTail(array a) is the subarray whose elements are all elements of the input array after the first. Function ArrayCon(number head, array a) is the array whose elements are head followed by the elements of a.

```<code>function Count(array capacities, number balls) -> number
    If balls == 0:
       return 1
    Else if capacities is empty:
       return 0
    Else:
       Let sum: number
       sum <- 0
       For b from 0 to max(balls, capacities[0]):
           sum <- sum + Count(ArrayTail(capacities), b)
       End For
       return sum
    End If/Else
End function

function Rank(array capacities, array counts) -> number
    Precondition: length(capacities) == length(counts)
    Precondition: counts[i] <= capacities[i] for all i < length(counts)
    If counts is empty:
        return 0
    Else:
        Let total: number
        total <- 0
        For c in counts:
            total <- total + c
        End For
        Let r: number
        r <- Rank(ArrayTail(capacities), ArrayTail(counts))
        For b from 0 to (counts[0]-1):
            r <- r + Count(ArrayTail(capacities), total - b)
        End For
        return r
    End If/Else
End function

function Unrank(array capacities, number balls, number rank) -> array
    Precondition: rank < Count(capacities, balls)
    If capacities is empty:
        return empty array
    Else
        Let c0: number
        c0 <- 0
        Loop until "return":
            Let subcount: number
            subcount <- Count(ArrayTail(capacities), balls-c0)
            If subcount <= rank:
                c0 <- c0 + 1
                rank <- rank - subcount
            Else
                return ArrayCon(c0, Unrank(ArrayTail(capacities), balls-c0, rank))
            End If/Else
        End Loop
    End If/Else
End function
</code>```

Body:
Here's a way (in pseudocode), though it doesn't look very efficient. It would probably be smart to add some short-circuiting in places where the number of balls won't fit in the total remaining capacity. Perhaps some clever caching could help, if a given list of capacities will be used many times.

All numbers are non-negative integers. Function ArrayTail(array a) is the subarray whose elements are all elements of the input array after the first. Function ArrayCon(number head, array a) is the array whose elements are head followed by the elements of a.

function Count(array capacities, number balls) -> number
    If balls == 0:
       return 1
    Else if capacities is empty:
       return 0
    Else:
       Let sum: number
       sum <- 0
       For b from 0 to max(balls, capacities[0]):
           sum <- sum + Count(ArrayTail(capacities), b)
       End For
       return sum
    End If/Else
End function

function Rank(array capacities, array counts) -> number
    Precondition: length(capacities) == length(counts)
    Precondition: counts[i] <= capacities[i] for all i < length(counts)
    If counts is empty:
        return 0
    Else:
        Let total: number
        total <- 0
        For c in counts:
            total <- total + c
        End For
        Let r: number
        r <- Rank(ArrayTail(capacities), ArrayTail(counts))
        For b from 0 to (counts[0]-1):
            r <- r + Count(ArrayTail(capacities), total - b)
        End For
        return r
    End If/Else
End function

function Unrank(array capacities, number balls, number rank) -> array
    Precondition: rank < Count(capacities, balls)
    If capacities is empty:
        return empty array
    Else
        Let c0: number
        c0 <- 0
        Loop until "return":
            Let subcount: number
            subcount <- Count(ArrayTail(capacities), balls-c0)
            If subcount <= rank:
                c0 <- c0 + 1
                rank <- rank - subcount
            Else
                return ArrayCon(c0, Unrank(ArrayTail(capacities), balls-c0, rank))
            End If/Else
        End Loop
    End If/Else
End function


问:
How to compare 2 tables from 2 databases (and servers) different ? (Oracle & Mysql)
I want to compare 2 tables from 2 databases (and servers) different ... One is Oracle, the other is Mysql.

I did that for tables in the same DB like that :

```<code>SELECT FIELD 1, FIELD 2
FROM SCHEMA.TABLENAME1
MINUS
SELECT FIELD 1, FIELD 2
FROM SCHEMA.TABLENAME2
</code>```

I'm using dbeaver for my queries.

答:
```<code>select col1, col2, ..., coln
from sch1.table1
minus
select col1, col2, ..., coln
from sch2.table1
</code>```

is working well, but you have to do two more

```<code>select col1, col2, ..., coln
from sch2.table1
minus
select col1, col2, ..., coln
from sch1.table1
</code>```

and

```<code>select count(*) ftom sch1.table1
union all
select count(*) ftom sch2.table1
</code>```

And as you see that queries should be in the same RDBMS.

Body:
I want to compare 2 tables from 2 databases (and servers) different ... One is Oracle, the other is Mysql.

I did that for tables in the same DB like that :

SELECT FIELD 1, FIELD 2
FROM SCHEMA.TABLENAME1
MINUS
SELECT FIELD 1, FIELD 2
FROM SCHEMA.TABLENAME2

I'm using dbeaver for my queries.

Body:
select col1, col2, ..., coln
from sch1.table1
minus
select col1, col2, ..., coln
from sch2.table1

is working well, but you have to do two more

select col1, col2, ..., coln
from sch2.table1
minus
select col1, col2, ..., coln
from sch1.table1

and

select count(*) ftom sch1.table1
union all
select count(*) ftom sch2.table1

And as you see that queries should be in the same RDBMS.


问:
C++ how to parse a ppm file?
I'm trying to parse a ppm file.

The spec is this: http://netpbm.sourceforge.net/doc/ppm.html

Example:

```<code>
P3
# feep.ppm
4 4
15
 0  0  0    0  0  0    0  0  0   15  0 15
 0  0  0    0 15  7    0  0  0    0  0  0
 0  0  0    0  0  0    0 15  7    0  0  0
15  0 15    0  0  0    0  0  0    0  0  0
</code>```

The stuff after the "15" are the rgb values of all pixels in the give image.

I have tried this so far:

```<code>

void read_and_draw_ppm_file() {
    ifstream infile;
    infile.open(TEXTURE_FILE.c_str());
    string line;
    int count = 0;
    while (getline(infile, line) && count < 4) {
        count++;
    }

    char c;

    int red = -1, green = -1, blue = -1;
    int rgb_count = 0;
    for (int i = 0; i < TEXTURE_WIDTH; i++) {
        for (int j = 0; j < TEXTURE_HEIGHT; j++) {

              infile >> c;

            if (rgb_count == 0) {
                if (red != -1 && blue != -1 && green != -1) {
                    cout << red<<endl;
                    cout << green<<endl;
                    cout << blue<<endl;

                    uint32_t colour = (255 << 24) + (int(red) << 16) + (int(green) << 8) + int(blue);
                    window.setPixelColour(i, j, colour);

                     red = -1;
                    blue = -1;
                    green = -1;
                }
                red = (int) (unsigned char) c;
                rgb_count++;

            } else if (rgb_count == 1) {
                green = (int) (unsigned char) c;
                rgb_count++;
            } else if (rgb_count == 2) {
                blue = (int) (unsigned char) c;
                rgb_count = 0;
            }
        }

    }
    infile.close();
}

</code>```

The idea is to basically extract triplets of 3 bytes, then convert each to rgb respectively.

Problem is, when I display the image into the screen, the image isn't quite the same as it's supposed to be.

Where am I going wrong?

The original image:

Rendered Image image:

答:
You read in a value for red, then increment j.  Then you read in green, and increment j.  Next you read blue, store the pixel value, and increment j.

So you're writing out your values spaced out every 3 rows.

Title: C++ how to parse a ppm file?

Body:
I'm trying to parse a ppm file.

The spec is this: http://netpbm.sourceforge.net/doc/ppm.html

Example:

P3
# feep.ppm
4 4
15
 0  0  0    0  0  0    0  0  0   15  0 15
 0  0  0    0 15  7    0  0  0    0  0  0
 0  0  0    0  0  0    0 15  7    0  0  0
15  0 15    0  0  0    0  0  0    0  0  0

The stuff after the "15" are the rgb values of all pixels in the give image.

I have tried this so far:

void read_and_draw_ppm_file() {
    ifstream infile;
    infile.open(TEXTURE_FILE.c_str());
    string line;
    int count = 0;
    while (getline(infile, line) && count < 4) {
        count++;
    }

    char c;

    int red = -1, green = -1, blue = -1;
    int rgb_count = 0;
    for (int i = 0; i < TEXTURE_WIDTH; i++) {
        for (int j = 0; j < TEXTURE_HEIGHT; j++) {

              infile >> c;

            if (rgb_count == 0) {
                if (red != -1 && blue != -1 && green != -1) {
                    cout << red<<endl;
                    cout << green<<endl;
                    cout << blue<<endl;

                    uint32_t colour = (255 << 24) + (int(red) << 16) + (int(green) << 8) + int(blue);
                    window.setPixelColour(i, j, colour);

                     red = -1;
                    blue = -1;
                    green = -1;
                }
                red = (int) (unsigned char) c;
                rgb_count++;

            } else if (rgb_count == 1) {
                green = (int) (unsigned char) c;
                rgb_count++;
            } else if (rgb_count == 2) {
                blue = (int) (unsigned char) c;
                rgb_count = 0;
            }
        }

    }
    infile.close();
}

The idea is to basically extract triplets of 3 bytes, then convert each to rgb respectively.

Problem is, when I display the image into the screen, the image isn't quite the same as it's supposed to be.

Where am I going wrong?

The original image:

Rendered Image image:


问:
c# unexpected backgroundWorker behaviour
I have attached a backgroundWorker component to my main form which runs a parallel task of capturing the screen for an animated gif. The worker's function has a while loop that runs until I use CancelAsync() on the worker, at which point it exits the loop, does some other things like saving the gif file and so on and returns some results to the UI thread.

```<code>private bool capturing = false;

public MainForm()
{
    InitializeComponent();
    backgroundWorker.DoWork += backgroundWorker_DoWork;
    backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
    backgroundWorker.WorkerSupportsCancellation = true;
}

private void captureBtn_Click(object sender, EventArgs e)
{
    Debug.WriteLine("Button clicked");
    if (capturing) { return; }
    if (!backgroundWorker.IsBusy)
    {
        backgroundWorker.RunWorkerAsync();
    }
}

private void stopCaptureBtn_Click(object sender, EventArgs e)
{
    if (backgroundWorker.IsBusy)
    {
        backgroundWorker.CancelAsync();
    }
}

private void backgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    capturing = true;
    Debug.WriteLine("DoWork running");

    while (!backgroundWorker.CancellationPending)
    {
        Debug.WriteLine("Capturing frame {0}", frames);
        //do the capturing to memory stream
    }

    Debug.WriteLine("DoWork cancelled");

    //do some other things like saving the gif etc
    e.Result = someResult;
}

private void backgroundWorker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
    Debug.WriteLine("RunWorkerCompleted running");
    capturing = false;
    //does something with the e.Result
}
</code>```

My console output during a normal test is something like this:

```<code>Button clicked
DoWork running
Capturing frame 0
Capturing frame 1
Capturing frame 2
Capturing frame 3
Capturing frame 4
Capturing frame 5
Cancel button clicked
DoWork cancelled
The thread 0x2e4c has exited with code 0 (0x0).
DoWork running
DoWork cancelled
The thread 0x1010 has exited with code 0 (0x0).
RunWorkerCompleted running
</code>```

The function seems to be running twice, I can see 2 separate threads exiting and also I don't seem to get any results from capturing. If I set a breakpoint inside the backgroundWorker_DoWork function and continue later, the first run does the capturing normally. What could be going on?

答:
Its getting called twice because binding the event second time right after InitializeComponent().
Just comment those lines and it should work fine.
Here's the same example without the issue of running twice.

Sample Output
...
...
...
Capturing frame 2632
Capturing frame 2633
Capturing frame 2634
DoWork cancelled
RunWorkerCompleted running

```<code>public partial class Form1 : Form
    {
        private bool capturing = false;
        public Form1()
        {
            InitializeComponent();
            backgroundWorker1.WorkerSupportsCancellation = true;

  // Don't need to re-bind
            //backgroundWorker1.DoWork += backgroundWorker1_DoWork;
            //backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
            //backgroundWorker1.WorkerSupportsCancellation = true;
        }

private void captureBtn_Click(object sender, EventArgs e)
        {
            Debug.WriteLine("Button clicked");
            if (capturing) { return; }
            if (!backgroundWorker1.IsBusy)
            {
                backgroundWorker1.RunWorkerAsync();
            }
        }

        private void stopCaptureBtn_Click(object sender, EventArgs e)
        {
            if (backgroundWorker1.IsBusy)
            {
                backgroundWorker1.CancelAsync();
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            capturing = true;
            Debug.WriteLine("DoWork running");
            int frames = 1;

            while (!backgroundWorker1.CancellationPending)
            {
                Debug.WriteLine("Capturing frame {0}", frames);
                //do the capturing to memory stream
                frames++;
            }

            Debug.WriteLine("DoWork cancelled");

            //do some other things like saving the gif etc
            //e.Result = someResult;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Debug.WriteLine("RunWorkerCompleted running");
            capturing = false;
            //does something with the e.Result
        }

</code>```

Body:
I have attached a backgroundWorker component to my main form which runs a parallel task of capturing the screen for an animated gif. The worker's function has a while loop that runs until I use CancelAsync() on the worker, at which point it exits the loop, does some other things like saving the gif file and so on and returns some results to the UI thread.

private bool capturing = false;

public MainForm()
{
    InitializeComponent();
    backgroundWorker.DoWork += backgroundWorker_DoWork;
    backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
    backgroundWorker.WorkerSupportsCancellation = true;
}

private void captureBtn_Click(object sender, EventArgs e)
{
    Debug.WriteLine("Button clicked");
    if (capturing) { return; }
    if (!backgroundWorker.IsBusy)
    {
        backgroundWorker.RunWorkerAsync();
    }
}

private void stopCaptureBtn_Click(object sender, EventArgs e)
{
    if (backgroundWorker.IsBusy)
    {
        backgroundWorker.CancelAsync();
    }
}

private void backgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    capturing = true;
    Debug.WriteLine("DoWork running");

    while (!backgroundWorker.CancellationPending)
    {
        Debug.WriteLine("Capturing frame {0}", frames);
        //do the capturing to memory stream
    }

    Debug.WriteLine("DoWork cancelled");

    //do some other things like saving the gif etc
    e.Result = someResult;
}

private void backgroundWorker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
    Debug.WriteLine("RunWorkerCompleted running");
    capturing = false;
    //does something with the e.Result
}

My console output during a normal test is something like this:

Button clicked
DoWork running
Capturing frame 0
Capturing frame 1
Capturing frame 2
Capturing frame 3
Capturing frame 4
Capturing frame 5
Cancel button clicked
DoWork cancelled
The thread 0x2e4c has exited with code 0 (0x0).
DoWork running
DoWork cancelled
The thread 0x1010 has exited with code 0 (0x0).
RunWorkerCompleted running

The function seems to be running twice, I can see 2 separate threads exiting and also I don't seem to get any results from capturing. If I set a breakpoint inside the backgroundWorker_DoWork function and continue later, the first run does the capturing normally. What could be going on?

Body:
Its getting called twice because binding the event second time right after InitializeComponent().
Just comment those lines and it should work fine.
Here's the same example without the issue of running twice.

Sample Output
...
...
...
Capturing frame 2632
Capturing frame 2633
Capturing frame 2634
DoWork cancelled
RunWorkerCompleted running

public partial class Form1 : Form
    {
        private bool capturing = false;
        public Form1()
        {
            InitializeComponent();
            backgroundWorker1.WorkerSupportsCancellation = true;

  // Don't need to re-bind
            //backgroundWorker1.DoWork += backgroundWorker1_DoWork;
            //backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
            //backgroundWorker1.WorkerSupportsCancellation = true;
        }

private void captureBtn_Click(object sender, EventArgs e)
        {
            Debug.WriteLine("Button clicked");
            if (capturing) { return; }
            if (!backgroundWorker1.IsBusy)
            {
                backgroundWorker1.RunWorkerAsync();
            }
        }

        private void stopCaptureBtn_Click(object sender, EventArgs e)
        {
            if (backgroundWorker1.IsBusy)
            {
                backgroundWorker1.CancelAsync();
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            capturing = true;
            Debug.WriteLine("DoWork running");
            int frames = 1;

            while (!backgroundWorker1.CancellationPending)
            {
                Debug.WriteLine("Capturing frame {0}", frames);
                //do the capturing to memory stream
                frames++;
            }

            Debug.WriteLine("DoWork cancelled");

            //do some other things like saving the gif etc
            //e.Result = someResult;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Debug.WriteLine("RunWorkerCompleted running");
            capturing = false;
            //does something with the e.Result
        }


问:
Intel compiler backwards compatible to Compaq compiler
I have a recent edition of the Intel Compiler on my computer.  However, I am trying to run an old fortran file designed to run on an old Compaq compiler.  It seems to have a problem with USE MSIMSL, USE File.f90, as well as ALLOCATE

Is there a way to have the Intel compile work as the old Compaq compiler?

答:
If you don't have the specific Intel Fortran compiler which includes a version of the visual numerics IMSL library, then I don't think you are going to get this to work, short of either buying the IMSL library or porting the code to use something else, like Intel's MKL or whatever open source stuff you can scrape off netlib.

If you do have IMSL, then you will need to change USE MIMSL to USE NUMERICAL_LIBRARIES and then add a few compiler version specific incantations to get the IMSL inclusion to build.

The USE command is clearly syntactically incorrect, and the fact it worked in the DEC/Compaq compiler is probably only accidental. In Fortran 90 and 95 USE is intended for module importing. They should be changed to INCLUDE.

ALLOCATE is also a standard feature of Fortran 90 and 95. Without more information about what the exact nature of the problem is, it really isn't possible to suggest what might be happening.

Finally, 10 seconds with google found me this link which discusses migrating from Compaq to Intel compilers. Perhaps it will be of use. Best of luck.


问:
Insert select2 tags jQuery array in PHP
I have seen many threads on stackoverflow about this concern but I couldn't achieve that so that made this post again. I am using select2 jQuery plugin where I want to insert Tags in SQL using PHP. Like [Data, Data, Data]

I try to do that which I learn through google, well I am professionalize in this, I am new in PHP.
Please help 'How I Insert this in DB where show , between two words as above I mentioned in Like'

My Code Is

```<code>if(isset($_POST['submit'])) {
    $name = "Your_Name";
    $email = "Your_Email";

    $stmt = $con->prepare("INSERT INTO `test` (`name`, `email`, `color_name`) VALUES (':name',':email',':color')");
    foreach ($data as $row)
    {
        ':name' = $name;
        ':email' = $email;
        ':color' = 'MYStatus'; //I want mention here Select2 Tags Data and insert in DB where [, (space)] every two words. like [Green, Red, Blue, Pink]
        $stmt->execute();
    }
  }
</code>```

```<code><!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://shashani-humanth.github.io/Notebook-AdminPanel/js/select2/select2.css">
</head>
<body>
<form class="bs-example form-horizontal" id="formid" method="POST" onSubmit="return validate();">

    <div class="form-group col-sm-6">
      <div>
        <input type="hidden" name="selectname[]" id="select2-tags" style="width:260px" value="brown"/>
      </div>
    </div>

    <div class="form-group">
        <div class="col-lg-offset-2 col-lg-10">
            <button type="submit" name="submit" class="btn btn-sm btn-default" id="submit">Save and Publish</button>
        </div>
    </div>
</form>
<script src="http://shashani-humanth.github.io/Notebook-AdminPanel/js/jquery.min.js"></script>
  <script src="http://shashani-humanth.github.io/Notebook-AdminPanel/js/bootstrap.js"></script>
<script src="http://shashani-humanth.github.io/Notebook-AdminPanel/js/select2/select2.min.js"></script>
<script type="text/javascript" language="javascript">
    if ($.fn.select2) {
      $("#select2-option").select2();
      $("#select2-tags").select2({
        tags:["Red", "Green", "Blue", "Pink"],
        tokenSeparators: [",", " "]}
      );
    }
</script>
</body>
</html>
</code>```

答:
Your form is likely being sent like this:

```<code>Array
(
    [selectname] => Array
        (
            [0] => brown,Green,Blue
        )

)
</code>```

So, since you are wanting it to be formatted as brown, Green, Blue, then you can explode() and implode() or just use a str_replace():

```<code># Exploding, imploding
$tags = implode(", ", explode(",", $_POST['selectname'][0]));

# String replace would be
$tags = str_replace(',', ', ', $_POST['selectname'][0]);
</code>```

If you are trying to split up that string to insert each tag separately, you would use explode() on the comma, then loop the results of the explode().

I would probably use trim() in there to remove empty space, just incase. Also, if you want to make sure they are all formatted the same, you might want to do ucwords() to make sure each word has an uppercase as the first letter (your default value brown is all lower and the reset have the first letters upper).

If you do method 1, you can apply a ucfirst() and trim() if you use array_map() on the exploded string:

```<code># A full combination of functions
$tags = implode(", ", array_map(function($v){
    return ucfirst(trim($v));
}, explode(",", $_POST['selectname'][0])));
</code>```

would give you the string:

```<code>Brown, Green, Blue
</code>```

EDIT:

Since you are actually storing per row, you can fetch back to an array using a select:

```<code>function getColorTags($name, $con)
{
    # Query by name, just return the color_name field though
    $query = $con->prepare("SELECT `color_name` FROM `test` WHERE `name` = ?");
    # Execute the query with bind value
    $query->execute([$name]);
    # Loop the results
    while($result = $query->fetch(\PDO::FETCH_ASSOC)) {
        # Store the tags
        $row[] = $result['color_name'];
    }
    # Return the tags or an empty array
    return (isset($row))? $row : [];
}
</code>```

To use:

```<code># Fetch the tags by name, make sure to inject the database connection
$tags = getColorTags('Some Name', $con);
# Print out the array
print_r($tags);
</code>```

EDIT #2

To do it both together on the same page, you would just use json_encode():

```<code><?php
function insertTags($data, $email, $name, $con)
{
    $stmt = $con->prepare("INSERT INTO `test` (`name`, `email`, `color_name`) VALUES (?,?,?)");

    foreach ($data as $string) {
        # Explode and filter the tags from the js
        $arr = array_filter(array_map('trim', explode(',', $string)));
        # Loop the "selectname"
        foreach($arr as $tag) {
            # Execute all the rows
            $stmt->execute([$name, $email, $tag]);
        }
    }
}
# This fetches using the email as the primary key
function getColorTags($email, $con)
{
    # Query by name, just return the color_name field though
    $query = $con->prepare("SELECT `color_name` FROM `test` WHERE `email` = ?");
    # Execute the query with bind value
    $query->execute([$name]);
    # Loop the results
    while($result = $query->fetch(\PDO::FETCH_ASSOC)) {
        # Store the tags
        $row[] = $result['color_name'];
    }
    # Return the tags or an empty array
    return (isset($row))? $row : [];
}

# Pull these out so you can use them in general
$name = "Your_Name"; // Assuming this is from the session
$email = "Your_Email"; // Assuming this is from the session
# Here is where you insert
if(isset($_POST['submit'])) {
    # This will insert your tags separately on new rows
    insertTags($_POST['selectname'], $email, $name, $con);
    # This will pull them back from the database (helpful if they already have some in there)
    $tags = getColorTags($email, $con);
}
# Here you check if there are tags already generated after submission,
# if not, then pull them.
if(!isset($tags))
    $tags = getColorTags($email, $con);
?><!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://shashani-humanth.github.io/Notebook-AdminPanel/js/select2/select2.css">
</head>
<body>
<form class="bs-example form-horizontal" id="formid" method="POST" onSubmit="return validate();">
    <div class="form-group col-sm-6">
        <div>
            <input type="hidden" name="selectname[]" id="select2-tags" style="width:260px" value="brown"/>
        </div>
    </div>

    <div class="form-group">
        <div class="col-lg-offset-2 col-lg-10">
            <button type="submit" name="submit" class="btn btn-sm btn-default" id="submit">Save and Publish</button>
        </div>
    </div>
</form>

<script src="http://shashani-humanth.github.io/Notebook-AdminPanel/js/jquery.min.js"></script>
  <script src="http://shashani-humanth.github.io/Notebook-AdminPanel/js/bootstrap.js"></script>
<script src="http://shashani-humanth.github.io/Notebook-AdminPanel/js/select2/select2.min.js"></script>

<script type="text/javascript" language="javascript">
    if ($.fn.select2) {
        $("#select2-option").select2();
        $("#select2-tags").select2({
            // Now use this native function to echo the array back to JS
            tags: <?php echo json_encode($tags) ?>,
            tokenSeparators: [",", " "]}
        );
    }
</script>

</body>
</html>
</code>```

Title: Insert select2 tags jQuery array in PHP

Body:
I have seen many threads on stackoverflow about this concern but I couldn't achieve that so that made this post again. I am using select2 jQuery plugin where I want to insert Tags in SQL using PHP. Like [Data, Data, Data]

I try to do that which I learn through google, well I am professionalize in this, I am new in PHP.
Please help 'How I Insert this in DB where show , between two words as above I mentioned in Like'

My Code Is

if(isset($_POST['submit'])) {
    $name = "Your_Name";
    $email = "Your_Email";

    $stmt = $con->prepare("INSERT INTO `test` (`name`, `email`, `color_name`) VALUES (':name',':email',':color')");
    foreach ($data as $row)
    {
        ':name' = $name;
        ':email' = $email;
        ':color' = 'MYStatus'; //I want mention here Select2 Tags Data and insert in DB where [, (space)] every two words. like [Green, Red, Blue, Pink]
        $stmt->execute();
    }
  }

<!DOCTYPE html>

<link rel="stylesheet" type="text/css" href="http://shashani-humanth.github.io/Notebook-AdminPanel/js/select2/select2.css">

<form class="bs-example form-horizontal" id="formid" method="POST" onSubmit="return validate();">

        <input type="hidden" name="selectname[]" id="select2-tags" style="width:260px" value="brown"/>

            <button type="submit" name="submit" class="btn btn-sm btn-default" id="submit">Save and Publish</button>

</form>

Body:
Your form is likely being sent like this:

Array
(
    [selectname] => Array
        (
            [0] => brown,Green,Blue
        )

)

So, since you are wanting it to be formatted as brown, Green, Blue, then you can explode() and implode() or just use a str_replace():

# Exploding, imploding
$tags = implode(", ", explode(",", $_POST['selectname'][0]));

# String replace would be
$tags = str_replace(',', ', ', $_POST['selectname'][0]);

If you are trying to split up that string to insert each tag separately, you would use explode() on the comma, then loop the results of the explode().

I would probably use trim() in there to remove empty space, just incase. Also, if you want to make sure they are all formatted the same, you might want to do ucwords() to make sure each word has an uppercase as the first letter (your default value brown is all lower and the reset have the first letters upper).

If you do method 1, you can apply a ucfirst() and trim() if you use array_map() on the exploded string:

# A full combination of functions
$tags = implode(", ", array_map(function($v){
    return ucfirst(trim($v));
}, explode(",", $_POST['selectname'][0])));

would give you the string:

Brown, Green, Blue

EDIT:

Since you are actually storing per row, you can fetch back to an array using a select:

function getColorTags($name, $con)
{
    # Query by name, just return the color_name field though
    $query = $con->prepare("SELECT `color_name` FROM `test` WHERE `name` = ?");
    # Execute the query with bind value
    $query->execute([$name]);
    # Loop the results
    while($result = $query->fetch(\PDO::FETCH_ASSOC)) {
        # Store the tags
        $row[] = $result['color_name'];
    }
    # Return the tags or an empty array
    return (isset($row))? $row : [];
}

To use:

# Fetch the tags by name, make sure to inject the database connection
$tags = getColorTags('Some Name', $con);
# Print out the array
print_r($tags);

EDIT #2

To do it both together on the same page, you would just use json_encode():

<?php
function insertTags($data, $email, $name, $con)
{
    $stmt = $con->prepare("INSERT INTO `test` (`name`, `email`, `color_name`) VALUES (?,?,?)");

    foreach ($data as $string) {
        # Explode and filter the tags from the js
        $arr = array_filter(array_map('trim', explode(',', $string)));
        # Loop the "selectname"
        foreach($arr as $tag) {
            # Execute all the rows
            $stmt->execute([$name, $email, $tag]);
        }
    }
}
# This fetches using the email as the primary key
function getColorTags($email, $con)
{
    # Query by name, just return the color_name field though
    $query = $con->prepare("SELECT `color_name` FROM `test` WHERE `email` = ?");
    # Execute the query with bind value
    $query->execute([$name]);
    # Loop the results
    while($result = $query->fetch(\PDO::FETCH_ASSOC)) {
        # Store the tags
        $row[] = $result['color_name'];
    }
    # Return the tags or an empty array
    return (isset($row))? $row : [];
}

# Pull these out so you can use them in general
$name = "Your_Name"; // Assuming this is from the session
$email = "Your_Email"; // Assuming this is from the session
# Here is where you insert
if(isset($_POST['submit'])) {
    # This will insert your tags separately on new rows
    insertTags($_POST['selectname'], $email, $name, $con);
    # This will pull them back from the database (helpful if they already have some in there)
    $tags = getColorTags($email, $con);
}
# Here you check if there are tags already generated after submission,
# if not, then pull them.
if(!isset($tags))
    $tags = getColorTags($email, $con);
?><!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://shashani-humanth.github.io/Notebook-AdminPanel/js/select2/select2.css">
</head>
<body>
<form class="bs-example form-horizontal" id="formid" method="POST" onSubmit="return validate();">
    <div class="form-group col-sm-6">
        <div>
            <input type="hidden" name="selectname[]" id="select2-tags" style="width:260px" value="brown"/>
        </div>
    </div>

    <div class="form-group">
        <div class="col-lg-offset-2 col-lg-10">
            <button type="submit" name="submit" class="btn btn-sm btn-default" id="submit">Save and Publish</button>
        </div>
    </div>
</form>

<script src="http://shashani-humanth.github.io/Notebook-AdminPanel/js/jquery.min.js"></script>
  <script src="http://shashani-humanth.github.io/Notebook-AdminPanel/js/bootstrap.js"></script>
<script src="http://shashani-humanth.github.io/Notebook-AdminPanel/js/select2/select2.min.js"></script>

<script type="text/javascript" language="javascript">
    if ($.fn.select2) {
        $("#select2-option").select2();
        $("#select2-tags").select2({
            // Now use this native function to echo the array back to JS
            tags: <?php echo json_encode($tags) ?>,
            tokenSeparators: [",", " "]}
        );
    }
</script>

</body>
</html>


问:
Static files not found in Django 1.4
While deploying a Django app. I am having problem with static files. I am having JS and CSS files in static directory. But browser is not able to find those files. I am having same files and settings on local machine that is ubuntu same as server OS, and have working on local. Although it has same settings but I am pasting that static directory and files setting below.

```<code># Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = os.path.join(ROOT_PATH,'static')

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS =(
                os.path.join(ROOT_PATH,'static'),
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
</code>```

Here root path in above code is defined before that is :

```<code>import os
#from django.contrib.sites.models import Site
ROOT_PATH = os.path.dirname(__file__)
</code>```

I am using mod_wsgi with apache2, in my understanding it should find the files when it is loading /somefoldername then browser should go in that directory but didn't get where is problem. To know about environment and wsgi settings e.t.c. I am following here is question in which I posted my wsgi file details and way it is working: 500 server error on Django site after shifting to server

I am many time having issues while finding apps and other templates and modules etc. even in syncdb commmand on server, for templates I appended root path and it started working also added project path in wsgi file but still that static files issue is not solved.

答:
Warning

This will only work if DEBUG is True.

That's because this view is grossly inefficient and probably insecure. This is only intended for local development, and should never be used in production.

If you still need to server static locally (e.g. for testing without debug) you can run dev server in insecure mode:

```<code>python manage.py runserver --insecure
</code>```

Enjoy cheer :)

Title: Static files not found in Django 1.4

Body:
While deploying a Django app. I am having problem with static files. I am having JS and CSS files in static directory. But browser is not able to find those files. I am having same files and settings on local machine that is ubuntu same as server OS, and have working on local. Although it has same settings but I am pasting that static directory and files setting below.

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = os.path.join(ROOT_PATH,'static')

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS =(
                os.path.join(ROOT_PATH,'static'),
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

Here root path in above code is defined before that is :

import os
#from django.contrib.sites.models import Site
ROOT_PATH = os.path.dirname(__file__)

I am using mod_wsgi with apache2, in my understanding it should find the files when it is loading /somefoldername then browser should go in that directory but didn't get where is problem. To know about environment and wsgi settings e.t.c. I am following here is question in which I posted my wsgi file details and way it is working: 500 server error on Django site after shifting to server

I am many time having issues while finding apps and other templates and modules etc. even in syncdb commmand on server, for templates I appended root path and it started working also added project path in wsgi file but still that static files issue is not solved.

Body:
Warning

This will only work if DEBUG is True.

That's because this view is grossly inefficient and probably insecure. This is only intended for local development, and should never be used in production.

If you still need to server static locally (e.g. for testing without debug) you can run dev server in insecure mode:

python manage.py runserver --insecure

Enjoy cheer :)


问:
Accessing and showing modal located in another component
I have a PersonList component, wherever user clicks on List.Item I want to pass some details like personId to PersonModal and display it. I'm using Ant Design component for modal.

Below is what I tried, but unfortunately I'm getting an error like:

Warning: Can't call setState on a component that is not yet mounted.
  This is a no-op, but it might indicate a bug in your application.
  Instead, assign to this.state directly or define a state = {};
  class property with the desired state in the PersonModal component.

PersonModal.js

```<code>import React from "react";
import {Modal} from "antd";

class PersonModal extends React.Component {
    constructor(props) {
        super(props);
        console.log(this.props.personId)
    }

    state = { visible: false };

    showModal = () => {
        this.setState({
            visible: true,
        });
    };

    // handleOk (...)
    // handleCancel (...)

    render() {
        return <Modal
            title="Basic Modal"
            visible={this.state.visible}
            onOk={this.handleOk}
            onCancel={this.handleCancel}
        >
            Modal body
        </Modal>
    }
}
export default PersonModal;
</code>```

PersonList.js

```<code>import React from "react";
import {Icon, Input, List, Avatar} from "antd";
import PersonModal from "PersonModal/PersonModal"

class PersonList extends React.Component {

    showModal(personId) {
        const modal = new PersonModal({personId: 123})
        modal.showModal()
    }

    render() {
        const persons = this.props.list;
        return (
            <div>
            <List
                itemLayout="horizontal"
                dataSource={persons}
                renderItem={item => (
                    <>
                    <List.Item onClick={this.showModal(123)} style={{cursor: 'pointer'}}>
                        <List.Item.Meta
                            avatar={<Avatar src="avatar.png"/>}
                            title={<span>{item.firstName} {item.lastName}</span>}
                            description={<span>{item.city}, {item.country}</span>}
                        />
                    </List.Item>
                    </>
                )}
            />
            </div>
        );
    }
}
</code>```

What would be correct way of approaching this problem? Since I am new to React i suppose this is not a correct approach.

Reproduced issue on stackblitz here

答:
you need to track the visible state of the PersonModal in the PersonList component. You should have a boolean variable to control the visibility of the PersonModal.

and the PersonModal will not control its visiblity state, rather it will get it from its clients , in your case the client is PersonList. so lets begin with the code

first, edit the PersonModal component to expect props from its clients

```<code>class PersonModal extends React.Component {
    // handleOk (...)
    // handleCancel (...)

    handleCancel = () => {

        // because the client controls the visivlity state of the component
        this.props.hideModal();
    }

    render() {
         /// this.props.isVisible is required, and it will be a boolean true or false.
        const shouldBeVisible = this.props.isVisible;

        return <Modal
            title="Basic Modal"
            visible={shouldBeVisible}
            onOk={this.handleOk}
            onCancel={this.handleCancel}
        >
            Modal body
        </Modal>
    }
}
export default PersonModal;

</code>```

so now your PersonModal component expexts a prop; which is isVisible prop.

```<code>
class PersonList extends React.Component {

    state = {
        // the client controls the visibility of the modal with this state key;
        showModal: false,
        personId: null
    }

    // edited
    showModal = (personId) => {
       // set state to update the UI and show the PersonModal
        this.setState({
            showModal: true,
            personId: personId
        });
    }

     hideModal= () => this.setState({showModal: false});

    render() {
        const persons = this.props.list;
        return (
            <div>
             // now PersonModal will only be visible when the parent of it tells it to
            <PersonModal
            isVisible = {this.state.showModal}
                hideModal= {this.hideModal}
/>
            <List
                itemLayout="horizontal"
                dataSource={persons}
                renderItem={item => (
                    <>
                    <List.Item onClick={() => this.showModal(123)} style={{cursor: 'pointer'}}>
                        <List.Item.Meta
                            avatar={<Avatar src="avatar.png"/>}
                            title={<span>{item.firstName} {item.lastName}</span>}
                            description={<span>{item.city}, {item.country}</span>}
                        />
                    </List.Item>
                    </>
                )}
            />
            </div>
        );
    }
}
</code>```

hope it helps you;

this is how the problem is approached in the React world

Body:
I have a PersonList component, wherever user clicks on List.Item I want to pass some details like personId to PersonModal and display it. I'm using Ant Design component for modal.

Below is what I tried, but unfortunately I'm getting an error like:

Warning: Can't call setState on a component that is not yet mounted.
  This is a no-op, but it might indicate a bug in your application.
  Instead, assign to this.state directly or define a state = {};
  class property with the desired state in the PersonModal component.

PersonModal.js

import React from "react";
import {Modal} from "antd";

class PersonModal extends React.Component {
    constructor(props) {
        super(props);
        console.log(this.props.personId)
    }

    state = { visible: false };

    showModal = () => {
        this.setState({
            visible: true,
        });
    };

    // handleOk (...)
    // handleCancel (...)

    render() {
        return <Modal
            title="Basic Modal"
            visible={this.state.visible}
            onOk={this.handleOk}
            onCancel={this.handleCancel}
        >
            Modal body
        </Modal>
    }
}
export default PersonModal;

PersonList.js

import React from "react";
import {Icon, Input, List, Avatar} from "antd";
import PersonModal from "PersonModal/PersonModal"

class PersonList extends React.Component {

    showModal(personId) {
        const modal = new PersonModal({personId: 123})
        modal.showModal()
    }

    render() {
        const persons = this.props.list;
        return (

            <List
                itemLayout="horizontal"
                dataSource={persons}
                renderItem={item => (
                    <>
                    <List.Item onClick={this.showModal(123)} style={{cursor: 'pointer'}}>
                        <List.Item.Meta
                            avatar={<Avatar src="avatar.png"/>}
                            title={{item.firstName} {item.lastName}}
                            description={{item.city}, {item.country}}
                        />
                    </List.Item>
                    </>
                )}
            />

        );
    }
}

What would be correct way of approaching this problem? Since I am new to React i suppose this is not a correct approach.

Reproduced issue on stackblitz here

Body:
you need to track the visible state of the PersonModal in the PersonList component. You should have a boolean variable to control the visibility of the PersonModal.

and the PersonModal will not control its visiblity state, rather it will get it from its clients , in your case the client is PersonList. so lets begin with the code

first, edit the PersonModal component to expect props from its clients

class PersonModal extends React.Component {
    // handleOk (...)
    // handleCancel (...)

    handleCancel = () => {

        // because the client controls the visivlity state of the component
        this.props.hideModal();
    }

    render() {
         /// this.props.isVisible is required, and it will be a boolean true or false.
        const shouldBeVisible = this.props.isVisible;

        return <Modal
            title="Basic Modal"
            visible={shouldBeVisible}
            onOk={this.handleOk}
            onCancel={this.handleCancel}
        >
            Modal body
        </Modal>
    }
}
export default PersonModal;

so now your PersonModal component expexts a prop; which is isVisible prop.

class PersonList extends React.Component {

    state = {
        // the client controls the visibility of the modal with this state key;
        showModal: false,
        personId: null
    }

    // edited
    showModal = (personId) => {
       // set state to update the UI and show the PersonModal
        this.setState({
            showModal: true,
            personId: personId
        });
    }

     hideModal= () => this.setState({showModal: false});

    render() {
        const persons = this.props.list;
        return (
            <div>
             // now PersonModal will only be visible when the parent of it tells it to
            <PersonModal
            isVisible = {this.state.showModal}
                hideModal= {this.hideModal}
/>
            <List
                itemLayout="horizontal"
                dataSource={persons}
                renderItem={item => (
                    <>
                    <List.Item onClick={() => this.showModal(123)} style={{cursor: 'pointer'}}>
                        <List.Item.Meta
                            avatar={<Avatar src="avatar.png"/>}
                            title={<span>{item.firstName} {item.lastName}</span>}
                            description={<span>{item.city}, {item.country}</span>}
                        />
                    </List.Item>
                    </>
                )}
            />
            </div>
        );
    }
}

hope it helps you;

this is how the problem is approached in the React world


问:
How to load only the first related data with EF Core
i have got an issue that i identified as that:

let's suppose these objects.

```<code>public class Order{
    int id{get;set;}
    string name {get;set;}
    public virtual User User {get; set;}
}

public class OrderItem{
    int id{get;set;}
    string name {get;set;}
    public virtual Order Order {get; set;}
}

public class User{
    int id{get;set;}
    string name {get;set;}

}
</code>```

So the problem is when i tried to get an query like this

```<code>context.Order
.Where(pre => pre.Id == Id)
.OrderByDescending(pre => pre.Id)
.Skip(( pageNumber - 1 ) * pageSize)
.Take(pageSize)
.Include(pre => pre.OrderItem)
.Select(pre => new
  {
    pre.name,
    pre.OrderItem
  }).ToList()

</code>```

All the problem happens with the include OrderItem, when i get it on select the orderItem come with all their related data.

My final object became like it:

```<code>{
  name,
  OrderItem :{
    name,
    Order : {
     Id,
     name,
     User: {
       name,
       Id
     }
    }
  }
}
</code>```

but what i want is just the name and orderItem:

```<code>{
  name,
  OrderItem :{
    name
  }
}
</code>```

答:
Follow up on @kit's comment, then one solution could be:</p>

```<code>context.Order
.Where(pre => pre.Id == Id)
.OrderByDescending(pre => pre.Id)
.Skip(( pageNumber - 1 ) * pageSize)
.Take(pageSize)
.Include(pre => pre.OrderItem)
.Select(pre => new
  {
    pre.name,
    OrderItem = new {
      pre.OrderItem.name
    }
  }).ToList()
</code>```

Body:
i have got an issue that i identified as that:

let's suppose these objects.

public class Order{
    int id{get;set;}
    string name {get;set;}
    public virtual User User {get; set;}
}

public class OrderItem{
    int id{get;set;}
    string name {get;set;}
    public virtual Order Order {get; set;}
}

public class User{
    int id{get;set;}
    string name {get;set;}

}

So the problem is when i tried to get an query like this

context.Order
.Where(pre => pre.Id == Id)
.OrderByDescending(pre => pre.Id)
.Skip(( pageNumber - 1 ) * pageSize)
.Take(pageSize)
.Include(pre => pre.OrderItem)
.Select(pre => new
  {
    pre.name,
    pre.OrderItem
  }).ToList()

All the problem happens with the include OrderItem, when i get it on select the orderItem come with all their related data.

My final object became like it:

{
  name,
  OrderItem :{
    name,
    Order : {
     Id,
     name,
     User: {
       name,
       Id
     }
    }
  }
}

but what i want is just the name and orderItem:

{
  name,
  OrderItem :{
    name
  }
}

Body:
Follow up on @kit's comment, then one solution could be:

context.Order
.Where(pre => pre.Id == Id)
.OrderByDescending(pre => pre.Id)
.Skip(( pageNumber - 1 ) * pageSize)
.Take(pageSize)
.Include(pre => pre.OrderItem)
.Select(pre => new
  {
    pre.name,
    OrderItem = new {
      pre.OrderItem.name
    }
  }).ToList()


问:
recursive html-loader includes not working
I am moving a project that used grunt across to webpack.

I am using HTML snippets a lot to reuse HTML components across various files.

For HTML includes that do not require passing of variables I am using webpack html-loader.

For those that do I am using mustache and html-loader together.

This is working well at the top level, but is not recursive, so a snippet that contains another snippet just shows the include code, and not the interpolated HTML.

The easiest way to demonstrate was to create a simple repo that demonstrates the problem:
https://github.com/JamieMcDonnell/webpack-html-loader

My HTML template is:

    <title>Getting Started</title>

      <%= require('html-loader?interpolate!./snippets/no-variables.html') %>
      <%= require('mustache-loader!html-loader?interpolate!./snippets/variable.html')({someVariable: 'MY VARIABLE'}) %>
      <%= require('html-loader?interpolate!./snippets/recursive.html') %>

```

<p>The first 2 includes are imported without a problem.</p>

<p>The 3rd, recursive.html, looks like:</p>

<pre class="lang-html prettyprint-override"><code><h1>I am a top level include</h1>
<%= require('html-loader?interpolate!./sub/sub.html') %>
<%= require('mustache-loader!html-loader?interpolate!./sub/variable.html')({someVariable: 'MY SUB VARIABLE'}) %>
</code>```

sub/sub.html and sub/variable.html are super simple, and should work. I suppose I am missing a property or something to enable recursive loading or something, but am unable to find it.

Please check the /dist/ folder for the result. Can anyone see what I am doing wrong here?

Thanks so much for your time and help ;)

答:
You need to import nested files like</p>

```<code>${require('html-loader?!./sub/sub.html')}
${require('mustache-loader!html-loader?!./sub/variable.html')({someVariable: 'MY SUB VARIABLE'})}
</code>```

Body:
I am moving a project that used grunt across to webpack.

I am using HTML snippets a lot to reuse HTML components across various files.

For HTML includes that do not require passing of variables I am using webpack html-loader.

For those that do I am using mustache and html-loader together.

This is working well at the top level, but is not recursive, so a snippet that contains another snippet just shows the include code, and not the interpolated HTML.

The easiest way to demonstrate was to create a simple repo that demonstrates the problem:
https://github.com/JamieMcDonnell/webpack-html-loader

My HTML template is:

    <title>Getting Started</title>

      <%= require('html-loader?interpolate!./snippets/no-variables.html') %>
      <%= require('mustache-loader!html-loader?interpolate!./snippets/variable.html')({someVariable: 'MY VARIABLE'}) %>
      <%= require('html-loader?interpolate!./snippets/recursive.html') %>

The first 2 includes are imported without a problem.

The 3rd, recursive.html, looks like:

I am a top level include

<%= require('html-loader?interpolate!./sub/sub.html') %>
<%= require('mustache-loader!html-loader?interpolate!./sub/variable.html')({someVariable: 'MY SUB VARIABLE'}) %>

sub/sub.html and sub/variable.html are super simple, and should work. I suppose I am missing a property or something to enable recursive loading or something, but am unable to find it.

Please check the /dist/ folder for the result. Can anyone see what I am doing wrong here?

Thanks so much for your time and help ;)

Body:
You need to import nested files like

${require('html-loader?!./sub/sub.html')}
${require('mustache-loader!html-loader?!./sub/variable.html')({someVariable: 'MY SUB VARIABLE'})}