问:
How to parse a Ternary Statement in C#
I'm accepting an input string that I want to be a ternary statement that works on strings.  So my method signature would look like this:

```<code>public string Parse(string value, string ternaryStatement)
</code>```

and there parameters would give these results:

```<code>Parse(null, "=?It's Null:It's Not Null") == "It's Null" // Empty string would
Parse("", "=?It's Null:It's Not Null") == "It's Null"   // be same as null
</code>```

This example is fairly simple, Split the string first by '?' then by ':'

But of course I need a method to handle escape characters, "\", "\?" and ":", where "\" is valid anywhere, "\?" would only be valid before the first unescaped "?" and ":" would only be valid after that same "?".

```<code>Parse(@"\?\", @"=\\\?\\?\:Match\::\:No Match\:") == ":Match:"
Parse(@"\?\", @"!=\\\?\\?\:No Match\::\:Match\:") == ":Match:"
</code>```

But this is really complicated.  I believe I can perform it using regular expressions, but that just creates another problem since this is well beyond my limited understanding of regular expressions.  What's the best way to tackle this problem?

Edit 1

Some of the background:  I'm storing a format for a URL in a database config table (It's actually Dynamics 365 for Customer Engagement, but that doesn't matter at this point).  The format is stored as strings, and the parameters that are required are defined in code.  So generally it looks like this:

Format: "https://something.com?Foo={0}&Bar={1}"

Description: "0 - Foo, 1 - Bar"

where the description is used both for the person that is formatting the url, and the developer that needs to know how to structure the format statement.

The problem I'm running into right now is that I have a url that requires at least one of two different parameters.  If one of the values is null or empty, it will error if included in the url.  So I need a way of saying, if Foo is null or Bar is null, don't include the name or &.  Ideally I'd like to implement this like this:

```<code>"https://something.com?{0:=?:Foo={{0}}}&}{1:=?:Bar={{1}}}}"
</code>```

So if Foo is null and Bar is "Bar" the output would be

```<code>"https://something.com?Bar=Bar"
</code>```

I could also see this being used if we need to switch between a 0/1 for a boolean to true/false without having to change code:

```<code>"https://something.com?{0:=0?false:true}"
</code>```

答:
Solution to returning different values based on input string

Why do you need to pass in a ternary statement / wouldn't this make more sense?

```<code>string Parse(string value, string returnIfNull, string returnIfNotNull)
{
    return string.IsNullOrEmpty(value) ? returnIfNull: returnIfNotNull;
}

Console.WriteLine(Parse("", "treat as null", "not expected"));
Console.WriteLine(Parse("hello", "not expected", "this value's not null"));
</code>```

Parsing a ternary string for values

However, if you really need to do this, you could use something like the below:

```<code>private static readonly Regex TernaryParserRegex = new Regex(
    @"^=\?(?<ifNull>(?:\\(\\\\)*:|[^:])*)(?<!\\):(?<ifNotNull>(?:\\(\\\\)*:|[^:])*)$"
    /* , RegexOptions.Compiled //include this line for performance if appropriate */
);
private string[] ParseTernaryString (string ternaryStatement)
{
    var results = TernaryParserRegex.Match(ternaryStatement);
    if (results.Success)
    {
        string[] returnVal = {
            results.Groups["ifNull"].Value
            ,
            results.Groups["ifNotNull"].Value
        };
        return returnVal;
    }
    else
    {
        throw new Exception("Invalid Ternary Statement"); //use an appropriate exception type here; or have the function return `{null,null}` / some other default as appropriate
    }
}
public string Parse(string value, string ternaryStatement)
{
    var returnValues = ParseTernaryString(ternaryStatement);
    return string.IsNullOrEmpty(value) ? returnValues[0]: returnValues[1];
}

//Example Usage:
Console.WriteLine(Parse("", "=?treat as null:not expected"));
Console.WriteLine(Parse("hello", "=?not expected:this value's not null"));
</code>```

An explanation of the regex & additional examples are available here:
https://regex101.com/r/YJ9qd3/1

Appending non-null/blank values to a URL's Query String

```<code>public void Main()
{
    var url = "https://example.com?something=keepMe&foo=FooWasHere&bar=swapMeQuick";
    var dict = new System.Collections.Generic.Dictionary<string, string>();
    dict.Add("foo", null);
    dict.Add("bar", "hello");
    dict.Add("boo", "new");
    Console.WriteLine(CreateUri(url, dict).ToString());
}

Uri CreateUri(string uri, IDictionary<string, string> parameters)
{
    return CreateUri(new Uri(uri), parameters);
}
Uri CreateUri(Uri uri, IDictionary<string, string> parameters)
{
    var query = HttpUtility.ParseQueryString(uri.Query); //https://msdn.microsoft.com/en-us/library/ms150046(v=vs.110).aspx; though returns HttpValueCollection
    foreach (string key in parameters.Keys)
    {
        if (string.IsNullOrEmpty(parameters[key]))
        { //parameter is null or empty; if such a parameter already exists on our URL, remove it
            query.Remove(key); //if this parameter does not already exist, has no effect (but no exception is thrown)
        }
        else
        { //parameter has a value; add or update the query string with this value
            query.Set(key, parameters[key]);
        }
    }
    var builder = new UriBuilder(uri);
    builder.Query = query.ToString();
    return builder.Uri;
}
</code>```

Title: How to parse a Ternary Statement in C#

Body:
I'm accepting an input string that I want to be a ternary statement that works on strings.  So my method signature would look like this:

public string Parse(string value, string ternaryStatement)

and there parameters would give these results:

Parse(null, "=?It's Null:It's Not Null") == "It's Null" // Empty string would
Parse("", "=?It's Null:It's Not Null") == "It's Null"   // be same as null

This example is fairly simple, Split the string first by '?' then by ':'

But of course I need a method to handle escape characters, "\", "\?" and ":", where "\" is valid anywhere, "\?" would only be valid before the first unescaped "?" and ":" would only be valid after that same "?".

