问:
Use R to Randomly Assign of Participants to Treatments on a Daily Basis
The Problem:

I am attempting to use R to generate a random study design where half of the participants are randomly assigned to "Treatement 1" and the other half are assigned to "Treatment 2". However, because half of the subjects are male and half are female and I also want to ensure that an equal number of males and females are exposed to each treatment, half of the males and females should be assigned to "Treatment 1" and the remaining half should be assigned to "Treatment 2".

There are two complications to this design: (1) This is a yearlong study and the assignment of participants to treatment must occur on a daily basis; and (2) Each participant must be exposed to "Treatment 1" a minimum 10 times in a 28 day period.

Is this even possible to automate this in the R interface? I assume so, but I think my beginner status as an R programmer prohibits me from finding the solution on my own. I have been struggling for days to figure out how to actualize this, and have looked through many similar-sounding posts on this site that were not able to be successfully applied here. I am hoping someone out there knows some tricks that could help me get unstuck in solving this problem, any advice would be greatly appreciated!

What I Have Tried:

Specific Information

```<code># There are 16 participants
p <- c("P01", "P02", "P03", "P04", "P05", "P06", "P07", "P08", "P09", "P10", "P11", "P12", "P13", "P14", "P15", "P16")

# Half are male and half are female
g <- c(rep("M", 8), rep("F", 8))

# I make a dataframe but this may not be necessary
df <- cbind.data.frame(p,g)

# There are 365 days in one year
d <- seq(1,365,1)
</code>```

...unfortunately, I am not sure how to proceed from here.

Ideal Outcome:

I am envisioning something approximate to this table as the outcome:

Basically there is a column for each participant and a row for each day. Associated with each day is an assignment to either Treatment 1 (T1) or Treatment 2 (T2), with 4 of the 8 males and 4 of the 8 females being assigned to T1 and the remainder to T2. These treatments are reassigned every day for 1 year. Not depicted in this chart is the need for each participant to be exposed to T1 at least 10 times in a 28-day period. The table does not have to look like that if something else makes more sense!

答:
Here is my approach. Surely it can be optimized, but I want to share my idea:

library(tidyverse)
p <- c("P01", "P02", "P03", "P04", "P05", "P06", "P07", "P08", "P09", "P10", "P11", "P12", "P13", "P14", "P15", "P16")

g <- c(rep("M", 8), rep("F", 8))

df <- data.frame(participant=p, sex=g)
```

<p>First I create a data.frame for 13 cycles with 28 days. This gives us 13*28=364 days.</p>

<pre class="lang-r prettyprint-override"><code>days <- data.frame(day=rep(1:28, 13), cycle=rep(1:13, each=28))
df <- merge(df, days)  # merge/cross_join with df
</code>```

Now I build a function that creates a logical vector for each group (male/female) with the condition "at least 10 times TRUE per participant"

rand_assign <- function(n_participants=16){
  # create all possible combinations with 50 % treatment 1, 50 % treatment 2
  comb <- list(0:1) %>%
    rep(n_participants/2) %>%
    expand.grid() %>%
    filter(rowSums(.)==n_participants/4)

  save_list <- list()
  for (i in 1:2) {
    repeat {
      a <- comb %>%
        nrow() %>%
        seq(1,.,1) %>%
        sample(28, replace=TRUE) %>%
        slice(comb,.)
      if (all(colSums(a) >= 10)) {
        break
      }
    }
    save_list[[i]] <- a
  }

  c <- save_list %>%
    cbind.data.frame() %>%
    t() %>%
    as.vector
  return(c)
}
```

<p>Last step is combining the vector with the given data.frame</p>

<pre class="lang-r prettyprint-override"><code>df %>%
  group_by(cycle) %>%
  mutate(treat_1 := rand_assign()) %>%
  group_by(sex) %>%
  pivot_wider(names_from=c(sex,participant), values_from=treat_1) %>%
  mutate(day = 1:nrow(.)) %>%
  dplyr::select(-cycle)
</code>```

This yields

# A tibble: 364 x 17
     day M_P01 M_P02 M_P03 M_P04 M_P05 M_P06 M_P07 M_P08 F_P09 F_P10 F_P11 F_P12 F_P13
   <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int>
 1     1     1     1     0     1     0     1     0     0     0     0     1     1     1
 2     2     1     0     0     0     1     0     1     1     0     0     0     1     1
 3     3     0     1     0     1     0     1     1     0     0     1     0     1     0
 4     4     0     1     1     1     0     0     1     0     0     1     1     0     1
 5     5     0     1     1     0     1     0     0     1     1     0     0     1     1
 6     6     0     1     1     1     1     0     0     0     1     0     0     0     1
 7     7     0     0     0     1     1     1     0     1     0     0     1     0     0
 8     8     1     0     1     0     0     1     0     1     0     0     1     0     1
 9     9     0     1     0     1     1     0     1     0     1     0     1     1     0
10    10     1     1     0     0     1     1     0     0     1     1     0     0     0
```

with 1 and 0 corresponding to Treatment 1 or 2.

Body:
The Problem:

I am attempting to use R to generate a random study design where half of the participants are randomly assigned to "Treatement 1" and the other half are assigned to "Treatment 2". However, because half of the subjects are male and half are female and I also want to ensure that an equal number of males and females are exposed to each treatment, half of the males and females should be assigned to "Treatment 1" and the remaining half should be assigned to "Treatment 2".

There are two complications to this design: (1) This is a yearlong study and the assignment of participants to treatment must occur on a daily basis; and (2) Each participant must be exposed to "Treatment 1" a minimum 10 times in a 28 day period.

Is this even possible to automate this in the R interface? I assume so, but I think my beginner status as an R programmer prohibits me from finding the solution on my own. I have been struggling for days to figure out how to actualize this, and have looked through many similar-sounding posts on this site that were not able to be successfully applied here. I am hoping someone out there knows some tricks that could help me get unstuck in solving this problem, any advice would be greatly appreciated!

What I Have Tried:

Specific Information

# There are 16 participants
p <- c("P01", "P02", "P03", "P04", "P05", "P06", "P07", "P08", "P09", "P10", "P11", "P12", "P13", "P14", "P15", "P16")

# Half are male and half are female
g <- c(rep("M", 8), rep("F", 8))

# I make a dataframe but this may not be necessary
df <- cbind.data.frame(p,g)

# There are 365 days in one year
d <- seq(1,365,1)

...unfortunately, I am not sure how to proceed from here.

Ideal Outcome:

I am envisioning something approximate to this table as the outcome:

Basically there is a column for each participant and a row for each day. Associated with each day is an assignment to either Treatment 1 (T1) or Treatment 2 (T2), with 4 of the 8 males and 4 of the 8 females being assigned to T1 and the remainder to T2. These treatments are reassigned every day for 1 year. Not depicted in this chart is the need for each participant to be exposed to T1 at least 10 times in a 28-day period. The table does not have to look like that if something else makes more sense!

Body:
Here is my approach. Surely it can be optimized, but I want to share my idea:

library(tidyverse)
p <- c("P01", "P02", "P03", "P04", "P05", "P06", "P07", "P08", "P09", "P10", "P11", "P12", "P13", "P14", "P15", "P16")

g <- c(rep("M", 8), rep("F", 8))

df <- data.frame(participant=p, sex=g)

First I create a data.frame for 13 cycles with 28 days. This gives us 13*28=364 days.

days <- data.frame(day=rep(1:28, 13), cycle=rep(1:13, each=28))
df <- merge(df, days)  # merge/cross_join with df

Now I build a function that creates a logical vector for each group (male/female) with the condition "at least 10 times TRUE per participant"

rand_assign <- function(n_participants=16){
  # create all possible combinations with 50 % treatment 1, 50 % treatment 2
  comb <- list(0:1) %>%
    rep(n_participants/2) %>%
    expand.grid() %>%
    filter(rowSums(.)==n_participants/4)

  save_list <- list()
  for (i in 1:2) {
    repeat {
      a <- comb %>%
        nrow() %>%
        seq(1,.,1) %>%
        sample(28, replace=TRUE) %>%
        slice(comb,.)
      if (all(colSums(a) >= 10)) {
        break
      }
    }
    save_list[[i]] <- a
  }

  c <- save_list %>%
    cbind.data.frame() %>%
    t() %>%
    as.vector
  return(c)
}

Last step is combining the vector with the given data.frame

df %>%
  group_by(cycle) %>%
  mutate(treat_1 := rand_assign()) %>%
  group_by(sex) %>%
  pivot_wider(names_from=c(sex,participant), values_from=treat_1) %>%
  mutate(day = 1:nrow(.)) %>%
  dplyr::select(-cycle)

This yields

# A tibble: 364 x 17
     day M_P01 M_P02 M_P03 M_P04 M_P05 M_P06 M_P07 M_P08 F_P09 F_P10 F_P11 F_P12 F_P13
   <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int>
 1     1     1     1     0     1     0     1     0     0     0     0     1     1     1
 2     2     1     0     0     0     1     0     1     1     0     0     0     1     1
 3     3     0     1     0     1     0     1     1     0     0     1     0     1     0
 4     4     0     1     1     1     0     0     1     0     0     1     1     0     1
 5     5     0     1     1     0     1     0     0     1     1     0     0     1     1
 6     6     0     1     1     1     1     0     0     0     1     0     0     0     1
 7     7     0     0     0     1     1     1     0     1     0     0     1     0     0
 8     8     1     0     1     0     0     1     0     1     0     0     1     0     1
 9     9     0     1     0     1     1     0     1     0     1     0     1     1     0
10    10     1     1     0     0     1     1     0     0     1     1     0     0     0

with 1 and 0 corresponding to Treatment 1 or 2.


来源: stackexchange

问:
Error after cell insertion: invlalid number of sections
After receiving a new object, I call this func to insert a cell:

```<code>private func addCellToTheTop(recipe: Recipe) {
    guard let recipeTableView = self.recipeTableView else { return }
    recipesForShow.insert(recipe, at: 0)
    recipeTableView.beginUpdates()
    recipeTableView.insertRows(at: [IndexPath.init(row: 0, section: 0)], with: .automatic)
    recipeTableView.endUpdates()
}
</code>```

But I get an error

Why the number of section does not match?

If it is important:

```<code>func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
}

func numberOfSections(in tableView: UITableView) -> Int {
        return recipesForShow.count
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return TableCellConfig.spaceBetweenCells
}

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UIView()
        headerView.backgroundColor = UIColor.clear
        return headerView
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    //...
}
</code>```

答:
You are getting this exception because you are appending a new element to the array that is being used to determine the numberOfSection whereas you are inserting a new row into the tableView. To fix this you need to insert section instead of inserting new row, here's how:

recipeTableView.insertSections([0], with: .automatic)
```

ContentLicense: CC BY-SA 4.0

Body:
After receiving a new object, I call this func to insert a cell:

private func addCellToTheTop(recipe: Recipe) {
    guard let recipeTableView = self.recipeTableView else { return }
    recipesForShow.insert(recipe, at: 0)
    recipeTableView.beginUpdates()
    recipeTableView.insertRows(at: [IndexPath.init(row: 0, section: 0)], with: .automatic)
    recipeTableView.endUpdates()
}

But I get an error

Why the number of section does not match?

If it is important:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
}

func numberOfSections(in tableView: UITableView) -> Int {
        return recipesForShow.count
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return TableCellConfig.spaceBetweenCells
}

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UIView()
        headerView.backgroundColor = UIColor.clear
        return headerView
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    //...
}


问:
iPad - General Network->What is the UI control?
In the below image, what is the UI control used to create the "Other Network" dialog? We need to create a similar non-full-screen popup.

答: It should be a view controller presented modally using UIModalPresentationFormSheet as its modalPresentationStyle.

ContentLicense: CC BY-SA 3.0


