问:
Update an existing dataframe with input values in R shiny
i am working on a shiny application where my user will

input an integer value

select a value from list

if my user click on action button, an existing dataframe has to be updated with the values entered.

The updated dataframe should be displayed on dashboard body

```<code>library(shiny)
library(shinydashboard)

ui <-

dashboardPage(

    dashboardHeader(title = "title"),
    dashboardSidebar(

      selectInput("transaction_type", "select transaction type:", choices =
  tranlist,selected = NULL),
  selectInput("entry_type", "select entry type", choices = entrylist),
  selectInput("sic", "select sic", choices = siclist),
  selectInput("markettype", "select market type", choices = marketlist),
  numericInput("qty", "enter quantity","",min = 0),
  numericInput("volume", "enter Total_amnt","",min = 0),

    ),
    dashboardBody(
      tableOutput("result")
    )
  )

server <- function(input, output,session){

pos <- reactive({

if(input$goButton >0){

 pos <- test[test$transaction_type == input$transaction_type &&
 test$entry_type == input$entry_type && test$qty == input$qty &&
 test$total_amount == input$volume && test$Average_Amnt == (input$volume/
 input$qty) && test$markettype == input$markettype && test$sic == input$sic]
 }  else{pos<- test}

return(pos)

})

output$result <- renderTable(pos())

}
</code>```

While clicking the action button, i'm getting the following error.

Listening on http://127.0.0.1:7447
    Warning: Error in <-: invalid subscript type 'list'
    Stack trace (innermost first):
    80: xtable.data.frame
    79:
    78: do.call
    77: origRenderFunc
    76: output$result
     1: runApp

Please help me. Thanks in advance.

dput output is below

```<code>> dput(test)
structure(list(transaction_type = structure(4L, .Label = c("10",
"11", "15", "20", "21", "25"), class = "factor"), entry_type =
structure(13L, .Label = c("AMER",
"ARC", "BOC", "CCD", "CIE", "CTX", "DISC", "EFT", "JCB", "MAST",
"POP", "POS", "PPD", "RCK", "TEL", "VISA", "WEB"), class = "factor"),
qty = 391L, total_amount = 10212.13, sic = structure(12L, .Label = c("4900",
"5047", "6012", "6300", "6513", "7372", "7393", "7399", "7997",
"8099", "8351", "8931", "8999", "9311", "9399"), class = "factor"),
markettype = structure(1L, .Label = c("0", "1", "2", "3",
"4"), class = "factor"), Average_Amnt = 26.1179795396419), .Names =
c("transaction_type",
"entry_type", "qty", "total_amount", "sic", "markettype", "Average_Amnt"
), row.names = c(NA, -1L), spec = structure(list(cols = structure(list(
location_id = structure(list(), class = c("collector_integer",
"collector")), settle_date = structure(list(format = ""), .Names = "format",
class = c("collector_date",
"collector")), transaction_type = structure(list(), class =
c("collector_integer",
"collector")), entry_type = structure(list(), class =
c("collector_character",
"collector")), response_code = structure(list(), class =
c("collector_character",
"collector")), funding_type = structure(list(), class =
c("collector_character",
"collector")), qty = structure(list(), class = c("collector_integer",
"collector")), service_fee = structure(list(), class = c("collector_skip",
"collector")), total_amount = structure(list(), class =
c("collector_double",
"collector")), organization_id = structure(list(), class =
c("collector_skip",
"collector")), status = structure(list(), class = c("collector_character",
"collector")), sic = structure(list(), class = c("collector_integer",
"collector")), markettype = structure(list(), class = c("collector_integer",
"collector")), isoid = structure(list(), class = c("collector_skip",
"collector")), city = structure(list(), class = c("collector_skip",
"collector")), StateProvince = structure(list(), class =
c("collector_character",
"collector")), postalcode = structure(list(), class = c("collector_skip",
"collector")), CreateDate = structure(list(format = ""), .Names = "format",
class = c("collector_datetime",
"collector")), DeleteDate = structure(list(), class = c("collector_skip",
"collector"))), .Names = c("location_id", "settle_date",
"transaction_type", "entry_type", "response_code", "funding_type",
"qty", "service_fee", "total_amount", "organization_id", "status",
"sic", "markettype", "isoid", "city", "StateProvince", "postalcode",
"CreateDate", "DeleteDate")), default = structure(list(), class =
c("collector_guess",
"collector"))), .Names = c("cols", "default"), class = "col_spec"), class =
c("tbl_df",
"tbl", "data.frame"))
</code>```

答:
The following code worked for me.</p>

```<code>library(shiny)
library(shinydashboard)

ui =   dashboardPage(

dashboardHeader(title = "title"),
dashboardSidebar(

  selectInput("transaction_type", "select transaction type:", choices =
                tranlist),
  selectInput("entry_type", "select entry type", choices = entrylist),
  selectInput("sic", "select sic", choices = siclist),
  selectInput("markettype", "select market type", choices = marketlist),
  numericInput("qty", "enter quantity","",min = 0),
  numericInput("volume", "enter Total_amnt","",min = 0),
  actionButton("goButton","Enter")

),
dashboardBody(
  tableOutput("result")

)
)

#server.R

function(input, output,session){

pos <- eventReactive(input$goButton,{

if(input$goButton >0){

test[1:7] = c(input$transaction_type, input$entry_type, input$qty,
input$volume , input$sic, input$markettype, input$volume/input$qty)
}  else{pos <- test}

 test

})

output$result <- renderTable(pos())

}
</code>```

Body:
i am working on a shiny application where my user will

input an integer value

select a value from list

if my user click on action button, an existing dataframe has to be updated with the values entered.

The updated dataframe should be displayed on dashboard body

library(shiny)
library(shinydashboard)

ui <-

dashboardPage(

    dashboardHeader(title = "title"),
    dashboardSidebar(

      selectInput("transaction_type", "select transaction type:", choices =
  tranlist,selected = NULL),
  selectInput("entry_type", "select entry type", choices = entrylist),
  selectInput("sic", "select sic", choices = siclist),
  selectInput("markettype", "select market type", choices = marketlist),
  numericInput("qty", "enter quantity","",min = 0),
  numericInput("volume", "enter Total_amnt","",min = 0),

    ),
    dashboardBody(
      tableOutput("result")
    )
  )

server <- function(input, output,session){

pos <- reactive({

if(input$goButton >0){

 pos <- test[test$transaction_type == input$transaction_type &&
 test$entry_type == input$entry_type && test$qty == input$qty &&
 test$total_amount == input$volume && test$Average_Amnt == (input$volume/
 input$qty) && test$markettype == input$markettype && test$sic == input$sic]
 }  else{pos<- test}

return(pos)

})

output$result <- renderTable(pos())

}

While clicking the action button, i'm getting the following error.

Listening on http://127.0.0.1:7447
    Warning: Error in <-: invalid subscript type 'list'
    Stack trace (innermost first):
    80: xtable.data.frame
    79:
    78: do.call
    77: origRenderFunc
    76: output$result
     1: runApp

Please help me. Thanks in advance.

dput output is below

> dput(test)
structure(list(transaction_type = structure(4L, .Label = c("10",
"11", "15", "20", "21", "25"), class = "factor"), entry_type =
structure(13L, .Label = c("AMER",
"ARC", "BOC", "CCD", "CIE", "CTX", "DISC", "EFT", "JCB", "MAST",
"POP", "POS", "PPD", "RCK", "TEL", "VISA", "WEB"), class = "factor"),
qty = 391L, total_amount = 10212.13, sic = structure(12L, .Label = c("4900",
"5047", "6012", "6300", "6513", "7372", "7393", "7399", "7997",
"8099", "8351", "8931", "8999", "9311", "9399"), class = "factor"),
markettype = structure(1L, .Label = c("0", "1", "2", "3",
"4"), class = "factor"), Average_Amnt = 26.1179795396419), .Names =
c("transaction_type",
"entry_type", "qty", "total_amount", "sic", "markettype", "Average_Amnt"
), row.names = c(NA, -1L), spec = structure(list(cols = structure(list(
location_id = structure(list(), class = c("collector_integer",
"collector")), settle_date = structure(list(format = ""), .Names = "format",
class = c("collector_date",
"collector")), transaction_type = structure(list(), class =
c("collector_integer",
"collector")), entry_type = structure(list(), class =
c("collector_character",
"collector")), response_code = structure(list(), class =
c("collector_character",
"collector")), funding_type = structure(list(), class =
c("collector_character",
"collector")), qty = structure(list(), class = c("collector_integer",
"collector")), service_fee = structure(list(), class = c("collector_skip",
"collector")), total_amount = structure(list(), class =
c("collector_double",
"collector")), organization_id = structure(list(), class =
c("collector_skip",
"collector")), status = structure(list(), class = c("collector_character",
"collector")), sic = structure(list(), class = c("collector_integer",
"collector")), markettype = structure(list(), class = c("collector_integer",
"collector")), isoid = structure(list(), class = c("collector_skip",
"collector")), city = structure(list(), class = c("collector_skip",
"collector")), StateProvince = structure(list(), class =
c("collector_character",
"collector")), postalcode = structure(list(), class = c("collector_skip",
"collector")), CreateDate = structure(list(format = ""), .Names = "format",
class = c("collector_datetime",
"collector")), DeleteDate = structure(list(), class = c("collector_skip",
"collector"))), .Names = c("location_id", "settle_date",
"transaction_type", "entry_type", "response_code", "funding_type",
"qty", "service_fee", "total_amount", "organization_id", "status",
"sic", "markettype", "isoid", "city", "StateProvince", "postalcode",
"CreateDate", "DeleteDate")), default = structure(list(), class =
c("collector_guess",
"collector"))), .Names = c("cols", "default"), class = "col_spec"), class =
c("tbl_df",
"tbl", "data.frame"))

Body:
The following code worked for me.

library(shiny)
library(shinydashboard)

ui =   dashboardPage(

dashboardHeader(title = "title"),
dashboardSidebar(

  selectInput("transaction_type", "select transaction type:", choices =
                tranlist),
  selectInput("entry_type", "select entry type", choices = entrylist),
  selectInput("sic", "select sic", choices = siclist),
  selectInput("markettype", "select market type", choices = marketlist),
  numericInput("qty", "enter quantity","",min = 0),
  numericInput("volume", "enter Total_amnt","",min = 0),
  actionButton("goButton","Enter")

),
dashboardBody(
  tableOutput("result")

)
)

#server.R

function(input, output,session){

pos <- eventReactive(input$goButton,{

if(input$goButton >0){

test[1:7] = c(input$transaction_type, input$entry_type, input$qty,
input$volume , input$sic, input$markettype, input$volume/input$qty)
}  else{pos <- test}

 test

})

output$result <- renderTable(pos())

}


来源: stackexchange

问:
Group rows into a new row and sum in r
So I have data that seems like this:

```<code> Week        Total Amount        Person
   1            $5                 A
   1            $5                 B
   1            $4                 C
   1            $2                 D
   1            $1                 E
   2            $5                 A
   2            $1                 B
   2            $1                 H
   2            $3                 G
   2            $5                 C
   2            $5                 F
</code>```

How do I make it so that I will show the top 3 for each week and sum all other amounts into "Others"? I want it to show:

```<code> Week        Total Amount        Person
   1            $5                 A
   1            $5                 B
   1            $4                 C
   1            $3                 Others
   2            $5                 A
   2            $5                 C
   2            $5                 F
   2            $5                 Others
</code>```

Notice that the other amounts that are not top 3 are summed into a new total amount, and it accounts for the random number of rows for each week (say week 1 has 5 total amounts for each person, but week 2 has 6, and week 3 may be 8 or 10, and week 4 may be 1 total, but I want the equation to apply for each row)