Parse(@"\?\", @"=\\\?\\?\:Match\::\:No Match\:") == ":Match:"
Parse(@"\?\", @"!=\\\?\\?\:No Match\::\:Match\:") == ":Match:"

But this is really complicated.  I believe I can perform it using regular expressions, but that just creates another problem since this is well beyond my limited understanding of regular expressions.  What's the best way to tackle this problem?

Edit 1

Some of the background:  I'm storing a format for a URL in a database config table (It's actually Dynamics 365 for Customer Engagement, but that doesn't matter at this point).  The format is stored as strings, and the parameters that are required are defined in code.  So generally it looks like this:

Format: "https://something.com?Foo={0}&Bar={1}"

Description: "0 - Foo, 1 - Bar"

where the description is used both for the person that is formatting the url, and the developer that needs to know how to structure the format statement.

The problem I'm running into right now is that I have a url that requires at least one of two different parameters.  If one of the values is null or empty, it will error if included in the url.  So I need a way of saying, if Foo is null or Bar is null, don't include the name or &.  Ideally I'd like to implement this like this:

"https://something.com?{0:=?:Foo={{0}}}&}{1:=?:Bar={{1}}}}"

So if Foo is null and Bar is "Bar" the output would be

"https://something.com?Bar=Bar"

I could also see this being used if we need to switch between a 0/1 for a boolean to true/false without having to change code:

"https://something.com?{0:=0?false:true}"

Body:
Solution to returning different values based on input string

Why do you need to pass in a ternary statement / wouldn't this make more sense?

string Parse(string value, string returnIfNull, string returnIfNotNull)
{
    return string.IsNullOrEmpty(value) ? returnIfNull: returnIfNotNull;
}

Console.WriteLine(Parse("", "treat as null", "not expected"));
Console.WriteLine(Parse("hello", "not expected", "this value's not null"));

Parsing a ternary string for values

However, if you really need to do this, you could use something like the below:

private static readonly Regex TernaryParserRegex = new Regex(
    @"^=\?(?<ifNull>(?:\\(\\\\)*:|[^:])*)(?<!\\):(?<ifNotNull>(?:\\(\\\\)*:|[^:])*)$"
    /* , RegexOptions.Compiled //include this line for performance if appropriate */
);
private string[] ParseTernaryString (string ternaryStatement)
{
    var results = TernaryParserRegex.Match(ternaryStatement);
    if (results.Success)
    {
        string[] returnVal = {
            results.Groups["ifNull"].Value
            ,
            results.Groups["ifNotNull"].Value
        };
        return returnVal;
    }
    else
    {
        throw new Exception("Invalid Ternary Statement"); //use an appropriate exception type here; or have the function return `{null,null}` / some other default as appropriate
    }
}
public string Parse(string value, string ternaryStatement)
{
    var returnValues = ParseTernaryString(ternaryStatement);
    return string.IsNullOrEmpty(value) ? returnValues[0]: returnValues[1];
}

//Example Usage:
Console.WriteLine(Parse("", "=?treat as null:not expected"));
Console.WriteLine(Parse("hello", "=?not expected:this value's not null"));

An explanation of the regex & additional examples are available here:
https://regex101.com/r/YJ9qd3/1

Appending non-null/blank values to a URL's Query String

public void Main()
{
    var url = "https://example.com?something=keepMe&foo=FooWasHere&bar=swapMeQuick";
    var dict = new System.Collections.Generic.Dictionary<string, string>();
    dict.Add("foo", null);
    dict.Add("bar", "hello");
    dict.Add("boo", "new");
    Console.WriteLine(CreateUri(url, dict).ToString());
}

Uri CreateUri(string uri, IDictionary<string, string> parameters)
{
    return CreateUri(new Uri(uri), parameters);
}
Uri CreateUri(Uri uri, IDictionary<string, string> parameters)
{
    var query = HttpUtility.ParseQueryString(uri.Query); //https://msdn.microsoft.com/en-us/library/ms150046(v=vs.110).aspx; though returns HttpValueCollection
    foreach (string key in parameters.Keys)
    {
        if (string.IsNullOrEmpty(parameters[key]))
        { //parameter is null or empty; if such a parameter already exists on our URL, remove it
            query.Remove(key); //if this parameter does not already exist, has no effect (but no exception is thrown)
        }
        else
        { //parameter has a value; add or update the query string with this value
            query.Set(key, parameters[key]);
        }
    }
    var builder = new UriBuilder(uri);
    builder.Query = query.ToString();
    return builder.Uri;
}


来源: stackexchange

问:
How to sum value of two json object key?
```<code>"bills": [
    {
        "refNo": 17,
        "billDate": "1-apr-2016",
        "dueDate": "30-apr-2016",
        "pendingAmount": 4500,
        "overdueDays": 28
    },
    {
        "refNo": 20,
        "billDate": "15-apr-2016",
        "dueDate": "3-may-2016",
        "pendingAmount": 56550,
        "overdueDays": 15
    }
]
</code>```

I want to sum "pendingAmount" field.
It should be return like pendingAmount: 61050

答:
You could use the following snippet:

```<code>var sum = JSON.parse(bills).reduce(function(acc, val){
  return acc.pendingAmount + val.pendingAmount;
}, {pendingAmount: 0});
</code>```

it uses the array.prototype.reduce() function on the parsed JSON. The second argument of the reduce is the initial value passed to the reduce function

ContentLicense: CC BY-SA 4.0

Body:
"bills": [
    {
        "refNo": 17,
        "billDate": "1-apr-2016",
        "dueDate": "30-apr-2016",
        "pendingAmount": 4500,
        "overdueDays": 28
    },
    {
        "refNo": 20,
        "billDate": "15-apr-2016",
        "dueDate": "3-may-2016",
        "pendingAmount": 56550,
        "overdueDays": 15
    }
]

I want to sum "pendingAmount" field.
It should be return like pendingAmount: 61050

Body:
You could use the following snippet:

var sum = JSON.parse(bills).reduce(function(acc, val){
  return acc.pendingAmount + val.pendingAmount;
}, {pendingAmount: 0});

it uses the array.prototype.reduce() function on the parsed JSON. The second argument of the reduce is the initial value passed to the reduce function

ContentLicense: CC BY-SA 3.0


问:
Illegal mix of collations (latin5_turkish_ci,IMPLICIT) and (latin1_swedish_ci,COERCIBLE) for operation '='
How can i solve

```<code>"Illegal mix of collations (latin5_turkish_ci,IMPLICIT)
and (latin1_swedish_ci,COERCIBLE)
for operation '='" problem?
</code>```

My query: select * from up where name='camış'

connection options:

```<code>SET NAMES 'latin5'
SET character_set_connection = 'latin5'
SET collation_connection = latin5_turkish_ci
</code>```

--
I changed the collate as latin5_turkish_ci but doesn't work.
Between, after a few minutes (lots of queries), the problem disappears on its own.

答:
This rather bad idea but should work:

```<code>SELECT *
  FROM up
 WHERE CONVERT(name USING latin5) COLLATE latin5_turkish_ci = 'camış'
</code>```

Good idea is to convert all your column to desired character set (and this should be UTF-8).

[+] By converting I mean not changing default collation of table/column, but to convert all data in it. So I would create new column with target character set, populate it with UPDATE table SET new_column = CONVERT(old_column USING characterset), drop old column and rename new one.

ContentLicense: CC BY-SA 2.5

Body:
How can i solve

"Illegal mix of collations (latin5_turkish_ci,IMPLICIT)
and (latin1_swedish_ci,COERCIBLE)
for operation '='" problem?

My query: select * from up where name='camış'

connection options:

SET NAMES 'latin5'
SET character_set_connection = 'latin5'
SET collation_connection = latin5_turkish_ci

--
I changed the collate as latin5_turkish_ci but doesn't work.
Between, after a few minutes (lots of queries), the problem disappears on its own.

Body:
This rather bad idea but should work:

SELECT *
  FROM up
 WHERE CONVERT(name USING latin5) COLLATE latin5_turkish_ci = 'camış'

Good idea is to convert all your column to desired character set (and this should be UTF-8).

[+] By converting I mean not changing default collation of table/column, but to convert all data in it. So I would create new column with target character set, populate it with UPDATE table SET new_column = CONVERT(old_column USING characterset), drop old column and rename new one.


问:
Cell reuse bug in collectionView
Hello to all dear friends. I'm experiencing a problem with cell reuse. In practice I select multiple cells. In the "didSelected" method, I modify a property, called "isSelectedCell", to true and add a green border (to indicate the selection); While in the "didDeselect" method I carry it to false and remove the color of the border. But when I scroll down some cells, never selected, appear to be selected and the property is true. Because? How do I prevent this. It seems that when a cell is reused, the properties take on old ones and not their own.</p>

答:
it's due to the cell reuse of CollectionView.

as you can see in this article

when a cell disappear, it's reused to be the new one that going to appear.

Title: Cell reuse bug in collectionView


问:
Notepad++: Replace find query with words from list
I would like to replace all "var_"

```<code>var_
   Hello
var_
   Whats
var_
   Up?
...
</code>```

with words from this list

```<code>alpha
beta
gamma
...
</code>```

so the end result is

```<code>alpha
   Hello
beta
   Whats
gamma
   Up?
...
</code>```

Would appreciate help on achieving this!

答:
This is sort of impossible / overly complicated with a regex. However, if you combine it with a programming language, you can get it done quickly. E.g. in python it would look like this:

```<code>import sys
import re
import fileinput

if len(sys.argv) < 3:
  exit("Usage: " + sys.argv[0] + " <filename> <replacements>")

input_file = sys.argv[1]
replacements = sys.argv[2:]
num_of_replacements = len(replacements)
replacement_index = 0
searcher = re.compile("^var_\\b")

for line in fileinput.input(input_file, inplace=True, backup='.bak'):
  match = searcher.match(line)
  if match is None:
    print(line.rstrip())
  else:
    print(re.sub("^var_\\b", line.rstrip(), replacements[replacement_index]))
    replacement_index = replacement_index + 1
</code>```

Usage: replacer.py ExampleInput.txt alpha beta gamma

Update

It's possible to modify the program to accept the string you search for as the 1st param:

```<code>replacer.py "var_" ExampleInput.txt alpha beta gamma
</code>```

The modified python script looks like this:

```<code>import sys
import re
import fileinput

if len(sys.argv) < 4:
  exit("Usage: " + sys.argv[0] + " <pattern> <filename> <replacements>")

search = "\\b" + sys.argv[1] + "\\b"
input_file = sys.argv[2]
replacements = sys.argv[3:]
num_of_replacements = len(replacements)
replacement_index = 0
searcher = re.compile(search)

for line in fileinput.input(input_file, inplace=True, backup='.bak'):
  match = searcher.match(line)
  if match is None:
    print(line.rstrip())
  else:
    print(re.sub(search, line.rstrip(), replacements[replacement_index]))
    replacement_index = replacement_index + 1
</code>```

Note: this script still has a few limitations:

it expects that the string you search for occurs only once each line.

it replaces the searched string only if it's a distinct word

you can accidentally incorporate any python regex syntax into the search param

Body:
I would like to replace all "var_"

var_
   Hello
var_
   Whats
var_
   Up?
...

with words from this list

alpha
beta
gamma
...

so the end result is

alpha
   Hello
beta
   Whats
gamma
   Up?
...

Would appreciate help on achieving this!

Body:
This is sort of impossible / overly complicated with a regex. However, if you combine it with a programming language, you can get it done quickly. E.g. in python it would look like this:

import sys
import re
import fileinput

if len(sys.argv) < 3:
  exit("Usage: " + sys.argv[0] + " <filename> <replacements>")

input_file = sys.argv[1]
replacements = sys.argv[2:]
num_of_replacements = len(replacements)
replacement_index = 0
searcher = re.compile("^var_\\b")

for line in fileinput.input(input_file, inplace=True, backup='.bak'):
  match = searcher.match(line)
  if match is None:
    print(line.rstrip())
  else:
    print(re.sub("^var_\\b", line.rstrip(), replacements[replacement_index]))
    replacement_index = replacement_index + 1

Usage: replacer.py ExampleInput.txt alpha beta gamma

Update

It's possible to modify the program to accept the string you search for as the 1st param:

replacer.py "var_" ExampleInput.txt alpha beta gamma

The modified python script looks like this:

import sys
import re
import fileinput

if len(sys.argv) < 4:
  exit("Usage: " + sys.argv[0] + " <pattern> <filename> <replacements>")

search = "\\b" + sys.argv[1] + "\\b"
input_file = sys.argv[2]
replacements = sys.argv[3:]
num_of_replacements = len(replacements)
replacement_index = 0
searcher = re.compile(search)

for line in fileinput.input(input_file, inplace=True, backup='.bak'):
  match = searcher.match(line)
  if match is None:
    print(line.rstrip())
  else:
    print(re.sub(search, line.rstrip(), replacements[replacement_index]))
    replacement_index = replacement_index + 1

Note: this script still has a few limitations:

it expects that the string you search for occurs only once each line.

it replaces the searched string only if it's a distinct word

you can accidentally incorporate any python regex syntax into the search param


问:
Shiny R filter %in% on data.table vs data.frame
my code has been working with data.frames, but now that I converted to data.table I have trouble with filtering the data.table by the user's input. filter_expr is set TRUE and at the end only rows that are TRUE are supposed to be in the final table version. I think the %in% operatormight be the problem, but I could not find an answer yet.

dput of my date:

```<code>structure(list(fruit = c("Apple", "Apple", "Apple", "Apple",
"Apple", "Apple", "Banana", "Banana", "Banana", "Banana", "Banana",
"Banana", "Citrus", "Citrus", "Citrus", "Citrus", "Citrus", "Citrus"
), Month = c(1L, 9L, 12L, 1L, 9L, 12L, 1L, 9L, 12L, 1L, 9L, 12L,
1L, 9L, 12L, 1L, 9L, 12L), Fertilizer = c("A", "A", "A", "B",
"B", "B", "A", "A", "A", "B", "B", "B", "A", "A", "A", "B", "B",
"B"), red = c("+", "+", "+", "+", "+", "+", "+", "+", "+", "+",
"+", "+", "+", "+", "+", "+", "+", "+"), green = c("+", "-",
"+", "-", "+", "-", "+", "-", "+", "-", "+", "-", "+", "-", "+",
"-", "+", "-"), yellow = c("+", "+", "-", "+", "+", "-", "+",
"+", "-", "+", "+", "-", "+", "+", "-", "+", "+", "-")), .Names = c("fruit",
"Month", "Fertilizer", "red", "green", "yellow"), row.names = c(NA,
-18L), class = c("data.table", "data.frame"), .internal.selfref = <pointer: 0x10280e978>)
</code>```

I used this file for testing.

```<code>library(shiny)
library(data.table)
library(DT)

ui <- (fluidPage(tagList(
  navbarPage(
    "My Application",
    tabPanel("Pregated Data",
             sidebarLayout(
               sidebarPanel(
                 conditionalPanel(condition = "input.tabselected == 1",
                                  fileInput(inputId = 'file_input', 'Choose CSV File',
                                            accept=c('text/csv',
                                                     'text/comma-separated-values,text/plain',
                                                     '.csv')),
                                  #progressbar
                                  tags$hr(),
                                  checkboxInput('header', 'Header', TRUE),
                                  radioButtons('sep', 'Separator',
                                               c(Comma=',',
                                                 Semicolon=';',
                                                 Tab='\t'),
                                               ',')

                 ),
                 conditionalPanel(condition = "input.tabselected == 2",
                                  uiOutput("file_input"))
               ),
               mainPanel(
                 tabsetPanel(
                   tabPanel("Data", value = 1, dataTableOutput('table1')),
                   tabPanel("checkboxes",value = 2,conditionalPanel(condition = "input.choice ==1"),
                            dataTableOutput('fruit_table')),
                            id = "tabselected"
                 )
               )
             )
    )
  )
)))

server <- function(input, output) {

  fileData <- reactive(
    if (is.null(input$file_input)){
      return()
    }else{
      tdata <- fread(input$file_input$datapath, header=input$header, sep=input$sep)
      return(tdata)
    }
  )

  output$table1 <- renderDataTable({
    if(is.null(fileData())){
      return(NULL)
    }else{
      datatable( fileData(), options = list(pageLength = 25))
    }
  })

  output$file_input <- renderUI ({
    if(is.null(fileData())){
      return()
    }else{
      tagList(
        checkboxGroupInput(inputId = "fruit",
                           label = "fruit",
                           choices = c(unique(fileData()[,get("fruit")])),
                           selected = fileData()[1, 1, with = FALSE]),
        radioButtons(inputId = "month",
                     label = "Month",
                     choices =unique(fileData()[,get("Month")]),
                     selected = fileData()[1,Month],
                     inline = TRUE),
        checkboxGroupInput(inputId = "tube",
                           label = "Fertilizer",
                           choices = unique(fileData()[,get("Fertilizer")]),
                           selected = fileData()[1, 3, with = F]),
        ###checkboxes from Loop:
        lapply(1:(length(fileData())-3), function(i) {
          checkboxGroupInput(inputId = paste0("color",i),
                             label = colnames(fileData()[,i+3, with = FALSE]),
                             choices = c(unique(fileData()[,get(colnames(fileData()[,i+3, with = FALSE]))])),
                             inline = TRUE,
                             selected = fileData()[1, i+3, with = FALSE])
        }
      )
      )
    }})

  ###returns table form boolean-Gates csv file rigth after upload
  output$fruit_table <- renderDataTable({
    if(is.null(fileData())){
      return(NULL)
    }else{

      validate(
        need(input$fruit, 'Check at least one fruit!'),
        need(input$tube, 'Check at least one Fertilizer!'),
        need(!is.null(input$color1) | !is.null(input$color2) | !is.null(input$color3),
             "Check at least one Color!")
      )

      filter_expr <- TRUE

      if (!(is.null(input$fruit))) {
        filter_expr <- filter_expr & fileData()[,fruit] %in% input$fruit
      }
      #

      if (!(is.null(input$month))) {
        filter_expr <- filter_expr & fileData()[,Month]  == as.integer(input$month)
      }

      if (!(is.null(input$tube))) {
        filter_expr <- filter_expr & fileData()[,Fertilizer] %in% input$tube
      }

      #colname <- c(colnames(fileData()[,4:length(fileData())]))
      #print(colname)
      lapply(1:(length(fileData())-3), function(i) {
        if (!(is.null(paste0("input$color",i)))) {
          filter_expr <- filter_expr & fileData()[,colnames(fileData()[,3+i,with = FALSE])] %in% paste0("input$color",i)
          print(fileData()[,colnames(fileData()[,3+1,with = FALSE])]%in% paste0("input$color",i))
          #print(fileData()[,colname[i],with = FALSE])
        }

      })

      datatable(fileData()[filter_expr,],options = list(pageLength = 25))

    }
  })
}
shinyApp(ui = ui, server = server)
</code>```

Thanks for any help!

答:
Assuming this would apply to your example, here a toy example. The difference is naming the variable vs inserting the col id.

```<code>iris[,5] %in% "setosa" # outputs a vector
iris2 = iris
setDT(iris2)

iris2[,5] %in% "setosa" # outputs single T/F
iris2[,Species] %in% "setosa" # outputs a vector
</code>```

Not sure if this is what you need..

Body:
my code has been working with data.frames, but now that I converted to data.table I have trouble with filtering the data.table by the user's input. filter_expr is set TRUE and at the end only rows that are TRUE are supposed to be in the final table version. I think the %in% operatormight be the problem, but I could not find an answer yet.

dput of my date:

structure(list(fruit = c("Apple", "Apple", "Apple", "Apple",
"Apple", "Apple", "Banana", "Banana", "Banana", "Banana", "Banana",
"Banana", "Citrus", "Citrus", "Citrus", "Citrus", "Citrus", "Citrus"
), Month = c(1L, 9L, 12L, 1L, 9L, 12L, 1L, 9L, 12L, 1L, 9L, 12L,
1L, 9L, 12L, 1L, 9L, 12L), Fertilizer = c("A", "A", "A", "B",
"B", "B", "A", "A", "A", "B", "B", "B", "A", "A", "A", "B", "B",
"B"), red = c("+", "+", "+", "+", "+", "+", "+", "+", "+", "+",
"+", "+", "+", "+", "+", "+", "+", "+"), green = c("+", "-",
"+", "-", "+", "-", "+", "-", "+", "-", "+", "-", "+", "-", "+",
"-", "+", "-"), yellow = c("+", "+", "-", "+", "+", "-", "+",
"+", "-", "+", "+", "-", "+", "+", "-", "+", "+", "-")), .Names = c("fruit",
"Month", "Fertilizer", "red", "green", "yellow"), row.names = c(NA,
-18L), class = c("data.table", "data.frame"), .internal.selfref = <pointer: 0x10280e978>)

I used this file for testing.

library(shiny)
library(data.table)
library(DT)

ui <- (fluidPage(tagList(
  navbarPage(
    "My Application",
    tabPanel("Pregated Data",
             sidebarLayout(
               sidebarPanel(
                 conditionalPanel(condition = "input.tabselected == 1",
                                  fileInput(inputId = 'file_input', 'Choose CSV File',
                                            accept=c('text/csv',
                                                     'text/comma-separated-values,text/plain',
                                                     '.csv')),
                                  #progressbar
                                  tags$hr(),
                                  checkboxInput('header', 'Header', TRUE),
                                  radioButtons('sep', 'Separator',
                                               c(Comma=',',
                                                 Semicolon=';',
                                                 Tab='\t'),
                                               ',')

                 ),
                 conditionalPanel(condition = "input.tabselected == 2",
                                  uiOutput("file_input"))
               ),
               mainPanel(
                 tabsetPanel(
                   tabPanel("Data", value = 1, dataTableOutput('table1')),
                   tabPanel("checkboxes",value = 2,conditionalPanel(condition = "input.choice ==1"),
                            dataTableOutput('fruit_table')),
                            id = "tabselected"
                 )
               )
             )
    )
  )
)))

server <- function(input, output) {

  fileData <- reactive(
    if (is.null(input$file_input)){
      return()
    }else{
      tdata <- fread(input$file_input$datapath, header=input$header, sep=input$sep)
      return(tdata)
    }
  )

  output$table1 <- renderDataTable({
    if(is.null(fileData())){
      return(NULL)
    }else{
      datatable( fileData(), options = list(pageLength = 25))
    }
  })

  output$file_input <- renderUI ({
    if(is.null(fileData())){
      return()
    }else{
      tagList(
        checkboxGroupInput(inputId = "fruit",
                           label = "fruit",
                           choices = c(unique(fileData()[,get("fruit")])),
                           selected = fileData()[1, 1, with = FALSE]),
        radioButtons(inputId = "month",
                     label = "Month",
                     choices =unique(fileData()[,get("Month")]),
                     selected = fileData()[1,Month],
                     inline = TRUE),
        checkboxGroupInput(inputId = "tube",
                           label = "Fertilizer",
                           choices = unique(fileData()[,get("Fertilizer")]),
                           selected = fileData()[1, 3, with = F]),
        ###checkboxes from Loop:
        lapply(1:(length(fileData())-3), function(i) {
          checkboxGroupInput(inputId = paste0("color",i),
                             label = colnames(fileData()[,i+3, with = FALSE]),
                             choices = c(unique(fileData()[,get(colnames(fileData()[,i+3, with = FALSE]))])),
                             inline = TRUE,
                             selected = fileData()[1, i+3, with = FALSE])
        }
      )
      )
    }})

  ###returns table form boolean-Gates csv file rigth after upload
  output$fruit_table <- renderDataTable({
    if(is.null(fileData())){
      return(NULL)
    }else{

      validate(
        need(input$fruit, 'Check at least one fruit!'),
        need(input$tube, 'Check at least one Fertilizer!'),
        need(!is.null(input$color1) | !is.null(input$color2) | !is.null(input$color3),
             "Check at least one Color!")
      )

      filter_expr <- TRUE

      if (!(is.null(input$fruit))) {
        filter_expr <- filter_expr & fileData()[,fruit] %in% input$fruit
      }
      #

      if (!(is.null(input$month))) {
        filter_expr <- filter_expr & fileData()[,Month]  == as.integer(input$month)
      }

      if (!(is.null(input$tube))) {
        filter_expr <- filter_expr & fileData()[,Fertilizer] %in% input$tube
      }

      #colname <- c(colnames(fileData()[,4:length(fileData())]))
      #print(colname)
      lapply(1:(length(fileData())-3), function(i) {
        if (!(is.null(paste0("input$color",i)))) {
          filter_expr <- filter_expr & fileData()[,colnames(fileData()[,3+i,with = FALSE])] %in% paste0("input$color",i)
          print(fileData()[,colnames(fileData()[,3+1,with = FALSE])]%in% paste0("input$color",i))
          #print(fileData()[,colname[i],with = FALSE])
        }

      })

      datatable(fileData()[filter_expr,],options = list(pageLength = 25))

    }
  })
}
shinyApp(ui = ui, server = server)

Thanks for any help!

Body:
Assuming this would apply to your example, here a toy example. The difference is naming the variable vs inserting the col id.

iris[,5] %in% "setosa" # outputs a vector
iris2 = iris
setDT(iris2)

iris2[,5] %in% "setosa" # outputs single T/F
iris2[,Species] %in% "setosa" # outputs a vector

Not sure if this is what you need..


问:
Action Mailer production.rb not working when deployed via Sendgrid and Heroku
I'm currently in the process of trying to send Account Confirmation emails to any new user that creates an account on my Rails app.

I've successfully deployed locally via development.rb, but for some reason I get an error message every time "We're sorry, but something went wrong. If you are the application owner check the logs for more information". I've reviewed several resources both here on Stack Overflow as well as Heroku, Youtube and have not been able to find a solution.

Here is my code in environments/production.rb:

```<code># Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = true
config.action_mailer.perform_deliveries = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: "smtp.sendgrid.net",
port: 587,
domain: ENV["SENDGRID_DOMAIN"],
authentication: "plain",
enable_starttls_auto: true,
user_name: ENV["SENDGRID_USERNAME"],
password: ENV["SENDGRID_PASSWORD"]
}

config.action_mailer.default_url_options = {:host => "<myherokuappname>.herokuapp.com/"}

config.action_mailer.perform_caching = false
</code>```

Again just to confirm, I am able to deploy emails locally, just not at the production level. Any tips would be greatly appreciated.

答:
I recently integrated SendGrid into my Heroku app too. My production.rb settings are as follows:

```<code>  config.action_mailer.raise_delivery_errors = true
  config.action_mailer.default_url_options = { host: '<myherokuappname>.herokuapp.com' }
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    :user_name => ENV['SENDGRID_USERNAME'],
    :password => ENV['SENDGRID_PASSWORD'],
    :domain => '<myherokuappname>.herokuapp.com',
    :address => 'smtp.sendgrid.net',
    :port => 587,
    :authentication => :plain,
    :enable_starttls_auto => true
  }
</code>```

I tested this out just a few minutes ago and it sends fine.

Body:
I'm currently in the process of trying to send Account Confirmation emails to any new user that creates an account on my Rails app.

I've successfully deployed locally via development.rb, but for some reason I get an error message every time "We're sorry, but something went wrong. If you are the application owner check the logs for more information". I've reviewed several resources both here on Stack Overflow as well as Heroku, Youtube and have not been able to find a solution.

Here is my code in environments/production.rb:

# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = true
config.action_mailer.perform_deliveries = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: "smtp.sendgrid.net",
port: 587,
domain: ENV["SENDGRID_DOMAIN"],
authentication: "plain",
enable_starttls_auto: true,
user_name: ENV["SENDGRID_USERNAME"],
password: ENV["SENDGRID_PASSWORD"]
}

config.action_mailer.default_url_options = {:host => "<myherokuappname>.herokuapp.com/"}

config.action_mailer.perform_caching = false

Again just to confirm, I am able to deploy emails locally, just not at the production level. Any tips would be greatly appreciated.

Body:
I recently integrated SendGrid into my Heroku app too. My production.rb settings are as follows:

  config.action_mailer.raise_delivery_errors = true
  config.action_mailer.default_url_options = { host: '<myherokuappname>.herokuapp.com' }
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    :user_name => ENV['SENDGRID_USERNAME'],
    :password => ENV['SENDGRID_PASSWORD'],
    :domain => '<myherokuappname>.herokuapp.com',
    :address => 'smtp.sendgrid.net',
    :port => 587,
    :authentication => :plain,
    :enable_starttls_auto => true
  }