问:
How can I send input parameter data to a report on a dashboard in Splunk
I am using Splunk to create a dashboard.  I added a report to the dashboard that returns all of the data from the search into a table. I want to add a few input fields so the user to option to filter the data of the report.  The first input is a textbox field.  The default and initial values are set to with an *.  That I hope means everything.
This is the xml created from the dashboard:

```<code><form>
  <label>Thru Train Dashboard</label>
  <fieldset submitButton="false" autoRun="true">
    <input type="text" token="purchCostReferenceToken" searchWhenChanged="true">
      <label>TMS Reference Number</label>
      <default>*</default>
      <initialValue>*</initialValue>
    </input>
  </fieldset>
  <row>
    <panel>
      <title>Thru Train XML DATA</title>
      <table>
        <search ref="ThruTrainReportNestedResults"></search>
        <option name="drilldown">row</option>
        <option name="rowNumbers">true</option>
      </table>
    </panel>
  </row>
</form>
</code>```

I know I have to use the token value purchCostReferenceToken as an input to the report ThruTrainReportNestedResults.  But not sure how to do that since the report search as no input parameters.

This is the search query that creates the report, ThruTrainReportNestedResults

```<code> sourcetype... | xmlkv | rex max_match=0 "\<purchasedCostTripSegment\>(?P<segment>[^\<]+)" |eval Segments =  mvrange(1,mvcount(mvindex(segment, 0, 2))+1,1) | rex max_match=0 "\<carrier\>(?P<Carriers>[^\<]+)" | rex max_match=0 "\<billingMethod\>(?P<BillingMethod>[^\<]+)" | rex max_match=0 "<purchasedCostTripSegment>[\s\S]*?<origin>\s*<ns2:numberCode>(?P<Origin>\d+)"  | rex max_match=0 "<purchasedCostTripSegment>[\s\S]*?<destination>\s*<ns2:numberCode>(?P<Destination>\d+)" | rex max_match=0 "<purchasedCostTripSegment>[\s\S]*?<stopOff>\s*<ns2:stopOffLocation>\s*<ns2:numberCode>(?P<StopOffLocation>\d+)" | eval Time =_time | convert timeformat="%m-%d-%Y %H:%M:%S" ctime(Time) | table purchCostReference, eventType, Time, Segments, Carriers, BillingMethod, Origin, Destination, StopOffLocation | sort Time
</code>```

Is there a way to filter the results of this query from a dashboard using input data?  The input data that I would want to filter on would be the purchCostReference, eventType, and Segments

UPDATE
I removed the reference to the report and added the search string that creates the report but am getting the error Invalid character in tag name.  The search string is very long...

```<code><row>
    <panel>
      <title>Thru Train XML DATA</title>
      <table>
        <search base="baseSearch">
             <query>
                index... sourcetype="..." "<billingMethod>RULE</billingMethod>" "createMessage MsgSource" | xmlkv | rex max_match=0 "\<purchasedCostTripSegment\>(?P<segment>[^\<]+)" |eval Segments =  mvrange(1,mvcount(mvindex(segment, 0, 2))+1,1) | rex max_match=0 "\<carrier\>(?P<Carriers>[^\<]+)" | rex max_match=0 "\<billingMethod\>(?P<BillingMethod>[^\<]+)" | rex max_match=0 "<purchasedCostTripSegment>[\s\S]*?<origin>\s*<ns2:numberCode>(?P<Origin>\d+)"  | rex max_match=0 "<purchasedCostTripSegment>[\s\S]*?<destination>\s*<ns2:numberCode>(?P<Destination>\d+)" | rex max_match=0 "<purchasedCostTripSegment>[\s\S]*?<stopOff>\s*<ns2:stopOffLocation>\s*<ns2:numberCode>(?P<StopOffLocation>\d+)" | eval Time =_time | convert timeformat="%m-%d-%Y %H:%M:%S" ctime(Time) | table purchCostReference, eventType, Time, Segments, Carriers, BillingMethod, Origin, Destination, StopOffLocation | sort Time
            </query>
        </search>
        <option name="drilldown">row</option>
        <option name="rowNumbers">true</option>
      </table>
    </panel>
  </row>
</code>```

UPDATE I encoded the search query and added between the query tags with the token element as described in a previous comment.  I do not get an error but get no results either.  Just a blank table...

```<code><query>             ...sourcetype%....%22%20%22%3CbillingMethod%3ERULE%3C%2FbillingMethod%3E%22%20%22createMessage%20MsgSource%22%20%7C%20xmlkv%20%7C%20rex%20max_match%3D0%20%22%5C%3CpurchasedCostTripSegment%5C%3E%28%3FP%3Csegment%3E%5B%5E%5C%3C%5D%2B%29%22%20%7Ceval%20Segments%20%3D%20%20mvrange%281%2Cmvcount%28mvindex%28segment%2C%200%2C%202%29%29%2B1%2C1%29%20%7C%20rex%20max_match%3D0%20%22%5C%3Ccarrier%5C%3E%28%3FP%3CCarriers%3E%5B%5E%5C%3C%5D%2B%29%22%20%7C%20rex%20max_match%3D0%20%22%5C%3CbillingMethod%5C%3E%28%3FP%3CBillingMethod%3E%5B%5E%5C%3C%5D%2B%29%22%20%7C%20rex%20max_match%3D0%20%22%3CpurchasedCostTripSegment%3E%5B%5Cs%5CS%5D%2A%3F%3Corigin%3E%5Cs%2A%3Cns2%3AnumberCode%3E%28%3FP%3COrigin%3E%5Cd%2B%29%22%20%20%7C%20rex%20max_match%3D0%20%22%3CpurchasedCostTripSegment%3E%5B%5Cs%5CS%5D%2A%3F%3Cdestination%3E%5Cs%2A%3Cns2%3AnumberCode%3E%28%3FP%3CDestination%3E%5Cd%2B%29%22%20%7C%20rex%20max_match%3D0%20%22%3CpurchasedCostTripSegment%3E%5B%5Cs%5CS%5D%2A%3F%3CstopOff%3E%5Cs%2A%3Cns2%3AstopOffLocation%3E%5Cs%2A%3Cns2%3AnumberCode%3E%28%3FP%3CStopOffLocation%3E%5Cd%2B%29%22%20%7C%20eval%20Time%20%3D_time%20%7C%20convert%20timeformat%3D%22%25m-%25d-%25Y%20%25H%3A%25M%3A%25S%22%20ctime%28Time%29%20%7C%20table%20purchCostReference%2C%20eventType%2C%20Time%2C%20Segments%2C%20Carriers%2C%20BillingMethod%2C%20Origin%2C%20Destination%2C%20StopOffLocation%20%7C%20sort%20Time purchCostReference=$purchCostReferenceToken$
</query>
</code>```

This is a screen shot of the results:

UPDATE
I removed the complexity of the search so that it only has the index, source and sourcetype that is the same as the report and a text field to limit the search. Below is the query string:

```<code><query>index="indexname same as report" source="source name same as report" sourcetype="source type name same as report" "createMessage MsgSource"</query>
</code>```

It returns a blank dashboard with no error as pictured above.

UPDATE
I recreated the dashboard using the report query and have the search returning all of the table results.  I have an input for the reference number as a text box.  The token name is: purchCostReferenceToken

I want to limit the table results based on this token. This is the query:

```<code><form>
  <label>Thru Train Dashboard</label>
  <fieldset submitButton="false" autoRun="true">
    <input type="text" token="purchCostReferenceToken" searchWhenChanged="true">
      <label>Enter a TMS Reference Number to Filter Table</label>
      <default>*</default>
      <initialValue>*</initialValue>
    </input>
  </fieldset>
  <row>
    <panel>
      <title>Thru Train Data</title>
      <table>
        <search>
          <query>index=... "<billingMethod>RULE</billingMethod>" "createMessage MsgSource" | xmlkv | rex max_match=0 "\<purchasedCostTripSegment\>(?P<segment>[^\<]+)" |eval Segments =  mvrange(1,mvcount(mvindex(segment, 0, 2))+1,1) | rex max_match=0 "\<carrier\>(?P<Carriers>[^\<]+)" | rex max_match=0 "\<billingMethod\>(?P<BillingMethod>[^\<]+)" | rex max_match=0 "<purchasedCostTripSegment>[\s\S]*?<origin>\s*<ns2:numberCode>(?P<Origin>\d+)"  | rex max_match=0 "<purchasedCostTripSegment>[\s\S]*?<destination>\s*<ns2:numberCode>(?P<Destination>\d+)" | rex max_match=0 "<purchasedCostTripSegment>[\s\S]*?<stopOff>\s*<ns2:stopOffLocation>\s*<ns2:numberCode>(?P<StopOffLocation>\d+)" | eval Time =_time | convert timeformat="%m-%d-%Y %H:%M:%S" ctime(Time) | table purchCostReference, eventType, Time, Segments, Carriers, BillingMethod, Origin, Destination, StopOffLocation | sort Time</query>
          <earliest>-30d@d</earliest>
          <latest>now</latest>
        </search>
        <option name="drilldown">none</option>
      </table>
    </panel>
  </row>
</form>
</code>```

Where do I add the token to limit the search?
I tried adding this to the end of the query and all results were returned:

```<code>purchCostReference=$purchCostReferenceToken$
</code>```

答:
You cannot send parameters to a Report. https://docs.splunk.com/Documentation/Splunk/8.0.4/Viz/PanelreferenceforSimplifiedXML#search

You will need to use an inline search, something like the following. You will need to include your search and filter it appropraitely with the token $purchaseCoseReferenceToken

```<code><form>
  <label>Thru Train Dashboard</label>
  <fieldset submitButton="false" autoRun="true">
    <input type="text" token="purchCostReferenceToken" searchWhenChanged="true">
      <label>TMS Reference Number</label>
      <default>*</default>
      <initialValue>*</initialValue>
    </input>
  </fieldset>
  <row>
    <panel>
      <title>Thru Train XML DATA</title>
      <table>
        <search>
            <query>
            sourcetype=blah somefield="$purchCostReferenceToken$"
            </query>
        </search>
        <option name="drilldown">row</option>
        <option name="rowNumbers">true</option>
      </table>
    </panel>
  </row>
</form>
</code>```

Body:
I am using Splunk to create a dashboard.  I added a report to the dashboard that returns all of the data from the search into a table. I want to add a few input fields so the user to option to filter the data of the report.  The first input is a textbox field.  The default and initial values are set to with an *.  That I hope means everything.
This is the xml created from the dashboard:

<form>
  Thru Train Dashboard
  <fieldset submitButton="false" autoRun="true">
    <input type="text" token="purchCostReferenceToken" searchWhenChanged="true">
      TMS Reference Number
      <default>*</default>
      <initialValue>*</initialValue>
    </input>
  </fieldset>
  <row>
    <panel>
      <title>Thru Train XML DATA</title>

        <search ref="ThruTrainReportNestedResults"></search>
        <option name="drilldown">row</option>
        <option name="rowNumbers">true</option>

    </panel>
  </row>
</form>

I know I have to use the token value purchCostReferenceToken as an input to the report ThruTrainReportNestedResults.  But not sure how to do that since the report search as no input parameters.

This is the search query that creates the report, ThruTrainReportNestedResults

 sourcetype... | xmlkv | rex max_match=0 "\<purchasedCostTripSegment\>(?P<segment>[^\<]+)" |eval Segments =  mvrange(1,mvcount(mvindex(segment, 0, 2))+1,1) | rex max_match=0 "\<carrier\>(?P<Carriers>[^\<]+)" | rex max_match=0 "\<billingMethod\>(?P<BillingMethod>[^\<]+)" | rex max_match=0 "<purchasedCostTripSegment>[\s\S]*?<origin>\s*<ns2:numberCode>(?P<Origin>\d+)"  | rex max_match=0 "<purchasedCostTripSegment>[\s\S]*?<destination>\s*<ns2:numberCode>(?P<Destination>\d+)" | rex max_match=0 "<purchasedCostTripSegment>[\s\S]*?<stopOff>\s*<ns2:stopOffLocation>\s*<ns2:numberCode>(?P<StopOffLocation>\d+)" | eval Time =_time | convert timeformat="%m-%d-%Y %H:%M:%S" ctime(Time) | table purchCostReference, eventType, Time, Segments, Carriers, BillingMethod, Origin, Destination, StopOffLocation | sort Time