答:
This can easily be using tidyverse. Say this in in a dataframe called df.

```<code>library(tidyverse)

df.new <- df %>%
  group_by(Week) %>%
  arrange(`Total Amount`) %>%
  mutate(Person = ifelse(row_number() > 3, "Others", Person)) %>%
  group_by(Week, Person) %>%
  summarize(`Total Amount` = sum(`Total Amount`))
</code>```

If there is a "$" in the column (its a string column), you will first need to convert it before you can use the summarize line. You can use a function such as parse_number() to do this.

ContentLicense: CC BY-SA 3.0

Title: Group rows into a new row and sum in r

Body:
So I have data that seems like this:

 Week        Total Amount        Person
   1            $5                 A
   1            $5                 B
   1            $4                 C
   1            $2                 D
   1            $1                 E
   2            $5                 A
   2            $1                 B
   2            $1                 H
   2            $3                 G
   2            $5                 C
   2            $5                 F

How do I make it so that I will show the top 3 for each week and sum all other amounts into "Others"? I want it to show:

 Week        Total Amount        Person
   1            $5                 A
   1            $5                 B
   1            $4                 C
   1            $3                 Others
   2            $5                 A
   2            $5                 C
   2            $5                 F
   2            $5                 Others

Notice that the other amounts that are not top 3 are summed into a new total amount, and it accounts for the random number of rows for each week (say week 1 has 5 total amounts for each person, but week 2 has 6, and week 3 may be 8 or 10, and week 4 may be 1 total, but I want the equation to apply for each row)

Body:
This can easily be using tidyverse. Say this in in a dataframe called df.

library(tidyverse)

df.new <- df %>%
  group_by(Week) %>%
  arrange(`Total Amount`) %>%
  mutate(Person = ifelse(row_number() > 3, "Others", Person)) %>%
  group_by(Week, Person) %>%
  summarize(`Total Amount` = sum(`Total Amount`))

If there is a "$" in the column (its a string column), you will first need to convert it before you can use the summarize line. You can use a function such as parse_number() to do this.


问:
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"id","selector":"name"}
enter image description hereSource

```<code><input id="name" name="name" type="text" style="box-sizing:border-box;-moz-box-sizing:border-box;position:absolute;left:130px;top:50px;width:220px;">
</code>```

This is my code

```<code>WebElement VARName = driver.findElement(By.id("name"));
    VARName.sendKeys("Krishna-05");
</code>```

The page in this subject is a pop up page.

Error:

Exception in thread "main" org.openqa.selenium.NoSuchElementException:
  no such element: Unable to locate element:
  {"method":"id","selector":"name"}   (Session info:
  chrome=61.0.3163.100)   (Driver info: chromedriver=2.32.498550
  (9dec58e66c31bcc53a9ce3c7226f0c1c5810906a),platform=Windows NT
  10.0.10240 x86_64) (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 0 milliseconds

I tried finding with css,xpath,name etc and no use. All of them exhibit the same error. I'm using Selenium Webdriver with Java on Eclipse.

```<code>package open_chrome;

import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;

public class Chrome_Driver {

public static void main(String[] args) throws InterruptedException{

    WebDriver driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("https://<website.com>/");

    driver.findElement(By.id("email")).sendKeys("docker@de.com");
    driver.findElement(By.id("password")).sendKeys("Test1234");
    driver.findElement(By.cssSelector("body > div:nth-child(1) > div > div >
    form > div:nth-child(5) > button")).click();
    //Adding New VAR

    driver.findElement(By.id("ext-gen224")).click();
    driver.findElement(By.id("ext-gen367")).click();
    String parentWindow = driver.getWindowHandle();
//      Set<String> handles =  driver.getWindowHandles();
    for(String childWindow:driver.getWindowHandles())
    {
        driver.switchTo().window(childWindow);
        driver.findElement(By.id("name")).sendKeys("Krishna-05");
    }
</code>```

答:
There can be many facts . Does your element visible . I mean for example may be you have a scrolling ? May be there is iframe ?
 If this will not help please provide  the class of your test with start and all steps , browser info...  I will try to help.</p>

Body:
enter image description hereSource

<input id="name" name="name" type="text" style="box-sizing:border-box;-moz-box-sizing:border-box;position:absolute;left:130px;top:50px;width:220px;">

This is my code

WebElement VARName = driver.findElement(By.id("name"));
    VARName.sendKeys("Krishna-05");

The page in this subject is a pop up page.

Error:

Exception in thread "main" org.openqa.selenium.NoSuchElementException:
  no such element: Unable to locate element:
  {"method":"id","selector":"name"}   (Session info:
  chrome=61.0.3163.100)   (Driver info: chromedriver=2.32.498550
  (9dec58e66c31bcc53a9ce3c7226f0c1c5810906a),platform=Windows NT
  10.0.10240 x86_64) (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 0 milliseconds

I tried finding with css,xpath,name etc and no use. All of them exhibit the same error. I'm using Selenium Webdriver with Java on Eclipse.

package open_chrome;

import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;

public class Chrome_Driver {

public static void main(String[] args) throws InterruptedException{

    WebDriver driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("https://<website.com>/");

    driver.findElement(By.id("email")).sendKeys("docker@de.com");
    driver.findElement(By.id("password")).sendKeys("Test1234");
    driver.findElement(By.cssSelector("body > div:nth-child(1) > div > div >
    form > div:nth-child(5) > button")).click();
    //Adding New VAR

    driver.findElement(By.id("ext-gen224")).click();
    driver.findElement(By.id("ext-gen367")).click();
    String parentWindow = driver.getWindowHandle();
//      Set<String> handles =  driver.getWindowHandles();
    for(String childWindow:driver.getWindowHandles())
    {
        driver.switchTo().window(childWindow);
        driver.findElement(By.id("name")).sendKeys("Krishna-05");
    }


问:
Typescript empty object and any difference
Could somebody explain me which is the difference between {} and any?

for example, which's the difference between setting generic interface parameter as Interface<{}> or as Interface<any>.

Any ideas?

答:
So there are types in JavaScript. Like number, string, object and boolean. any matches any of these types. {} just matches an empty object.

```<code>function fn1(foo: any): void {}
function fn2(foo: {}): void {}

fn1(23); // OK
fn1('test'); // OK
fn1(undefined); // OK
fn2({}); // OK
fn2(23); // Not OK
fn2(null); // Not OK
</code>```

Body:
So there are types in JavaScript. Like number, string, object and boolean. any matches any of these types. {} just matches an empty object.

function fn1(foo: any): void {}
function fn2(foo: {}): void {}

fn1(23); // OK
fn1('test'); // OK
fn1(undefined); // OK
fn2({}); // OK
fn2(23); // Not OK
fn2(null); // Not OK


问:
Error Domain=NSOSStatusErrorDomain Code=-5000 using setResourceValue on Swift
my question would be simple I am trying to add tags to some files in Finder using Swift and I am experiencing following error: Error Domain=NSOSStatusErrorDomain Code=-5000 "afpAccessDenied: Insufficient access privileges for operation "

and here is my function to do that:

```<code>    for product in fetchedObjects
    {
        let url = NSURL(fileURLWithPath: product.fileURLString!)

        print(product.fileNr)

        do
        {
            var tags = [String]()

            tags += ["test"]
            try url.setResourceValue(tags, forKey: URLResourceKey.tagNamesKey)
        }
        catch let error as NSError
        {
            print(error)
        }
    }
</code>```

Maybe somebody could help me?

答:
The error message means that you don't have authorization to access the files.

If you need to ask the user for admin permissions, you can take a look at the LocalAuthentication framework (available in iOS 8+ and MacOS 10.10+).

The example uses an LAPolicy of deviceOwnerAuthenticationWithBiometrics, which requires TouchID or FaceID. Here's the same example allowing the user to authenticate with their password as well:

```<code>let myContext = LAContext()
let myLocalizedReasonString = <#String explaining why app needs authentication#>

var authError: NSError?
if #available(iOS 8.0, macOS 10.12.1, *) {
    if myContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &authError) {
        myContext.evaluatePolicy(. deviceOwnerAuthentication, localizedReason: myLocalizedReasonString) { success, evaluateError in
            if success {
                // User authenticated successfully, take appropriate action
            } else {
                // User did not authenticate successfully, look at error and take appropriate action
            }
        }
    } else {
        // Could not evaluate policy; look at authError and present an appropriate message to user
    }
} else {
    // Fallback on earlier versions
}
</code>```

Body:
my question would be simple I am trying to add tags to some files in Finder using Swift and I am experiencing following error: Error Domain=NSOSStatusErrorDomain Code=-5000 "afpAccessDenied: Insufficient access privileges for operation "

and here is my function to do that:

    for product in fetchedObjects
    {
        let url = NSURL(fileURLWithPath: product.fileURLString!)

        print(product.fileNr)

        do
        {
            var tags = [String]()

            tags += ["test"]
            try url.setResourceValue(tags, forKey: URLResourceKey.tagNamesKey)
        }
        catch let error as NSError
        {
            print(error)
        }
    }

Maybe somebody could help me?

Body:
The error message means that you don't have authorization to access the files.

If you need to ask the user for admin permissions, you can take a look at the LocalAuthentication framework (available in iOS 8+ and MacOS 10.10+).

The example uses an LAPolicy of deviceOwnerAuthenticationWithBiometrics, which requires TouchID or FaceID. Here's the same example allowing the user to authenticate with their password as well:

let myContext = LAContext()
let myLocalizedReasonString = <#String explaining why app needs authentication#>

var authError: NSError?
if #available(iOS 8.0, macOS 10.12.1, *) {
    if myContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &authError) {
        myContext.evaluatePolicy(. deviceOwnerAuthentication, localizedReason: myLocalizedReasonString) { success, evaluateError in
            if success {
                // User authenticated successfully, take appropriate action
            } else {
                // User did not authenticate successfully, look at error and take appropriate action
            }
        }
    } else {
        // Could not evaluate policy; look at authError and present an appropriate message to user
    }
} else {
    // Fallback on earlier versions
}


问:
c++ conversion string- unsigned char
I have a string value:
std::string bl="0x"+"a0"; //where a0 is a heva number. I did add 0x because i want my      vector

```<code>std::vector<unsigned char>vect;
</code>```

vect.push_back(bl.begin(), bl.end()); //error  is not working.

Need help. What to do?
I am working in ubuntu c++ code.

答:
the reason is simple, you are trying to insert an invalid element into your container.

std::string has no implicit conversion to change its data into vector of unsigned char.

ContentLicense: CC BY-SA 2.5

Title: c++ conversion string- unsigned char

Body:
I have a string value:
std::string bl="0x"+"a0"; //where a0 is a heva number. I did add 0x because i want my      vector

std::vector<unsigned char>vect;

vect.push_back(bl.begin(), bl.end()); //error  is not working.

Need help. What to do?
I am working in ubuntu c++ code.


问:
What is the difference between AccessLevel.PACKAGE and AccessLevel.MODULE?
In Lombok, what is the actual difference between

```<code>@Getter(AccessLevel.PACKAGE)
private int country;
</code>```

and

```<code>@Getter(AccessLevel.MODULE)
private int country;
</code>```

?

答:
That is a good question. I tried creating some setters for some test methods and all I got was (decompiled):

```<code>for Module AccessLevel:
void setTestModule(Integer testModule) {
    this.testModule = testModule;
}

for Package AccessLevel:
void setTestPackage(Integer testPackage) {
    this.testPackage = testPackage;
}
</code>```

So, on first look it appears that there is no difference. So, I looked into the source code and all I could verify is that for the time being they are handled the same (from the source here):

lombok.javac.handlers.JavacHandlerUtil.toJavacModifier(AccessLevel accessLevel)
  or lombok.eclipse.handlers.EclipseHandlerUtil.toEclipseModifier(AccessLevel accessLevel)

```<code>/**
 * Turns an {@code AccessLevel} instance into the flag bit used by javac.
 */
public static int toJavacModifier(AccessLevel accessLevel) {
    switch (accessLevel) {
    case MODULE:
    case PACKAGE:
        return 0;
    default:
    case PUBLIC:
        return Flags.PUBLIC;
    case NONE:
    case PRIVATE:
        return Flags.PRIVATE;
    case PROTECTED:
        return Flags.PROTECTED;
    }
}
</code>```

I think that there will be some future work on that for java 9 probably, but for now it appears to be the same.

Body:
In Lombok, what is the actual difference between

@Getter(AccessLevel.PACKAGE)
private int country;

and

@Getter(AccessLevel.MODULE)
private int country;

?

Body:
That is a good question. I tried creating some setters for some test methods and all I got was (decompiled):

for Module AccessLevel:
void setTestModule(Integer testModule) {
    this.testModule = testModule;
}

for Package AccessLevel:
void setTestPackage(Integer testPackage) {
    this.testPackage = testPackage;
}

So, on first look it appears that there is no difference. So, I looked into the source code and all I could verify is that for the time being they are handled the same (from the source here):

lombok.javac.handlers.JavacHandlerUtil.toJavacModifier(AccessLevel accessLevel)
  or lombok.eclipse.handlers.EclipseHandlerUtil.toEclipseModifier(AccessLevel accessLevel)

/**
 * Turns an {@code AccessLevel} instance into the flag bit used by javac.
 */
public static int toJavacModifier(AccessLevel accessLevel) {
    switch (accessLevel) {
    case MODULE:
    case PACKAGE:
        return 0;
    default:
    case PUBLIC:
        return Flags.PUBLIC;
    case NONE:
    case PRIVATE:
        return Flags.PRIVATE;
    case PROTECTED:
        return Flags.PROTECTED;
    }
}

I think that there will be some future work on that for java 9 probably, but for now it appears to be the same.


问:
SQL Implementation with Sliding-Window functions or Recursive CTEs
I have a problem that it's very easy to be solved in C# code for example, but I have no idea how to write in a SQL query with Recursive CTE-s or Sliding-Windows functions.

Here is the situation: let's say I have a table with 3 columns (ID, Date, Amount), and here is some data:

```<code>ID  Date         Amount
-----------------------
1   01.01.2016    -500
2   01.02.2016    1000
3   01.03.2016    -200
4   01.04.2016     300
5   01.05.2016     500
6   01.06.2016    1000
7   01.07.2016    -100
8   01.08.2016     200
</code>```

The result I want to get from the table is this (ID, Amount .... Order By Date):

```<code>ID  Amount
-----------------------
2    300
4    300
5    500
6    900
8    200
</code>```

The idea is to distribute the amounts into installments, for each client separately, but the thing is when negative amount comes into play you need to remove amount from the last installment. I don't know how clear I am, so here is an example:

Let's say I have 3 Invoices for one client with amounts 500, 200, -300.

If i start distribute these Invoices, first i distribute the amount 500, then 200. But when i come to the third one -300, then i need to remove from the last Invoice. In other words 200 - 300 = -100, so the amount from second Invoice will disappear, but there are still -100 that needs to be substracted from first Invoice. So 500 - 100 = 400. The result i need is result with one row (first invoice with amount 400)

Another example when the first invoice is with negative amount (-500, 300, 500).
In this case, the first (-500) invoice will make the second disappear and another 200 will be substracted from the third. So the result will be: Third Invoice with amount 300.

This is something like Stack implementation in programming language, but i need to make it with sliding-window functions in SQL Server.

I need an implementation with Sliding Function or Recursive CTEs.
Not with cycles ...

Thanks.

答:
I add client ID in table for more general solution. Then I implemented the stack stored as XML in query field. And emulated a program cycle with Recursive-CTE:

```<code>with Data as(  -- Numbering rows for iteration on CTE
    select Client, id, Amount,
           cast(row_number() over(partition by Client order by Date) as int) n
      from TabW
),
CTE(Client, n, stack) as( -- Recursive CTE
    select Client, 1, cast(NULL as xml) from Data where n=1
  UNION ALL
    select D.Client, D.n+1, (
-- Stack operations to process current row (D)
select row_number() over(order by n) n,
       -- Use calculated amount in first positive and oldest stack cell
       -- Else preserve value stored in stack
       case when n=1 or (n=0 and last=1) then new else Amount end Amount,
       -- Set ID in stack cell for positive and new data
       case when n=1 and D.Amount>0 then D.id else id end id
  from (
    select Y.Amount, Y.id, new,
           -- Count positive stack entries
           sum(case when new<=0 or (n=0 and Amount<0) then 0 else 1 end) over (order by n) n,
           row_number() over(order by n desc) last  -- mark oldest stack cell by 1
      from (
        select X.*,sum(Amount) over(order by n) new
          from (
                select case when C.stack.value('(/row/@Amount)[1]','int')<0 then -1 else 0 end n,
                       D.Amount, D.id  -- Data from new record
              union all  -- And expand current stack in XML to table
            select node.value('@n','int') n, node.value('@Amount','int'), node.value('@id','int')
              from C.stack.nodes('//row') N(node)
          ) X
      ) Y where n>=0 -- Suppress new cell if the stack contained a negative amount
 ) Z
where n>0 or (n=0 and last=1)
  for xml raw, type

           )
      from Data D, CTE C
     where D.n=C.n and D.Client=C.Client
) -- Expand stack into result table
select CTE.Client, node.value('@id','int') id, node.value('@Amount','int')
  from CTE join (select Client, max(n) max_n from Data group by Client) X on CTE.Client=X.Client and CTE.n=X.max_n+1
 cross apply stack.nodes('//row') N(node)
 order by CTE.Client, node.value('@n','int') desc
</code>```

Test on sqlfiddle.com

I think this method is slower than @RadimBača. And it is shown to demonstrate the possibilities of implementing a sequential algorithm on SQL.

Body:
I have a problem that it's very easy to be solved in C# code for example, but I have no idea how to write in a SQL query with Recursive CTE-s or Sliding-Windows functions.

Here is the situation: let's say I have a table with 3 columns (ID, Date, Amount), and here is some data:

ID  Date         Amount
-----------------------
1   01.01.2016    -500
2   01.02.2016    1000
3   01.03.2016    -200
4   01.04.2016     300
5   01.05.2016     500
6   01.06.2016    1000
7   01.07.2016    -100
8   01.08.2016     200

The result I want to get from the table is this (ID, Amount .... Order By Date):

ID  Amount
-----------------------
2    300
4    300
5    500
6    900
8    200

The idea is to distribute the amounts into installments, for each client separately, but the thing is when negative amount comes into play you need to remove amount from the last installment. I don't know how clear I am, so here is an example:

Let's say I have 3 Invoices for one client with amounts 500, 200, -300.

If i start distribute these Invoices, first i distribute the amount 500, then 200. But when i come to the third one -300, then i need to remove from the last Invoice. In other words 200 - 300 = -100, so the amount from second Invoice will disappear, but there are still -100 that needs to be substracted from first Invoice. So 500 - 100 = 400. The result i need is result with one row (first invoice with amount 400)

Another example when the first invoice is with negative amount (-500, 300, 500).
In this case, the first (-500) invoice will make the second disappear and another 200 will be substracted from the third. So the result will be: Third Invoice with amount 300.

This is something like Stack implementation in programming language, but i need to make it with sliding-window functions in SQL Server.

I need an implementation with Sliding Function or Recursive CTEs.
Not with cycles ...

Thanks.

Body:
I add client ID in table for more general solution. Then I implemented the stack stored as XML in query field. And emulated a program cycle with Recursive-CTE:

with Data as(  -- Numbering rows for iteration on CTE
    select Client, id, Amount,
           cast(row_number() over(partition by Client order by Date) as int) n
      from TabW
),
CTE(Client, n, stack) as( -- Recursive CTE
    select Client, 1, cast(NULL as xml) from Data where n=1
  UNION ALL
    select D.Client, D.n+1, (
-- Stack operations to process current row (D)
select row_number() over(order by n) n,
       -- Use calculated amount in first positive and oldest stack cell
       -- Else preserve value stored in stack
       case when n=1 or (n=0 and last=1) then new else Amount end Amount,
       -- Set ID in stack cell for positive and new data
       case when n=1 and D.Amount>0 then D.id else id end id
  from (
    select Y.Amount, Y.id, new,
           -- Count positive stack entries
           sum(case when new<=0 or (n=0 and Amount<0) then 0 else 1 end) over (order by n) n,
           row_number() over(order by n desc) last  -- mark oldest stack cell by 1
      from (
        select X.*,sum(Amount) over(order by n) new
          from (
                select case when C.stack.value('(/row/@Amount)[1]','int')<0 then -1 else 0 end n,
                       D.Amount, D.id  -- Data from new record
              union all  -- And expand current stack in XML to table
            select node.value('@n','int') n, node.value('@Amount','int'), node.value('@id','int')
              from C.stack.nodes('//row') N(node)
          ) X
      ) Y where n>=0 -- Suppress new cell if the stack contained a negative amount
 ) Z
where n>0 or (n=0 and last=1)
  for xml raw, type

           )
      from Data D, CTE C
     where D.n=C.n and D.Client=C.Client
) -- Expand stack into result table
select CTE.Client, node.value('@id','int') id, node.value('@Amount','int')
  from CTE join (select Client, max(n) max_n from Data group by Client) X on CTE.Client=X.Client and CTE.n=X.max_n+1
 cross apply stack.nodes('//row') N(node)
 order by CTE.Client, node.value('@n','int') desc

Test on sqlfiddle.com

I think this method is slower than @RadimBača. And it is shown to demonstrate the possibilities of implementing a sequential algorithm on SQL.


问:
How can I build multiple projects in Ant with one build file?
Can I build multiple projects from one build-file. Example:

```<code><project basedir="." default="all" name="app1">
    ...
</project>

<project basedir="." default="all" name="app2">
    ...
</project>
</code>```

Currently I type ant -f build1.xml compile and it builds my application and I have to use two separate build files. Is there some way to get it running in a way that i have both the projects defined a common build-file and I can type something like ant app1 compile or ant app2 compile?

Here's what my build-file looks like:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project name="azebooster" default="dist" basedir=".">

    <!-- Globals -->
    <property name="src" location="src/com/aelitis"/>
    <property name="build" location="build/azebooster"/>
    <property name="jar" location="jar/azebooster"/>
    <property name="resources" location="res/azebooster"/>

    <!-- Paths -->
    <path id="classpath">
        <fileset dir="." includes="**/*.jar"/>
    </path>

    <!-- Start it -->
    <target name="init">
      <tstamp/>
      <mkdir dir="${build}"/>
      <mkdir dir="${jar}"/>
    </target>

    <!-- Build it -->
    <target name="compile" depends="init" description="compile the source" >
        <javac srcdir="${src}" destdir="${build}">
            <classpath>
                <path refid="classpath"/>
            </classpath>
        </javac>
    </target>

    <!-- Jar it -->
    <target name="jar" depends="compile">
        <jar destfile="${jar}/${ant.project.name}.jar">
            <fileset dir="${build}"/>
            <fileset dir="${resources}" />
        </jar>
    </target>

    <!-- Clean it -->
    <target name="clean" description="clean up" >
        <tstamp/>
        <delete dir="${build}"/>
        <delete dir="${jar}"/>
    </target>

</project>
</code>```

Thank you.

答:
You will probably be able to do what you want using macros (though it depends precisely on what is common between your two projects), though your command is more likely to be

```<code>ant compile app1
</code>```

or

```<code>ant compile app2
</code>```

where compile is a target which calls a macro, using app1/app2 as a parameter to either decide which macro to call or to pass into the macro itself.

Body:
Can I build multiple projects from one build-file. Example:

<project basedir="." default="all" name="app1">
    ...
</project>

<project basedir="." default="all" name="app2">
    ...
</project>

Currently I type ant -f build1.xml compile and it builds my application and I have to use two separate build files. Is there some way to get it running in a way that i have both the projects defined a common build-file and I can type something like ant app1 compile or ant app2 compile?

Here's what my build-file looks like:

<?xml version="1.0" encoding="UTF-8"?>
<project name="azebooster" default="dist" basedir=".">

    <property name="src" location="src/com/aelitis"/>
    <property name="build" location="build/azebooster"/>
    <property name="jar" location="jar/azebooster"/>
    <property name="resources" location="res/azebooster"/>

    <path id="classpath">
        <fileset dir="." includes="**/*.jar"/>
    </path>

    <target name="init">
      <tstamp/>
      <mkdir dir="${build}"/>
      <mkdir dir="${jar}"/>
    </target>

    <target name="compile" depends="init" description="compile the source" >
        <javac srcdir="${src}" destdir="${build}">
            <classpath>
                <path refid="classpath"/>
            </classpath>
        </javac>
    </target>

    <target name="jar" depends="compile">
        <jar destfile="${jar}/${ant.project.name}.jar">
            <fileset dir="${build}"/>
            <fileset dir="${resources}" />
        </jar>
    </target>

    <target name="clean" description="clean up" >
        <tstamp/>
        <delete dir="${build}"/>
        <delete dir="${jar}"/>
    </target>

</project>

Thank you.

Body:
You will probably be able to do what you want using macros (though it depends precisely on what is common between your two projects), though your command is more likely to be

ant compile app1

or

ant compile app2

where compile is a target which calls a macro, using app1/app2 as a parameter to either decide which macro to call or to pass into the macro itself.


问:
Add blog posts without category in django 1.11
I want to be able to add some blog posts with categories and some without categories in django. with this models django admin won't let me add blog posts without a category. Thanks.</p>

```<code>from django.db import models
from django.db.models import permalink

class Blog(models.Model):
    title = models.CharField(max_length=100, unique=True)
    slug = models.SlugField(max_length=100, unique=True)
    body = models.TextField()
    pub_date = models.DateField(db_index=True, auto_now_add=True)
    # Many-to-one relationship.
    category = models.ForeignKey('blog.Category')

class Category(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100)
</code>```

答:
Update your model like this:

```<code>category = models.ForeignKey('blog.Category', blank=True, null=True)
</code>```

blank=True allow forms to have a blank value.
null=True allows a null value in the database.

Edit: here is the documentation

Body:
I want to be able to add some blog posts with categories and some without categories in django. with this models django admin won't let me add blog posts without a category. Thanks.

from django.db import models
from django.db.models import permalink

class Blog(models.Model):
    title = models.CharField(max_length=100, unique=True)
    slug = models.SlugField(max_length=100, unique=True)
    body = models.TextField()
    pub_date = models.DateField(db_index=True, auto_now_add=True)
    # Many-to-one relationship.
    category = models.ForeignKey('blog.Category')

class Category(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100)

Body:
Update your model like this:

category = models.ForeignKey('blog.Category', blank=True, null=True)

blank=True allow forms to have a blank value.
null=True allows a null value in the database.

Edit: here is the documentation


问:
Swift 4 String index offset by too slow while processing a large string
I'm processing a csv file with last column not being always same format.
Each row has this structure:

```<code>"Root/Word1","some string","some string","some œ0'fqw[å”ƒ#”≠§
\nfw@\tfa0j
"
"Root/Word2","some string","some string","some string"
...
</code>```

So 6 columns and the last can contain \n. Which makes it hard to split by components.
Another restriction is that all the strings can be any possible special character. Which makes it hard to use regex.

I decided to solve the problem brute force first. (Yes I have seen that index offset by is O(n). But can't come up with an alternative.)

```<code>static func importData(_ db: DB) {
    let csvString = readDataFromCSV(fileName: "data", fileType: "csv")!

    let totalCharCount = csvString.count
    print("total: \(totalCharCount)")
    for i in 0..<totalCharCount {
        print(i)
        if i+5 >= totalCharCount {
            continue
        }
        let index = csvString.index(csvString.startIndex, offsetBy: i)
        let endIndex = csvString.index(csvString.startIndex, offsetBy:i+5)

        let part = csvString[index ..< endIndex]
        if part == "Root/" {
            let accum = lookInside(i: i, totalCharCount: totalCharCount, csvString: csvString)

            var rows = accum.components(separatedBy: "\",\"")

            if var lastt = rows.last {
                lastt.removeLast()
                lastt.removeLast()
                rows[rows.count-1] = lastt
            }
        }
    }
}

static func lookInside(i:Int, totalCharCount: Int, csvString: String) -> String {
    var accum = ""
    var found = false
    var j = i+5
    while !found {

        if j+5 >= totalCharCount {
            found = true
        }
        let index2 = csvString.index(csvString.startIndex, offsetBy: j)
        let endIndex2 = csvString.index(csvString.startIndex, offsetBy:j+5)

        if csvString[index2 ..< endIndex2] == "Root/" {
            found = true
            accum.removeLast()
        } else {
            accum += String(csvString[index2])
        }
        j += 1
    }

    return accum
}
</code>```

Basically I'm traversing the whole string looking for a pattern "Root/".
When found, I advance from this moment to the next occurrence of the pattern.

Problem is that the csv results in a string 200k chars long and when I run this on simulator it lasts too much time (~30min).

So now I'm asking some help here because according to Instruments all the time is consumed in String.index(offset by) method which is called too many times.

答:
I have found a solution just using components and matching patterns.
This works in less than 4s.
Thanks for all the info, I learnt a lot from it.</p>

```<code>        let csvString = readDataFromCSV(fileName: "data", fileType: "csv")!
        var components = csvString.components(separatedBy: "Root/")
        var result = [Note]()
        for i in components {
            let noteComponents = i.components(separatedBy: "\",\"")
</code>```

Body:
I'm processing a csv file with last column not being always same format.
Each row has this structure:

"Root/Word1","some string","some string","some œ0'fqw[å”ƒ#”≠§
\nfw@\tfa0j
"
"Root/Word2","some string","some string","some string"
...

So 6 columns and the last can contain \n. Which makes it hard to split by components.
Another restriction is that all the strings can be any possible special character. Which makes it hard to use regex.

I decided to solve the problem brute force first. (Yes I have seen that index offset by is O(n). But can't come up with an alternative.)

static func importData(_ db: DB) {
    let csvString = readDataFromCSV(fileName: "data", fileType: "csv")!

    let totalCharCount = csvString.count
    print("total: \(totalCharCount)")
    for i in 0..<totalCharCount {
        print(i)
        if i+5 >= totalCharCount {
            continue
        }
        let index = csvString.index(csvString.startIndex, offsetBy: i)
        let endIndex = csvString.index(csvString.startIndex, offsetBy:i+5)

        let part = csvString[index ..< endIndex]
        if part == "Root/" {
            let accum = lookInside(i: i, totalCharCount: totalCharCount, csvString: csvString)

            var rows = accum.components(separatedBy: "\",\"")

            if var lastt = rows.last {
                lastt.removeLast()
                lastt.removeLast()
                rows[rows.count-1] = lastt
            }
        }
    }
}

static func lookInside(i:Int, totalCharCount: Int, csvString: String) -> String {
    var accum = ""
    var found = false
    var j = i+5
    while !found {

        if j+5 >= totalCharCount {
            found = true
        }
        let index2 = csvString.index(csvString.startIndex, offsetBy: j)
        let endIndex2 = csvString.index(csvString.startIndex, offsetBy:j+5)

        if csvString[index2 ..< endIndex2] == "Root/" {
            found = true
            accum.removeLast()
        } else {
            accum += String(csvString[index2])
        }
        j += 1
    }

    return accum
}

Basically I'm traversing the whole string looking for a pattern "Root/".
When found, I advance from this moment to the next occurrence of the pattern.

Problem is that the csv results in a string 200k chars long and when I run this on simulator it lasts too much time (~30min).

So now I'm asking some help here because according to Instruments all the time is consumed in String.index(offset by) method which is called too many times.

Body:
I have found a solution just using components and matching patterns.
This works in less than 4s.
Thanks for all the info, I learnt a lot from it.

        let csvString = readDataFromCSV(fileName: "data", fileType: "csv")!
        var components = csvString.components(separatedBy: "Root/")
        var result = [Note]()
        for i in components {
            let noteComponents = i.components(separatedBy: "\",\"")


问:
Flutter Layout: How can I put a Row inside a Flex (or another Row) in Flutter? Also using Stack widget
I need to put 2 composed widgets in one Row:

The composed widget is named "boxText". I need it twice, each inside a Border with two Texts and a TextFormField like:

```<code>Stack
  Image and others
  Form
    Row or Flex or Whatever:
    +------------------------------+    +------------------------------+
    | Text  Text TextFormField     |    | Text Text  TextFormField     |
    +------------------------------+    +------------------------------+
</code>```

My code (and tears):
IMPORTANT: Exception occurs only when TextFormField is added.

```<code>@override
Widget build(BuildContext context) {
// Composed Widget
 Widget boxText = new Container(
  decoration: new BoxDecoration(
    border: new Border.all(
      color: Colors.cyan[100],
      width: 3.0,
      style: BorderStyle.solid,
    ),
  ),
  margin: new EdgeInsets.all(5.0),
  padding: new EdgeInsets.all(8.0),
  child: new Row(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: <Widget>[
      new Text(
        'Text',
        style: null,
      ),
      new Text(
        'Text',
        style: null,
      ),
      new TextFormField(
        decoration: const InputDecoration(
          hintText: '',
          labelText: 'label',
        ),
        obscureText: true,
      ),
    ],
  ),
);

return new Scaffold(
  key: _scaffoldKey,
  body: new Stack(
    alignment: AlignmentDirectional.topStart,
    textDirection: TextDirection.ltr,
    fit: StackFit.loose,
    overflow: Overflow.clip,
    children: <Widget>[

      new Container(
        color: Colors.red[200],
        margin: new EdgeInsets.only(
          left: MediaQuery.of(context).size.width * 0.05,
          right: MediaQuery.of(context).size.width * 0.05,
          top: MediaQuery.of(context).size.height * 0.4,
          bottom: MediaQuery.of(context).size.height * 0.1,
        ),
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        child: new Form(
          key: _formKey,
          child: new ListView(
            padding: const EdgeInsets.symmetric(horizontal: 16.0),
            children: <Widget>[
              new Flex(
                direction: Axis.horizontal,
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  boxText,
                  boxText,
                ],
              ),
            ],
          ),
        ),
      ),
    ],
  ),
    );
  }
</code>```

How, if possible, can put this widgets to work without:

```<code>══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞══

The following assertion was thrown during performLayout():

An InputDecorator, which is typically created by a TextField, cannot
have an unbounded width.

This happens when the parent widget does not provide a finite width
constraint. For example, if the InputDecorator is contained by a Row,
then its width must be constrained. An Expanded widget or a SizedBox
can be used to constrain the width of the InputDecorator or the
TextField that contains it.

'package:flutter/src/material/input_decorator.dart':

Failed assertion: line 945 pos 7: 'layoutConstraints.maxWidth <
double.infinity'
</code>```

答:
Wrap BOTH your Container and TextFormField inside a Flexible widget.

```<code>Widget boxText = new Flexible(child: new Container(
      decoration: new BoxDecoration(
        border: new Border.all(
          color: Colors.cyan[100],
          width: 3.0,
          style: BorderStyle.solid,
        ),
      ),
      margin: new EdgeInsets.all(5.0),
      padding: new EdgeInsets.all(8.0),
      child: new Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[

          new Text(
            'Text',
            style: null,
          ),
          new Text(
            'Text',
            style: null,
          ),
          new Flexible (child: new TextFormField(
            decoration: const InputDecoration(
              hintText: '',
              labelText: 'label',
            ),
            obscureText: true,
          ),),
        ],
      ),
    ));
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to put 2 composed widgets in one Row:

The composed widget is named "boxText". I need it twice, each inside a Border with two Texts and a TextFormField like:

Stack
  Image and others
  Form
    Row or Flex or Whatever:
    +------------------------------+    +------------------------------+
    | Text  Text TextFormField     |    | Text Text  TextFormField     |
    +------------------------------+    +------------------------------+

My code (and tears):
IMPORTANT: Exception occurs only when TextFormField is added.

@override
Widget build(BuildContext context) {
// Composed Widget
 Widget boxText = new Container(
  decoration: new BoxDecoration(
    border: new Border.all(
      color: Colors.cyan[100],
      width: 3.0,
      style: BorderStyle.solid,
    ),
  ),
  margin: new EdgeInsets.all(5.0),
  padding: new EdgeInsets.all(8.0),
  child: new Row(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: <Widget>[
      new Text(
        'Text',
        style: null,
      ),
      new Text(
        'Text',
        style: null,
      ),
      new TextFormField(
        decoration: const InputDecoration(
          hintText: '',
          labelText: 'label',
        ),
        obscureText: true,
      ),
    ],
  ),
);

return new Scaffold(
  key: _scaffoldKey,
  body: new Stack(
    alignment: AlignmentDirectional.topStart,
    textDirection: TextDirection.ltr,
    fit: StackFit.loose,
    overflow: Overflow.clip,
    children: <Widget>[

      new Container(
        color: Colors.red[200],
        margin: new EdgeInsets.only(
          left: MediaQuery.of(context).size.width * 0.05,
          right: MediaQuery.of(context).size.width * 0.05,
          top: MediaQuery.of(context).size.height * 0.4,
          bottom: MediaQuery.of(context).size.height * 0.1,
        ),
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        child: new Form(
          key: _formKey,
          child: new ListView(
            padding: const EdgeInsets.symmetric(horizontal: 16.0),
            children: <Widget>[
              new Flex(
                direction: Axis.horizontal,
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  boxText,
                  boxText,
                ],
              ),
            ],
          ),
        ),
      ),
    ],
  ),
    );
  }

How, if possible, can put this widgets to work without:

══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞══

The following assertion was thrown during performLayout():

An InputDecorator, which is typically created by a TextField, cannot
have an unbounded width.

This happens when the parent widget does not provide a finite width
constraint. For example, if the InputDecorator is contained by a Row,
then its width must be constrained. An Expanded widget or a SizedBox
can be used to constrain the width of the InputDecorator or the
TextField that contains it.

'package:flutter/src/material/input_decorator.dart':

Failed assertion: line 945 pos 7: 'layoutConstraints.maxWidth <
double.infinity'

Body:
Wrap BOTH your Container and TextFormField inside a Flexible widget.

Widget boxText = new Flexible(child: new Container(
      decoration: new BoxDecoration(
        border: new Border.all(
          color: Colors.cyan[100],
          width: 3.0,
          style: BorderStyle.solid,
        ),
      ),
      margin: new EdgeInsets.all(5.0),
      padding: new EdgeInsets.all(8.0),
      child: new Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[

          new Text(
            'Text',
            style: null,
          ),
          new Text(
            'Text',
            style: null,
          ),
          new Flexible (child: new TextFormField(
            decoration: const InputDecoration(
              hintText: '',
              labelText: 'label',
            ),
            obscureText: true,
          ),),
        ],
      ),
    ));


问:
Compare only time from datetime in entity framework 6 with odp.net Oracle 12c
I am using entity framework 6 with oracle and Sql. Timespan datatype is not working with oracle. so i changed datatype to datetime. now i want to compare only time in datetime with Linq query. ex.

```<code>var db0010016 = _idb0010016Rep.GetAll().Where(e => e.ExecutionTime.TimeOfDay == viewmodel.ExecutionTime).FirstOrDefault();
</code>```

in above example e.ExecutionTime is datetime  and viewmodel.ExecutionTime is timespan. i am using timeofday function to convert it to timespan

above query failed to execute so i used DbFunctions.CreateTime() function

```<code>var db0010016 = _idb0010016Rep.FindBy(e => DbFunctions.CreateTime(e.ExecutionTime.Hour, e.ExecutionTime.Minute, e.ExecutionTime.Second) == exetime).FirstOrDefault();
</code>```

above ex exetime is timespan.still i am getting below error

```<code>{"Invalid parameter binding\r\nParameter name: ParameterName"}
</code>```

答:
EF6 query translator does not support DateTime.TimeOfDay, and Oracle provider does not support DbFunctions.CreateTime and TimeSpan parameters/constants.

Still there are some options before switching the storage from DateTime to string as suggested by another answer.

First, for equality checks you could compare the time components by either extracting them into separate variables (query parameters):

```<code>var hour = viewmodel.ExecutionTime.Hours;
var minute = viewmodel.ExecutionTime.Minutes;
var second = viewmodel.ExecutionTime.Seconds;

var db0010016 = _idb0010016Rep.FindBy(e =>
    e.ExecutionTime.Hour == hour && e.ExecutionTime.Minute == minute && e.ExecutionTime.Second == second)
    .FirstOrDefault();
</code>```

or into fake DateTime variable (queryParameter):

```<code>var executionTime = DateTime.Today + viewmodel.ExecutionTime;
var db0010016 = _idb0010016Rep.FindBy(e =>
    e.ExecutionTime.Hour == executionTime.Hour && e.ExecutionTime.Minute == executionTime.Minute && e.ExecutionTime.Second == executionTime.Second)
    .FirstOrDefault();
</code>```

Second, you can work with time converted to seconds. This allows you also to perform any comparison:

```<code>var executionTime = (int)viewmodel.ExecutionTime.TotalSeconds;
var db0010016 = _idb0010016Rep.FindBy(e =>
    60 * 60 * e.ExecutionTime.Hour + 60 * e.ExecutionTime.Minute + e.ExecutionTime.Second == executionTime)
    .FirstOrDefault();
</code>```

But doing all that manually is quite annoying and error prone. What I can offer is s small utility class providing custom extension method:

```<code>public static partial class QueryableExtensions
{
    public static IQueryable<T> ConvertTimeSpans<T>(this IQueryable<T> source)
    {
        var expr = new TimeSpanConverter().Visit(source.Expression);
        return source == expr ? source : source.Provider.CreateQuery<T>(expr);
    }

    class TimeSpanConverter : ExpressionVisitor
    {
        static readonly Expression<Func<DateTime, int>> ConvertTimeOfDay = dt =>
            60 * (60 * dt.Hour + dt.Minute) + dt.Second;

        static int ConvertTimespan(TimeSpan ts) =>
            60 * (60 * ts.Hours + ts.Minutes) + ts.Seconds;

        protected override Expression VisitMember(MemberExpression node)
        {
            if (node.Type == typeof(TimeSpan))
            {
                if (node.Member.DeclaringType == typeof(DateTime) && node.Member.Name == nameof(DateTime.TimeOfDay))
                    return ConvertTimeOfDay.ReplaceParameter(0, base.Visit(node.Expression));
                // Evaluate the TimeSpan value, convert and wrap it into closure (to keep non const semantics)
                return ConvertTimespan(base.VisitMember(node).Evaluate<TimeSpan>()).ToClosure().Body;
            }
            return base.VisitMember(node);
        }

        protected override Expression VisitBinary(BinaryExpression node)
        {
            if (node.Left.Type == typeof(TimeSpan))
                return Expression.MakeBinary(node.NodeType, Visit(node.Left), Visit(node.Right));
            return base.VisitBinary(node);
        }
    }

    static T Evaluate<T>(this Expression source) => Expression.Lambda<Func<T>>(source).Compile().Invoke();

    static Expression<Func<T>> ToClosure<T>(this T value) => () => value;

    static Expression ReplaceParameter(this LambdaExpression source, int index, Expression target) =>
        new ParameterReplacer { Source = source.Parameters[index], Target = target }.Visit(source.Body);

    class ParameterReplacer : ExpressionVisitor
    {
        public ParameterExpression Source;
        public Expression Target;
        protected override Expression VisitParameter(ParameterExpression node) => node == Source ? Target : node;
    }
}
</code>```

It uses two small custom ExpressionVisitor classes to convert the DateTime.TimeOfDay property and TimeSpan class properties similar to your viewModel.ExecutionTime.

Now you should be use your original query like this:

```<code>var db0010016 = _idb0010016Rep.GetAll()
   .Where(e => e.ExecutionTime.TimeOfDay == viewmodel.ExecutionTime)
   .ConvertTimeStamps() // the magic happens here
   .FirstOrDefault();
</code>```

In case you want to use milliseconds instead of seconds, all you need is to change the first two statements in TimeSpanConverter class as follows:

```<code>static readonly Expression<Func<DateTime, int>> ConvertTimeOfDay = dt =>
    1000 * (60 * (60 * dt.Hour + dt.Minute) + dt.Second) + dt.Millisecond;

static int ConvertTimespan(TimeSpan ts) =>
    1000 * (60 * (60 * ts.Hours + ts.Minutes) + ts.Seconds) + ts.Milliseconds;
</code>```

Body:
I am using entity framework 6 with oracle and Sql. Timespan datatype is not working with oracle. so i changed datatype to datetime. now i want to compare only time in datetime with Linq query. ex.

var db0010016 = _idb0010016Rep.GetAll().Where(e => e.ExecutionTime.TimeOfDay == viewmodel.ExecutionTime).FirstOrDefault();

in above example e.ExecutionTime is datetime  and viewmodel.ExecutionTime is timespan. i am using timeofday function to convert it to timespan

above query failed to execute so i used DbFunctions.CreateTime() function

var db0010016 = _idb0010016Rep.FindBy(e => DbFunctions.CreateTime(e.ExecutionTime.Hour, e.ExecutionTime.Minute, e.ExecutionTime.Second) == exetime).FirstOrDefault();

above ex exetime is timespan.still i am getting below error

{"Invalid parameter binding\r\nParameter name: ParameterName"}

Body:
EF6 query translator does not support DateTime.TimeOfDay, and Oracle provider does not support DbFunctions.CreateTime and TimeSpan parameters/constants.

Still there are some options before switching the storage from DateTime to string as suggested by another answer.

First, for equality checks you could compare the time components by either extracting them into separate variables (query parameters):

var hour = viewmodel.ExecutionTime.Hours;
var minute = viewmodel.ExecutionTime.Minutes;
var second = viewmodel.ExecutionTime.Seconds;

var db0010016 = _idb0010016Rep.FindBy(e =>
    e.ExecutionTime.Hour == hour && e.ExecutionTime.Minute == minute && e.ExecutionTime.Second == second)
    .FirstOrDefault();

or into fake DateTime variable (queryParameter):

var executionTime = DateTime.Today + viewmodel.ExecutionTime;
var db0010016 = _idb0010016Rep.FindBy(e =>
    e.ExecutionTime.Hour == executionTime.Hour && e.ExecutionTime.Minute == executionTime.Minute && e.ExecutionTime.Second == executionTime.Second)
    .FirstOrDefault();

Second, you can work with time converted to seconds. This allows you also to perform any comparison:

var executionTime = (int)viewmodel.ExecutionTime.TotalSeconds;
var db0010016 = _idb0010016Rep.FindBy(e =>
    60 * 60 * e.ExecutionTime.Hour + 60 * e.ExecutionTime.Minute + e.ExecutionTime.Second == executionTime)
    .FirstOrDefault();

But doing all that manually is quite annoying and error prone. What I can offer is s small utility class providing custom extension method:

public static partial class QueryableExtensions
{
    public static IQueryable<T> ConvertTimeSpans<T>(this IQueryable<T> source)
    {
        var expr = new TimeSpanConverter().Visit(source.Expression);
        return source == expr ? source : source.Provider.CreateQuery<T>(expr);
    }

    class TimeSpanConverter : ExpressionVisitor
    {
        static readonly Expression<Func<DateTime, int>> ConvertTimeOfDay = dt =>
            60 * (60 * dt.Hour + dt.Minute) + dt.Second;

        static int ConvertTimespan(TimeSpan ts) =>
            60 * (60 * ts.Hours + ts.Minutes) + ts.Seconds;

        protected override Expression VisitMember(MemberExpression node)
        {
            if (node.Type == typeof(TimeSpan))
            {
                if (node.Member.DeclaringType == typeof(DateTime) && node.Member.Name == nameof(DateTime.TimeOfDay))
                    return ConvertTimeOfDay.ReplaceParameter(0, base.Visit(node.Expression));
                // Evaluate the TimeSpan value, convert and wrap it into closure (to keep non const semantics)
                return ConvertTimespan(base.VisitMember(node).Evaluate<TimeSpan>()).ToClosure().Body;
            }
            return base.VisitMember(node);
        }

        protected override Expression VisitBinary(BinaryExpression node)
        {
            if (node.Left.Type == typeof(TimeSpan))
                return Expression.MakeBinary(node.NodeType, Visit(node.Left), Visit(node.Right));
            return base.VisitBinary(node);
        }
    }

    static T Evaluate<T>(this Expression source) => Expression.Lambda<Func<T>>(source).Compile().Invoke();

    static Expression<Func<T>> ToClosure<T>(this T value) => () => value;

    static Expression ReplaceParameter(this LambdaExpression source, int index, Expression target) =>
        new ParameterReplacer { Source = source.Parameters[index], Target = target }.Visit(source.Body);

    class ParameterReplacer : ExpressionVisitor
    {
        public ParameterExpression Source;
        public Expression Target;
        protected override Expression VisitParameter(ParameterExpression node) => node == Source ? Target : node;
    }
}

It uses two small custom ExpressionVisitor classes to convert the DateTime.TimeOfDay property and TimeSpan class properties similar to your viewModel.ExecutionTime.

Now you should be use your original query like this:

var db0010016 = _idb0010016Rep.GetAll()
   .Where(e => e.ExecutionTime.TimeOfDay == viewmodel.ExecutionTime)
   .ConvertTimeStamps() // the magic happens here
   .FirstOrDefault();

In case you want to use milliseconds instead of seconds, all you need is to change the first two statements in TimeSpanConverter class as follows:

static readonly Expression<Func<DateTime, int>> ConvertTimeOfDay = dt =>
    1000 * (60 * (60 * dt.Hour + dt.Minute) + dt.Second) + dt.Millisecond;

static int ConvertTimespan(TimeSpan ts) =>
    1000 * (60 * (60 * ts.Hours + ts.Minutes) + ts.Seconds) + ts.Milliseconds;


问:
Find, in a list, all arrays whose first element is the same as the ones that match a condition
This is a question that was very hard to title.

In C#, I have a set of int[,] arrays stored in a List<int[,]> paths, each holding a set of coordenates to form a path.
An example would be { {0,0}, {0,1}, {1,1}, {2,1} }.

Now, I want to keep in paths all paths that have the same first index as one of the first indexes of all paths that match a condition.

To better demonstrate what I mean, say I get all the paths that are of an odd length:

```<code>paths.Where(x => x.GetLength(0) % 2 == 1).ToList();
</code>```

Say this returns a list containing some arrays whose first coords are either {0,0} or {0,1}, for example. I want paths to be paths.Where( x=> x's first coords are either {0,0} or {0,1}). How can i achieve this?

Hopefully, what I mean is understandable.

答:
If you're set on using your current data structure, then you can do this, but the syntax isn't going to be pretty. It's basically like what A. Milto suggested in his answer, except that you need bounds checking to avoid throwing an exception in the case of an empty path. So if you define your paths like so:

```<code>var arrayPaths = new List<int[,]>();
arrayPaths.Add(new[,] { { 0, 0 }, { 0, 1 }, { 1, 1 }, { 2, 1 } });  // Include: starts with (0, 0)
arrayPaths.Add(new[,] { { 0, 1 }, { 0, 1 }, { 1, 1 }, { 2, 1 } });  // Include: starts with (0, 1)
arrayPaths.Add(new[,] { { 1, 0 }, { 0, 1 }, { 1, 1 }, { 2, 1 } });  // Exclude: starts with (1, 0)
arrayPaths.Add(new int[0,0]);                                       // Exclude: has no data
</code>```

Then the subset of paths that start at (0, 0) or (0, 1) is:

```<code>arrayPaths.Where(p =>
    p.GetUpperBound(0) >= 0 &&
    p.GetUpperBound(1) >= 1 &&
    (
        (p[0, 0] == 0 && p[0, 1] == 0) ||
        (p[0, 0] == 0 && p[0, 1] == 1)
    ));
</code>```

Neville Nazerane had a good suggestion in his comment: using a data structure other than an array of integers to represent a point should result in code that's much more readily understandable. For instance, suppose you define a coordinate like so:

```<code>public struct Coordinate
{
    public Coordinate(int x, int y)
    {
        X = x;
        Y = y;
    }

    public int X { get; }
    public int Y { get; }

    public bool Equals(int x, int y) =>
        X == x && Y == y;
}
</code>```

Then you can define the set of paths given above like this:

```<code>var objectPaths = new List<List<Coordinate>>();
objectPaths.Add(new List<Coordinate> { new Coordinate(0, 0), new Coordinate(0, 1), new Coordinate(1, 1), new Coordinate(2, 1) });
objectPaths.Add(new List<Coordinate> { new Coordinate(0, 1), new Coordinate(0, 1), new Coordinate(1, 1), new Coordinate(2, 1) });
objectPaths.Add(new List<Coordinate> { new Coordinate(1, 0), new Coordinate(0, 1), new Coordinate(1, 1), new Coordinate(2, 1) });
objectPaths.Add(new List<Coordinate>());
</code>```

And now the subset of paths you're interested in is:

```<code>objectPaths.Where(p => p.Count > 0 && (p[0].Equals(0, 0) || p[0].Equals(0, 1)));
</code>```

If you want a more concise syntax for specifying paths in code, then you might consider a very simple class to represent a path. For instance:

```<code>public class Path : List<Coordinate>
{
    public Path() { }

    public Path(params (int x, int y)[] coordinates) =>
        AddRange(coordinates.Select(c => new Coordinate(c.x, c.y)));
}
</code>```

Now you can define the set of paths as:

```<code>var paths = new List<Path>();
paths.Add(new Path((0, 0), (0, 1), (1, 1), (2, 1)));
paths.Add(new Path((0, 1), (0, 1), (1, 1), (2, 1)));
paths.Add(new Path((1, 0), (0, 1), (1, 1), (2, 1)));
paths.Add(new Path());
</code>```

And the syntax for selecting the subset you wanted is the same as before.

Body:
This is a question that was very hard to title.

In C#, I have a set of int[,] arrays stored in a List<int[,]> paths, each holding a set of coordenates to form a path.
An example would be { {0,0}, {0,1}, {1,1}, {2,1} }.

Now, I want to keep in paths all paths that have the same first index as one of the first indexes of all paths that match a condition.

To better demonstrate what I mean, say I get all the paths that are of an odd length:

paths.Where(x => x.GetLength(0) % 2 == 1).ToList();

Say this returns a list containing some arrays whose first coords are either {0,0} or {0,1}, for example. I want paths to be paths.Where( x=> x's first coords are either {0,0} or {0,1}). How can i achieve this?

Hopefully, what I mean is understandable.

Body:
If you're set on using your current data structure, then you can do this, but the syntax isn't going to be pretty. It's basically like what A. Milto suggested in his answer, except that you need bounds checking to avoid throwing an exception in the case of an empty path. So if you define your paths like so:

var arrayPaths = new List<int[,]>();
arrayPaths.Add(new[,] { { 0, 0 }, { 0, 1 }, { 1, 1 }, { 2, 1 } });  // Include: starts with (0, 0)
arrayPaths.Add(new[,] { { 0, 1 }, { 0, 1 }, { 1, 1 }, { 2, 1 } });  // Include: starts with (0, 1)
arrayPaths.Add(new[,] { { 1, 0 }, { 0, 1 }, { 1, 1 }, { 2, 1 } });  // Exclude: starts with (1, 0)
arrayPaths.Add(new int[0,0]);                                       // Exclude: has no data

Then the subset of paths that start at (0, 0) or (0, 1) is:

arrayPaths.Where(p =>
    p.GetUpperBound(0) >= 0 &&
    p.GetUpperBound(1) >= 1 &&
    (
        (p[0, 0] == 0 && p[0, 1] == 0) ||
        (p[0, 0] == 0 && p[0, 1] == 1)
    ));

Neville Nazerane had a good suggestion in his comment: using a data structure other than an array of integers to represent a point should result in code that's much more readily understandable. For instance, suppose you define a coordinate like so:

public struct Coordinate
{
    public Coordinate(int x, int y)
    {
        X = x;
        Y = y;
    }

    public int X { get; }
    public int Y { get; }

    public bool Equals(int x, int y) =>
        X == x && Y == y;
}

Then you can define the set of paths given above like this:

var objectPaths = new List<List<Coordinate>>();
objectPaths.Add(new List<Coordinate> { new Coordinate(0, 0), new Coordinate(0, 1), new Coordinate(1, 1), new Coordinate(2, 1) });
objectPaths.Add(new List<Coordinate> { new Coordinate(0, 1), new Coordinate(0, 1), new Coordinate(1, 1), new Coordinate(2, 1) });
objectPaths.Add(new List<Coordinate> { new Coordinate(1, 0), new Coordinate(0, 1), new Coordinate(1, 1), new Coordinate(2, 1) });
objectPaths.Add(new List<Coordinate>());

And now the subset of paths you're interested in is:

objectPaths.Where(p => p.Count > 0 && (p[0].Equals(0, 0) || p[0].Equals(0, 1)));

If you want a more concise syntax for specifying paths in code, then you might consider a very simple class to represent a path. For instance:

public class Path : List<Coordinate>
{
    public Path() { }

    public Path(params (int x, int y)[] coordinates) =>
        AddRange(coordinates.Select(c => new Coordinate(c.x, c.y)));
}

Now you can define the set of paths as:

var paths = new List<Path>();
paths.Add(new Path((0, 0), (0, 1), (1, 1), (2, 1)));
paths.Add(new Path((0, 1), (0, 1), (1, 1), (2, 1)));
paths.Add(new Path((1, 0), (0, 1), (1, 1), (2, 1)));
paths.Add(new Path());

And the syntax for selecting the subset you wanted is the same as before.


问:
Image on UIBarButtonItem
In my iPhone application, I'm adding a toolbar on UINavigation controller as navigation bar do not take more then two bar buttons on it.
So far .. I have successfully added the UIToolBar with three BarButtonItems on it. However I am not able to display an image on BarButtonItems.

Can any one tell me .. how to add image on UIToolBar BarButtonItems? Where ToolBar is already added on nav controller.

答:
```<code>   button = [[UIBarButtonItem alloc] initWithCustomView:[[UIImageView alloc] initWithImage:image]];
button.action = @selector(myaction);
button.target = self;
</code>```

Try this.

Title: Image on UIBarButtonItem

Body:
   button = [[UIBarButtonItem alloc] initWithCustomView:[[UIImageView alloc] initWithImage:image]];
button.action = @selector(myaction);
button.target = self;

Try this.


问:
Rewrite a csv file by rearranging columns and rows
I have a csv file (let's call it input.csv) that looks like this:

```<code>ID; Text_1; Points_1; Text_2; Points_2
1; "Hello world one"; 33; "Hello world two"; 90
2, "Goodbye world one"; 44; "Goodbye world two";100
</code>```

I want to create another csv file (let's call it output.csv) that rearranges the columns like this:

```<code> ID; Field; Sent; Points;
 1; Text_1;"Hello world one"; 33
 1; Text_2;"Hello world two"; 90
 2; Text_1;"Goodbye world one"; 44
 2; Text_2;"Goodbye world two"; 100
</code>```

It does not seem as easy as a priori I thought. I wonder if there is a way to directly transcribe the file. Thanks in advance.

I've tried this with some help, but I have difficulties to read and copy the columns and rows in the order I said.

```<code>with open("results.csv", "r") as text:
    reader = csv.DictReader(text, delimiter=";")

rows = [l.split(";") for l in text.split("\n")]
del filas[0]

newlist = list()
for l in filas:
  newlist.append([l[0], 'Texto_1', l[2]])
  newlist.append([l[0], 'Texto_2', l[4]])
</code>```

答:
The following code won't provide you what you are exactly looking for but I believe it will help you to reorganize the columns in a csv file.

```<code>import csv

with open('input.csv', 'r') as infile, open('output.csv', 'w') as outfile:
    # output dict needs a list for new column ordering
    fieldnames = ['ID', 'Text_1', 'Text_2', 'Points_1', 'Points_2']
    writer = csv.DictWriter(outfile, fieldnames=fieldnames)
    # reorder the header first
    writer.writeheader()
    for row in csv.DictReader(infile):
        # writes the reordered rows to the new file
        writer.writerow(row)
</code>```

For the following input:

```<code>ID, Text_1, Points_1, Text_2, Points_2
1, "Hello world one", 33, "Hello world two", 90
2, "Goodbye world one", 44, "Goodbye world two",100
</code>```

The above program will output:

```<code>ID, Text_1, Text_2, Points_1, Points_2
1, "Hello world one", "Hello world two", 33, 90
2, "Goodbye world one", "Goodbye world two", 44, 100
</code>```

Body:
I have a csv file (let's call it input.csv) that looks like this:

ID; Text_1; Points_1; Text_2; Points_2
1; "Hello world one"; 33; "Hello world two"; 90
2, "Goodbye world one"; 44; "Goodbye world two";100

I want to create another csv file (let's call it output.csv) that rearranges the columns like this:

 ID; Field; Sent; Points;
 1; Text_1;"Hello world one"; 33
 1; Text_2;"Hello world two"; 90
 2; Text_1;"Goodbye world one"; 44
 2; Text_2;"Goodbye world two"; 100

It does not seem as easy as a priori I thought. I wonder if there is a way to directly transcribe the file. Thanks in advance.

I've tried this with some help, but I have difficulties to read and copy the columns and rows in the order I said.

with open("results.csv", "r") as text:
    reader = csv.DictReader(text, delimiter=";")

rows = [l.split(";") for l in text.split("\n")]
del filas[0]

newlist = list()
for l in filas:
  newlist.append([l[0], 'Texto_1', l[2]])
  newlist.append([l[0], 'Texto_2', l[4]])

Body:
The following code won't provide you what you are exactly looking for but I believe it will help you to reorganize the columns in a csv file.

import csv

with open('input.csv', 'r') as infile, open('output.csv', 'w') as outfile:
    # output dict needs a list for new column ordering
    fieldnames = ['ID', 'Text_1', 'Text_2', 'Points_1', 'Points_2']
    writer = csv.DictWriter(outfile, fieldnames=fieldnames)
    # reorder the header first
    writer.writeheader()
    for row in csv.DictReader(infile):
        # writes the reordered rows to the new file
        writer.writerow(row)

For the following input:

ID, Text_1, Points_1, Text_2, Points_2
1, "Hello world one", 33, "Hello world two", 90
2, "Goodbye world one", 44, "Goodbye world two",100

The above program will output:

ID, Text_1, Text_2, Points_1, Points_2
1, "Hello world one", "Hello world two", 33, 90
2, "Goodbye world one", "Goodbye world two", 44, 100


问:
How to scale a path in SVG at the same origin?
I would like to create an animation on a path in a SVG. It scales back and forth at the same origin. The problem is my current solution works on Chrome but not on Firefox.

```<code>.svg-map-pg-logo {
  animation-name: star;
  animation-duration: 0.5s;
  animation-iteration-count: infinite;
}

@keyframes star {
    0%   {
      transform: scale(1, 1);
      transform-origin: center center;
    }
    100% {
      transform: scale(1.2, 1.2);
      transform-origin: center center;
    }
}
</code>```

On firefox, the path scales while moving to a direction. On Chrome it just scales at its original origin. How to make the scale not moving?

This is what happens on Firefox:

This is what happens on Chrome and what I want:

https://codepen.io/joshuajazleung/pen/jaaPwW

答:
You want transform-box: fill-box;

```<code>.svg-map-pg-logo {
  animation-name: star;
  animation-duration: 0.5s;
  animation-iteration-count: infinite;
  transform-origin: center center;
  transform-box: fill-box;
}

@keyframes star {
    0%   {
      transform: scale(1, 1);
    }
    100% {
      transform: scale(1.2, 1.2);
    }
}
</code>```

Chrome incorrectly defaults to this when the transform-origin is set to center.

Body:
I would like to create an animation on a path in a SVG. It scales back and forth at the same origin. The problem is my current solution works on Chrome but not on Firefox.

.svg-map-pg-logo {
  animation-name: star;
  animation-duration: 0.5s;
  animation-iteration-count: infinite;
}

@keyframes star {
    0%   {
      transform: scale(1, 1);
      transform-origin: center center;
    }
    100% {
      transform: scale(1.2, 1.2);
      transform-origin: center center;
    }
}

On firefox, the path scales while moving to a direction. On Chrome it just scales at its original origin. How to make the scale not moving?

This is what happens on Firefox:

This is what happens on Chrome and what I want:

https://codepen.io/joshuajazleung/pen/jaaPwW

Body:
You want transform-box: fill-box;

.svg-map-pg-logo {
  animation-name: star;
  animation-duration: 0.5s;
  animation-iteration-count: infinite;
  transform-origin: center center;
  transform-box: fill-box;
}

@keyframes star {
    0%   {
      transform: scale(1, 1);
    }
    100% {
      transform: scale(1.2, 1.2);
    }
}

Chrome incorrectly defaults to this when the transform-origin is set to center.


问:
Golang Revel Assertf causes panic
I have created revel test suite, I use Assertf for checking an error.

```<code>t.Assertf(err == nil, "error occurred: %v", err)
</code>```

It worked without any problem in my Windows and also Mac OSX. But in my remote server, Ubuntu 16.04, whenever assert error, I got error message like this.

```<code>server.go:2753: http: panic serving [::1]:44626: open /go/src/runtime/debug/stack.go: no such file or directory

goroutine 74 [running]:
net/http.(*conn).serve.func1(0xc4204a7f40)
    /usr/local/go/src/net/http/server.go:1721 +0xd0
panic(0xa04ba0, 0xc4204c2f60)
    /usr/local/go/src/runtime/panic.go:489 +0x2cf
github.com/revel/revel.MustReadLines(0xc420198a4c, 0x1e, 0x1, 0xc4204d2a80, 0x3e)
    /go/src/github.com/revel/revel/util.go:56 +0x168
github.com/revel/revel.NewErrorFromPanic(0xa04ba0, 0xc4204c2f00, 0x0)
    /go/src/github.com/revel/revel/errors.go:63 +0x25b
github.com/revel/revel.handleInvocationPanic(0xc42024e0c0, 0xa04ba0, 0xc4204c2f00)
    /go/src/github.com/revel/revel/panic.go:25 +0x4d
github.com/revel/revel.PanicFilter.func1(0xc42024e0c0)
    /go/src/github.com/revel/revel/panic.go:16 +0x5c
panic(0xa04ba0, 0xc4204c2f00)
    /usr/local/go/src/runtime/panic.go:489 +0x2cf
github.com/revel/revel.InterceptorFilter.func1(0xc42024e0c0)
    /go/src/github.com/revel/revel/intercept.go:97 +0x7d
panic(0xa04ba0, 0xc4204c2f00)
    /usr/local/go/src/runtime/panic.go:489 +0x2cf
github.com/revel/revel.MustReadLines(0xc42018605a, 0x1e, 0x1, 0xc420278d10, 0xad)
    /go/src/github.com/revel/revel/util.go:56 +0x168
github.com/revel/revel.NewErrorFromPanic(0x9feea0, 0xc4204d8aa0, 0xc4204d8aa0)
    /go/src/github.com/revel/revel/errors.go:63 +0x25b
github.com/revel/modules/testrunner/app/controllers.TestRunner.Run.func1.1(0xaa9ba0, 0xc4204c2a80, 0x16, 0xc4204d284c, 0x15, 0xc4204d2862, 0x14, 0xc4203fac78)
    /go/src/github.com/revel/modules/testrunner/app/controllers/testrunner.go:113 +0x70
panic(0x9feea0, 0xc4204d8aa0)
    /usr/local/go/src/runtime/panic.go:489 +0x2cf
github.com/revel/revel/testing.(*TestSuite).Assertf(0xc4204c2a80, 0xc4203fa600, 0xac7700, 0x16, 0xc4203fa620, 0x1, 0x1)
    /go/src/github.com/revel/revel/testing/testsuite.go:313 +0x87
madvrstudio/bnkjigsaw/tests.(*ReceiptValidationTest).TestValidateAppStore(0xc4204c2a80)
</code>```

答: Assert triggers a panic, and the panic filter is failing because it cannot locate the source file of the go code that caused the error. If you have stripped away the source files from the deployment this could cause that (IMHO it really shouldn't) but looking at the code it is attempting to load up the file which the stack says has the error on it.</p>

Title: Golang Revel Assertf causes panic

Body:
I have created revel test suite, I use Assertf for checking an error.

t.Assertf(err == nil, "error occurred: %v", err)

It worked without any problem in my Windows and also Mac OSX. But in my remote server, Ubuntu 16.04, whenever assert error, I got error message like this.

server.go:2753: http: panic serving [::1]:44626: open /go/src/runtime/debug/stack.go: no such file or directory

goroutine 74 [running]:
net/http.(*conn).serve.func1(0xc4204a7f40)
    /usr/local/go/src/net/http/server.go:1721 +0xd0
panic(0xa04ba0, 0xc4204c2f60)
    /usr/local/go/src/runtime/panic.go:489 +0x2cf
github.com/revel/revel.MustReadLines(0xc420198a4c, 0x1e, 0x1, 0xc4204d2a80, 0x3e)
    /go/src/github.com/revel/revel/util.go:56 +0x168
github.com/revel/revel.NewErrorFromPanic(0xa04ba0, 0xc4204c2f00, 0x0)
    /go/src/github.com/revel/revel/errors.go:63 +0x25b
github.com/revel/revel.handleInvocationPanic(0xc42024e0c0, 0xa04ba0, 0xc4204c2f00)
    /go/src/github.com/revel/revel/panic.go:25 +0x4d
github.com/revel/revel.PanicFilter.func1(0xc42024e0c0)
    /go/src/github.com/revel/revel/panic.go:16 +0x5c
panic(0xa04ba0, 0xc4204c2f00)
    /usr/local/go/src/runtime/panic.go:489 +0x2cf
github.com/revel/revel.InterceptorFilter.func1(0xc42024e0c0)
    /go/src/github.com/revel/revel/intercept.go:97 +0x7d
panic(0xa04ba0, 0xc4204c2f00)
    /usr/local/go/src/runtime/panic.go:489 +0x2cf
github.com/revel/revel.MustReadLines(0xc42018605a, 0x1e, 0x1, 0xc420278d10, 0xad)
    /go/src/github.com/revel/revel/util.go:56 +0x168
github.com/revel/revel.NewErrorFromPanic(0x9feea0, 0xc4204d8aa0, 0xc4204d8aa0)
    /go/src/github.com/revel/revel/errors.go:63 +0x25b
github.com/revel/modules/testrunner/app/controllers.TestRunner.Run.func1.1(0xaa9ba0, 0xc4204c2a80, 0x16, 0xc4204d284c, 0x15, 0xc4204d2862, 0x14, 0xc4203fac78)
    /go/src/github.com/revel/modules/testrunner/app/controllers/testrunner.go:113 +0x70
panic(0x9feea0, 0xc4204d8aa0)
    /usr/local/go/src/runtime/panic.go:489 +0x2cf
github.com/revel/revel/testing.(*TestSuite).Assertf(0xc4204c2a80, 0xc4203fa600, 0xac7700, 0x16, 0xc4203fa620, 0x1, 0x1)
    /go/src/github.com/revel/revel/testing/testsuite.go:313 +0x87
madvrstudio/bnkjigsaw/tests.(*ReceiptValidationTest).TestValidateAppStore(0xc4204c2a80)


问:
Question regarding chaining multiple any_of criteria #Mongoid
I have a requirement where I need to run a MongoDB query like the following:

```db.collection.find({ $or : [{"field1" : "value1"}, {"field2" : "value2"}],
$or : [{"field3" : "value3"}, {"field4" : "value4"}]})
```

i.e.

```
(field1 == value 1 or field2 == value2) and (field3 == value3 or field4
== value4)
```

I want to achieve this through criteria chaining because the query gets formed
dynamically from different parts of the code. But if I try doing something like the following

```
criteria = Collection.any_of({"field1" => "value1"}, {"field2" =>
"value2"})
criteria = criteria.any_of({"field3" => "value3"}, {"field4" => "value4"})
```

I get the resultant query where all these are combined into a single $or
statement like

```
db.collection.find({ $or : [{"field1" : "value1"}, {"field2" : "value2"},
{"field3" : "value3"}, {"field4" : "value4"}]})
```

What is the way to achieve "and" of the two "any_of" using criteria chaining?

答:
You can do it with avoid any_of.</p>

```<code>criteria = Collection.where('$or' => [{"field1" => "value1"}, {"field2" => "value2"}])
criteria = criteria.where('$or' => [{"field3" => "value3"}, {"field4" => "value4"}])
</code>```

Body:
I have a requirement where I need to run a MongoDB query like the following:

db.collection.find({ $or : [{"field1" : "value1"}, {"field2" : "value2"}],
$or : [{"field3" : "value3"}, {"field4" : "value4"}]})

i.e.

(field1 == value 1 or field2 == value2) and (field3 == value3 or field4
== value4)

I want to achieve this through criteria chaining because the query gets formed
dynamically from different parts of the code. But if I try doing something like the following

criteria = Collection.any_of({"field1" => "value1"}, {"field2" =>
"value2"})
criteria = criteria.any_of({"field3" => "value3"}, {"field4" => "value4"})

I get the resultant query where all these are combined into a single $or
statement like

db.collection.find({ $or : [{"field1" : "value1"}, {"field2" : "value2"},
{"field3" : "value3"}, {"field4" : "value4"}]})

What is the way to achieve "and" of the two "any_of" using criteria chaining?

Body:
You can do it with avoid any_of.

criteria = Collection.where('$or' => [{"field1" => "value1"}, {"field2" => "value2"}])
criteria = criteria.where('$or' => [{"field3" => "value3"}, {"field4" => "value4"}])


问:
check if the n-th variadic template argument is of a certain type
I'd like to implement something like same_type() function in C++11 like below (this is what I have tried so far but it can not cope with the use cases mentioned below). The function is to check if T is of the same type of the n-th argument of Args, currently n=0 should be enough for my requirement, although n=other meaningful value would be something better to have (not very important if not straightforward).

```<code>template<typename T, typename... Args>
struct MyClass
{
    // check if T is of the same type of the n-th argument of Args
    bool same_type() {
        // currently, I only check the first argument
        // but if possible, it would be more useful to extend
        // this function to check the n-th argument
        return std::is_same<T,typename std::tuple_element<0, std::tuple<Args...> >::type>;
    }
};
</code>```

I have already had a look at this answer, but it does not consider the following use cases.

Use cases:

1.use with references and const qualifier:

```<code>MyClass<int,const int&> c;
// expect to see 1, type of int should match const int&, i.e. reference or const should NOT affect the result
std::cout<<c.same_type();
</code>```

2.use with no argument supplied:

```<code>MyClass<int> c;
// expect to see 0 as there is no variadic argument provided to compare with int
std::cout<<c.same_type();
</code>```

答:
I think you're looking to check compatibility more than 'sameness'. here's one way:</p>

```<code>#include <tuple>
#include <type_traits>
#include <iostream>
#include <string>

template<class...Ts>
struct nth_is_compatible
{
  using tuple = std::tuple<Ts...>;

  template<class T, std::size_t N> static constexpr bool check()
  {
    return std::is_convertible<decltype(std::get<N>(std::declval<tuple>())), T>::value;
  }

};

struct Monkey
{
  Monkey(std::string) {} // conversion constructor
};

int main()
{

  using checklist = nth_is_compatible<const int&, float, std::string>;
  constexpr auto list = checklist();

  std::cout << list.check<int, 0>() << std::endl;
  std::cout << list.check<int, 1>() << std::endl;
  std::cout << list.check<int, 2>() << std::endl;

  // prove it's a constexpr and that it works for conversions
  constexpr auto monkeyable = checklist::check<Monkey, 2>();
  std::cout << monkeyable << std::endl;
}
</code>```

Body:
I'd like to implement something like same_type() function in C++11 like below (this is what I have tried so far but it can not cope with the use cases mentioned below). The function is to check if T is of the same type of the n-th argument of Args, currently n=0 should be enough for my requirement, although n=other meaningful value would be something better to have (not very important if not straightforward).

template<typename T, typename... Args>
struct MyClass
{
    // check if T is of the same type of the n-th argument of Args
    bool same_type() {
        // currently, I only check the first argument
        // but if possible, it would be more useful to extend
        // this function to check the n-th argument
        return std::is_same<T,typename std::tuple_element<0, std::tuple<Args...> >::type>;
    }
};

I have already had a look at this answer, but it does not consider the following use cases.

Use cases:

1.use with references and const qualifier:

MyClass<int,const int&> c;
// expect to see 1, type of int should match const int&, i.e. reference or const should NOT affect the result
std::cout<<c.same_type();

2.use with no argument supplied:

MyClass<int> c;
// expect to see 0 as there is no variadic argument provided to compare with int
std::cout<<c.same_type();

Body:
I think you're looking to check compatibility more than 'sameness'. here's one way:

#include <tuple>
#include <type_traits>
#include <iostream>
#include <string>

template<class...Ts>
struct nth_is_compatible
{
  using tuple = std::tuple<Ts...>;

  template<class T, std::size_t N> static constexpr bool check()
  {
    return std::is_convertible<decltype(std::get<N>(std::declval<tuple>())), T>::value;
  }

};

struct Monkey
{
  Monkey(std::string) {} // conversion constructor
};

int main()
{

  using checklist = nth_is_compatible<const int&, float, std::string>;
  constexpr auto list = checklist();

  std::cout << list.check<int, 0>() << std::endl;
  std::cout << list.check<int, 1>() << std::endl;
  std::cout << list.check<int, 2>() << std::endl;

  // prove it's a constexpr and that it works for conversions
  constexpr auto monkeyable = checklist::check<Monkey, 2>();
  std::cout << monkeyable << std::endl;
}


问:
iterating through STRINGS in Python (3)
: Write a   function,   named foldStrings(string1,  string2)    that    takes,  as  arguments,  two strings.        If

the two strings are equal   in  length, the function    returns a   string  that    is  formed  by  alternating characters  in  each    of the  two strings.        If  the two strings are not equal   in  length, the function    returns the string  “The    two strings are not
equal   in  length.”

For example, >>>foldStrings(“abc”,  “def”)

should  return  the string  “adbecf” and >>>foldStrings(“a”,    “bc”)

should  return  the string  “The    two strings are not equal in length.”

This is what I have so far:

```<code>def foldStrings(str1, str2):
newStr = ""
counter = 0
if len(str2) == len(str1):
    while counter < len(str2):
        for element in str1:
            for index in str2:
                newStr = newStr + element
                newStr = newStr + index
                counter += 1
    return newStr
else:
    return "The two Strings are not equal in length"
</code>```

and it prints this: 's1s2s3s4s5s6a1a2a3a4a5a6n1n2n3n4n5n6t1t2t3t4t5t6o1o2o3o4o5o6s1s2s3s4s5s6'
instead of this:
's1a2n3t4o5s6'

答:
You can skip using a counter variable by using range

```<code>def foldStrings(str1, str2):
    if len(str1) != len(str2):
        return "The two Strings are not equal in length"
        # This should really be a raise ValueError("The two Strings are not equal in length")
    newStr = ''
    for i in range(len(str1)):
        newStr += str1[i] + str2[i]
    return newStr
</code>```

Here's a slightly more compact way to replace the for loop

```<code>newStr = ''.join([x for pair in zip(str1, str2) for x in pair])
</code>```

Title: iterating through STRINGS in Python (3)

Body:
: Write a   function,   named foldStrings(string1,  string2)    that    takes,  as  arguments,  two strings.        If

the two strings are equal   in  length, the function    returns a   string  that    is  formed  by  alternating characters  in  each    of the  two strings.        If  the two strings are not equal   in  length, the function    returns the string  “The    two strings are not
equal   in  length.”

For example, >>>foldStrings(“abc”,  “def”)

should  return  the string  “adbecf” and >>>foldStrings(“a”,    “bc”)

should  return  the string  “The    two strings are not equal in length.”

This is what I have so far:

def foldStrings(str1, str2):
newStr = ""
counter = 0
if len(str2) == len(str1):
    while counter < len(str2):
        for element in str1:
            for index in str2:
                newStr = newStr + element
                newStr = newStr + index
                counter += 1
    return newStr
else:
    return "The two Strings are not equal in length"

and it prints this: 's1s2s3s4s5s6a1a2a3a4a5a6n1n2n3n4n5n6t1t2t3t4t5t6o1o2o3o4o5o6s1s2s3s4s5s6'
instead of this:
's1a2n3t4o5s6'

Body:
You can skip using a counter variable by using range

def foldStrings(str1, str2):
    if len(str1) != len(str2):
        return "The two Strings are not equal in length"
        # This should really be a raise ValueError("The two Strings are not equal in length")
    newStr = ''
    for i in range(len(str1)):
        newStr += str1[i] + str2[i]
    return newStr

Here's a slightly more compact way to replace the for loop

newStr = ''.join([x for pair in zip(str1, str2) for x in pair])