I tested this out just a few minutes ago and it sends fine.


问:
Display success message after downloading CSV
I have developed a small Wordpress Plugin to download as a CSV file users' data from the database.

Everything works fine, although I am having issues figuring out how to display a success message.

Below the code of the method that takes care of the data export:

```<code>/*
* Export CSV File
*/
public function export_CSV()
{

    if ($this->users) {

        $fileName =  "Export_users_" . date("Y-m-d_H:i:s", time());
        $fileName = $fileName.".csv";
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header('Content-Description: File Transfer');
        header('Content-Encoding: UTF-8');
        header("Content-type: application/csv;charset=UTF-8");
        header("Content-Disposition: attachment; filename={$fileName}");
        header("Expires: 0");
        header("Pragma: public");
        echo "\xEF\xBB\xBF"; // UTF-8 BOM
        $fh = @fopen( 'php://output', 'w' );
        $headerDisplayed = false;

        foreach ($this->users as $user) {

            if($user) {

                $user_meta = get_user_meta($user->data->ID);

                //Push user meta into $user array

                foreach($user_meta as $key => $var)
                {
                    $user->data->$key = trim($var[0]);
                }

                //convert object in array;

                $usersArray = (array)$user->data;

                // Add a header row if it hasn't been added yet

                if ( $headerDisplayed == false ) {

                    // Use the keys from $directory as the titles

                    fputcsv($fh, array_keys($usersArray));

                    $headerDisplayed = true;
                }

                // Put the data into the stream

                fputcsv($fh,$usersArray);

            }//end if

        }//end foreach

        // Close the file

        fclose($fh);

        // Users exported successfully

        $this->response = "Users exported successfully!";

        // Make sure nothing else is sent

        exit;

    } else {

        // No results found

        $this->response = "Sorry, no results found!";

    }

}
</code>```