Is there a way to filter the results of this query from a dashboard using input data?  The input data that I would want to filter on would be the purchCostReference, eventType, and Segments

UPDATE
I removed the reference to the report and added the search string that creates the report but am getting the error Invalid character in tag name.  The search string is very long...

<row>
    <panel>
      <title>Thru Train XML DATA</title>

        <search base="baseSearch">
             <query>
                index... sourcetype="..." "<billingMethod>RULE</billingMethod>" "createMessage MsgSource" | xmlkv | rex max_match=0 "\<purchasedCostTripSegment\>(?P<segment>[^\<]+)" |eval Segments =  mvrange(1,mvcount(mvindex(segment, 0, 2))+1,1) | rex max_match=0 "\<carrier\>(?P<Carriers>[^\<]+)" | rex max_match=0 "\<billingMethod\>(?P<BillingMethod>[^\<]+)" | rex max_match=0 "<purchasedCostTripSegment>[\s\S]*?<origin>\s*<ns2:numberCode>(?P<Origin>\d+)"  | rex max_match=0 "<purchasedCostTripSegment>[\s\S]*?<destination>\s*<ns2:numberCode>(?P<Destination>\d+)" | rex max_match=0 "<purchasedCostTripSegment>[\s\S]*?<stopOff>\s*<ns2:stopOffLocation>\s*<ns2:numberCode>(?P<StopOffLocation>\d+)" | eval Time =_time | convert timeformat="%m-%d-%Y %H:%M:%S" ctime(Time) | table purchCostReference, eventType, Time, Segments, Carriers, BillingMethod, Origin, Destination, StopOffLocation | sort Time
            </query>
        </search>
        <option name="drilldown">row</option>
        <option name="rowNumbers">true</option>

    </panel>
  </row>

UPDATE I encoded the search query and added between the query tags with the token element as described in a previous comment.  I do not get an error but get no results either.  Just a blank table...

<query>             ...sourcetype%....%22%20%22%3CbillingMethod%3ERULE%3C%2FbillingMethod%3E%22%20%22createMessage%20MsgSource%22%20%7C%20xmlkv%20%7C%20rex%20max_match%3D0%20%22%5C%3CpurchasedCostTripSegment%5C%3E%28%3FP%3Csegment%3E%5B%5E%5C%3C%5D%2B%29%22%20%7Ceval%20Segments%20%3D%20%20mvrange%281%2Cmvcount%28mvindex%28segment%2C%200%2C%202%29%29%2B1%2C1%29%20%7C%20rex%20max_match%3D0%20%22%5C%3Ccarrier%5C%3E%28%3FP%3CCarriers%3E%5B%5E%5C%3C%5D%2B%29%22%20%7C%20rex%20max_match%3D0%20%22%5C%3CbillingMethod%5C%3E%28%3FP%3CBillingMethod%3E%5B%5E%5C%3C%5D%2B%29%22%20%7C%20rex%20max_match%3D0%20%22%3CpurchasedCostTripSegment%3E%5B%5Cs%5CS%5D%2A%3F%3Corigin%3E%5Cs%2A%3Cns2%3AnumberCode%3E%28%3FP%3COrigin%3E%5Cd%2B%29%22%20%20%7C%20rex%20max_match%3D0%20%22%3CpurchasedCostTripSegment%3E%5B%5Cs%5CS%5D%2A%3F%3Cdestination%3E%5Cs%2A%3Cns2%3AnumberCode%3E%28%3FP%3CDestination%3E%5Cd%2B%29%22%20%7C%20rex%20max_match%3D0%20%22%3CpurchasedCostTripSegment%3E%5B%5Cs%5CS%5D%2A%3F%3CstopOff%3E%5Cs%2A%3Cns2%3AstopOffLocation%3E%5Cs%2A%3Cns2%3AnumberCode%3E%28%3FP%3CStopOffLocation%3E%5Cd%2B%29%22%20%7C%20eval%20Time%20%3D_time%20%7C%20convert%20timeformat%3D%22%25m-%25d-%25Y%20%25H%3A%25M%3A%25S%22%20ctime%28Time%29%20%7C%20table%20purchCostReference%2C%20eventType%2C%20Time%2C%20Segments%2C%20Carriers%2C%20BillingMethod%2C%20Origin%2C%20Destination%2C%20StopOffLocation%20%7C%20sort%20Time purchCostReference=$purchCostReferenceToken$
</query>

This is a screen shot of the results:

UPDATE
I removed the complexity of the search so that it only has the index, source and sourcetype that is the same as the report and a text field to limit the search. Below is the query string:

<query>index="indexname same as report" source="source name same as report" sourcetype="source type name same as report" "createMessage MsgSource"</query>

It returns a blank dashboard with no error as pictured above.

UPDATE
I recreated the dashboard using the report query and have the search returning all of the table results.  I have an input for the reference number as a text box.  The token name is: purchCostReferenceToken

I want to limit the table results based on this token. This is the query:

<form>
  Thru Train Dashboard
  <fieldset submitButton="false" autoRun="true">
    <input type="text" token="purchCostReferenceToken" searchWhenChanged="true">
      Enter a TMS Reference Number to Filter Table
      <default>*</default>
      <initialValue>*</initialValue>
    </input>
  </fieldset>
  <row>
    <panel>
      <title>Thru Train Data</title>

        <search>
          <query>index=... "<billingMethod>RULE</billingMethod>" "createMessage MsgSource" | xmlkv | rex max_match=0 "\<purchasedCostTripSegment\>(?P<segment>[^\<]+)" |eval Segments =  mvrange(1,mvcount(mvindex(segment, 0, 2))+1,1) | rex max_match=0 "\<carrier\>(?P<Carriers>[^\<]+)" | rex max_match=0 "\<billingMethod\>(?P<BillingMethod>[^\<]+)" | rex max_match=0 "<purchasedCostTripSegment>[\s\S]*?<origin>\s*<ns2:numberCode>(?P<Origin>\d+)"  | rex max_match=0 "<purchasedCostTripSegment>[\s\S]*?<destination>\s*<ns2:numberCode>(?P<Destination>\d+)" | rex max_match=0 "<purchasedCostTripSegment>[\s\S]*?<stopOff>\s*<ns2:stopOffLocation>\s*<ns2:numberCode>(?P<StopOffLocation>\d+)" | eval Time =_time | convert timeformat="%m-%d-%Y %H:%M:%S" ctime(Time) | table purchCostReference, eventType, Time, Segments, Carriers, BillingMethod, Origin, Destination, StopOffLocation | sort Time</query>
          <earliest>-30d@d</earliest>
          <latest>now</latest>
        </search>
        <option name="drilldown">none</option>

    </panel>
  </row>
</form>

Where do I add the token to limit the search?
I tried adding this to the end of the query and all results were returned:

purchCostReference=$purchCostReferenceToken$

Body:
You cannot send parameters to a Report. https://docs.splunk.com/Documentation/Splunk/8.0.4/Viz/PanelreferenceforSimplifiedXML#search

You will need to use an inline search, something like the following. You will need to include your search and filter it appropraitely with the token $purchaseCoseReferenceToken

<form>
  <label>Thru Train Dashboard</label>
  <fieldset submitButton="false" autoRun="true">
    <input type="text" token="purchCostReferenceToken" searchWhenChanged="true">
      <label>TMS Reference Number</label>
      <default>*</default>
      <initialValue>*</initialValue>
    </input>
  </fieldset>
  <row>
    <panel>
      <title>Thru Train XML DATA</title>
      <table>
        <search>
            <query>
            sourcetype=blah somefield="$purchCostReferenceToken$"
            </query>
        </search>
        <option name="drilldown">row</option>
        <option name="rowNumbers">true</option>
      </table>
    </panel>
  </row>
</form>


问:
If I extract something from a stream, does the stream not contain what I extracted anymore?
If I have code like below and I store "This" in str first from stream streem:

```<code>using namespace std;
int main()
{
    istringstream streem("This is the content in the stream.");
    string str;
    streem>>str;
    cout<<str; //This will cout "This"
</code>```

If I do streem>>str again and cout<<str again, this will display is.
So does this mean that "This" does not exist in the istringstream anymore?
What aboutfile streams`, because they retain data?

答:
The answer is different for different streams  .

The stringstream has a memory buffer and an indicator that remembers where you were up to on the reading. So the next read starts where the previous read left off.

File streams work in a similar way, they remember which point of the file they are up to. In both cases you can change position (including resetting to the beginning) using seekg.

File streams don't have separate read and write positions, so this same code might behave differently for a file stream . (In fact I think it causes undefined behaviour to read and write without an intervening seek).

Other input streams might not have seekable buffers, e.g. cin .

Body:
If I have code like below and I store "This" in str first from stream streem:

using namespace std;
int main()
{
    istringstream streem("This is the content in the stream.");
    string str;
    streem>>str;
    cout<<str; //This will cout "This"

If I do streem>>str again and cout<<str again, this will display is.
So does this mean that "This" does not exist in the istringstream anymore?
What aboutfile streams`, because they retain data?


问:
Trying to run 2 queries in one connection
I have a small piece of code I am trying to run in which I first check if the value exists and then update my database if it does not. My problem is I can run one query or the other but not both, because then it states the database is open and cannot be accessed. I know for sure I can write to the database. It is not read protected, located where I can't access it etc. The routine runs if I just try to update and not check. The check definitely results in no record. I have tried separate routines using completely different variables for the connection. I am stumped big time. I have tried closing, using, disposing, but I need someone a lot smarter than me to advise me of what I am doing wrong...

```<code>For Each strfile As String In flist
    Dim pth As String = Path.GetDirectoryName(strfile)
    Dim objReader As New System.IO.StreamReader(strfile)
    Dim dVal As String = String.Empty
    TextLine = objReader.ReadLine()
    SplitLine = Split(TextLine, ",")
    dVal = SplitLine(1)

    Using Dcon As New OleDbConnection
        Dcon.ConnectionString = dbProvider
        Dcon.Open()

        Dim q1 As String = "SELECT Shares.[_Date] FROM Shares WHERE (((Shares.[_Date])=" & dVal & "))"
        Dim comd As OleDbCommand = New OleDbCommand(q1, Dcon)
        comd.ExecuteReader()

        Dim q2 As String = "INSERT INTO Shares (Code, _Date, _Open, _High, _Low, _Close, _Volume) " &
                                                                  "SELECT F1, F2, F3, F4, F5, F6, F7 FROM [Text;HDR=NO;DATABASE=" & pth & "].[" & Path.GetFileName(strfile) & "];"

        Dim cmd As OleDbCommand = New OleDbCommand(q2, Dcon)

        cmd.ExecuteNonQuery()
        Dcon.Close()
    End Using
Next
</code>```

I have tried separate routines, I have tried opening, closing and then re-opening. I have tried one connection, I have tried two. Does anybody know what I am doing wrong and why it keeps telling me the database is exclusively opened and why it won't let me write to it?

Thank you in advance to those who help.

答:
Thank you all for your help, but at 2am I had an epiphany and realised it was not the database that was the problem.

I had left the streamreader open and that was what was causing the problem.

I have taken on board your comments though and appreciate the assistance in developing better code.