I have to use exit otherwise the CSV file will contain all the html of the page. Is there a way to run a javascript file to update the message in the front end?

Thanks in advance!

答:
I came up with a solution by passing the response message as a variable in the header.

```<code>$this->response = "Users downloaded Successfully!";
header("Location:?page=export-users&response=".$this->response);
</code>```

and then retrieve it like so:

```<code><?php if(isset($_GET['response'])){ ?>
        <div class="updated notice">
            <p><?php echo __( $_GET['response']);?></p>
        </div><!--error notice-->
    <?php } ?>
</code>```

Body:
I have developed a small Wordpress Plugin to download as a CSV file users' data from the database.

Everything works fine, although I am having issues figuring out how to display a success message.

Below the code of the method that takes care of the data export:

/*
* Export CSV File
*/
public function export_CSV()
{

    if ($this->users) {

        $fileName =  "Export_users_" . date("Y-m-d_H:i:s", time());
        $fileName = $fileName.".csv";
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header('Content-Description: File Transfer');
        header('Content-Encoding: UTF-8');
        header("Content-type: application/csv;charset=UTF-8");
        header("Content-Disposition: attachment; filename={$fileName}");
        header("Expires: 0");
        header("Pragma: public");
        echo "\xEF\xBB\xBF"; // UTF-8 BOM
        $fh = @fopen( 'php://output', 'w' );
        $headerDisplayed = false;

        foreach ($this->users as $user) {

            if($user) {

                $user_meta = get_user_meta($user->data->ID);

                //Push user meta into $user array

                foreach($user_meta as $key => $var)
                {
                    $user->data->$key = trim($var[0]);
                }

                //convert object in array;

                $usersArray = (array)$user->data;

                // Add a header row if it hasn't been added yet

                if ( $headerDisplayed == false ) {

                    // Use the keys from $directory as the titles

                    fputcsv($fh, array_keys($usersArray));

                    $headerDisplayed = true;
                }

                // Put the data into the stream

                fputcsv($fh,$usersArray);

            }//end if

        }//end foreach

        // Close the file

        fclose($fh);

        // Users exported successfully

        $this->response = "Users exported successfully!";

        // Make sure nothing else is sent

        exit;

    } else {

        // No results found

        $this->response = "Sorry, no results found!";

    }

}

I have to use exit otherwise the CSV file will contain all the html of the page. Is there a way to run a javascript file to update the message in the front end?

Thanks in advance!

Body:
I came up with a solution by passing the response message as a variable in the header.

$this->response = "Users downloaded Successfully!";
header("Location:?page=export-users&response=".$this->response);

and then retrieve it like so:

<?php if(isset($_GET['response'])){ ?>
        <div class="updated notice">
            <p><?php echo __( $_GET['response']);?></p>
        </div><!--error notice-->
    <?php } ?>


问:
AJAX SEO Friendly and History Navigation
i'm working on some website that has a section with pure AJAX, but i want it to have SEO Friendly URL's.

I've been googling and saw that i can make all my links "Return false", that way i can have my url's working awesome with search engines... but i have a problem, i want it to have history too, but i dont know how to make it... something like this:

```<code><a href="contacts.html">Contacts</a>
</code>```

And onclick = return false; but i need it to have

```<code><a href="#contacts">Contacts</a>
</code>```

so the history and back button can work...

I was thinking if i could just use the History type (using #) but i dont know how friendly is that type of URL.

Any tip or Idea?!

Thank you!!

答:
HTML5 introduced some ways of controlling the history of the browser. See the MDC Doc on "Manipulating the browser history". Using history.pushState() you can both have the history cake and eat the ajax cake. This would only work in the latest browsers as with much of the new and fancy HTML5 features.

Also, using an click event handler that calls event.preventDefault() is preferred to using return false.

Body:
i'm working on some website that has a section with pure AJAX, but i want it to have SEO Friendly URL's.

I've been googling and saw that i can make all my links "Return false", that way i can have my url's working awesome with search engines... but i have a problem, i want it to have history too, but i dont know how to make it... something like this:

Contacts

And onclick = return false; but i need it to have

Contacts

so the history and back button can work...

I was thinking if i could just use the History type (using #) but i dont know how friendly is that type of URL.

Any tip or Idea?!

Thank you!!


问:
Connection timed out: connect JAVA and Wampserver
I need help about database connection time error, I'm using wamp server
I can access PHPMyAdmin throw this link "192.168.1.88/phpmyadmin", it works fine but I get a timeout error in NetBeans, and I tried ping between the PC and it works fine

Here is the stack trace:

```<code>  java.net.SocketException
  MESSAGE: java.net.ConnectException: Connection timed out: connect

  STACKTRACE:

  java.net.SocketException: java.net.ConnectException: Connection timed out: connect
  at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:156)
  at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:276)
  at com.mysql.jdbc.Connection.createNewIO(Connection.java:2666)
  at com.mysql.jdbc.Connection.<init>(Connection.java:1531)
  at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266)
  at java.sql.DriverManager.getConnection(DriverManager.java:664)
  at java.sql.DriverManager.getConnection(DriverManager.java:247)
  at assurancebensaidv2.jdbcManager.<init>(jdbcManager.java:38)
  at assurancebensaidv2.Login.<init>(Login.java:37)
  at assurancebensaidv2.Login$8.run(Login.java:761)
  at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
  at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
  at java.awt.EventQueue.access$500(EventQueue.java:97)
  at java.awt.EventQueue$3.run(EventQueue.java:709)
  at java.awt.EventQueue$3.run(EventQueue.java:703)
  at java.security.AccessController.doPrivileged(Native Method)
  at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
  at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
  at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
  at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
  at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
  at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
  at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
  at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
</code>```

Here is a snippet from my code:

```<code>public class jdbcManager {

    public HashMap<String, String> item = new HashMap<>();
    public static Connection conn;
    private Statement s;
    private ResultSet rs;

    public jdbcManager() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException ex) {
            javax.swing.JOptionPane.showMessageDialog(null, "Erreur Driver  ", "Etat de L'opération", javax.swing.JOptionPane.INFORMATION_MESSAGE);
            Logger.getLogger(jdbcManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        //===================================================================
        try {
            conn = DriverManager.getConnection("jdbc:mysql://192.168.1.88:3306/agenceassurance", "root", "12345");
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
          //  javax.swing.JOptionPane.showMessageDialog(null, "Erreur Connection Base de donnée", "Etat de L'operation", javax.swing.JOptionPane.INFORMATION_MESSAGE);
         }
    }}
</code>```

答:
As you are trying to connect to MySQL from a remote machine you need to create an account on MYSQL Server that is allowed to connect from a remote ip.

By default and for obvious security reasons the root account is setup to only be allowed to connect to MySQL Server from the machine running MySQL Server.

Dont change root to be allowed to connect remotely Create a new User account that is only allowed to see the single database you want to connect to

Body:
I need help about database connection time error, I'm using wamp server
I can access PHPMyAdmin throw this link "192.168.1.88/phpmyadmin", it works fine but I get a timeout error in NetBeans, and I tried ping between the PC and it works fine

Here is the stack trace:

  java.net.SocketException
  MESSAGE: java.net.ConnectException: Connection timed out: connect

  STACKTRACE:

  java.net.SocketException: java.net.ConnectException: Connection timed out: connect
  at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:156)
  at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:276)
  at com.mysql.jdbc.Connection.createNewIO(Connection.java:2666)
  at com.mysql.jdbc.Connection.<init>(Connection.java:1531)
  at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266)
  at java.sql.DriverManager.getConnection(DriverManager.java:664)
  at java.sql.DriverManager.getConnection(DriverManager.java:247)
  at assurancebensaidv2.jdbcManager.<init>(jdbcManager.java:38)
  at assurancebensaidv2.Login.<init>(Login.java:37)
  at assurancebensaidv2.Login$8.run(Login.java:761)
  at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
  at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
  at java.awt.EventQueue.access$500(EventQueue.java:97)
  at java.awt.EventQueue$3.run(EventQueue.java:709)
  at java.awt.EventQueue$3.run(EventQueue.java:703)
  at java.security.AccessController.doPrivileged(Native Method)
  at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
  at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
  at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
  at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
  at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
  at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
  at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
  at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

Here is a snippet from my code:

public class jdbcManager {

    public HashMap<String, String> item = new HashMap<>();
    public static Connection conn;
    private Statement s;
    private ResultSet rs;

    public jdbcManager() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException ex) {
            javax.swing.JOptionPane.showMessageDialog(null, "Erreur Driver  ", "Etat de L'opération", javax.swing.JOptionPane.INFORMATION_MESSAGE);
            Logger.getLogger(jdbcManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        //===================================================================
        try {
            conn = DriverManager.getConnection("jdbc:mysql://192.168.1.88:3306/agenceassurance", "root", "12345");
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
          //  javax.swing.JOptionPane.showMessageDialog(null, "Erreur Connection Base de donnée", "Etat de L'operation", javax.swing.JOptionPane.INFORMATION_MESSAGE);
         }
    }}


问:
SAXParseException error in XML Parsing
Using web service call ,I got the following response from server. Now i need to parse this response, Extract all field values and store it in String values

```<code><?xml version="1.0" encoding="utf-8"?>
<ecomexpress-objects version="1.0"><object pk="1" model="awb">
    <field type="BigIntegerField" name="awb_number">102019265</field>
    <field type="CharField" name="orderid">8008444</field>
    <field type="FloatField" name="actual_weight">2</field>
    <field type="CharField" name="origin">DELHI-DSW</field>
    <field type="CharField" name="destination">Mumbai - BOW</field>
    <field type="CharField" name="current_location_name">Mumbai - BOW</field>
    <field type="CharField" name="current_location_code">BOW</field>
    <field type="CharField" name="customer">Ecom Express Private Limited - 32012</field>
    <field type="CharField" name="consignee">BEECHAND VERMA</field>
    <field type="CharField" name="pickupdate">22-Jan-2014</field>
    <field type="CharField" name="status">Undelivered</field>
    <field type="CharField" name="tracking_status">Undelivered</field>
    <field type="CharField" name="reason_code">221 - Consignee Refused To Accept</field>
    <field type="CharField" name="reason_code_description">Consignee Refused To Accept</field>
    <field type="CharField" name="reason_code_number">221 </field>
    <field type="CharField" name="receiver"></field>
    <field type="CharField" name="expected_date" >15-Feb-2014</field>
    <field type="CharField" name="last_update_date" ></field>
    <field type="CharField" name="delivery_date" ></field>
    <field type="CharField" name="ref_awb" >703063993</field>
    <field type="CharField" name="rts_shipment" >0</field>
    <field type="CharField" name="system_delivery_update" ></field>
    <field type="CharField" name="rts_system_delivery_status" Undelivered</field>
    <field type="CharField" name="rts_reason_code_number">777</field>
    <field type="CharField" name="rts_last_update">22 Jan, 2014, 12:44 </field>
    <field type="CharField" name="pincode" >400037</field>
    <field type="CharField" name="city" >MUMBAI</field>
    <field type="CharField" name="state" >Maharashtra</field>
    <field name="scans">
</ecomexpress-objects>
</code>```

If i try the following code to parse

```<code>    String xml=result.toString();
    try{
       DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputSource is;
        is = new InputSource(new StringReader(xml));
        Document doc = db.parse(is);
        NodeList nodelist = doc.getChildNodes();
       }
      catch (SAXException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
</code>```

I get the following error.

```<code>    org.xml.sax.SAXParseException: expected: /field read: ecomexpress-objects (position:END_TAG </ecomexpress-objects>@1:1917 in java.io.StringReader@39978dff)
</code>```

I need to store all field values in respective string variables

答:
There are several errors in your xml :

No closing tag object .

Undelivered appears in attribute at : <field type="CharField"

name="rts_system_delivery_status" Undelivered</field>

 should be closed like <field name="scans"/>

As long as xml is invalid, you keep getting exceptions.

Title: SAXParseException error in XML Parsing

Body:
Using web service call ,I got the following response from server. Now i need to parse this response, Extract all field values and store it in String values

<?xml version="1.0" encoding="utf-8"?>
<ecomexpress-objects version="1.0"><object pk="1" model="awb">
    <field type="BigIntegerField" name="awb_number">102019265</field>
    <field type="CharField" name="orderid">8008444</field>
    <field type="FloatField" name="actual_weight">2</field>
    <field type="CharField" name="origin">DELHI-DSW</field>
    <field type="CharField" name="destination">Mumbai - BOW</field>
    <field type="CharField" name="current_location_name">Mumbai - BOW</field>
    <field type="CharField" name="current_location_code">BOW</field>
    <field type="CharField" name="customer">Ecom Express Private Limited - 32012</field>
    <field type="CharField" name="consignee">BEECHAND VERMA</field>
    <field type="CharField" name="pickupdate">22-Jan-2014</field>
    <field type="CharField" name="status">Undelivered</field>
    <field type="CharField" name="tracking_status">Undelivered</field>
    <field type="CharField" name="reason_code">221 - Consignee Refused To Accept</field>
    <field type="CharField" name="reason_code_description">Consignee Refused To Accept</field>
    <field type="CharField" name="reason_code_number">221 </field>
    <field type="CharField" name="receiver"></field>
    <field type="CharField" name="expected_date" >15-Feb-2014</field>
    <field type="CharField" name="last_update_date" ></field>
    <field type="CharField" name="delivery_date" ></field>
    <field type="CharField" name="ref_awb" >703063993</field>
    <field type="CharField" name="rts_shipment" >0</field>
    <field type="CharField" name="system_delivery_update" ></field>
    <field type="CharField" name="rts_system_delivery_status" Undelivered</field>
    <field type="CharField" name="rts_reason_code_number">777</field>
    <field type="CharField" name="rts_last_update">22 Jan, 2014, 12:44 </field>
    <field type="CharField" name="pincode" >400037</field>
    <field type="CharField" name="city" >MUMBAI</field>
    <field type="CharField" name="state" >Maharashtra</field>
    <field name="scans">
</ecomexpress-objects>