Body:
I have a small piece of code I am trying to run in which I first check if the value exists and then update my database if it does not. My problem is I can run one query or the other but not both, because then it states the database is open and cannot be accessed. I know for sure I can write to the database. It is not read protected, located where I can't access it etc. The routine runs if I just try to update and not check. The check definitely results in no record. I have tried separate routines using completely different variables for the connection. I am stumped big time. I have tried closing, using, disposing, but I need someone a lot smarter than me to advise me of what I am doing wrong...

For Each strfile As String In flist
    Dim pth As String = Path.GetDirectoryName(strfile)
    Dim objReader As New System.IO.StreamReader(strfile)
    Dim dVal As String = String.Empty
    TextLine = objReader.ReadLine()
    SplitLine = Split(TextLine, ",")
    dVal = SplitLine(1)

    Using Dcon As New OleDbConnection
        Dcon.ConnectionString = dbProvider
        Dcon.Open()

        Dim q1 As String = "SELECT Shares.[_Date] FROM Shares WHERE (((Shares.[_Date])=" & dVal & "))"
        Dim comd As OleDbCommand = New OleDbCommand(q1, Dcon)
        comd.ExecuteReader()

        Dim q2 As String = "INSERT INTO Shares (Code, _Date, _Open, _High, _Low, _Close, _Volume) " &
                                                                  "SELECT F1, F2, F3, F4, F5, F6, F7 FROM [Text;HDR=NO;DATABASE=" & pth & "].[" & Path.GetFileName(strfile) & "];"

        Dim cmd As OleDbCommand = New OleDbCommand(q2, Dcon)

        cmd.ExecuteNonQuery()
        Dcon.Close()
    End Using
Next

I have tried separate routines, I have tried opening, closing and then re-opening. I have tried one connection, I have tried two. Does anybody know what I am doing wrong and why it keeps telling me the database is exclusively opened and why it won't let me write to it?

Thank you in advance to those who help.


问:
many functions and many variables
for the seek of simplicity I will only use three functions as follows. I need to evaluate the functions at first and later on use these results for other calculations. I would like to create an interface such that I only provide the value of input variable x and then easily calculate all the functions. I would like to use a class for this purpose. How can I do this with OOP?</p>

```<code>def function1(x):
    y=x+2
    z= x-2
    return y,z

value1=function1(x)
def function2 (x):
    y1= value1[0] *10 # value1 can be replaced by function1(x)
    z1= value1[1] +5  # but the aim and it will work but i have so many functions
    return y1,z1
def main(x):
    print(f1(x),f2(x))

main(2)
</code>```

答:
Solution

You could in principle create a class as follows and then use the functions to calculate what you want. If you want to access the evaluated results for function_01(x), just use f.values['function_01']. I chose to use it like this so that you could dynamically save the results of all the methods (functions) and the dict keys would be self-explanatory.

You can also directly evaluate any of the methods (function_01,02,03)

Also, you could create some short aliases if you like using enable_func_aliases = True while instantiating the class object or later calling create_func_aliases() method.

# implementation of class Functions
f = Functions(x=10, evaluate=True)
print(f)
print(f.values) # values is a dict
# To create short aliases for functions (methods)
f.create_func_aliases()
```

<p><strong>Output</strong>:  </p>

<pre class="lang-sh prettyprint-override"><code>Functions( x: 10, evaluate: True )
{'function_01': (12, 8),
'function_02': (143, 5, 243),
'function_03': (2100, 0, 8)}
</code>```

Code: class Functions

class Functions(object):

    def __init__(self, x=None, evaluate: bool=False,
                 enable_func_aliases: bool=False):
        self.x = x
        self.evaluate = evaluate
        self.enable_func_aliases = enable_func_aliases
        self.values = dict()
        self._update()

    def __repr__(self):
        return '{}( x: {}, evaluate: {} )'\
            .format(self.__class__.__name__, self.x, self.evaluate)

    def evaluate_functions(self):
        self.evaluate = True
        self._update_values()

    def _update(self):
        if self.evaluate:
            self.evaluate_functions()
        if self.enable_func_aliases:
            self.create_func_aliases()

    def _update_values(self):
        self.values.update({'function_01': self.function_01()})
        self.values.update({'function_02': self.function_02()})
        self.values.update({'function_03': self.function_03()})

    def create_func_aliases(self):
        self.enable_func_aliases = True
        self.f01 = self.function_01
        self.f02 = self.function_02
        self.f03 = self.function_03

    def function_01(self, x=None):
        if x is None: x = self.x
        if x is not None:
            y = x + 2
            z = x - 2
            return (y, z)

    def function_02(self, x=None):
        if x is None: x = self.x
        if x is not None:
            y = x**2 + 4*x + 3
            z1 = x - 5
            z2 = y + 10*x
            return (y, z1, z2)

    def function_03(self, x=None):
        if x is None: x = self.x
        if x is not None:
            y1 = 10*x + 2*(x**3)
            y2 = x**3 - 10*(x**2)
            z = x - 2
            return (y1, y2, z)