If i try the following code to parse

    String xml=result.toString();
    try{
       DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputSource is;
        is = new InputSource(new StringReader(xml));
        Document doc = db.parse(is);
        NodeList nodelist = doc.getChildNodes();
       }
      catch (SAXException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

I get the following error.

    org.xml.sax.SAXParseException: expected: /field read: ecomexpress-objects (position:END_TAG </ecomexpress-objects>@1:1917 in java.io.StringReader@39978dff)

I need to store all field values in respective string variables


答:
Use this:</p>

```<code>let sum, billsPOJO;

billsPOJO = YOURJSON.bills;

sum = 0;

for (let i = 0; billsPOJO.length; i++) {
 sum += billsPOJO[i].pendingAmount;
}
</code>```

Title: How to sum value of two json object key?

Body:
Use this:

let sum, billsPOJO;

billsPOJO = YOURJSON.bills;

sum = 0;

for (let i = 0; billsPOJO.length; i++) {
 sum += billsPOJO[i].pendingAmount;
}


问:
ModelAttribute in abstract class with value from subclass
I want to have a common method annoted @ModelAttribute in an abstract class but with value from subclasses. The final goal is to retrieve the value of a variable in JSP. The value is different in each subclass controller but I don't want to duplicate the @ModelAttribute method.

The abstract class

```<code>public abstract class BaseController {

    protected String PATH = "";

    public void setPATH(String inPath) {
        PATH = inPath;
    }

    @PostConstruct
    private void init() {
        setPATH(PATH);
    }

    @ModelAttribute("controllerPath")
    public String getControllerPath() {
        return PATH;
    }
}
</code>```

The sublass, a controller

```<code>@Controller
@RequestMapping(OneController.PATH)
public class OneController extends BaseController {

    protected static final String PATH = "/one";

    public OneController() {
        setPATH(PATH);
    }
}
</code>```

JSP

```<code>Value for controllerPath: ${controllerPath}
</code>```

The value of ${controllerPath} is always empty with Spring version 4.0.9.RELEASE but works (the value is set with the value from the subclass controller) with Spring version 3.1.2.RELEASE.
How do I update my code to work with Spring 4 ?

答:
You need to declare abstract the ModelAttribute method in your abstract controller.

```<code>public abstract class BaseController {

    protected String PATH = "";

    public void setPATH(String inPath) {
        PATH = inPath;
    }

    @PostConstruct
    private void init() {
        setPATH(PATH);
    }

    @ModelAttribute("controllerPath")
    public abstract String getControllerPath();
}
</code>```

And on each controller which extends the abstract controller:

```<code>@Controller
@RequestMapping(OneController.PATH)
public class OneController extends BaseController {

    protected static final String PATH = "/one";

    @Override
    public String getControllerPath(){
        return PATH;
    }
}
</code>```

UPDATE:

If you dont want to repeat the new method in all Controllers:

In your abstract controller

```<code>@ModelAttribute("controllerPath")
 public String getControllerPath(){
     return "";
 }
</code>```

Where you want to override the value. Add Override annotation

```<code>@Override
public String getControllerPath(){
    return PATH;
}
</code>```

Body:
I want to have a common method annoted @ModelAttribute in an abstract class but with value from subclasses. The final goal is to retrieve the value of a variable in JSP. The value is different in each subclass controller but I don't want to duplicate the @ModelAttribute method.

The abstract class

public abstract class BaseController {

    protected String PATH = "";

    public void setPATH(String inPath) {
        PATH = inPath;
    }

    @PostConstruct
    private void init() {
        setPATH(PATH);
    }

    @ModelAttribute("controllerPath")
    public String getControllerPath() {
        return PATH;
    }
}

The sublass, a controller

@Controller
@RequestMapping(OneController.PATH)
public class OneController extends BaseController {

    protected static final String PATH = "/one";

    public OneController() {
        setPATH(PATH);
    }
}

JSP

Value for controllerPath: ${controllerPath}

The value of ${controllerPath} is always empty with Spring version 4.0.9.RELEASE but works (the value is set with the value from the subclass controller) with Spring version 3.1.2.RELEASE.
How do I update my code to work with Spring 4 ?

Body:
You need to declare abstract the ModelAttribute method in your abstract controller.

public abstract class BaseController {

    protected String PATH = "";

    public void setPATH(String inPath) {
        PATH = inPath;
    }

    @PostConstruct
    private void init() {
        setPATH(PATH);
    }

    @ModelAttribute("controllerPath")
    public abstract String getControllerPath();
}

And on each controller which extends the abstract controller:

@Controller
@RequestMapping(OneController.PATH)
public class OneController extends BaseController {

    protected static final String PATH = "/one";

    @Override
    public String getControllerPath(){
        return PATH;
    }
}

UPDATE:

If you dont want to repeat the new method in all Controllers:

In your abstract controller

@ModelAttribute("controllerPath")
 public String getControllerPath(){
     return "";
 }

Where you want to override the value. Add Override annotation

@Override
public String getControllerPath(){
    return PATH;
}


问:
CSS a:hover keep original color
Is it possible to keep the color on a link with a class while other links do change.

For example I have a theme but i want it to support different colors set by the user.

Most links change color on :hover but some must stay the same color.

#red is generated by the theme. I want to 'inherit' the a.someclass:link color in the a.someclass:hover

example:

```<code>a:link
{
  color: #red;
}
a:hover {
  color: #black;
}
</code>```

The above part is generated which I cannot alter.

As suggested in answers and comments below I need to build this with jQuery

sure I can copy #red to the a.someclass:hover {} but then i have to hardcode the color and since the user should be able to change the color that is not an option.

I need something to overide the a:hover { color } if the class is someclass

答:
You can make use of currentColor

```<code>a.no-color-change:hover {
  color: currentColor;
}
</code>```

Title: CSS a:hover keep original color

Body:
Is it possible to keep the color on a link with a class while other links do change.

For example I have a theme but i want it to support different colors set by the user.

Most links change color on :hover but some must stay the same color.

#red is generated by the theme. I want to 'inherit' the a.someclass:link color in the a.someclass:hover

example:

a:link
{
  color: #red;
}
a:hover {
  color: #black;
}

The above part is generated which I cannot alter.

As suggested in answers and comments below I need to build this with jQuery

sure I can copy #red to the a.someclass:hover {} but then i have to hardcode the color and since the user should be able to change the color that is not an option.

I need something to overide the a:hover { color } if the class is someclass

Body:
You can make use of currentColor

a.no-color-change:hover {
  color: currentColor;
}


问:
Urlencode to list in python
```<code>   finalKeywords = []
   #after populating finalKeywords
   query = {
       "apiKey" : self.apikey,
        "country" : country,
        "currency" : currency,
        "kw" : finalKeywords,
        "t" : int(time.time())
    }
    uri = urllib.urlencode(query, True)
    print uri
</code>```

After decoding uri I get

```<code>country=&apiKey=5f0092f1777c3a5ed0de&kw=iphone&kw=android&t=1496924489&currency=usd
</code>```

While my expected output is

```<code>country=&apiKey=5f0092f1777c3a5ed0de&kw[0]=iphone&kw[1]=android&t=1496924489&currency=usd
</code>```

What to do..? I have been looking for solutions but unable to get.

答:
Like this?

```<code>query = {
       "apiKey" : self.apikey,
        "country" : country,
        "currency" : currency,
        "kw[]" : finalKeywords,
        "t" : int(time.time())
    }
</code>```

If you need to have the positional values in there as well for some reason, this is one way to do it:

```<code>query = {
        "apiKey" : self.apikey,
        "country" : country,
        "currency" : currency,
        "t" : int(time.time())
    }
for p,q in enumerate(finalKeywords):
   query["kw[{pos}]".format(pos=p)] = q
</code>```

Title: Urlencode to list in python

Body:
   finalKeywords = []
   #after populating finalKeywords
   query = {
       "apiKey" : self.apikey,
        "country" : country,
        "currency" : currency,
        "kw" : finalKeywords,
        "t" : int(time.time())
    }
    uri = urllib.urlencode(query, True)
    print uri

After decoding uri I get

country=&apiKey=5f0092f1777c3a5ed0de&kw=iphone&kw=android&t=1496924489&currency=usd

While my expected output is

country=&apiKey=5f0092f1777c3a5ed0de&kw[0]=iphone&kw[1]=android&t=1496924489&currency=usd

What to do..? I have been looking for solutions but unable to get.

Body:
Like this?

query = {
       "apiKey" : self.apikey,
        "country" : country,
        "currency" : currency,
        "kw[]" : finalKeywords,
        "t" : int(time.time())
    }

If you need to have the positional values in there as well for some reason, this is one way to do it:

query = {
        "apiKey" : self.apikey,
        "country" : country,
        "currency" : currency,
        "t" : int(time.time())
    }
for p,q in enumerate(finalKeywords):
   query["kw[{pos}]".format(pos=p)] = q


问:
Function calling in openerp reports
How is this sum_taxes method getting its lot parameter set? This is a code sample from the auction addon in openerp.

```<code>    import pooler
    import time
    from report import report_sxw
    from osv import osv

    class seller_form_report(report_sxw.rml_parse):
        def __init__(self, cr, uid, name, context):
            super(seller_form_report, self).__init__(cr, uid, name, context=context)
            lot=self.pool.get('auction.lots').browse(cr,uid,uid)
            #address=lot.bord_vnd_id.address_get(self.cr,self.uid,[partner.id])
        #   partner=lot.bord_vnd_id.partner_id
        #   address=partner.address and partner.address[0] or ""
        #   street = address and address.street or ""

            self.localcontext.update({
                'time': time,
                'sum_taxes': self.sum_taxes,
                'sellerinfo' : self.seller_info,
                'grand_total' : self.grand_seller_total,
        #       'street':street,
        #       'address':address,
    })

    def sum_taxes(self, lot):
        taxes=[]
        amount=0.0
        if lot.bord_vnd_id.tax_id:
            taxes.append(lot.bord_vnd_id.tax_id)
        elif lot.auction_id and lot.auction_id.seller_costs:
            taxes += lot.auction_id.seller_costs
        tax=self.pool.get('account.tax').compute(self.cr,self.uid,taxes,lot.obj_price,1)
        for t in tax:
            amount+=t['amount']
        return amount
    def seller_info(self):
        objects = [object for object in self.localcontext.get('objects')]
        ret_dict = {}
        ret_list = []
        for object in objects:

            partner = ret_dict.get(object.bord_vnd_id.partner_id.id,False)
            if not partner:
                ret_dict[object.bord_vnd_id.partner_id.id] = {'partner' : object.bord_vnd_id.partner_id or False,'lots':[object]}
            else:
                lots = partner.get('lots')
                lots.append(object)
#       buyer_ids=self.pool.get(auction.lots).read(cr,uid,lot)
        return ret_dict.values()
    def grand_seller_total(self,o):
        grand_total = 0
        for oo in o:
            grand_total =grand_total + oo['obj_price']+ self.sum_taxes(oo)
        return grand_total

report_sxw.report_sxw('report.seller_form_report', 'auction.lots', 'addons/auction/report/seller_form_report.rml', parser=seller_form_report)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
</code>```

答:
It's not actually calling the function in that code, the function probably gets called from within the report and passes the lot parameter there. In the code example you posted, it's just putting a function pointer into the context.

For more info on OpenERP reports, check out the reports section of the developer book. I also find it really helpful to run the OpenERP server in Eclipse and step through the code in debug mode. Then you can see where the sum_taxes() method is being called from.

Title: Function calling in openerp reports

Body:
How is this sum_taxes method getting its lot parameter set? This is a code sample from the auction addon in openerp.

    import pooler
    import time
    from report import report_sxw
    from osv import osv

    class seller_form_report(report_sxw.rml_parse):
        def __init__(self, cr, uid, name, context):
            super(seller_form_report, self).__init__(cr, uid, name, context=context)
            lot=self.pool.get('auction.lots').browse(cr,uid,uid)
            #address=lot.bord_vnd_id.address_get(self.cr,self.uid,[partner.id])
        #   partner=lot.bord_vnd_id.partner_id
        #   address=partner.address and partner.address[0] or ""
        #   street = address and address.street or ""

            self.localcontext.update({
                'time': time,
                'sum_taxes': self.sum_taxes,
                'sellerinfo' : self.seller_info,
                'grand_total' : self.grand_seller_total,
        #       'street':street,
        #       'address':address,
    })

    def sum_taxes(self, lot):
        taxes=[]
        amount=0.0
        if lot.bord_vnd_id.tax_id:
            taxes.append(lot.bord_vnd_id.tax_id)
        elif lot.auction_id and lot.auction_id.seller_costs:
            taxes += lot.auction_id.seller_costs
        tax=self.pool.get('account.tax').compute(self.cr,self.uid,taxes,lot.obj_price,1)
        for t in tax:
            amount+=t['amount']
        return amount
    def seller_info(self):
        objects = [object for object in self.localcontext.get('objects')]
        ret_dict = {}
        ret_list = []
        for object in objects:

            partner = ret_dict.get(object.bord_vnd_id.partner_id.id,False)
            if not partner:
                ret_dict[object.bord_vnd_id.partner_id.id] = {'partner' : object.bord_vnd_id.partner_id or False,'lots':[object]}
            else:
                lots = partner.get('lots')
                lots.append(object)
#       buyer_ids=self.pool.get(auction.lots).read(cr,uid,lot)
        return ret_dict.values()
    def grand_seller_total(self,o):
        grand_total = 0
        for oo in o:
            grand_total =grand_total + oo['obj_price']+ self.sum_taxes(oo)
        return grand_total

report_sxw.report_sxw('report.seller_form_report', 'auction.lots', 'addons/auction/report/seller_form_report.rml', parser=seller_form_report)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:


问:
Watson generic word from utterance
Trying to create a set of entities & intents for things of the ilk "describe <something>" or "tell me about <something>" or "list instances of <something>".  The <something>s are not known in advance.  Consequently, I cannot exhaustively list the possible values for the entity.

My impression from (albeit very little) use and from the documentation is that the conversation API isn't good at this type of thing.  Experience thus far says that it will recognize things that match the examples given for some entity, but I haven't seen that it can generalize to something like

describe @target

show me instances of @target

without knowing the set of values for @target.

What am I missing?

答:
Which services are you talking about?  NLC is able to do this, and so is Conversation, by using wildcards.  Either one of these can be trained to recognize intents with wildcard values in their training data.  Just use an asterisk ( like this - "*" ) for the wildcard.

You don't have to train Conversation with every possible utterance, it learns from it's training data.  So if you provided the service a series of utterances like "describe apples", "describe oranges", "describe fireflies", and "describe astrophysics", and then associated all of them with an intent of "#provide_description", then the Conversation service would indicte this intent for requests like "describe math".

Please also try to use real utterances for your training.  I am not sure that your users will speak in two word sentences all of the time.  Provide enough training data for each intent so the service is able to learn the various different ways people express the same intents.

Title: Watson generic word from utterance


问:
searching a 2d array in python - best method + indentation error
I have created the following 2d array (list of lists) in Python:

```<code>#creating a 2d array (3 rows by 7 columns) and populating it with numbers
matrix=[1,2,3,4,5,6,7],[8,9,10,11,12,13,14],[15,16,17,18,19,20,21]
rows=len(matrix) #finding the max number of rows in the matrix, in this case 3
columns=len(matrix[0]) #finding the max number of columns in each row, 7 in this case
</code>```

I am trying to search for a specific element in the array (say the number 9), and then print "found", if found, and "not found", if not in the array, with the following code:

```<code>number=int(input("What number are you looking for?"))
for i in range(rows):
      for j in range(columns):
        if matrix[i][j]==number:
          print("Found it!")
          break
else:
  print("not found")
</code>```

The output however, is erroneous:

```<code>>>What number are you looking for? 9
>>Found it!
>>not found
</code>```

I have two questions: 1. could someone please explain identatation clearly, with reference to this problem and why the second "not found" always is output.
2. Is there a better more efficient way to do this, without the use of numpy

*note, this is not a duplicate, as I have searched the other entries and they don't quite deal with what I am explicitly asking.

repl.it here:
https://repl.it/IcJ3/3

Someone just suggested an answer as below: (I had already tried this)

https://repl.it/IcJ3/5
Note, it doesn't work at all either:

```<code>number=int(input("What number are you looking for?"))
for i in range(rows):
      for j in range(columns):
        if matrix[i][j]==number:
          print("Found it!")
          break
        else:
          print("not found")
</code>```

Erroneous output, still!

```<code>What number are you looking for? 9
not found
not found
not found
not found
not found
not found
not found
not found
Found it!
not found
not found
not found
not found
not found
not found
not found
</code>```

答:
```<code>matrix =[1,2,3,4,5,6,7],[8,9,10,11,12,13,14],[15,16,17,18,19,20,21]

def search_elm(arr, num):
    elm = False
    for i in range(len(arr)):
      for j in range(len(arr[0])):
        if arr[i][j] == num:
          elm = True
    return elm
</code>```

and you can use it like:

```<code>if search_elm(matrix, 44):
    print 'Found!'
else:
    print 'Not Found'
</code>```

Body:
I have created the following 2d array (list of lists) in Python:

#creating a 2d array (3 rows by 7 columns) and populating it with numbers
matrix=[1,2,3,4,5,6,7],[8,9,10,11,12,13,14],[15,16,17,18,19,20,21]
rows=len(matrix) #finding the max number of rows in the matrix, in this case 3
columns=len(matrix[0]) #finding the max number of columns in each row, 7 in this case

I am trying to search for a specific element in the array (say the number 9), and then print "found", if found, and "not found", if not in the array, with the following code:

number=int(input("What number are you looking for?"))
for i in range(rows):
      for j in range(columns):
        if matrix[i][j]==number:
          print("Found it!")
          break
else:
  print("not found")

The output however, is erroneous:

>>What number are you looking for? 9
>>Found it!
>>not found

I have two questions: 1. could someone please explain identatation clearly, with reference to this problem and why the second "not found" always is output.
2. Is there a better more efficient way to do this, without the use of numpy

*note, this is not a duplicate, as I have searched the other entries and they don't quite deal with what I am explicitly asking.

repl.it here:
https://repl.it/IcJ3/3

Someone just suggested an answer as below: (I had already tried this)

https://repl.it/IcJ3/5
Note, it doesn't work at all either:

number=int(input("What number are you looking for?"))
for i in range(rows):
      for j in range(columns):
        if matrix[i][j]==number:
          print("Found it!")
          break
        else:
          print("not found")

Erroneous output, still!

What number are you looking for? 9
not found
not found
not found
not found
not found
not found
not found
not found
Found it!
not found
not found
not found
not found
not found
not found
not found

Body:
matrix =[1,2,3,4,5,6,7],[8,9,10,11,12,13,14],[15,16,17,18,19,20,21]

def search_elm(arr, num):
    elm = False
    for i in range(len(arr)):
      for j in range(len(arr[0])):
        if arr[i][j] == num:
          elm = True
    return elm

and you can use it like:

if search_elm(matrix, 44):
    print 'Found!'
else:
    print 'Not Found'


问:
Angular - Get ng-model value generated dinamically
My problem is directly connected with this

Angular - Dynamic ng-model inside ng-repeater

All works fine, it means that all selects are gereratet correctly with all options. The problem is in the controller, i can't get the ng-models'value, it returns "undefined" and i don't know how i can to this.

This is my HTML

```<code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="MyApp" ng-controller="ricercaAttivita">
    <div class="accordion-group" ng-repeat="masterAttribute in masterAttributes">
        <select class="trip dark" ng-model="{{masterAttribute.Name}}" ng-options="attr.Id as attr.Value for attr in masterAttribute.Values">
            <option value="">TUTTE</option>
        </select>
    </div>
    <button class="btn btn-default btn-green btn-3-column sidebar-filtri-button" ng-click="search()">Cerca</button>
</body>
</code>```

CONTROLLER

```<code>var tantoSvagoApp = angular.module('MyApp');

tantoSvagoApp.controller("ricercaAttivita") {
  $scope.search = function(page) {
    angular.forEach($scope.masterAttributes,function(value,index){
       console.log($scope.masterAttributes.Name);
    }
  }
</code>```

答:
Remove {{..}} from ng-model.
Change it to : ng-model="masterAttribute.Name"

and, in controller use the iterator (value) not $scope prop inside foreach,

Do it Like :

```<code>var tantoSvagoApp = angular.module('MyApp');

tantoSvagoApp.controller("ricercaAttivita") {
  $scope.search = function(page) {
    angular.forEach($scope.masterAttributes,function(masterAttribute,index){
       console.log(masterAttribute.Name);
    }
  }
}
</code>```

Told you same in linked question as well :)

Body:
My problem is directly connected with this

Angular - Dynamic ng-model inside ng-repeater

All works fine, it means that all selects are gereratet correctly with all options. The problem is in the controller, i can't get the ng-models'value, it returns "undefined" and i don't know how i can to this.

This is my HTML

        <select class="trip dark" ng-model="{{masterAttribute.Name}}" ng-options="attr.Id as attr.Value for attr in masterAttribute.Values">
            <option value="">TUTTE</option>
        </select>

    <button class="btn btn-default btn-green btn-3-column sidebar-filtri-button" ng-click="search()">Cerca</button>

CONTROLLER

var tantoSvagoApp = angular.module('MyApp');

tantoSvagoApp.controller("ricercaAttivita") {
  $scope.search = function(page) {
    angular.forEach($scope.masterAttributes,function(value,index){
       console.log($scope.masterAttributes.Name);
    }
  }

Body:
Remove {{..}} from ng-model.
Change it to : ng-model="masterAttribute.Name"

and, in controller use the iterator (value) not $scope prop inside foreach,

Do it Like :

var tantoSvagoApp = angular.module('MyApp');

tantoSvagoApp.controller("ricercaAttivita") {
  $scope.search = function(page) {
    angular.forEach($scope.masterAttributes,function(masterAttribute,index){
       console.log(masterAttribute.Name);
    }
  }
}

Told you same in linked question as well :)


问:
Spring message in JSTL Tag
According to this post from 3 years ago the only way to display a spring message in a jstl tag is to wrap it in a <c:set var="someVar"> which does "work" but it seems very far from ideal.

Fast forward 3 years, is this still the only way to handle this?

Here is my code

Works, but not "ideal"

```<code><c:set var="closeMessage">
    <spring:message code='lman.ilr.closeItemDetail'/>
</c:set>
<dsg:sidePanelContent closePanelText="${closeMessage}">
</code>```

Doesn't work, returns a string of <spring:message code='lman.ilr.closeItemDetail'/>

```<code><dsg:sidePanelContent closePanelText="<spring:message code='lman.ilr.closeItemDetail'/>">
</code>```

答:
In case for reference,</p>

```<code><c:choose>
  <c:when test="${serviceVO.id eq 0}">
     <spring:message code="label.service.createservice" var="buttonName"/>
  </c:when>
  <c:otherwise>
    <spring:message code="label.updateservice" var="buttonName"/>
  </c:otherwise>
</c:choose>

<c:out value="${buttonName}"> //Prints the desired value...
</code>```

Title: Spring message in JSTL Tag

Body:
According to this post from 3 years ago the only way to display a spring message in a jstl tag is to wrap it in a <c:set var="someVar"> which does "work" but it seems very far from ideal.

Fast forward 3 years, is this still the only way to handle this?

Here is my code

Works, but not "ideal"

<c:set var="closeMessage">
    <spring:message code='lman.ilr.closeItemDetail'/>
</c:set>
<dsg:sidePanelContent closePanelText="${closeMessage}">

Doesn't work, returns a string of <spring:message code='lman.ilr.closeItemDetail'/>

<dsg:sidePanelContent closePanelText="<spring:message code='lman.ilr.closeItemDetail'/>">

Body:
In case for reference,

<c:choose>
  <c:when test="${serviceVO.id eq 0}">
     <spring:message code="label.service.createservice" var="buttonName"/>
  </c:when>
  <c:otherwise>
    <spring:message code="label.updateservice" var="buttonName"/>
  </c:otherwise>
</c:choose>

<c:out value="${buttonName}"> //Prints the desired value...


问:
How to sum value of two json object key?
```<code>"bills": [
    {
        "refNo": 17,
        "billDate": "1-apr-2016",
        "dueDate": "30-apr-2016",
        "pendingAmount": 4500,
        "overdueDays": 28
    },
    {
        "refNo": 20,
        "billDate": "15-apr-2016",
        "dueDate": "3-may-2016",
        "pendingAmount": 56550,
        "overdueDays": 15
    }
]
</code>```

I want to sum "pendingAmount" field.
It should be return like pendingAmount: 61050

答:
You can use Array#map and then Array#reduce to flatten your object and then sum the result of the map :

```<code>bills.map(bill => bill.pendingAmount).reduce((acc, amount) => acc + amount);
</code>```

here's a snippet :

var bills = [
          {
            "refNo": 17,
            "billDate": "1-apr-2016",
            "dueDate": "30-apr-2016",
            "pendingAmount": 4500,
            "overdueDays": 28
          },
          {
            "refNo": 20,
            "billDate": "15-apr-2016",
            "dueDate": "3-may-2016",
            "pendingAmount": 56550,
            "overdueDays": 15
          }
        ];
var res = bills.map(bill => bill.pendingAmount).reduce((acc, amount) => acc + amount);
console.log(res)```

Hope it helps,

Best regards,

Body:
"bills": [
    {
        "refNo": 17,
        "billDate": "1-apr-2016",
        "dueDate": "30-apr-2016",
        "pendingAmount": 4500,
        "overdueDays": 28
    },
    {
        "refNo": 20,
        "billDate": "15-apr-2016",
        "dueDate": "3-may-2016",
        "pendingAmount": 56550,
        "overdueDays": 15
    }
]

I want to sum "pendingAmount" field.
It should be return like pendingAmount: 61050

Body:
You can use Array#map and then Array#reduce to flatten your object and then sum the result of the map :

bills.map(bill => bill.pendingAmount).reduce((acc, amount) => acc + amount);

here's a snippet :

var bills = [
          {
            "refNo": 17,
            "billDate": "1-apr-2016",
            "dueDate": "30-apr-2016",
            "pendingAmount": 4500,
            "overdueDays": 28
          },
          {
            "refNo": 20,
            "billDate": "15-apr-2016",
            "dueDate": "3-may-2016",
            "pendingAmount": 56550,
            "overdueDays": 15
          }
        ];
var res = bills.map(bill => bill.pendingAmount).reduce((acc, amount) => acc + amount);
console.log(res)

Hope it helps,

Best regards,


问:
Should the password field be unique?
In light of the recent Gawker Media password leak, I've realized that many users share the same passwords. To help encourage stronger passwords, would it be helpful if passwords are constrained to be unique among all users?

One immediate downside I could think of (besides account creation performance?) is being able to know that someone is using a given string as a password. This knowledge, combined with a list of users, could be quite dangerous.

Is there a way to mitigate that downside while retaining the alleged benefits of not allowing repeat passwords?

It's kind of like the XKCD kick bot where you aren't allowed to repeat short, unoriginal sentences like "yah" or "lol".

Edit^2: I thought you could unique-ify against a hash, but as someone pointed out, with varying salts, this would not have the intended effect. Good eye!

答:
eeeuh

I might be misreading your question, but I hope you do not store the actual password?

You should hash the password with a random salt. That way, there is no way for you to ever tell if one or more users have the same password.

If your systems, in any way, allows you to determine if two or more users have the same password, you are storing the passwords the wrong way.

Title: Should the password field be unique?


问:
How to refresh page on back button click?
I use .htaccess to route all of my traffic to a single index.php file. The code below to directs traffic, but for some reason it doesn't work with the back button. I don't know what to do to get the back button working. I've tried a variety of things and googled quite a bit and none of it has worked so I'm hoping someone here can help!

```<code><?php
   if(isset($_GET['parameters'])) {
      if($_GET['parameters'] == "repair")
         include 'repair.html';
      else if($_GET['parameters'] == "training")
         include 'training.html';
      else if($_GET['parameters'] == "products")
         include 'products.html';
      else if($_GET['parameters'] == "about")
         include 'about.html';
      else if($_GET['parameters'] == "employees")
         include 'employees.html';
      else if($_GET['parameters'] == "training")
         include 'training.html';
      else if($_GET['parameters'] == "newaccount")
         include 'newaccount.html';
      else if($_GET['parameters'] == "contact")
         include 'contact.html';
      else if($_GET['parameters'] == "recommended")
         include 'recommended.html';
      else if($_GET['parameters'] == "careers")
         include 'careers.html';
      else
         include 'home.html';
   }
   else
      include 'home.html';
?>
</code>```

So far I've tried and failed to use: window.onbeforeunload
body onunload=""

There has got to be a way to onunload=location.reload() or something! Somehow has to know the syntax!!

答:
I found two ways to handle this. Choose the best for your case.
Solutions tested on Firefox 53 and Safari 10.1

1. Detect if user is using the back/foreward button, then reload whole page

```<code>if (!!window.performance && window.performance.navigation.type === 2) {
            // value 2 means "The page was accessed by navigating into the history"
            console.log('Reloading');
            window.location.reload(); // reload whole page

        }
</code>```

2. reload whole page if page is cached

```<code>window.onpageshow = function (event) {
        if (event.persisted) {
            window.location.reload();
        }
    };
</code>```

Body:
I use .htaccess to route all of my traffic to a single index.php file. The code below to directs traffic, but for some reason it doesn't work with the back button. I don't know what to do to get the back button working. I've tried a variety of things and googled quite a bit and none of it has worked so I'm hoping someone here can help!

<?php
   if(isset($_GET['parameters'])) {
      if($_GET['parameters'] == "repair")
         include 'repair.html';
      else if($_GET['parameters'] == "training")
         include 'training.html';
      else if($_GET['parameters'] == "products")
         include 'products.html';
      else if($_GET['parameters'] == "about")
         include 'about.html';
      else if($_GET['parameters'] == "employees")
         include 'employees.html';
      else if($_GET['parameters'] == "training")
         include 'training.html';
      else if($_GET['parameters'] == "newaccount")
         include 'newaccount.html';
      else if($_GET['parameters'] == "contact")
         include 'contact.html';
      else if($_GET['parameters'] == "recommended")
         include 'recommended.html';
      else if($_GET['parameters'] == "careers")
         include 'careers.html';
      else
         include 'home.html';
   }
   else
      include 'home.html';
?>

So far I've tried and failed to use: window.onbeforeunload
body onunload=""

There has got to be a way to onunload=location.reload() or something! Somehow has to know the syntax!!

Body:
I found two ways to handle this. Choose the best for your case.
Solutions tested on Firefox 53 and Safari 10.1

1. Detect if user is using the back/foreward button, then reload whole page

if (!!window.performance && window.performance.navigation.type === 2) {
            // value 2 means "The page was accessed by navigating into the history"
            console.log('Reloading');
            window.location.reload(); // reload whole page

        }

2. reload whole page if page is cached

window.onpageshow = function (event) {
        if (event.persisted) {
            window.location.reload();
        }
    };


问:
finding the first and last entry with a certain value in a row
I have a excel sheet containing multiple cells with a string foo in the first row. I want to find the first and last column in which the string is written. I have tried the following

```<code>Dim first_col As Integer
Dim last_col As Integer
Dim col As Integer
Dim found As Range
Dim ws_MLB as Worksheet
Dim foo as String

set ws_MLB = ThisWorkbook.Sheet(1)

Set found = ws_MLB.Rows(1).Find(foo)
If Not found Is Nothing Then
    col = found.Column
    first_col = col
    last_col = col
    Do
        found = ws_MLB.Rows(1).FindNext(found)
        col = found.Column

        If col < first_col Then
            first_col = col
            MsgBox ("This should not happen")
        ElseIf col > last_col Then
            last_col = col
        End If
    Loop While Not found Is Nothing And col <> first_col
Else
    MsgBox ("not found")
End If
</code>```

But this way I only get the the first value for both first_col and last_col. When I search for the string with the integrated excel search I find multiple instances. So the string is there. Have I done a mistake or is there a better way to do this?

edit forgot to mention that I also tried to change the search direction, but I still got the first entry.

答:
You can make this a lot easier by using the SearchDirection Parameter in .Find by using xlNext you search Left to Right then xlPrevious searches Right to Left.

```<code>Sub FindFL()

    Dim wbk As Workbook
    Dim ws As Worksheet
    Dim fColumn As Long, lColumn As Long

    Set wbk = ThisWorkbook 'Change this to your workbook
    Set ws = wbk.Worksheets("Sheet1") 'Change this to your worksheet

    With ws
        'Find first column that foo shows up
        fColumn = .Cells.Find(What:="foo", _
            After:=.Cells(1, 1), _
            LookIn:=xlValues, _
            LookAt:=xlWhole, _
            SearchOrder:=xlByColumns, _
            SearchDirection:=xlNext, _
            MatchCase:=False).Column
        'Find last column that foo shows up
        lColumn = .Cells.Find(What:="foo", _
            After:=.Cells(1, 1), _
            LookIn:=xlValues, _
            LookAt:=xlWhole, _
            SearchOrder:=xlByColumns, _
            SearchDirection:=xlPrevious, _
            MatchCase:=False).Column

        Debug.Print "First Column is " & fColumn; vbNewLine _
        ; "Last Column is " & lColumn
    End With
End Sub
</code>```

Body:
I have a excel sheet containing multiple cells with a string foo in the first row. I want to find the first and last column in which the string is written. I have tried the following

Dim first_col As Integer
Dim last_col As Integer
Dim col As Integer
Dim found As Range
Dim ws_MLB as Worksheet
Dim foo as String

set ws_MLB = ThisWorkbook.Sheet(1)

Set found = ws_MLB.Rows(1).Find(foo)
If Not found Is Nothing Then
    col = found.Column
    first_col = col
    last_col = col
    Do
        found = ws_MLB.Rows(1).FindNext(found)
        col = found.Column

        If col < first_col Then
            first_col = col
            MsgBox ("This should not happen")
        ElseIf col > last_col Then
            last_col = col
        End If
    Loop While Not found Is Nothing And col <> first_col
Else
    MsgBox ("not found")
End If

But this way I only get the the first value for both first_col and last_col. When I search for the string with the integrated excel search I find multiple instances. So the string is there. Have I done a mistake or is there a better way to do this?

edit forgot to mention that I also tried to change the search direction, but I still got the first entry.

Body:
You can make this a lot easier by using the SearchDirection Parameter in .Find by using xlNext you search Left to Right then xlPrevious searches Right to Left.

Sub FindFL()

    Dim wbk As Workbook
    Dim ws As Worksheet
    Dim fColumn As Long, lColumn As Long

    Set wbk = ThisWorkbook 'Change this to your workbook
    Set ws = wbk.Worksheets("Sheet1") 'Change this to your worksheet

    With ws
        'Find first column that foo shows up
        fColumn = .Cells.Find(What:="foo", _
            After:=.Cells(1, 1), _
            LookIn:=xlValues, _
            LookAt:=xlWhole, _
            SearchOrder:=xlByColumns, _
            SearchDirection:=xlNext, _
            MatchCase:=False).Column
        'Find last column that foo shows up
        lColumn = .Cells.Find(What:="foo", _
            After:=.Cells(1, 1), _
            LookIn:=xlValues, _
            LookAt:=xlWhole, _
            SearchOrder:=xlByColumns, _
            SearchDirection:=xlPrevious, _
            MatchCase:=False).Column

        Debug.Print "First Column is " & fColumn; vbNewLine _
        ; "Last Column is " & lColumn
    End With
End Sub


问:
ERROR: 'object' does not contain a definition for 'methodName'
I need to pass different objects instantiated from different classes which they have a function with same name, and I would like to call that function.

For example:

```<code>Class1 object1;
Class2 object2;
Class3 object3;

Object object = object1;
object1->functionname();

Object object = object2;
object2->functionname();

Object object = object3;
object3->functionname();
</code>```

this is not possible in c#...

In php it's pretty simple you can just do it with object like the sample above but in c# i get this error:  ERROR: 'object' does not contain a definition for 'methodName'

I though it's legal to call any method name on a object object! since it doesn't know what is really inside.

How can I do that?

答:
Create an interface that both classes implement.

Then pass the object via the type of your interface to your function:

```<code>interface IAnimal
{
    void Speak();
}

class Cat : IAnimal
{
    public void Speak()
    {
        MessageBox.Show("Meow!");
    }
}

class Dog : IAnimal
{
    public void Speak()
    {
        MessageBox.Show("Woof!");
    }
}

static class Program
{

    static void SpeakPlease(IAnimal animal)
    {
        animal.Speak();
    }
 //...
 }
</code>```

Body:
I need to pass different objects instantiated from different classes which they have a function with same name, and I would like to call that function.

For example:

Class1 object1;
Class2 object2;
Class3 object3;

Object object = object1;
object1->functionname();

Object object = object2;
object2->functionname();

Object object = object3;
object3->functionname();

this is not possible in c#...

In php it's pretty simple you can just do it with object like the sample above but in c# i get this error:  ERROR: 'object' does not contain a definition for 'methodName'

I though it's legal to call any method name on a object object! since it doesn't know what is really inside.

How can I do that?

Body:
Create an interface that both classes implement.

Then pass the object via the type of your interface to your function:

interface IAnimal
{
    void Speak();
}

class Cat : IAnimal
{
    public void Speak()
    {
        MessageBox.Show("Meow!");
    }
}

class Dog : IAnimal
{
    public void Speak()
    {
        MessageBox.Show("Woof!");
    }
}

static class Program
{

    static void SpeakPlease(IAnimal animal)
    {
        animal.Speak();
    }
 //...
 }