```

Title: many functions and many variables

Body:
for the seek of simplicity I will only use three functions as follows. I need to evaluate the functions at first and later on use these results for other calculations. I would like to create an interface such that I only provide the value of input variable x and then easily calculate all the functions. I would like to use a class for this purpose. How can I do this with OOP?

def function1(x):
    y=x+2
    z= x-2
    return y,z

value1=function1(x)
def function2 (x):
    y1= value1[0] *10 # value1 can be replaced by function1(x)
    z1= value1[1] +5  # but the aim and it will work but i have so many functions
    return y1,z1
def main(x):
    print(f1(x),f2(x))

main(2)

Body:
Solution

You could in principle create a class as follows and then use the functions to calculate what you want. If you want to access the evaluated results for function_01(x), just use f.values['function_01']. I chose to use it like this so that you could dynamically save the results of all the methods (functions) and the dict keys would be self-explanatory.

You can also directly evaluate any of the methods (function_01,02,03)

Also, you could create some short aliases if you like using enable_func_aliases = True while instantiating the class object or later calling create_func_aliases() method.

# implementation of class Functions
f = Functions(x=10, evaluate=True)
print(f)
print(f.values) # values is a dict
# To create short aliases for functions (methods)
f.create_func_aliases()

Output:

Functions( x: 10, evaluate: True )
{'function_01': (12, 8),
'function_02': (143, 5, 243),
'function_03': (2100, 0, 8)}

Code: class Functions

class Functions(object):

    def __init__(self, x=None, evaluate: bool=False,
                 enable_func_aliases: bool=False):
        self.x = x
        self.evaluate = evaluate
        self.enable_func_aliases = enable_func_aliases
        self.values = dict()
        self._update()

    def __repr__(self):
        return '{}( x: {}, evaluate: {} )'\
            .format(self.__class__.__name__, self.x, self.evaluate)

    def evaluate_functions(self):
        self.evaluate = True
        self._update_values()

    def _update(self):
        if self.evaluate:
            self.evaluate_functions()
        if self.enable_func_aliases:
            self.create_func_aliases()

    def _update_values(self):
        self.values.update({'function_01': self.function_01()})
        self.values.update({'function_02': self.function_02()})
        self.values.update({'function_03': self.function_03()})

    def create_func_aliases(self):
        self.enable_func_aliases = True
        self.f01 = self.function_01
        self.f02 = self.function_02
        self.f03 = self.function_03

    def function_01(self, x=None):
        if x is None: x = self.x
        if x is not None:
            y = x + 2
            z = x - 2
            return (y, z)

    def function_02(self, x=None):
        if x is None: x = self.x
        if x is not None:
            y = x**2 + 4*x + 3
            z1 = x - 5
            z2 = y + 10*x
            return (y, z1, z2)

    def function_03(self, x=None):
        if x is None: x = self.x
        if x is not None:
            y1 = 10*x + 2*(x**3)
            y2 = x**3 - 10*(x**2)
            z = x - 2
            return (y1, y2, z)


问:
Excluding common words from a text file in powershell
I am new at scripting in powershell and I am trying to create a code that will display the top 20 words in a text file(poem.txt), but will also exclude common words such as "and", "if", "a". I was able to finally get to filter the list but I cannot for the life of me figure out how to exclude common words. Any help would be great.

"poem.txt"

```<code>$contents = Get-Content -Path $file
$words = $contents.split(" .,?()") | Where-Object {$_}
$words | Group-Object | Where-Object Count -GE 20 | sort-object count -descending |% {$_.split(" ")} |? {$_ -notin "and", "if, "a"}
</code>```

答:
You syntax is correct, the order of executions piped is wrong. And no need to do |% {$_.split(" ")}. Your code works like this:

```<code>$words |? {$_ -notin "and", "if", "the"} | Group-Object | Where-Object Count -ge 20 | sort-object count -descending
</code>```

where-object {$_ -notin "and", "if", "a"} works on piped array $words but will not piped Microsoft.PowerShell.Commands.GroupInfo Group-Object

Body:
I am new at scripting in powershell and I am trying to create a code that will display the top 20 words in a text file(poem.txt), but will also exclude common words such as "and", "if", "a". I was able to finally get to filter the list but I cannot for the life of me figure out how to exclude common words. Any help would be great.

"poem.txt"

$contents = Get-Content -Path $file
$words = $contents.split(" .,?()") | Where-Object {$_}
$words | Group-Object | Where-Object Count -GE 20 | sort-object count -descending |% {$_.split(" ")} |? {$_ -notin "and", "if, "a"}

Body:
You syntax is correct, the order of executions piped is wrong. And no need to do |% {$_.split(" ")}. Your code works like this:

$words |? {$_ -notin "and", "if", "the"} | Group-Object | Where-Object Count -ge 20 | sort-object count -descending

where-object {$_ -notin "and", "if", "a"} works on piped array $words but will not piped Microsoft.PowerShell.Commands.GroupInfo Group-Object


问:
Streaming tweets from private twitter account
I am trying to create a twitter stream for accounts that I currently follow. Most of them are private. I was wondering if there was a way to create a twitter stream that catches tweets from private accounts?

Currently using Tweepy, but open to other APIs.

```<code>class listener(StreamListener):
    print("Running stream")
    def on_data(self, data):

        print("data")
        return(True)

    def on_error(self, status):

        print(status)

auth = OAuthHandler(ckey, csecret)

# Access to user's access key and access secret
auth.set_access_token(atoken, asecret)

# Calling api
api = API(auth)

twitterStream = Stream(auth, listener())
twitterStream.filter(follow=['x'])
</code>```

答: Have you checked out the documentation for data streaming in Tweepy. It seems to be close to what you want. As for those accounts tweets being private, if you follow them and they follow you then their tweets appear on your feed and with an authenticated account they should be available to your stream. </p>

Body:
I am trying to create a twitter stream for accounts that I currently follow. Most of them are private. I was wondering if there was a way to create a twitter stream that catches tweets from private accounts?

Currently using Tweepy, but open to other APIs.

class listener(StreamListener):
    print("Running stream")
    def on_data(self, data):

        print("data")
        return(True)

    def on_error(self, status):

        print(status)

auth = OAuthHandler(ckey, csecret)

# Access to user's access key and access secret
auth.set_access_token(atoken, asecret)

# Calling api
api = API(auth)

twitterStream = Stream(auth, listener())
twitterStream.filter(follow=['x'])


问:
How do I extract UK county name matches from string
I have a list of UK county names and 8397 job titles which may contain those county names. I am able to find whether those matches are True or False or filter to rows where a string match was found.

However, I'd like to exract the match to another column when found but not sure how to do this. E.g. If a match to Surrey from ukcounties is found in UK['Title'] then extract Surrey to another column.

Thanks!!

```<code>ukcounties = ['Somerset', 'Staffordshire', 'Suffolk', 'Surrey']

UK['Title'] =
['Relief Chef de Partie  Croydon  Surrey  Live in',
'Pastry Chef Baker  artisan bakery  Suffolk Coast']

UK.Title.apply(lambda sentence: any(word in sentence for word in ukcounties))

Output:
9        False
12       False
13        True
26       False
27       False
         ...
55157    False
55158    False
55159     True
55161     True
55165    False
Name: Title, Length: 8397, dtype: bool

UK[UK.Title.str.contains('|'.join(ukcounties))]
Output: 1003 rows × 12 columns
</code>```

答:
You may use

```<code>UK['Title'].str.extract(r'\b({})\b'.format('|'.join(ukcounties)))
</code>```

Pandas test:

```<code>>>> import pandas as pd
>>> UK = {'Title': ['Relief Chef de Partie  Croydon  Surrey  Live in',
'Pastry Chef Baker  artisan bakery  Suffolk Coast']}
>>> df = pd.DataFrame(UK)
>>> ukcounties = ['Somerset', 'Staffordshire', 'Suffolk', 'Surrey']
>>> df['Title'].str.extract(r'\b({})\b'.format('|'.join(ukcounties)))
#             0
#    0   Surrey
#    1  Suffolk
</code>```

The r'\b({})\b'.format('|'.join(ukcounties)) will form a regex like \b(Somerset|Staffordshire|Suffolk|Surrey)\b where

\b  - a word boundary

(Somerset|Staffordshire|Suffolk|Surrey) - Group 1: any of the words inside parentheses (| is an alternation operator)

\b  - a word boundary

Body:
I have a list of UK county names and 8397 job titles which may contain those county names. I am able to find whether those matches are True or False or filter to rows where a string match was found.

However, I'd like to exract the match to another column when found but not sure how to do this. E.g. If a match to Surrey from ukcounties is found in UK['Title'] then extract Surrey to another column.

Thanks!!

ukcounties = ['Somerset', 'Staffordshire', 'Suffolk', 'Surrey']

UK['Title'] =
['Relief Chef de Partie  Croydon  Surrey  Live in',
'Pastry Chef Baker  artisan bakery  Suffolk Coast']

UK.Title.apply(lambda sentence: any(word in sentence for word in ukcounties))

Output:
9        False
12       False
13        True
26       False
27       False
         ...
55157    False
55158    False
55159     True
55161     True
55165    False
Name: Title, Length: 8397, dtype: bool

UK[UK.Title.str.contains('|'.join(ukcounties))]
Output: 1003 rows × 12 columns

Body:
You may use

UK['Title'].str.extract(r'\b({})\b'.format('|'.join(ukcounties)))

Pandas test:

>>> import pandas as pd
>>> UK = {'Title': ['Relief Chef de Partie  Croydon  Surrey  Live in',
'Pastry Chef Baker  artisan bakery  Suffolk Coast']}
>>> df = pd.DataFrame(UK)
>>> ukcounties = ['Somerset', 'Staffordshire', 'Suffolk', 'Surrey']
>>> df['Title'].str.extract(r'\b({})\b'.format('|'.join(ukcounties)))
#             0
#    0   Surrey
#    1  Suffolk

The r'\b({})\b'.format('|'.join(ukcounties)) will form a regex like \b(Somerset|Staffordshire|Suffolk|Surrey)\b where

\b  - a word boundary

(Somerset|Staffordshire|Suffolk|Surrey) - Group 1: any of the words inside parentheses (| is an alternation operator)

\b  - a word boundary


问:
How to extract multiwords in R?
I want to extract certain words positioned between years and the following comma in a given text. The year may or may not have opening & closing parentheses. Note that the year 1998 has no opening & closing parentheses whereas (2020) and (2015) have.

```<code>library(stringr)
txt <- "Mining exercise (2020) Mining, p. 628; Computer Science text 1998 Computer Science, p.345-355; Data mining (2015) J. Data Science, pp. 31-33"
comp <- c("Mining", "Computer Science", "J. Data Science")
pattern <- str_c(comp,collapse ="|")
</code>```

str_extract_all(txt, str_c("(?<=\\(\\d{4}\\)\\s)(", pattern, ")(?=,)"))[[1]] gives me:

```<code>#  "Mining"          "J. Data Science"
</code>```

But the answer should be:

```<code># "Mining"  "Computer Science"  "J. Data Science"
</code>```

by taking into account the absence of opening & closing parentheses around 1998. Any help, please?

答:
Here is one option by removing the bracket surrounding the 4 digit year and then use the OP's pattern without the ()

```<code>library(stringr)
str_extract_all(str_replace_all(txt, "\\((\\d{4})\\)", "\\1"),
     str_c("(?<=\\d{4}\\s)(", pattern, ")(?=,)"))[[1]]
#[1] "Mining"           "Computer Science" "J. Data Science"
</code>```

Or another option is

```<code>str_extract_all(txt, str_c("(?<=\\(?\\d{4}\\)?\\s)(", pattern, ")(?=,)"))[[1]]
#[1] "Mining"           "Computer Science" "J. Data Science"
</code>```

Title: How to extract multiwords in R?

Body:
I want to extract certain words positioned between years and the following comma in a given text. The year may or may not have opening & closing parentheses. Note that the year 1998 has no opening & closing parentheses whereas (2020) and (2015) have.

library(stringr)
txt <- "Mining exercise (2020) Mining, p. 628; Computer Science text 1998 Computer Science, p.345-355; Data mining (2015) J. Data Science, pp. 31-33"
comp <- c("Mining", "Computer Science", "J. Data Science")
pattern <- str_c(comp,collapse ="|")

str_extract_all(txt, str_c("(?<=\\(\\d{4}\\)\\s)(", pattern, ")(?=,)"))[[1]] gives me:

#  "Mining"          "J. Data Science"

But the answer should be:

# "Mining"  "Computer Science"  "J. Data Science"

by taking into account the absence of opening & closing parentheses around 1998. Any help, please?

Body:
Here is one option by removing the bracket surrounding the 4 digit year and then use the OP's pattern without the ()

library(stringr)
str_extract_all(str_replace_all(txt, "\\((\\d{4})\\)", "\\1"),
     str_c("(?<=\\d{4}\\s)(", pattern, ")(?=,)"))[[1]]
#[1] "Mining"           "Computer Science" "J. Data Science"

Or another option is

str_extract_all(txt, str_c("(?<=\\(?\\d{4}\\)?\\s)(", pattern, ")(?=,)"))[[1]]
#[1] "Mining"           "Computer Science" "J. Data Science"


问:
Windows Phone 7 - SQLite with Encryption
I was using System.Data.SQLite for SQLite in Windows Mobile. It has built-in encryption support. I have found many SQLite implementation for Windows Phone 7. But, none of them have built-in support for encryption. Anybody knows any SQLite implementation for Windows Phone 7 that supports Encryption?</p>

答:
There doesn't seem to be any API in Windows Phone 7 that will let you encrypt / decrypt data based on user credentials similar to DPAPI so you have to do it yourself. The documentation suggests that the following algorithms are available on Windows Phone 7:

AES

HMACSHA1

HMACSHA256

Rfc2898DeriveBytes

RSA

SHA1

SHA256

These algorithms should give all you need to create a decent encryption schema and it should be good enough that you encrypt the sensitive columns in your database schema and not the whole database.

The only problem then would be to see what key to use. If it's possible to ask the user for a password (this very much depends on what type of application you are building), then you can use Rfc2898DerivedBytes to derive a password from the user input. Otherwise, you can create a key out from some device data. (see: How do I get a symmetric key in Windows Phone 7?) After deriving a key, you can use AES to do your encryption.

I know that this is exactly what you wanted, but at least should point you in the right direction.


问:
ASP.NET MVC parent child records iCollection first item
I have Albums and Images tables with a 1-many relationship. Models are automatically generated using EF database-first approach.

I want to get all albums with their images, and display only first image from each album on albums listing page. But I got confused, ICollection does not have indexes and I'm not able to convert it to a list inside view.

Sometimes it says it is Hashset

Album.cs

```<code>public partial class Album
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Album()
    {
        this.Images = new HashSet<Image>();
    }

    public int id { get; set; }
    public string title { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Image> Images { get; set; }
}
</code>```

Image.cs

```<code>public partial class Image
{
    public int id { get; set; }
    public int album_id { get; set; }
    public string img { get; set; }
    public string title { get; set; }

    public virtual Album Album { get; set; }
}
</code>```

HomeController.cs

```<code>ViewBag.Albums = db.Albums.Where(a => a.status == 1)
                          .Select(c => new
                                       {
                                            Album = c,
                                            Image = c.Images.OrderBy(i => i.sort)
                                       })
                          .AsEnumerable() // not execute yet
                          .Select(a => a.Album)
                          .OrderBy(a => a.sort)
                          .Take(6)
                          .ToList();
</code>```

View.html

```<code>@if (ViewBag.Albums != null) {
       foreach (var item in ViewBag.Albums)
       {
           <div class="album">
                 @{
                   string default_image = "no-img.png";

                   if (item.Images.Count > 0)
                   {
                      //var firstImg = item.Images.First();//this showing error that item.image dont have first()
                      //List<myproject.Models.Image> images = item.Images.ToList();//this also say hashset has no list()
                      //inside 1 albums many images can be returned, I want to display first one only.
                      default_image = item.id + "/" + item.Images[0].img;
                   }
                   int indx = 1;
                }
           </div>
       }
}
</code>```

答:
firstly:
You must create a viewmodel

```<code>public class ImageAlbumView
{
    public Image Image {get;set;}
    public Album Album {get;set;}
}
</code>```

HomeController.cs:

```<code>ViewBag.Albums = db.Albums.Where(a => a.status == 1)
                      .Select(c => new ImageAlbumView()
                                   {
                                        Album = c,
                                        Image = c.Images.OrderBy(i => i.id)
                                   })
                      .AsEnumerable() // not execute yet
                      .Select(a => a.Album)
                      .OrderBy(a => a.Image.id)
                      .Take(6)
                      .ToList();
</code>```

View.html:

```<code>@if ((List<ImageAlbumView>)ViewBag.Albums != null) {
   foreach (ImageAlbumViewitem in (List<ImageAlbumView>)ViewBag.Albums)
   {
       <div class="album">
             @{
               string default_image = "no-img.png";

               if (item.Images.Count > 0)
               {
                  default_image = item.id + "/" + item.Images[0].img;
               }
               int indx = 1;
            }
       </div>
   }
</code>```

}

Body:
I have Albums and Images tables with a 1-many relationship. Models are automatically generated using EF database-first approach.

I want to get all albums with their images, and display only first image from each album on albums listing page. But I got confused, ICollection does not have indexes and I'm not able to convert it to a list inside view.

Sometimes it says it is Hashset

Album.cs

public partial class Album
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Album()
    {
        this.Images = new HashSet<Image>();
    }

    public int id { get; set; }
    public string title { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Image> Images { get; set; }
}

Image.cs

public partial class Image
{
    public int id { get; set; }
    public int album_id { get; set; }
    public string img { get; set; }
    public string title { get; set; }

    public virtual Album Album { get; set; }
}

HomeController.cs

ViewBag.Albums = db.Albums.Where(a => a.status == 1)
                          .Select(c => new
                                       {
                                            Album = c,
                                            Image = c.Images.OrderBy(i => i.sort)
                                       })
                          .AsEnumerable() // not execute yet
                          .Select(a => a.Album)
                          .OrderBy(a => a.sort)
                          .Take(6)
                          .ToList();

View.html

@if (ViewBag.Albums != null) {
       foreach (var item in ViewBag.Albums)
       {

                 @{
                   string default_image = "no-img.png";

                   if (item.Images.Count > 0)
                   {
                      //var firstImg = item.Images.First();//this showing error that item.image dont have first()
                      //List<myproject.Models.Image> images = item.Images.ToList();//this also say hashset has no list()
                      //inside 1 albums many images can be returned, I want to display first one only.
                      default_image = item.id + "/" + item.Images[0].img;
                   }
                   int indx = 1;
                }

       }
}

Body:
firstly:
You must create a viewmodel

public class ImageAlbumView
{
    public Image Image {get;set;}
    public Album Album {get;set;}
}

HomeController.cs:

ViewBag.Albums = db.Albums.Where(a => a.status == 1)
                      .Select(c => new ImageAlbumView()
                                   {
                                        Album = c,
                                        Image = c.Images.OrderBy(i => i.id)
                                   })
                      .AsEnumerable() // not execute yet
                      .Select(a => a.Album)
                      .OrderBy(a => a.Image.id)
                      .Take(6)
                      .ToList();

View.html:

@if ((List<ImageAlbumView>)ViewBag.Albums != null) {
   foreach (ImageAlbumViewitem in (List<ImageAlbumView>)ViewBag.Albums)
   {
       <div class="album">
             @{
               string default_image = "no-img.png";

               if (item.Images.Count > 0)
               {
                  default_image = item.id + "/" + item.Images[0].img;
               }
               int indx = 1;
            }
       </div>
   }

}


问:
gatsby & graphql : filtering for a specific single image
I don't really understand graphql or gatsby that well but I believe all my images are loaded into graphql by putting this in my gatsby-config.js

    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: path.join(__dirname, `src/assets/images`),
      },
    },```
</div>
</div>
</p>

<p>I am then trying to query a specific image which I can do with </p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>    query MyQuery {
      allImageSharp(filter: {id: {eq: "7acfccd5-4aef-532b-8889-9d844ae2068b"}}) {
        edges {
          node {
            sizes {
              sizes
              srcSet
              src
              aspectRatio
            }
            id
          }
        }
      }
    }</code>```

And this returns what I want, but the id that I have to enter for this query is 7acfccd5-4aef-532b-8889-9d844ae2068b. Is this id even going to stay the same if I put it in my code? Is there a way to set the id to something more sensical?

If I save my query to a variable data, it turns out that on Netlify data.allImageSharp.edges[0] is null, while locally this value will return what I need

I'm looking for the best way to query a single image. Not multiple images.
If I could set my own id's then I could query these.

Update

I found an example in the gatsby-source-filesystem documentation, but don't really know how to add it to my code

答:
If you have an image with a path of src/images/exampleImage.jpg, you can query by the images name by querying using file rather than allImageSharp.

```<code>query HeaderQuery {
  exampleImage: file(
    extension: {eq: "jpg"},
    name: {eq: "exampleImage"}
  ) {
    childImageSharp {
      fluid {
        src
        srcSet
        sizes
        srcSetWebp
      }
    }
  }
}
</code>```

You can also replace {extension: {eq: "jpg"} with {extension: {regex: "/(jpg)|(jpeg)|(png)/"} to query files of any extension type.

Body:
I don't really understand graphql or gatsby that well but I believe all my images are loaded into graphql by putting this in my gatsby-config.js

    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: path.join(__dirname, `src/assets/images`),
      },
    },

I am then trying to query a specific image which I can do with

    query MyQuery {
      allImageSharp(filter: {id: {eq: "7acfccd5-4aef-532b-8889-9d844ae2068b"}}) {
        edges {
          node {
            sizes {
              sizes
              srcSet
              src
              aspectRatio
            }
            id
          }
        }
      }
    }

And this returns what I want, but the id that I have to enter for this query is 7acfccd5-4aef-532b-8889-9d844ae2068b. Is this id even going to stay the same if I put it in my code? Is there a way to set the id to something more sensical?

If I save my query to a variable data, it turns out that on Netlify data.allImageSharp.edges[0] is null, while locally this value will return what I need

I'm looking for the best way to query a single image. Not multiple images.
If I could set my own id's then I could query these.

Update

I found an example in the gatsby-source-filesystem documentation, but don't really know how to add it to my code

Body:
If you have an image with a path of src/images/exampleImage.jpg, you can query by the images name by querying using file rather than allImageSharp.

query HeaderQuery {
  exampleImage: file(
    extension: {eq: "jpg"},
    name: {eq: "exampleImage"}
  ) {
    childImageSharp {
      fluid {
        src
        srcSet
        sizes
        srcSetWebp
      }
    }
  }
}

You can also replace {extension: {eq: "jpg"} with {extension: {regex: "/(jpg)|(jpeg)|(png)/"} to query files of any extension type.


问:
Parallel Read Write to C++ stringstream
I am using std::stringstream for reading/writing binary data.

```<code>std::stringstream strm(std::stringstream::binary|std::stringstream::in|std::stringstream::out);

    strm.write(...) //happens in one thread
    strm.read(...)  //happens in another thread
</code>```

Does C++ standards guarantees that parallel read write to stringstream work? Or not.

答:
This is covered in [iostreams.threadsafety] in the Standard. The C++17 text reads:

Concurrent access to a stream object, stream buffer object, or C Library stream by
  multiple threads may result in a data race unless otherwise specified. [Note: Data races result in undefined behavior . —end note ]

There is no "otherwise specified" for std::stringstream so your case would be undefined behaviour.

Title: Parallel Read Write to C++ stringstream

Body:
I am using std::stringstream for reading/writing binary data.

std::stringstream strm(std::stringstream::binary|std::stringstream::in|std::stringstream::out);

    strm.write(...) //happens in one thread
    strm.read(...)  //happens in another thread

Does C++ standards guarantees that parallel read write to stringstream work? Or not.


问:
read_pdf FileNotFoundError: [Errno 2] No such file or directory: in Python
I am trying to scrape tables from pdf with read_pdf in python. I am using read_pdf but it doesn't do the job. Also, to mention, I do this in MAC with Jupiter notebook.
This is what I do:

```<code>from tabula import read_pdf
file = read_pdf(r'C:\Users\myname\Rprojects\Reports_scraping\data_scraped\icnarc_29052020\icnarc_200529.pdf')
</code>```

I get this error:

```<code>FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\myname\\Rprojects\\Reports_scraping\\data_scraped\\icnarc_29052020\\icnarc_200529.pdf'
</code>```

How I can solve this issue?

答:
There can be only one possibility, the file is not there, but you have already checked that I assume, if not, Once again check whether the spelling of file is correct. If this doesn't work, then do below trick

Execute the py code in same folder as file, and then use

```<code>from tabula import read_pdf
file = read_pdf(r'icnarc_200529.pdf')
</code>```

Sometimes, this simple method does the trick.

Body:
I am trying to scrape tables from pdf with read_pdf in python. I am using read_pdf but it doesn't do the job. Also, to mention, I do this in MAC with Jupiter notebook.
This is what I do:

from tabula import read_pdf
file = read_pdf(r'C:\Users\myname\Rprojects\Reports_scraping\data_scraped\icnarc_29052020\icnarc_200529.pdf')

I get this error:

FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\myname\\Rprojects\\Reports_scraping\\data_scraped\\icnarc_29052020\\icnarc_200529.pdf'

How I can solve this issue?

Body:
There can be only one possibility, the file is not there, but you have already checked that I assume, if not, Once again check whether the spelling of file is correct. If this doesn't work, then do below trick

Execute the py code in same folder as file, and then use

from tabula import read_pdf
file = read_pdf(r'icnarc_200529.pdf')

Sometimes, this simple method does the trick.


问:
streaming video from a python server to a web client
How do I stream a video from a python server to an html page web client (nodejs)?

I'm using a node js web project and I'm just writing frames with python and reading them with javascript but I can't use a high frame rate nor a high resolution.

Thanks for helping. This is the code I'm using to read the frame:

```<code>var button = document.getElementById('play');

button.addEventListener('click', function refresh() {

  document.getElementById("myimg").src = "images/color_img.jpg?" + new Date().getTime();
   v= setTimeout(refresh, 100);
});

var button2 = document.getElementById('pause');
button2.addEventListener('click', function myStopFunction() {
  clearTimeout(v);
});
</code>```

答:
thanks guys this is solved im using this python (flask) code to stream live feed from web cam :

```<code>    #!/usr/bin/env python
from flask import Flask, render_template, Response
import cv2
import sys
import numpy

app = Flask(__name__)

def get_frame():
    camera_port=0
    camera=cv2.VideoCapture(camera_port) #this makes a web cam object

    while True:
        retval, im = camera.read()
        imgencode=cv2.imencode('.jpg',im)[1]
        stringData=imgencode.tostring()
        yield (b'--frame\r\n'
            b'Content-Type: text/plain\r\n\r\n'+stringData+b'\r\n')

    del(camera)

@app.route('/vid')
def vid():
     return Response(get_frame(),mimetype='multipart/x-mixed-replace; boundary=frame')

if __name__ == '__main__':
    app.run(host='localhost',port=5000, debug=True, threaded=True)
</code>```

code written by mr Mohit Kumar i found it on youtube .

to retrieve the live feed i m using

```<code><img src="http://localhost:3000/vid">
</code>```

note : you have to specify clearly the protocole used.
       also it doesn't matter what web framework you are using (it worked on nodejs and flask)
thanks for help

Body:
How do I stream a video from a python server to an html page web client (nodejs)?

I'm using a node js web project and I'm just writing frames with python and reading them with javascript but I can't use a high frame rate nor a high resolution.

Thanks for helping. This is the code I'm using to read the frame:

var button = document.getElementById('play');

button.addEventListener('click', function refresh() {

  document.getElementById("myimg").src = "images/color_img.jpg?" + new Date().getTime();
   v= setTimeout(refresh, 100);
});

var button2 = document.getElementById('pause');
button2.addEventListener('click', function myStopFunction() {
  clearTimeout(v);
});

Body:
thanks guys this is solved im using this python (flask) code to stream live feed from web cam :

    #!/usr/bin/env python
from flask import Flask, render_template, Response
import cv2
import sys
import numpy

app = Flask(__name__)

def get_frame():
    camera_port=0
    camera=cv2.VideoCapture(camera_port) #this makes a web cam object

    while True:
        retval, im = camera.read()
        imgencode=cv2.imencode('.jpg',im)[1]
        stringData=imgencode.tostring()
        yield (b'--frame\r\n'
            b'Content-Type: text/plain\r\n\r\n'+stringData+b'\r\n')

    del(camera)

@app.route('/vid')
def vid():
     return Response(get_frame(),mimetype='multipart/x-mixed-replace; boundary=frame')

if __name__ == '__main__':
    app.run(host='localhost',port=5000, debug=True, threaded=True)

code written by mr Mohit Kumar i found it on youtube .

to retrieve the live feed i m using

<img src="http://localhost:3000/vid">

note : you have to specify clearly the protocole used.
       also it doesn't matter what web framework you are using (it worked on nodejs and flask)
thanks for help


问:
How can I get the output of Ansible ad-hoc command in JSON, CSV or other format?
What is the way to get the output of Ansible ad-hoc command in JSON, CSV or other format?</p>

答:
You could also do it through the environment variables if you do not want to modify the .cfg file, for example:

ANSIBLE_LOAD_CALLBACK_PLUGINS=true \
ANSIBLE_STDOUT_CALLBACK=json \
ansible all \
  -a "df -h /tmp"
```

More info on Ansible environment variables here:
https://docs.ansible.com/ansible/latest/reference_appendices/config.html#environment-variables.

Body:
You could also do it through the environment variables if you do not want to modify the .cfg file, for example:

ANSIBLE_LOAD_CALLBACK_PLUGINS=true \
ANSIBLE_STDOUT_CALLBACK=json \
ansible all \
  -a "df -h /tmp"

More info on Ansible environment variables here:
https://docs.ansible.com/ansible/latest/reference_appendices/config.html#environment-variables.


问:
CEdit Text Retrieval in mfc
I am using CEdit with the property of Multiline.My objective is to retrieve the individual line and place it in my CStringArray.

While retrieving the line using GetLine , I have to know the string length of that line.

How to get this?

I tried the function GetLineLength() but that will return the size of the entire line rather than the specified text.

I pasted the code that i have implemented so far:

```<code>CEdit m_strMnemonicCode;
CStringArray strMnemonicArray;
LPTSTR temp =  new TCHAR[50];;
int nLineCount = m_strMnemonicCode.GetLineCount();
for(int ni = 0 ; ni < nLineCount ; ni++)
{
    int len = m_strMnemonicCode.LineLength(m_strMnemonicCode.LineIndex(ni));
            //m_strMnemonicCode.GetLine(ni, strText.GetBuffer(len), len);
    m_strMnemonicCode.GetLine( ni , temp );
    strMnemonicArray.Add(strText);
}
</code>```

答:
But you need to know the length of the whole line, don't you?

I would not define the buffer as an array of TCHARs, but as a CString, then do GetBuffer() on it.

Check the example in CEdit::GetLineCount

It seems to do more or less what you need.

Edit

I've just written the following test, and it works perfectly for me:

```<code>int lc = m_Edit.GetLineCount();

CString strLine;
CStringArray arr;

for (int i = 0; i < lc ; i++)
{
    int len = m_Edit.LineLength(m_Edit.LineIndex(i));
    m_Edit.GetLine(i, strLine.GetBuffer(len), len);
    strLine.ReleaseBuffer(len);

    arr.Add(strLine);
}
</code>```

Maybe you are forgetting to add the buffer length to ReleaseBuffer()?

Title: CEdit Text Retrieval in mfc

Body:
I am using CEdit with the property of Multiline.My objective is to retrieve the individual line and place it in my CStringArray.

While retrieving the line using GetLine , I have to know the string length of that line.

How to get this?

I tried the function GetLineLength() but that will return the size of the entire line rather than the specified text.

I pasted the code that i have implemented so far:

CEdit m_strMnemonicCode;
CStringArray strMnemonicArray;
LPTSTR temp =  new TCHAR[50];;
int nLineCount = m_strMnemonicCode.GetLineCount();
for(int ni = 0 ; ni < nLineCount ; ni++)
{
    int len = m_strMnemonicCode.LineLength(m_strMnemonicCode.LineIndex(ni));
            //m_strMnemonicCode.GetLine(ni, strText.GetBuffer(len), len);
    m_strMnemonicCode.GetLine( ni , temp );
    strMnemonicArray.Add(strText);
}

Body:
But you need to know the length of the whole line, don't you?

I would not define the buffer as an array of TCHARs, but as a CString, then do GetBuffer() on it.

Check the example in CEdit::GetLineCount

It seems to do more or less what you need.

Edit

I've just written the following test, and it works perfectly for me:

int lc = m_Edit.GetLineCount();

CString strLine;
CStringArray arr;

for (int i = 0; i < lc ; i++)
{
    int len = m_Edit.LineLength(m_Edit.LineIndex(i));
    m_Edit.GetLine(i, strLine.GetBuffer(len), len);
    strLine.ReleaseBuffer(len);

    arr.Add(strLine);
}

Maybe you are forgetting to add the buffer length to ReleaseBuffer()?


问:
How do you use conditional Activity in ADF in case of failure?
I have pretty simple requirement but not sure how this can be implemented in ADF. I have a lookup activity which check certain value in SQL dataset. If it fails I want pipeline variable to be set to one value and if it succeeded then to another and continue on with pipeline. I tried to use "Success/Failure" output of lookup activity but issue is that I can not continue with pipeline since it waits for both activities to finish. I tried to use "IF" activity but I can not figure out how do I detect if previous activity failed to put it as "IF" Condition. What are my choices?</p>

答:
Put your lookup and variable setting on success/fail in their own pipeline.
Then call that pipeline in your main pipeline using ExecutePipeline activity - use the Completed result from ExecutePipeline as the dependency for subsequent tasks so that they run whether the inner failed or not.

See this post for more help.


问:
LiveData is duplicating MutableList
I want to update my Recyclerview items whenever there is a data change in Firestore.
So my activity have the following code:

```<code>taskViewModel.fetchedTaskLiveData.observe(
   this, Observer {
    if (it != null) {
     todoListAdapter.setListData(it)
     showRecyclerView()
   }

</code>```

Inside adapter setListData method:

```<code>fun setListData(data: MutableList<Todo>) {
        //this.todoList.clear()
        this.todoList.addAll(data)
        notifyDataSetChanged()
    }
</code>```

In this situation, whenever a changed list is fetched, Recyclerview is duplicating and adding the changed
list below the old list.

And if "this.todoList.clear()" is uncommented, list is getting cleared and no data is showing on data change.

I tried all possible solutions, but I think somewhere am missing a part. stuck since a long time.
Thanks a lot for all kind of suggestion.

答:
So I was stuck with this and found out after 12 hours a tiny change.
I corrected it by changing for with forEach and that changed the game.

Also I am clearing list items before adding the items.

```<code>todoList.clear()
</code>```

Title: LiveData is duplicating MutableList

Body:
I want to update my Recyclerview items whenever there is a data change in Firestore.
So my activity have the following code:

taskViewModel.fetchedTaskLiveData.observe(
   this, Observer {
    if (it != null) {
     todoListAdapter.setListData(it)
     showRecyclerView()
   }

Inside adapter setListData method:

fun setListData(data: MutableList<Todo>) {
        //this.todoList.clear()
        this.todoList.addAll(data)
        notifyDataSetChanged()
    }

In this situation, whenever a changed list is fetched, Recyclerview is duplicating and adding the changed
list below the old list.

And if "this.todoList.clear()" is uncommented, list is getting cleared and no data is showing on data change.

I tried all possible solutions, but I think somewhere am missing a part. stuck since a long time.
Thanks a lot for all kind of suggestion.

Body:
So I was stuck with this and found out after 12 hours a tiny change.
I corrected it by changing for with forEach and that changed the game.

Also I am clearing list items before adding the items.

todoList.clear()


问:
How can we draw 3D bulding structure from existing image Jquery,Css?
Please see this site it was made in flash:
Can we do it by jquery css?

Go here

And click on any building marked with "Release"
You will see one building on hover animation effect.
That i want to develop using jquery and css
Or you can suggest for development

答:
May 2020, in my answer on a similar Question, I showed the OP in my Answer how to use an SVG file instead and have much more control over the image overlay and use a CSS only solution (with  and some demo text showing on :hover). I also made the HTML page fully responsive for use on varying devices.

Posting the code snippet here only (go 'Full page' for a better look. Resize browser to test responsiveness):

/*
    Visit below answers on Stackoverflow for an explanation
    of the math used for responsive sizing of elements.

    https://stackoverflow.com/a/62033317/2015909
    https://stackoverflow.com/a/61867702/2015909
*/
/**************************/
/* preferred global rules */
/**************************/
html,body               { box-sizing: border-box; width: 100%; max-width: 100%; height: 100% }
*::before,*::after, *   { box-sizing: inherit }
body                    { margin: 0 }

/* responsive base font size using y = mx + b */
html    { font-size: calc(0.625vmin + 0.75rem) } /* (320,14)(1280,20) */
body    { font-size: 1rem }

[band]  { display: flex; flex-flow: column wrap; align-content: center }

[padded="1"], [padded="0"] [band*="padded"] {
/*
    responsive page padding
    and responsive band padding (same as responsive page padding, but at band level)
    p1(320,32) p2(1920, 72) => 0.025x + 24
    p3(320, 8) p4(1920,320) => 0.195x - 54.4

    'Band padding' is only active when 'page padding' is off
*/
    padding: calc( 2.5vh + 24px) calc(19.5vw - 54.4px);
}

/* Making sure the image fits in any viewport, either portrait or landscape */
@media (orientation: portrait ) { #construction-site { height: auto; width: 100% } }
@media (orientation: landscape) { #construction-site { height: 100%; width: auto } }
</style>```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body padded="0">
<div id="construction-site" band="padded">
    <svg viewbox="0 0 1600 1200"
         xmlns="http://www.w3.org/2000/svg"
         xmlns:xlink="http://www.w3.org/1999/xlink">

        <style>
            .line       { stroke: Black; stroke-opacity: 0; stroke-width: 2px; cursor: pointer }
            .polyline   { fill  : Red  ; fill-opacity  : 0 }

            .floor-text { fill: Black; stroke: none; fill-opacity: 0; cursor: default;
                          font-weight: bold; font-family: sans-serif;
                          /* responsive font using y = mx + b */
                          font-size: calc(-1vmin + 51.2px); /* (320,48)(1920,32) */
                        }

            .floor:hover>.line       { fill-opacity: .4; stroke-opacity: .8 }
            .floor:hover+.floor-text { fill-opacity: .7 }
        </style>

        <image href="https://i.imgur.com/0i4N0d3.jpg"/>

            <polyline class="line polyline"
                points="201.242,678.473 1121.43, 333.16 1370.24,
                        553.473 1387.74, 668.473 1127.49,
                        474.098 189.242, 753.473 202.242, 678.973"/>

            <line class="line" x1="1121.42" y1="333.472" x2="1127.45" y2="474.097"/>

        <text class="floor-text" x="800" y="150" text-anchor="middle">top floor demo text</text>
    </svg>
</div>
</body></code>```

Body:
May 2020, in my answer on a similar Question, I showed the OP in my Answer how to use an SVG file instead and have much more control over the image overlay and use a CSS only solution (with <a> and some demo text showing on :hover). I also made the HTML page fully responsive for use on varying devices.

Posting the code snippet here only (go 'Full page' for a better look. Resize browser to test responsiveness):

/*
    Visit below answers on Stackoverflow for an explanation
    of the math used for responsive sizing of elements.

    https://stackoverflow.com/a/62033317/2015909
    https://stackoverflow.com/a/61867702/2015909
*/
/**************************/
/* preferred global rules */
/**************************/
html,body               { box-sizing: border-box; width: 100%; max-width: 100%; height: 100% }
*::before,*::after, *   { box-sizing: inherit }
body                    { margin: 0 }

/* responsive base font size using y = mx + b */
html    { font-size: calc(0.625vmin + 0.75rem) } /* (320,14)(1280,20) */
body    { font-size: 1rem }

[band]  { display: flex; flex-flow: column wrap; align-content: center }

[padded="1"], [padded="0"] [band*="padded"] {
/*
    responsive page padding
    and responsive band padding (same as responsive page padding, but at band level)
    p1(320,32) p2(1920, 72) => 0.025x + 24
    p3(320, 8) p4(1920,320) => 0.195x - 54.4

    'Band padding' is only active when 'page padding' is off
*/
    padding: calc( 2.5vh + 24px) calc(19.5vw - 54.4px);
}

/* Making sure the image fits in any viewport, either portrait or landscape */
@media (orientation: portrait ) { #construction-site { height: auto; width: 100% } }
@media (orientation: landscape) { #construction-site { height: 100%; width: auto } }
</style>

<body padded="0">
<div id="construction-site" band="padded">
    <svg viewbox="0 0 1600 1200"
         xmlns="http://www.w3.org/2000/svg"
         xmlns:xlink="http://www.w3.org/1999/xlink">

        <style>
            .line       { stroke: Black; stroke-opacity: 0; stroke-width: 2px; cursor: pointer }
            .polyline   { fill  : Red  ; fill-opacity  : 0 }

            .floor-text { fill: Black; stroke: none; fill-opacity: 0; cursor: default;
                          font-weight: bold; font-family: sans-serif;
                          /* responsive font using y = mx + b */
                          font-size: calc(-1vmin + 51.2px); /* (320,48)(1920,32) */
                        }

            .floor:hover>.line       { fill-opacity: .4; stroke-opacity: .8 }
            .floor:hover+.floor-text { fill-opacity: .7 }
        </style>

        <image href="https://i.imgur.com/0i4N0d3.jpg"/>

        <a id="top-floor" class="floor" rel="noopener" target="_blank" href="javascript:void(0)" title="top floor, click for details...">
            <polyline class="line polyline"
                points="201.242,678.473 1121.43, 333.16 1370.24,
                        553.473 1387.74, 668.473 1127.49,
                        474.098 189.242, 753.473 202.242, 678.973"/>

            <line class="line" x1="1121.42" y1="333.472" x2="1127.45" y2="474.097"/>

        </a>
        <text class="floor-text" x="800" y="150" text-anchor="middle">top floor demo text</text>
    </svg>
</div>
</body>


问:
Get vector from exprTk as output
I can't seem to get a vector output from exprTk. I figure it should be relatively simple but in the manual I can only find how to input a vector and not how to output one.

What I currently have is the following:

```<code>typedef double T; // numeric type (float, double, mpfr etc...)
typedef exprtk::symbol_table<T> symbol_table_t;
typedef exprtk::expression<T>     expression_t;
typedef exprtk::parser<T>             parser_t;

std::string expression_string = "var z[2] := { x, y };";

T x = T(5.3);
T y = T(2.3);
std::vector<T> z;

symbol_table_t symbol_table;
symbol_table.add_variable("x", x);
symbol_table.add_variable("y", y);
symbol_table.add_vector("z", z);

expression_t expression;
expression.register_symbol_table(symbol_table);

//Check if expression is valid
parser_t parser;
if (!parser.compile(expression_string, expression))
{
    printf("Compilation error...\n");
    return;
}

T result = expression.value();
std::cout << result << std::endl;     \\returns: 5.3 as expected the first element of vector z.
std::cout << z[0] << std::endl;       \\Crashes the program
</code>```

What I want as output is just the vector z.
How do I do this, or what am I doing wrong?

答:
As per Section 20 - Expression Return Values of the readme, One can immediately exit an expression returning any number of variables of any type simply by using the return statement.

The example provided in the documentation is as follows:

```<code>std::string expression_string =
   " if (x < y)                                   "
   "   return [x + 1,'return-call 1'];            "
   " else if (x > y)                              "
   "   return [y / 2, y + 1, 'return-call 2'];    "
   " else if (equal(x,y))                         "
   "   x + y;                                     "
   " return [x, y, x + y, x - y, 'return-call 3'] ";

typedef exprtk::symbol_table<double> symbol_table_t;
typedef exprtk::expression<double>     expression_t;
typedef exprtk::parser<double>             parser_t;

symbol_table_t symbol_table;
expression_t   expression;
parser_t       parser;

double x = 0;
double y = 0;

symbol_table.add_variable("x",x);
symbol_table.add_variable("y",y);

expression.register_symbol_table(symbol_table);

parser.compile(expression_string,expression);

T result = expression.value();

if (expression.results().count())
{
   typedef exprtk::results_context<T> results_context_t;
   typedef typename results_context_t::type_store_t type_t;
   typedef typename type_t::scalar_view scalar_t;
   typedef typename type_t::vector_view vector_t;
   typedef typename type_t::string_view string_t;

   const results_context_t& results = expression.results();

   for (std::size_t i = 0; i < results.count(); ++i)
   {
      type_t t = results[i];

      switch (t.type)
      {
         case type_t::e_scalar : ...
                                 break;

         case type_t::e_vector : ...
                                 break;

         case type_t::e_string : ...
                                 break;

         default               : continue;
      }
}
</code>```

Note1:
Your expression will become:

```<code>var z[2] := { x, y }; return [z];
</code>```

Note2:
In order to have your "one-line" method you could write a simple free function that wraps the boiler plate code after the conditional and extracts the vector of your choosing (i'th result given it's of vector type) from the results list.

```<code>template <typename T>
bool get_vector(const std::size_t index,
                const results_context_t& results,
                std::vector<T>& v)
{
   ...
}
</code>```

Title: Get vector from exprTk as output

Body:
I can't seem to get a vector output from exprTk. I figure it should be relatively simple but in the manual I can only find how to input a vector and not how to output one.

What I currently have is the following:

typedef double T; // numeric type (float, double, mpfr etc...)
typedef exprtk::symbol_table<T> symbol_table_t;
typedef exprtk::expression<T>     expression_t;
typedef exprtk::parser<T>             parser_t;

std::string expression_string = "var z[2] := { x, y };";

T x = T(5.3);
T y = T(2.3);
std::vector<T> z;

symbol_table_t symbol_table;
symbol_table.add_variable("x", x);
symbol_table.add_variable("y", y);
symbol_table.add_vector("z", z);

expression_t expression;
expression.register_symbol_table(symbol_table);

//Check if expression is valid
parser_t parser;
if (!parser.compile(expression_string, expression))
{
    printf("Compilation error...\n");
    return;
}

T result = expression.value();
std::cout << result << std::endl;     \\returns: 5.3 as expected the first element of vector z.
std::cout << z[0] << std::endl;       \\Crashes the program

What I want as output is just the vector z.
How do I do this, or what am I doing wrong?

Body:
As per Section 20 - Expression Return Values of the readme, One can immediately exit an expression returning any number of variables of any type simply by using the return statement.

The example provided in the documentation is as follows:

std::string expression_string =
   " if (x < y)                                   "
   "   return [x + 1,'return-call 1'];            "
   " else if (x > y)                              "
   "   return [y / 2, y + 1, 'return-call 2'];    "
   " else if (equal(x,y))                         "
   "   x + y;                                     "
   " return [x, y, x + y, x - y, 'return-call 3'] ";

typedef exprtk::symbol_table<double> symbol_table_t;
typedef exprtk::expression<double>     expression_t;
typedef exprtk::parser<double>             parser_t;

symbol_table_t symbol_table;
expression_t   expression;
parser_t       parser;

double x = 0;
double y = 0;

symbol_table.add_variable("x",x);
symbol_table.add_variable("y",y);

expression.register_symbol_table(symbol_table);

parser.compile(expression_string,expression);

T result = expression.value();

if (expression.results().count())
{
   typedef exprtk::results_context<T> results_context_t;
   typedef typename results_context_t::type_store_t type_t;
   typedef typename type_t::scalar_view scalar_t;
   typedef typename type_t::vector_view vector_t;
   typedef typename type_t::string_view string_t;

   const results_context_t& results = expression.results();

   for (std::size_t i = 0; i < results.count(); ++i)
   {
      type_t t = results[i];

      switch (t.type)
      {
         case type_t::e_scalar : ...
                                 break;

         case type_t::e_vector : ...
                                 break;

         case type_t::e_string : ...
                                 break;

         default               : continue;
      }
}

Note1:
Your expression will become:

var z[2] := { x, y }; return [z];

Note2:
In order to have your "one-line" method you could write a simple free function that wraps the boiler plate code after the conditional and extracts the vector of your choosing (i'th result given it's of vector type) from the results list.

template <typename T>
bool get_vector(const std::size_t index,
                const results_context_t& results,
                std::vector<T>& v)
{
   ...
}


问:
CMake is unable to find SDL2_ttf, I'm trying to link it the same way I would with SDL2 and both are properly installed on Ubuntu 18.04
I get the error:

```<code>CMake Error at CMakeLists.txt:11 (find_package):
  By not providing "FindSDL2_ttf.cmake" in CMAKE_MODULE_PATH this project has
  asked CMake to find a package configuration file provided by "SDL2_ttf",
  but CMake did not find one.

  Could not find a package configuration file provided by "SDL2_ttf" with any
  of the following names:

    SDL2_ttfConfig.cmake
    sdl2_ttf-config.cmake

  Add the installation prefix of "SDL2_ttf" to CMAKE_PREFIX_PATH or set
  "SDL2_ttf_DIR" to a directory containing one of the above files.  If
  "SDL2_ttf" provides a separate development package or SDK, be sure it has
  been installed.
</code>```

Here is what my cmake file looks like:

```<code>cmake_minimum_required(VERSION 3.14)
project(Smithereens)

set(CMAKE_CXX_STANDARD 17)

add_executable(Smithereens main.cpp)

find_package(SDL2 REQUIRED)
include_directories(${SDL2_INCLUDE_DIRS})

find_package(SDL2_ttf REQUIRED)
include_directories(${SDL2_ttf_INCLUDE_DIRS})

target_link_libraries(Smithereens ${SDL2_LIBRARIES} ${SDL2_ttf_LIBRARIES})
</code>```

Both SDL2 and SDL2_ttf are installed on my machine, I'm sure I'm just linking incorrectly, learning CMake has been a huge headache for me.

答:
This works pretty well for me, Ubuntu 18.04.</p>

```<code>INCLUDE(FindPkgConfig)
PKG_SEARCH_MODULE(SDL2 REQUIRED sdl2)
PKG_SEARCH_MODULE(SDL2IMAGE REQUIRED SDL2_image>=2.0.0)
PKG_SEARCH_MODULE(SDL2TTF REQUIRED SDL2_ttf>=2.0.0)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

set(SOURCE_FILES main.cpp)

add_executable(${PROJECT_NAME} ${SOURCE_FILES})

target_include_directories(${PROJECT_NAME} PRIVATE
    include ${SDL2_INCLUDE_DIRS} ${SDL2IMAGE_INCLUDE_DIRS} ${SDL2TTF_INCLUDE_DIRS})

target_link_libraries(${PROJECT_NAME} PRIVATE
    ${SDL2_LIBRARIES} ${SDL2IMAGE_LIBRARIES} ${SDL2TTF_LIBRARIES})
</code>```

Body:
I get the error:

CMake Error at CMakeLists.txt:11 (find_package):
  By not providing "FindSDL2_ttf.cmake" in CMAKE_MODULE_PATH this project has
  asked CMake to find a package configuration file provided by "SDL2_ttf",
  but CMake did not find one.

  Could not find a package configuration file provided by "SDL2_ttf" with any
  of the following names:

    SDL2_ttfConfig.cmake
    sdl2_ttf-config.cmake

  Add the installation prefix of "SDL2_ttf" to CMAKE_PREFIX_PATH or set
  "SDL2_ttf_DIR" to a directory containing one of the above files.  If
  "SDL2_ttf" provides a separate development package or SDK, be sure it has
  been installed.

Here is what my cmake file looks like:

cmake_minimum_required(VERSION 3.14)
project(Smithereens)

set(CMAKE_CXX_STANDARD 17)

add_executable(Smithereens main.cpp)

find_package(SDL2 REQUIRED)
include_directories(${SDL2_INCLUDE_DIRS})

find_package(SDL2_ttf REQUIRED)
include_directories(${SDL2_ttf_INCLUDE_DIRS})

target_link_libraries(Smithereens ${SDL2_LIBRARIES} ${SDL2_ttf_LIBRARIES})

Both SDL2 and SDL2_ttf are installed on my machine, I'm sure I'm just linking incorrectly, learning CMake has been a huge headache for me.

Body:
This works pretty well for me, Ubuntu 18.04.

INCLUDE(FindPkgConfig)
PKG_SEARCH_MODULE(SDL2 REQUIRED sdl2)
PKG_SEARCH_MODULE(SDL2IMAGE REQUIRED SDL2_image>=2.0.0)
PKG_SEARCH_MODULE(SDL2TTF REQUIRED SDL2_ttf>=2.0.0)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

set(SOURCE_FILES main.cpp)

add_executable(${PROJECT_NAME} ${SOURCE_FILES})

target_include_directories(${PROJECT_NAME} PRIVATE
    include ${SDL2_INCLUDE_DIRS} ${SDL2IMAGE_INCLUDE_DIRS} ${SDL2TTF_INCLUDE_DIRS})

target_link_libraries(${PROJECT_NAME} PRIVATE
    ${SDL2_LIBRARIES} ${SDL2IMAGE_LIBRARIES} ${SDL2TTF_LIBRARIES})