问:
Jetty: Hide port number in the URL
I buy a domain name: test.com.

Then I run jetty by doing:

```<code>/opt/jetty# nohup java -jar start.jar
</code>```

When I go on my web site (http://test.com), It's not working, I need to add the port number like: http://test.com:8080 and this is very dirty. So, I want to delete or hide this port number.

What I tried is to run jetty with the port number like:

```<code>nohup java -jar start.jar -Djetty.http.port=8080
</code>```

Then, in the file jetty-http.xml (in /opt/jetty/etc), I changed the line:

```<code><Set name="port"><Property name="jetty.http.port" deprecated="jetty.port" default="8080" /></Set>
</code>```

I am using:

Vaadin.

Maven.

Jetty.

Where should I manage this?

EDIT :

As required, this is the pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>test</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>test</name>

    <prerequisites>
        <maven>3</maven>
    </prerequisites>

    <properties>
        <vaadin.version>8.0.4</vaadin.version>
        <vaadin.plugin.version>8.0.4</vaadin.plugin.version>
        <jetty.plugin.version>9.3.9.v20160517</jetty.plugin.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <jetty.port>8080</jetty.port>
        <vaadin.widgetset.mode>local</vaadin.widgetset.mode>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.vaadin</groupId>
                <artifactId>vaadin-bom</artifactId>
                <version>${vaadin.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin-compatibility-server</artifactId>
        </dependency>
        <dependency>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin-compatibility-client-compiled</artifactId>
        </dependency>
        <dependency>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin-server</artifactId>
        </dependency>
        <dependency>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin-client-compiled</artifactId>
        </dependency>
        <dependency>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin-themes</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                    <packagingExcludes>WEB-INF/classes/VAADIN/widgetsets/WEB-INF/**</packagingExcludes>
                </configuration>
            </plugin>
            <plugin>
                <groupId>com.vaadin</groupId>
                <artifactId>vaadin-maven-plugin</artifactId>
                <version>${vaadin.plugin.version}</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>update-theme</goal>
                            <goal>update-widgetset</goal>
                            <goal>compile</goal>
                            <goal>compile-theme</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-clean-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <filesets>
                        <fileset>
                            <directory>src/main/webapp/VAADIN/themes</directory>
                            <includes>
                                <include>**/styles.css</include>
                                <include>**/styles.scss.cache</include>
                            </includes>
                        </fileset>
                    </filesets>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>${jetty.plugin.version}</version>
                <configuration>
                    <contextPath>/login</contextPath>
                    <scanIntervalSeconds>2</scanIntervalSeconds>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

To prevent question, I tried to delete the
<jetty.port>8080</jetty.port> without sucess.

EDIT : Based on maven jetty plugin - remove localhost/server name from url

I tried to changed the localhostto myapplicationname from /etc/hosts. I restart jetty. And, it's not working

答:
If I understand the problem correctly, you need to use the 80 port as the Jetty's one (jetty.http.port), because http://test.com/ means that the port is the default — 80.

Additional references:

networking - Why was port 80 chosen as the default HTTP port and 443 as the default HTTPS port? - Super User.

java - Change Jetty default port - Stack Overflow.

Update

This sentence clarifies the problem a little bit:

I'm sorry, I don't know how I can provide more.. I installed Jetty 9 on a debian

— Bob, the original message.

Edit the /etc/default/jetty9 file as follows:

```<code># Additional arguments to pass to Jetty
JETTY_ARGS=jetty.port=80

# If you run Jetty on port numbers that are all higher than 1023, then you
# do not need authbind. It is used for binding Jetty to lower port numbers.
# (yes/no, default: no)
AUTHBIND=yes
</code>```

Then, restart the Jetty server:

```<code># service jetty9 restart
</code>```

Title: Jetty: Hide port number in the URL

Body:
I buy a domain name: test.com.

Then I run jetty by doing:

/opt/jetty# nohup java -jar start.jar

When I go on my web site (http://test.com), It's not working, I need to add the port number like: http://test.com:8080 and this is very dirty. So, I want to delete or hide this port number.

What I tried is to run jetty with the port number like:

nohup java -jar start.jar -Djetty.http.port=8080

Then, in the file jetty-http.xml (in /opt/jetty/etc), I changed the line:

<Set name="port"><Property name="jetty.http.port" deprecated="jetty.port" default="8080" /></Set>

I am using:

Vaadin.

Maven.

Jetty.

Where should I manage this?

EDIT :

As required, this is the pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>test</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>test</name>

    <prerequisites>
        <maven>3</maven>
    </prerequisites>

    <properties>
        <vaadin.version>8.0.4</vaadin.version>
        <vaadin.plugin.version>8.0.4</vaadin.plugin.version>
        <jetty.plugin.version>9.3.9.v20160517</jetty.plugin.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <jetty.port>8080</jetty.port>
        <vaadin.widgetset.mode>local</vaadin.widgetset.mode>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.vaadin</groupId>
                <artifactId>vaadin-bom</artifactId>
                <version>${vaadin.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin-compatibility-server</artifactId>
        </dependency>
        <dependency>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin-compatibility-client-compiled</artifactId>
        </dependency>
        <dependency>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin-server</artifactId>
        </dependency>
        <dependency>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin-client-compiled</artifactId>
        </dependency>
        <dependency>
            <groupId>com.vaadin</groupId>
            <artifactId>vaadin-themes</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                    <packagingExcludes>WEB-INF/classes/VAADIN/widgetsets/WEB-INF/**</packagingExcludes>
                </configuration>
            </plugin>
            <plugin>
                <groupId>com.vaadin</groupId>
                <artifactId>vaadin-maven-plugin</artifactId>
                <version>${vaadin.plugin.version}</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>update-theme</goal>
                            <goal>update-widgetset</goal>
                            <goal>compile</goal>
                            <goal>compile-theme</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-clean-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <filesets>
                        <fileset>
                            <directory>src/main/webapp/VAADIN/themes</directory>
                            <includes>
                                <include>**/styles.css</include>
                                <include>**/styles.scss.cache</include>
                            </includes>
                        </fileset>
                    </filesets>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>${jetty.plugin.version}</version>
                <configuration>
                    <contextPath>/login</contextPath>
                    <scanIntervalSeconds>2</scanIntervalSeconds>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

To prevent question, I tried to delete the
<jetty.port>8080</jetty.port> without sucess.

EDIT : Based on maven jetty plugin - remove localhost/server name from url

I tried to changed the localhostto myapplicationname from /etc/hosts. I restart jetty. And, it's not working

Body:
If I understand the problem correctly, you need to use the 80 port as the Jetty's one (jetty.http.port), because http://test.com/ means that the port is the default — 80.

Additional references:

networking - Why was port 80 chosen as the default HTTP port and 443 as the default HTTPS port? - Super User.

java - Change Jetty default port - Stack Overflow.

Update

This sentence clarifies the problem a little bit:

I'm sorry, I don't know how I can provide more.. I installed Jetty 9 on a debian

— Bob, the original message.

Edit the /etc/default/jetty9 file as follows:

# Additional arguments to pass to Jetty
JETTY_ARGS=jetty.port=80

# If you run Jetty on port numbers that are all higher than 1023, then you
# do not need authbind. It is used for binding Jetty to lower port numbers.
# (yes/no, default: no)
AUTHBIND=yes

Then, restart the Jetty server:

# service jetty9 restart


来源: stackexchange

问:
C# Linq Query from a list to select only records which have same id from another list
I am having a list of object. I would like to select item from the list and perform foreach operation on the selected items.And then Get the Data which have that Site.

C# Linq Query from a list to select only records which have same id from another list

Model

List of Sites

```<code>public class Site
{
    public string Name{ get; set; }
    public int SiteNo{ get; set; }
}

public class StudentSite
{
    public string Username{ get; set; }
    public string { get; set; }
    public IList<Site> SiteNo { get; set; }
    public DateTime? DateReceived { get; set; }
    public string firstname { get; set; }
    public string DataEntryUser { get; set; }
    public DateTime? CreatedDate { get; set; }
    public int? Count { get; set; }
}

var user = repository.Get(userid);  //it return me the list of sites 10 sites

results_temp12 = (from workstation in _entitiesCTRS2.AidsM.OrderBy(c => c.Lab_ID )
                 where user.User_InvSites.ToList().
                 ForEach(c => c.Inv_Site.SITE_NO
                    .Where( w=> workstation.Site_Number == c.Inv_Site.SITE_NO)
                    .ToList())
                    select new
                    StudentSite
                    {
                        firstname = workstation.First_Name,
                        CreatedDate = workstation.Entered_dt,
                        scanid = workstation.Scan_ID,
                        labid = workstation.Lab_ID,
                        SiteNo = workstation.Site_Number,
                        DateReceived = workstation.Date_Received,
                        DataEntryUser = workstation.Entered_By
                    }).ToList();
</code>```

答:
It's pretty easy:

```<code>list1.Where(item1 => list2.Any(item2 => item1.Id == item2.Id));
</code>```

This will give you every item in list1 whose ID is in list2.

ContentLicense: CC BY-SA 3.0

Body:
I am having a list of object. I would like to select item from the list and perform foreach operation on the selected items.And then Get the Data which have that Site.

C# Linq Query from a list to select only records which have same id from another list

Model

List of Sites

public class Site
{
    public string Name{ get; set; }
    public int SiteNo{ get; set; }
}

public class StudentSite
{
    public string Username{ get; set; }
    public string { get; set; }
    public IList<Site> SiteNo { get; set; }
    public DateTime? DateReceived { get; set; }
    public string firstname { get; set; }
    public string DataEntryUser { get; set; }
    public DateTime? CreatedDate { get; set; }
    public int? Count { get; set; }
}

var user = repository.Get(userid);  //it return me the list of sites 10 sites

results_temp12 = (from workstation in _entitiesCTRS2.AidsM.OrderBy(c => c.Lab_ID )
                 where user.User_InvSites.ToList().
                 ForEach(c => c.Inv_Site.SITE_NO
                    .Where( w=> workstation.Site_Number == c.Inv_Site.SITE_NO)
                    .ToList())
                    select new
                    StudentSite
                    {
                        firstname = workstation.First_Name,
                        CreatedDate = workstation.Entered_dt,
                        scanid = workstation.Scan_ID,
                        labid = workstation.Lab_ID,
                        SiteNo = workstation.Site_Number,
                        DateReceived = workstation.Date_Received,
                        DataEntryUser = workstation.Entered_By
                    }).ToList();

Body:
It's pretty easy:

list1.Where(item1 => list2.Any(item2 => item1.Id == item2.Id));

This will give you every item in list1 whose ID is in list2.


问:
os.tmpDir() is deprecated - node and formidable
I use node version 7.2.0 and formidable version 1.0.17 for file upload. After updating to the node version 7.2.0 I now get the following error when uploading files:

(node:3376) DeprecationWarning: os.tmpDir() is deprecated. Use os.tmpdir() instead.

I don't use the default of form.uploadDir but some custom path.

How would I fix that error?

答:
@idbehold, it worked like a charm.

It's not really an error, it's a deprecation warning. You can ask the formidable maintainers to fix it or you could just put something like the following at the top of your file:

var os = require('os');

os.tmpDir = os.tmpdir;

ContentLicense: CC BY-SA 4.0


问:
Python Selenium Can't see data
OK, so I'm new to programming with Python and HTML/Javascript but I have managed to scrape a website or two so far.  However, I have come across this site and its driving me round the bend.

My Code is:

```<code>#import libraries
from urllib.request import urlopen as ureq
from bs4 import BeautifulSoup as soup
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

#set chromepath to include .exe
chrome_path = r"C:\Program Files\Python37\chromedriver_win32\chromedriver.exe"
driver = webdriver.Chrome(chrome_path)

#set variables
myurl='http://www.ctbar.org/search/newsearch.asp'
driver.get(myurl) # loads the 1st page into the browser

element = driver.find_elements(By.ID, 'SearchResultsGrid')

print (element)
print('Done')

driver.quit()
</code>```

The only output I get is:

[]
Done

What bit(s) am I getting wrong??

Please help before I give up in frustration:-)

答:
The element you are finding located inside of iframe, you have to switch context to it first:</p>

```<code>driver.switch_to.frame(driver.find_element_by_id('SearchResultsFrame'))
# driver.switch_to_frame is deprecated
element = driver.find_elements(By.ID, 'SearchResultsGrid')
</code>```

Title: Python Selenium Can't see data

Body:
OK, so I'm new to programming with Python and HTML/Javascript but I have managed to scrape a website or two so far.  However, I have come across this site and its driving me round the bend.

My Code is:

#import libraries
from urllib.request import urlopen as ureq
from bs4 import BeautifulSoup as soup
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

#set chromepath to include .exe
chrome_path = r"C:\Program Files\Python37\chromedriver_win32\chromedriver.exe"
driver = webdriver.Chrome(chrome_path)

#set variables
myurl='http://www.ctbar.org/search/newsearch.asp'
driver.get(myurl) # loads the 1st page into the browser

element = driver.find_elements(By.ID, 'SearchResultsGrid')

print (element)
print('Done')

driver.quit()

The only output I get is:

[]
Done

What bit(s) am I getting wrong??

Please help before I give up in frustration:-)

Body:
The element you are finding located inside of iframe, you have to switch context to it first:

driver.switch_to.frame(driver.find_element_by_id('SearchResultsFrame'))
# driver.switch_to_frame is deprecated
element = driver.find_elements(By.ID, 'SearchResultsGrid')


问:
multiplot for gtable objects
The multiplot function is defined here in the cookbook

Consider the following graphs.

```<code>p1 = ggplot(mtcars,aes(y=mpg, x=cyl)) + geom_point()
p2 = ggplot(mtcars,aes(y=disp, x=cyl)) + geom_point()
multiplot(p1,p2, layout=matrix(1:2,nrow=1))
</code>```

I'd like to manipulate (with function DoStuff) the plot as a gtable object rather than as a ggplot object.

```<code>g1 = ggplot_gtable(ggplot_build(p1))
g1 = DoStuff(g1)
g2 = ggplot_gtable(ggplot_build(p1))
g2 = DoStuff(g2)
</code>```

I can print a gtable with grid.draw.

How can I modify the multiplot function, so that it also accepts gtable objects and not just ggplot objects?

答:
in my somewhat biased view you'd be better off using

```<code>gridExtra::grid.arrange(g1,g2, ncol=2)
</code>```

but to answer your question:

change

```<code>print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
                                layout.pos.col = matchidx$col))
</code>```

to something like

```<code>  if(inherits(plots[[i]], "gg")) {

    print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
                                    layout.pos.col = matchidx$col))

  } else if(inherits(plots[[i]], "gtable")) {

    pushViewport(viewport(layout.pos.row = matchidx$row,
                          layout.pos.col = matchidx$col))
    grid.draw(plots[[i]])
    upViewport()
  }
</code>```

and call it as before,

```<code>g1 <- ggplotGrob(p1)
g2 <- ggplotGrob(p2)
multiplot(g1,g2, layout=matrix(1:2,nrow=1))
</code>```

Title: multiplot for gtable objects

Body:
The multiplot function is defined here in the cookbook

Consider the following graphs.

p1 = ggplot(mtcars,aes(y=mpg, x=cyl)) + geom_point()
p2 = ggplot(mtcars,aes(y=disp, x=cyl)) + geom_point()
multiplot(p1,p2, layout=matrix(1:2,nrow=1))

I'd like to manipulate (with function DoStuff) the plot as a gtable object rather than as a ggplot object.

g1 = ggplot_gtable(ggplot_build(p1))
g1 = DoStuff(g1)
g2 = ggplot_gtable(ggplot_build(p1))
g2 = DoStuff(g2)

I can print a gtable with grid.draw.

How can I modify the multiplot function, so that it also accepts gtable objects and not just ggplot objects?

Body:
in my somewhat biased view you'd be better off using

gridExtra::grid.arrange(g1,g2, ncol=2)

but to answer your question:

change

print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
                                layout.pos.col = matchidx$col))

to something like

  if(inherits(plots[[i]], "gg")) {

    print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
                                    layout.pos.col = matchidx$col))

  } else if(inherits(plots[[i]], "gtable")) {

    pushViewport(viewport(layout.pos.row = matchidx$row,
                          layout.pos.col = matchidx$col))
    grid.draw(plots[[i]])
    upViewport()
  }

and call it as before,

g1 <- ggplotGrob(p1)
g2 <- ggplotGrob(p2)
multiplot(g1,g2, layout=matrix(1:2,nrow=1))


问:
Porting C++ to C# - templates
I'm porting a C++ application to C#, and have run across templates.  I've read up a little on these, and I understand that some templates are akin to .Net generics.  I read the SO answer to this case which nicely summed it up.

However, some uses of c++ templating don't seem to be directly related to generics.  In the below example from Wikipedia's Template metaprogramming article the template seems to accept a value, rather than a type.  I'm not quite sure how this would be ported to C#?

```<code>template <int N>
struct Factorial
{
    enum { value = N * Factorial<N - 1>::value };
};

template <>
struct Factorial<0>
{
    enum { value = 1 };
};

// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
    int x = Factorial<4>::value; // == 24
    int y = Factorial<0>::value; // == 1
}
</code>```

Clearly for this example I could do:

```<code>public int Factorial(int N){
    if(N == 0) return 1;
    return Factorial(N - 1);
}
</code>```

but this seems to me to be a refactoring to a function, rather than a port to semantically similar code.

答: The short answer is that, not everything that can be done in C++ templates can be done in C# generics.  In the case of templates which accept non type values, each situation will have to be handled and re factored appropriately on a case by case basis.</p>

ContentLicense: CC BY-SA 2.5

Title: Porting C++ to C# - templates

Body:
I'm porting a C++ application to C#, and have run across templates.  I've read up a little on these, and I understand that some templates are akin to .Net generics.  I read the SO answer to this case which nicely summed it up.

However, some uses of c++ templating don't seem to be directly related to generics.  In the below example from Wikipedia's Template metaprogramming article the template seems to accept a value, rather than a type.  I'm not quite sure how this would be ported to C#?

template <int N>
struct Factorial
{
    enum { value = N * Factorial<N - 1>::value };
};

template <>
struct Factorial<0>
{
    enum { value = 1 };
};

// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
    int x = Factorial<4>::value; // == 24
    int y = Factorial<0>::value; // == 1
}

Clearly for this example I could do:

public int Factorial(int N){
    if(N == 0) return 1;
    return Factorial(N - 1);
}

but this seems to me to be a refactoring to a function, rather than a port to semantically similar code.


问:
How to use same word in different optional Lexer tokens
I simplified my Antlr4 grammar to this:

```<code>grammar test;

directives:
    ('[' directive ']')* EOF;

directive:
      KEY1 OPERATOR OPTIONS1
    | KEY2 OPERATOR OPTIONS2;
OPERATOR: '=';

KEY1: 'Key1';
KEY2: 'Key2';

OPTIONS1: 'a'|'b'|'c';
OPTIONS2: 'c'|'d'|'e';
</code>```

When I try to use this grammar to parse:

```<code>[Key1=a][Key2=c]
</code>```

The Parser give an error:

```<code>line 1:14 mismatched input 'c' expecting OPTIONS2
</code>```

In my real work, OPTIONS1 and OPTIONS2 are different enum data types, 'c' is the one in both.

答:
You should split intersections:

```<code>OPTIONS1: 'a'|'b'|'c';
OPTIONS2: 'c'|'d'|'e';
</code>```

So, your rules will be:

```<code>OPTIONS1: 'a'|'b';
OPTIONS2: 'd'|'e';
OPTIONS3: 'c';
</code>```

and:

```<code>directive:
      KEY1 OPERATOR (OPTIONS1 | OPTIONS3)
    | KEY2 OPERATOR (OPTIONS2 | OPTIONS3)
</code>```

This happens, because Lexer performs token identification from tree leafs, so, your 'c' interpreted by lexer as OPTIONS1 instead of OPTIONS2 by their order in grammar.

I forgot how your tokens can be inlined (interpreted as macros), so it will look like this in preprocessor (it will work too):

```<code>directive:
      KEY1 OPERATOR ('a'|'b'|'c')
    | KEY2 OPERATOR ('c'|'d'|'e');
</code>```

You better to read their current syntax, it can be inlined. Drawback is that you will not see OPERATOR1 and OPERATOR2 in AST view.

Body:
I simplified my Antlr4 grammar to this:

grammar test;

directives:
    ('[' directive ']')* EOF;

directive:
      KEY1 OPERATOR OPTIONS1
    | KEY2 OPERATOR OPTIONS2;
OPERATOR: '=';

KEY1: 'Key1';
KEY2: 'Key2';

OPTIONS1: 'a'|'b'|'c';
OPTIONS2: 'c'|'d'|'e';

When I try to use this grammar to parse:

[Key1=a][Key2=c]

The Parser give an error:

line 1:14 mismatched input 'c' expecting OPTIONS2

In my real work, OPTIONS1 and OPTIONS2 are different enum data types, 'c' is the one in both.

Body:
You should split intersections:

OPTIONS1: 'a'|'b'|'c';
OPTIONS2: 'c'|'d'|'e';

So, your rules will be:

OPTIONS1: 'a'|'b';
OPTIONS2: 'd'|'e';
OPTIONS3: 'c';

and:

directive:
      KEY1 OPERATOR (OPTIONS1 | OPTIONS3)
    | KEY2 OPERATOR (OPTIONS2 | OPTIONS3)

This happens, because Lexer performs token identification from tree leafs, so, your 'c' interpreted by lexer as OPTIONS1 instead of OPTIONS2 by their order in grammar.

I forgot how your tokens can be inlined (interpreted as macros), so it will look like this in preprocessor (it will work too):

directive:
      KEY1 OPERATOR ('a'|'b'|'c')
    | KEY2 OPERATOR ('c'|'d'|'e');

You better to read their current syntax, it can be inlined. Drawback is that you will not see OPERATOR1 and OPERATOR2 in AST view.


问:
Retrieve custom attribute parameter values?
if i have created an attribute:

```<code>public class TableAttribute : Attribute {
    public string HeaderText { get; set; }
}
</code>```

which i apply to a few of my properties in a class

```<code>public class Person {
    [Table(HeaderText="F. Name")]
    public string FirstName { get; set; }
}
</code>```

in my view i have a list of people which i am displaying in a table.. how can i retrieve the value of HeaderText to use as my column headers? Something like...

```<code><th><%:HeaderText%></th>
</code>```

答:
Jon Skeet's solution is good if you allow multiple attributes of the same type to be declared on a property.  (AllowMultiple = true)

ex:

```<code>[Table(HeaderText="F. Name 1")]
[Table(HeaderText="F. Name 2")]
[Table(HeaderText="F. Name 3")]
public string FirstName { get; set; }
</code>```

In your case, I would assume you only want one attribute allowed per property.  In which case, you can access the properties of the custom attribute via:

```<code>var tableAttribute= propertyInfo.GetCustomAttribute<TableAttribute>();
Console.Write(tableAttribute.HeaderText);
// Outputs "F. Name" when accessing FirstName
// Outputs "L. Name" when accessing LastName
</code>```

Body:
if i have created an attribute:

public class TableAttribute : Attribute {
    public string HeaderText { get; set; }
}

which i apply to a few of my properties in a class

public class Person {
    [Table(HeaderText="F. Name")]
    public string FirstName { get; set; }
}

in my view i have a list of people which i am displaying in a table.. how can i retrieve the value of HeaderText to use as my column headers? Something like...

<%:HeaderText%>

Body:
Jon Skeet's solution is good if you allow multiple attributes of the same type to be declared on a property.  (AllowMultiple = true)

ex:

[Table(HeaderText="F. Name 1")]
[Table(HeaderText="F. Name 2")]
[Table(HeaderText="F. Name 3")]
public string FirstName { get; set; }

In your case, I would assume you only want one attribute allowed per property.  In which case, you can access the properties of the custom attribute via:

var tableAttribute= propertyInfo.GetCustomAttribute<TableAttribute>();
Console.Write(tableAttribute.HeaderText);
// Outputs "F. Name" when accessing FirstName
// Outputs "L. Name" when accessing LastName


问:
Dir pointers to access dir and files information with stat
I am a novice C programmer.
I am attempting to open a dir and read those files name and use stat to give me info on those files.Here I am just trying to see if they are Directories or files. Later Ill  get modified time and the size of the files etc. as of now I am only getting one level in, so the info for . and .. files. why?</p>

```<code>./check Dirc
whats in Dirc
two dir and two files
Program/ ProgramX/ test test2

Dir *ptrDir;
struct dirent *stDir;
struct stat buff;
if( ptrDir = opendir( argv[1] ) !=NULL){
    printf("%s\n",argv[1]);
    while( (stDir = readdir( ptrDir )) != NULL){
        if(stDir->d_name[0] !='.'){//i dont want the hidden files
            if( (stDir->d_name, &buff) == -1){ perror("stat broke");}
            printf("stDir name: %s\n", stDir->d_name);
            switch(buff.st_mode &s_IFMT){
                case S_IFDIR: printf("Directory\n"); break;
                case S_IFREG: printf("File\n"); break;
                default: print("default\n");
            }
        }
 }
}

OutPut:
Data:
stDir name: Program
stat broke: No such file or directory

Expected OutPut:
OutPut:
Data:
stDir name: Program
Directory
stDir name: ProgramX
Directory
stDir name: test
File
stDir name: test2
File
</code>```

答:
So I should have read the man pages better. Really what I was not doing was checking if a file found was not '.' in front, if it was not then take that file and build the path to place in stat. </p>

```<code>while ( (stDir = readdir(pDir)) != NULL) {
            char * ePath =  malloc(strlen(Data));
            strcpy(ePath,Data);
            strcat(ePath,stDir->d_name);
    if (oneFlag[1] == 'a'){
            printf("    %10s\n", stDir->d_name);
    } else if (oneFlag[1] == 'l') {
        if (stDir->d_name[0] != '.') {
   //printf("ePath value %s \n",ePath);
            if( stat( ePath, &buff) == -1){   perror("perror-stat broke"); exit(-1);  }....
</code>```

Body:
I am a novice C programmer.
I am attempting to open a dir and read those files name and use stat to give me info on those files.Here I am just trying to see if they are Directories or files. Later Ill  get modified time and the size of the files etc. as of now I am only getting one level in, so the info for . and .. files. why?

./check Dirc
whats in Dirc
two dir and two files
Program/ ProgramX/ test test2

Dir *ptrDir;
struct dirent *stDir;
struct stat buff;
if( ptrDir = opendir( argv[1] ) !=NULL){
    printf("%s\n",argv[1]);
    while( (stDir = readdir( ptrDir )) != NULL){
        if(stDir->d_name[0] !='.'){//i dont want the hidden files
            if( (stDir->d_name, &buff) == -1){ perror("stat broke");}
            printf("stDir name: %s\n", stDir->d_name);
            switch(buff.st_mode &s_IFMT){
                case S_IFDIR: printf("Directory\n"); break;
                case S_IFREG: printf("File\n"); break;
                default: print("default\n");
            }
        }
 }
}

OutPut:
Data:
stDir name: Program
stat broke: No such file or directory

Expected OutPut:
OutPut:
Data:
stDir name: Program
Directory
stDir name: ProgramX
Directory
stDir name: test
File
stDir name: test2
File

Body:
So I should have read the man pages better. Really what I was not doing was checking if a file found was not '.' in front, if it was not then take that file and build the path to place in stat.

while ( (stDir = readdir(pDir)) != NULL) {
            char * ePath =  malloc(strlen(Data));
            strcpy(ePath,Data);
            strcat(ePath,stDir->d_name);
    if (oneFlag[1] == 'a'){
            printf("    %10s\n", stDir->d_name);
    } else if (oneFlag[1] == 'l') {
        if (stDir->d_name[0] != '.') {
   //printf("ePath value %s \n",ePath);
            if( stat( ePath, &buff) == -1){   perror("perror-stat broke"); exit(-1);  }....


问:
Ordering a list of lists by lists len
I'm trying to order a list of lists by len size. But I'm getting a weird syntax error. I'm new to python so I'm probably doing something wrong

Relevant part of the code:

```<code> orderedpaths=[]
 if(len(paths)==1):
  orderedpaths=paths
 else:
  c=0
  while(len(paths)!=0):

   if(c==0):
    smallest=(len(paths[c])
    c+=1

   else:
    if(len[paths[c])<smallest):
     smallest=(len(paths[c]))
     orderedpaths.append(paths[c])
     del paths[c]
     c+=1

 return orderedpaths
</code>```

the error I'm getting is:

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "test.py", line 153
    c+=1
    ^
SyntaxError: invalid syntax
</code>```

I have no idea why.

答:
You can also use this pretty piece of code :) :

```<code>>>> a = [[1,2,3], [1,2,3,4], [1,2]]
>>> b = sorted(a, lambda x,y: 1 if len(x)>len(y) else -1 if len(x)<len(y) else 0)
>>> print b
[[1, 2], [1, 2, 3], [1, 2, 3, 4]]
</code>```

and swap 1 with -1 if you want another sorting order.

As commenters notice this code works only in python 2.x.
There is some prettier code which works in python 3.x as well:

```<code>>>> a = [[1,2,3], [1,2,3,4], [1,2]]
>>> b = sorted(a, key = len)
>>> print b
[[1, 2], [1, 2, 3], [1, 2, 3, 4]]
</code>```

Title: Ordering a list of lists by lists len

Body:
I'm trying to order a list of lists by len size. But I'm getting a weird syntax error. I'm new to python so I'm probably doing something wrong

Relevant part of the code:

 orderedpaths=[]
 if(len(paths)==1):
  orderedpaths=paths
 else:
  c=0
  while(len(paths)!=0):

   if(c==0):
    smallest=(len(paths[c])
    c+=1

   else:
    if(len[paths[c])<smallest):
     smallest=(len(paths[c]))
     orderedpaths.append(paths[c])
     del paths[c]
     c+=1

 return orderedpaths

the error I'm getting is:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "test.py", line 153
    c+=1
    ^
SyntaxError: invalid syntax

I have no idea why.

Body:
You can also use this pretty piece of code :) :

>>> a = [[1,2,3], [1,2,3,4], [1,2]]
>>> b = sorted(a, lambda x,y: 1 if len(x)>len(y) else -1 if len(x)<len(y) else 0)
>>> print b
[[1, 2], [1, 2, 3], [1, 2, 3, 4]]

and swap 1 with -1 if you want another sorting order.

As commenters notice this code works only in python 2.x.
There is some prettier code which works in python 3.x as well:

>>> a = [[1,2,3], [1,2,3,4], [1,2]]
>>> b = sorted(a, key = len)
>>> print b
[[1, 2], [1, 2, 3], [1, 2, 3, 4]]


问:
Unable to find valid certification path to requested target - error even after cert imported
I have a Java client trying to access a server with a self-signed certificate.

When I try to Post to the server, I get the following error:

unable to find valid certification path to requested target

Having done some research on the issue, I then did the following.

Saved my servers domain name as a root.cer file.

In my Glassfish server's JRE, I ran this:

```<code>keytool -import -alias example -keystore cacerts -file root.cer
</code>```

To check the cert was added to my cacert successfully, I did this:

```<code>keytool -list -v -keystore cacerts
</code>```

I can see the cert is present.

I then restarted Glassfish and retried the 'post'.

I am still getting the same error.

I have a feeling this is because my Glassfish is not actually reading the cacert file that I have amended but maybe some other one.

Have any of you had this issue and can push me in the right direction?

答:
I am working on a tutorial for REST web services at www.udemy.com (REST Java Web Services).  The example in the tutorial said that in order to have SSL, we must have a folder called "trust_store" in my eclipse "client" project that should contain a "key store" file (we had a "client" project to call the service, and "service" project that contained the REST web service - 2 projects in the same eclipse workspace, one the client, the other the service).  To keep things simple, they said to copy "keystore.jks" from the glassfish app server (glassfish\domains\domain1\config\keystore.jks) we are using and put it into this "trust_store" folder that they had me make in the client project.  That seems to make sense: the self-signed certs in the server's key_store would correspond to the certs in the client trust_store.  Now, doing this, I was getting the error that the original post mentions.  I have googled this and read that the error is due to the "keystore.jks" file on the client not containing a trusted/signed certificate, that the certificate it finds is self-signed.

To keep things clear, let me say that as I understand it, the "keystore.jks" contains self-signed certs, and the "cacerts.jks" file contains CA certs (signed by the CA).  The "keystore.jks" is the "keystore" and the "cacerts.jks" is the "trust store".  As "Bruno", a commenter, says above, "keystore.jks" is local, and "cacerts.jks" is for remote clients.

So, I said to myself, hey, glassfish also has the "cacerts.jks" file, which is glassfish's trust_store file.  cacerts.jsk is supposed to contain CA certificates.  And apparently I need my trust_store folder to contain a key store file that has at least one CA certificate.  So, I tried putting the "cacerts.jks" file in the "trust_store" folder I had made, on my client project, and changing the VM properties to point to "cacerts.jks" instead of "keystore.jks".  That got rid of the error.  I guess all it needed was a CA cert to work.

This may not be ideal for production, or even for development beyond just getting something to work.  For instance you could probably use "keytool" command to add CA certs to the "keystore.jks" file in the client.  But anyway hopefully this at least narrows down the possible scenarios that could be going on here to cause the error.

ALSO: my approach seemed to be useful for the client (server cert added to client trust_store), it looks like the comments above to resolve the original post are useful for the server (client cert added to server trust_store).  Cheers.

Eclipse project setup:

MyClientProject

src

test

JRE System Library

...

trust_store

---cacerts.jks
---keystore.jks

Snippet from MyClientProject.java file:

```<code>static {
  // Setup the trustStore location and password
  System.setProperty("javax.net.ssl.trustStore","trust_store/cacerts.jks");
  // comment out below line
  System.setProperty("javax.net.ssl.trustStore","trust_store/keystore.jks");
  System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
  //System.setProperty("javax.net.debug", "all");

  // for localhost testing only
  javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new javax.net.ssl.HostnameVerifier() {
        public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
          return hostname.equals("localhost");
        }

  });
}
</code>```

Body:
I have a Java client trying to access a server with a self-signed certificate.

When I try to Post to the server, I get the following error:

unable to find valid certification path to requested target

Having done some research on the issue, I then did the following.

Saved my servers domain name as a root.cer file.

In my Glassfish server's JRE, I ran this:

keytool -import -alias example -keystore cacerts -file root.cer

To check the cert was added to my cacert successfully, I did this:

keytool -list -v -keystore cacerts

I can see the cert is present.

I then restarted Glassfish and retried the 'post'.

I am still getting the same error.

I have a feeling this is because my Glassfish is not actually reading the cacert file that I have amended but maybe some other one.

Have any of you had this issue and can push me in the right direction?

Body:
I am working on a tutorial for REST web services at www.udemy.com (REST Java Web Services).  The example in the tutorial said that in order to have SSL, we must have a folder called "trust_store" in my eclipse "client" project that should contain a "key store" file (we had a "client" project to call the service, and "service" project that contained the REST web service - 2 projects in the same eclipse workspace, one the client, the other the service).  To keep things simple, they said to copy "keystore.jks" from the glassfish app server (glassfish\domains\domain1\config\keystore.jks) we are using and put it into this "trust_store" folder that they had me make in the client project.  That seems to make sense: the self-signed certs in the server's key_store would correspond to the certs in the client trust_store.  Now, doing this, I was getting the error that the original post mentions.  I have googled this and read that the error is due to the "keystore.jks" file on the client not containing a trusted/signed certificate, that the certificate it finds is self-signed.

To keep things clear, let me say that as I understand it, the "keystore.jks" contains self-signed certs, and the "cacerts.jks" file contains CA certs (signed by the CA).  The "keystore.jks" is the "keystore" and the "cacerts.jks" is the "trust store".  As "Bruno", a commenter, says above, "keystore.jks" is local, and "cacerts.jks" is for remote clients.

So, I said to myself, hey, glassfish also has the "cacerts.jks" file, which is glassfish's trust_store file.  cacerts.jsk is supposed to contain CA certificates.  And apparently I need my trust_store folder to contain a key store file that has at least one CA certificate.  So, I tried putting the "cacerts.jks" file in the "trust_store" folder I had made, on my client project, and changing the VM properties to point to "cacerts.jks" instead of "keystore.jks".  That got rid of the error.  I guess all it needed was a CA cert to work.

This may not be ideal for production, or even for development beyond just getting something to work.  For instance you could probably use "keytool" command to add CA certs to the "keystore.jks" file in the client.  But anyway hopefully this at least narrows down the possible scenarios that could be going on here to cause the error.

ALSO: my approach seemed to be useful for the client (server cert added to client trust_store), it looks like the comments above to resolve the original post are useful for the server (client cert added to server trust_store).  Cheers.

Eclipse project setup:

MyClientProject

src

test

JRE System Library

...

trust_store

---cacerts.jks
---keystore.jks

Snippet from MyClientProject.java file:

static {
  // Setup the trustStore location and password
  System.setProperty("javax.net.ssl.trustStore","trust_store/cacerts.jks");
  // comment out below line
  System.setProperty("javax.net.ssl.trustStore","trust_store/keystore.jks");
  System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
  //System.setProperty("javax.net.debug", "all");

  // for localhost testing only
  javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new javax.net.ssl.HostnameVerifier() {
        public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
          return hostname.equals("localhost");
        }

  });
}


问:
convert Decimal array to Double array
What's an efficient and hopefully elegant incantation to convert decimal[] to double[]?
I'm working with some fairly large arrays.

答:
You also can use and extension classes similar to this one

```<code>public static class ArrayExtension
{

   public static double[] ToDouble(this float[] arr) =>
                                    Array.ConvertAll(arr, x => (double)x);

}
</code>```

Then:

```<code>double[] doubleArr = decimalArr.ToDouble();
</code>```

Title: convert Decimal array to Double array

Body:
You also can use and extension classes similar to this one

public static class ArrayExtension
{

   public static double[] ToDouble(this float[] arr) =>
                                    Array.ConvertAll(arr, x => (double)x);

}

Then:

double[] doubleArr = decimalArr.ToDouble();


问:
thermometer class logic error
I'm trying to make a class that has a single constructor that accepts a temperature (in Celsius) as a double, and if the temperature is less than -273.15, it sets it to -273.15. It also calculates other temperatures for different units of measurement, but that's not important. For some reason, I'm getting a logic error that doesn't correct inputs less than -273.15 to -273.15.

```<code>public class TemperatureC
{

private double temperature;

public TemperatureC(double c)
{
    if (temperature < -273.15)
    {
        temperature = -273.15;
    }
    else
    {
        temperature = c;
    }
}

public TemperatureC()
{
    temperature = -273.15;
}

public double getC()
{
    return temperature;
}

public double getF()
{
    return ((temperature * 1.8) + 32);
}

public double getK()
{
    return (temperature + 273.15);
}

public void setC(double c)
{
    if (temperature >= -273.15)
    {
        temperature = c;
    }

}

}
</code>```

And this is what's using the class.

```<code>import java.util.Scanner;

public class TemperatureTester
{
public static void main(String[] args)
{
Scanner thermometer = new Scanner(System.in);
TemperatureC temp = new TemperatureC();

System.out.printf("Please enter the initial temperature:");
double intialTemp = thermometer.nextDouble();
temp.setC(intialTemp);

System.out.println("The current temperature in Celsius is:" + temp.getC());
System.out.println("The current temperature in Fahrenheit is:" + temp.getF());
System.out.println("The current temperature in Kelvin is:" + temp.getK());

System.out.printf("Please enter a new temperature:");
double secondTemp = thermometer.nextDouble();
temp.setC(secondTemp);

System.out.println("The current temperature in Celsius is:"+ temp.getC());
System.out.println("The current temperature in Fahrenheit is:"+ temp.getF());
System.out.println("The current temperature in Kelvin is:"+ temp.getK());

}
}
</code>```

And here is my faulty output:

```<code>Please enter the initial temperature:-900
The current temperature in Celsius is:-900.0
The current temperature in Fahrenheit is:-1588.0
The current temperature in Kelvin is:-626.85
Please enter a new temperature:-900
The current temperature in Celsius is:-900.0
The current temperature in Fahrenheit is:-1588.0
The current temperature in Kelvin is:-626.85
</code>```

It should correct inputs less than -273.15 to -273.15.

答:
Your issue is you are checking the default value of the constructor. Either set temperature to c first or check against c.

```<code>public TemperatureC(double c)
{

temperature = c;

if (temperature < -273.15)
{
    temperature = -273.15;
}
</code>```

that should work, as a side effect the else is no longer needed

Title: thermometer class logic error

Body:
I'm trying to make a class that has a single constructor that accepts a temperature (in Celsius) as a double, and if the temperature is less than -273.15, it sets it to -273.15. It also calculates other temperatures for different units of measurement, but that's not important. For some reason, I'm getting a logic error that doesn't correct inputs less than -273.15 to -273.15.

public class TemperatureC
{

private double temperature;

public TemperatureC(double c)
{
    if (temperature < -273.15)
    {
        temperature = -273.15;
    }
    else
    {
        temperature = c;
    }
}

public TemperatureC()
{
    temperature = -273.15;
}

public double getC()
{
    return temperature;
}

public double getF()
{
    return ((temperature * 1.8) + 32);
}

public double getK()
{
    return (temperature + 273.15);
}

public void setC(double c)
{
    if (temperature >= -273.15)
    {
        temperature = c;
    }

}

}

And this is what's using the class.

import java.util.Scanner;

public class TemperatureTester
{
public static void main(String[] args)
{
Scanner thermometer = new Scanner(System.in);
TemperatureC temp = new TemperatureC();

System.out.printf("Please enter the initial temperature:");
double intialTemp = thermometer.nextDouble();
temp.setC(intialTemp);

System.out.println("The current temperature in Celsius is:" + temp.getC());
System.out.println("The current temperature in Fahrenheit is:" + temp.getF());
System.out.println("The current temperature in Kelvin is:" + temp.getK());

System.out.printf("Please enter a new temperature:");
double secondTemp = thermometer.nextDouble();
temp.setC(secondTemp);

System.out.println("The current temperature in Celsius is:"+ temp.getC());
System.out.println("The current temperature in Fahrenheit is:"+ temp.getF());
System.out.println("The current temperature in Kelvin is:"+ temp.getK());

}
}

And here is my faulty output:

Please enter the initial temperature:-900
The current temperature in Celsius is:-900.0
The current temperature in Fahrenheit is:-1588.0
The current temperature in Kelvin is:-626.85
Please enter a new temperature:-900
The current temperature in Celsius is:-900.0
The current temperature in Fahrenheit is:-1588.0
The current temperature in Kelvin is:-626.85

It should correct inputs less than -273.15 to -273.15.

Body:
Your issue is you are checking the default value of the constructor. Either set temperature to c first or check against c.

public TemperatureC(double c)
{

temperature = c;

if (temperature < -273.15)
{
    temperature = -273.15;
}

that should work, as a side effect the else is no longer needed


问:
How to sort multiple ascending/descending columns in a data.frame: R
I am fairly new to R and perhaps don't know the best way to tackle this task but I have attempted a few various suggestions and none of them have allowed me to sort multiple columns in a data.frame.

Essentially for:

```<code>df = data.frame(matrix(c(-1,3,6,1,3,-5,2,4,9,-3,-1,-6,1,4,5), ncol=3)

       X1 X2 X3
   [1] -1 -5 -1
   [2]  3  2 -6
   [3]  6  4  1
   [4]  1  9  4
   [5]  3 -3  5
</code>```

I want to sort all of the columns independently from one another such that I could make all columns sort "descending", make half of the columns sort "ascending" and half "descending" etc.

```<code>       X1 X2 X3
   [1] -1 -5  5
   [2]  1 -3  4
   [3]  3  2  1
   [4]  3  4 -1
   [5]  6  9 -6
</code>```

The purpose of this is create column-wise gradients for use in heatmap.2 while also being able to control the mean, variance etc. of the columns. For example my data.frame would most likely be along the lines of:

```<code>df <- data.frame(matrix(runif(5200,0,1), ncol=10))
</code>```

However, when I attempt to use the sort or order command, I fail to be able to sort the columns independently of one another.

```<code>dfi <- df[order(df[[1]], decreasing =FALSE),]

        X1 X2 X3
    [1] -1 -5 -1
    [4]  1  9  4
    [2]  3  2 -6
    [5]  3 -3  5
    [3]  6  4  1

dfi <- df[order(df[[1]], df[[2]], decreasing =FALSE),]
        X1 X2 X3
    [1] -1 -5 -1
    [4]  1  9  4
    [2]  3  2 -6
    [5]  3 -3  5
    [3]  6  4  1
</code>```

I have attempted using for loops but to no success. I faced an inability to sort or order the columns independently (I don't have a reasonable for loop to show that someone could reproduce, and if this is the route to solve this problem, whoever answers will be much more knowledgable than I at the appropriate notation.)

Does anyone have any advice as to how to best go about this? I have been able to get the desired result by individually creating the columns, sorting them and then binding them together. However, since I need to make many many varying iterations of this (different variances, means, numbers of columns etc), that process is way too inefficient unless.

答:
You can also do this with mutate_at + sort:

```<code>library(dplyr)

df %>%
  mutate_at(1:2, funs(sort(.))) %>%
  mutate_at(3, funs(sort(., decreasing = TRUE)))
</code>```

Result:

```<code>  X1 X2 X3
1 -1 -5  5
2  1 -3  4
3  3  2  1
4  3  4 -1
5  6  9 -6
</code>```

You can also make it into a convenience function:

```<code>library(rlang)

arrange_indep = function(DF, asc = 1:ncol(DF), dsc=0){
  asc_quo = enquo(asc)
  dsc_quo = enquo(dsc)

  temp = DF %>%
    mutate_at(vars(!!asc_quo), funs(sort(.)))

  if(dsc_quo != quo(0)){
    temp = temp %>%
      mutate_at(vars(!!dsc_quo), funs(sort(., decreasing = TRUE)))
  }
  return(temp)
}
</code>```

Results & Usage:

1.) First two cols ascending, third col descending:

```<code>df %>%
  arrange_indep(1:2, 3)

  X1 X2 X3
1 -1 -5  5
2  1 -3  4
3  3  2  1
4  3  4 -1
5  6  9 -6
</code>```

2.) Same as 1.), but with non-standard evaluation:

```<code>df %>%
  arrange_indep(X1:X2, X3)

  X1 X2 X3
1 -1 -5  5
2  1 -3  4
3  3  2  1
4  3  4 -1
5  6  9 -6
</code>```

3.) First two cols ascending, keeping third col unsorted:

```<code>df %>%
  arrange_indep(1:2)

  X1 X2 X3
1 -1 -5 -1
2  1 -3 -6
3  3  2  1
4  3  4  4
5  6  9  5
</code>```

4.) First two cols descending, third col defaults to ascending:

```<code>df %>%
  arrange_indep(dsc=1:2)

  X1 X2 X3
1  6  9 -6
2  3  4 -1
3  3  2  1
4  1 -3  4
5 -1 -5  5
</code>```

5.) Using the default of arranging all cols by ascending order:

```<code>df %>%
  arrange_indep()

  X1 X2 X3
1 -1 -5 -6
2  1 -3 -1
3  3  2  1
4  3  4  4
5  6  9  5
</code>```

Body:
I am fairly new to R and perhaps don't know the best way to tackle this task but I have attempted a few various suggestions and none of them have allowed me to sort multiple columns in a data.frame.

Essentially for:

df = data.frame(matrix(c(-1,3,6,1,3,-5,2,4,9,-3,-1,-6,1,4,5), ncol=3)

       X1 X2 X3
   [1] -1 -5 -1
   [2]  3  2 -6
   [3]  6  4  1
   [4]  1  9  4
   [5]  3 -3  5

I want to sort all of the columns independently from one another such that I could make all columns sort "descending", make half of the columns sort "ascending" and half "descending" etc.

       X1 X2 X3
   [1] -1 -5  5
   [2]  1 -3  4
   [3]  3  2  1
   [4]  3  4 -1
   [5]  6  9 -6

The purpose of this is create column-wise gradients for use in heatmap.2 while also being able to control the mean, variance etc. of the columns. For example my data.frame would most likely be along the lines of:

df <- data.frame(matrix(runif(5200,0,1), ncol=10))

However, when I attempt to use the sort or order command, I fail to be able to sort the columns independently of one another.

dfi <- df[order(df[[1]], decreasing =FALSE),]

        X1 X2 X3
    [1] -1 -5 -1
    [4]  1  9  4
    [2]  3  2 -6
    [5]  3 -3  5
    [3]  6  4  1

dfi <- df[order(df[[1]], df[[2]], decreasing =FALSE),]
        X1 X2 X3
    [1] -1 -5 -1
    [4]  1  9  4
    [2]  3  2 -6
    [5]  3 -3  5
    [3]  6  4  1

I have attempted using for loops but to no success. I faced an inability to sort or order the columns independently (I don't have a reasonable for loop to show that someone could reproduce, and if this is the route to solve this problem, whoever answers will be much more knowledgable than I at the appropriate notation.)

Does anyone have any advice as to how to best go about this? I have been able to get the desired result by individually creating the columns, sorting them and then binding them together. However, since I need to make many many varying iterations of this (different variances, means, numbers of columns etc), that process is way too inefficient unless.

Body:
You can also do this with mutate_at + sort:

library(dplyr)

df %>%
  mutate_at(1:2, funs(sort(.))) %>%
  mutate_at(3, funs(sort(., decreasing = TRUE)))

Result:

  X1 X2 X3
1 -1 -5  5
2  1 -3  4
3  3  2  1
4  3  4 -1
5  6  9 -6

You can also make it into a convenience function:

library(rlang)

arrange_indep = function(DF, asc = 1:ncol(DF), dsc=0){
  asc_quo = enquo(asc)
  dsc_quo = enquo(dsc)

  temp = DF %>%
    mutate_at(vars(!!asc_quo), funs(sort(.)))

  if(dsc_quo != quo(0)){
    temp = temp %>%
      mutate_at(vars(!!dsc_quo), funs(sort(., decreasing = TRUE)))
  }
  return(temp)
}

Results & Usage:

1.) First two cols ascending, third col descending:

df %>%
  arrange_indep(1:2, 3)

  X1 X2 X3
1 -1 -5  5
2  1 -3  4
3  3  2  1
4  3  4 -1
5  6  9 -6

2.) Same as 1.), but with non-standard evaluation:

df %>%
  arrange_indep(X1:X2, X3)

  X1 X2 X3
1 -1 -5  5
2  1 -3  4
3  3  2  1
4  3  4 -1
5  6  9 -6

3.) First two cols ascending, keeping third col unsorted:

df %>%
  arrange_indep(1:2)

  X1 X2 X3
1 -1 -5 -1
2  1 -3 -6
3  3  2  1
4  3  4  4
5  6  9  5

4.) First two cols descending, third col defaults to ascending:

df %>%
  arrange_indep(dsc=1:2)

  X1 X2 X3
1  6  9 -6
2  3  4 -1
3  3  2  1
4  1 -3  4
5 -1 -5  5

5.) Using the default of arranging all cols by ascending order:

df %>%
  arrange_indep()

  X1 X2 X3
1 -1 -5 -6
2  1 -3 -1
3  3  2  1
4  3  4  4
5  6  9  5


问:
How would you count occurrences of a string (actually a char) within a string?
I am doing something where I realised I wanted to count how many /s I could find in a string, and then it struck me, that there were several ways to do it, but couldn't decide on what the best (or easiest) was.

At the moment I'm going with something like:

```<code>string source = "/once/upon/a/time/";
int count = source.Length - source.Replace("/", "").Length;
</code>```

But I don't like it at all, any takers?

I don't really want to dig out RegEx for this, do I?

I know my string is going to have the term I'm searching for, so you can assume that...

Of course for strings where length > 1,

```<code>string haystack = "/once/upon/a/time";
string needle = "/";
int needleCount = ( haystack.Length - haystack.Replace(needle,"").Length ) / needle.Length;
</code>```

答:
For the case of a string delimiter (not for the char case, as the subject says):

string source = "@@@once@@@upon@@@a@@@time@@@";

int count = source.Split(new[] { "@@@" }, StringSplitOptions.RemoveEmptyEntries).Length - 1;

The poster's original source value's ("/once/upon/a/time/") natural delimiter is a char '/' and responses do explain source.Split(char[]) option though...

Body:
I am doing something where I realised I wanted to count how many /s I could find in a string, and then it struck me, that there were several ways to do it, but couldn't decide on what the best (or easiest) was.

At the moment I'm going with something like:

string source = "/once/upon/a/time/";
int count = source.Length - source.Replace("/", "").Length;

But I don't like it at all, any takers?

I don't really want to dig out RegEx for this, do I?

I know my string is going to have the term I'm searching for, so you can assume that...

Of course for strings where length > 1,

string haystack = "/once/upon/a/time";
string needle = "/";
int needleCount = ( haystack.Length - haystack.Replace(needle,"").Length ) / needle.Length;


问:
How can I forward a message back to MessageReceived when I've called context.Wait in a LuisDialog intent handler?
I am building a small bot, which is working out nicely, but I am facing one flow issue that I just can't seem to get out of. I use a LuisDialog that interprets the user's message. Within a certain intent handler method, I display a carousel with a 'Unsubscribe' button in the panel, and call context.Wait(Uitschrijven) to handle the user's selection from the carousel.

This means that the next incoming message will hit this method:

```<code>private async Task Uitschrijven(IDialogContext context,IAwaitable<IMessageActivity> result)
{
    ...
}
</code>```

In this method, I'm expecting the user to have clicked a button from the carousel, which will send a message formatted something like "id:3". Of course, the user can just type some other new message rather than continuing this flow. The problem is that if they do, I that next message is received by my 'Uitschrijven' method, where it won't be handled correctly. How can I send it back to be re-interpreted by the LuisDialog, so that the correct intent is matched?

Ideally I would like to forward the message again to my MessageReceived function from my LuisDialog.

However, the Forward() method expect a resumeafter method, which I don't need.
There's also EndConversation, but it just ends the conversation without interpreting.

Does anyone know how to ensure that these new messages will be processed by the MessageReceived method so the user is able to continue in this scenario?

答:
My understanding is that you're receiving the user's response in a method like private async Task Uitschrijven(IDialogContext context,IAwaitable result) which exists within your Luis dialog, and if the incoming message came from your button, you want to process it, but if the message is something else, you want it to go back to the MessageReceived method of the same dialog. If that's correct, you can simply do something like this:

```<code>private async Task Uitschrijven(IDialogContext context,IAwaitable result)
{
    var message = await result;
    if( /* message matches what you're expecting from button */)
    {
        // process message from button
    }
    else
    {
        // simply pass the IAwaitable to MessageReceived
        await MessageReceived(context, result);
    }
}
</code>```

If I'm understanding the scenario correctly, this is likely better than the other suggestion of using a Scorable, since with a scorable, every single message would run through the Unsubscribe scorable, and this logic may be able to be triggered in places where it's not appropriate.

If you feel that that's not an accurate understanding of your requirements, please feel free to edit your question with more clarifying details!

Body:
I am building a small bot, which is working out nicely, but I am facing one flow issue that I just can't seem to get out of. I use a LuisDialog that interprets the user's message. Within a certain intent handler method, I display a carousel with a 'Unsubscribe' button in the panel, and call context.Wait(Uitschrijven) to handle the user's selection from the carousel.

This means that the next incoming message will hit this method:

private async Task Uitschrijven(IDialogContext context,IAwaitable<IMessageActivity> result)
{
    ...
}

In this method, I'm expecting the user to have clicked a button from the carousel, which will send a message formatted something like "id:3". Of course, the user can just type some other new message rather than continuing this flow. The problem is that if they do, I that next message is received by my 'Uitschrijven' method, where it won't be handled correctly. How can I send it back to be re-interpreted by the LuisDialog, so that the correct intent is matched?

Ideally I would like to forward the message again to my MessageReceived function from my LuisDialog.

However, the Forward() method expect a resumeafter method, which I don't need.
There's also EndConversation, but it just ends the conversation without interpreting.

Does anyone know how to ensure that these new messages will be processed by the MessageReceived method so the user is able to continue in this scenario?

Body:
My understanding is that you're receiving the user's response in a method like private async Task Uitschrijven(IDialogContext context,IAwaitable result) which exists within your Luis dialog, and if the incoming message came from your button, you want to process it, but if the message is something else, you want it to go back to the MessageReceived method of the same dialog. If that's correct, you can simply do something like this:

private async Task Uitschrijven(IDialogContext context,IAwaitable result)
{
    var message = await result;
    if( /* message matches what you're expecting from button */)
    {
        // process message from button
    }
    else
    {
        // simply pass the IAwaitable to MessageReceived
        await MessageReceived(context, result);
    }
}

If I'm understanding the scenario correctly, this is likely better than the other suggestion of using a Scorable, since with a scorable, every single message would run through the Unsubscribe scorable, and this logic may be able to be triggered in places where it's not appropriate.

If you feel that that's not an accurate understanding of your requirements, please feel free to edit your question with more clarifying details!


问:
Date and sum of name grouping in R
So this is the dataframe I'm working with

```<code>CAND_NAME   TRANSACTION_DT   TRANSACTION_AMT
K            10312017            100
K            11032017            500
K            11032017            100
K            11102017            200
K            11112017            200
R            11032016            200
R            11032017            100
R            11042017            500
</code>```

I wanted to group the TRANSACTION_DT into 7 days by candidate. In other words, 10292017 (or 10/29/2017), 10302017, 10312017, 11012017, 11022017, 11032017, and 11042017 would be grouped and the transaction amount for that group will be summed up.

I wanted this to give:

```<code>CAND_NAME   TRANSACTION_WK_START   TRANSACTION_AMT
K            10292017            700
K            11052017            400
R            10302016            200
R            10292017            600
</code>```

Note for R, the date 11032016 and 11032017 are different, and I don't want them to be grouped together.

So far I have

```<code>df.new <- df %>%
  group_by(TRANSACTION_DT,CAND_NAME) %>%
  summarize(TRANSACTION_AMT = sum(TRANSACTION_AMT))
</code>```

答:
Here is a potential solution.  Covert Transaction_dt to a date and then create a sequence of weeks.  In this case I am using the earliest date in the data.  This might be a problem since it may not start at the beginning of the week. If so, it would be a matter of defining the sequence to start from a known acceptable beginning. Then it is just a matter of cut and grouping.</p>

```<code>df<-structure(list(CAND_NAME = structure(c(1L, 1L, 1L, 1L, 1L, 2L,
            2L, 2L), .Label = c("K", "R"), class = "factor"), TRANSACTION_DT = c(10312017L,
             11032017L, 11032017L, 11102017L, 11112017L, 11032016L, 11032017L,
             11042017L), TRANSACTION_AMT = c(100L, 500L, 100L, 200L, 200L,
              200L, 100L, 500L)), .Names = c("CAND_NAME", "TRANSACTION_DT",
              "TRANSACTION_AMT"), class = "data.frame", row.names = c(NA, -8L))

#convert to dates
df$date<-as.Date(as.character(df$TRANSACTION_DT), format="%m%d%Y")
#define the breaks
breaks<-seq(from=min(df$date), to=max(df$date)+7, by = "week")
#define the cut points
df$breaks<-cut(df$date, breaks)

library(dplyr)
df %>%
  group_by(breaks,CAND_NAME) %>%
  summarize(TRANSACTION_AMT = sum(TRANSACTION_AMT))

#     breaks CAND_NAME TRANSACTION_AMT
#      <fctr>    <fctr>           <int>
#1 2016-11-03         R             200
#2 2017-10-26         K             100
#3 2017-11-02         K             600
#4 2017-11-02         R             600
#5 2017-11-09         K             400
</code>```

Title: Date and sum of name grouping in R

Body:
So this is the dataframe I'm working with

CAND_NAME   TRANSACTION_DT   TRANSACTION_AMT
K            10312017            100
K            11032017            500
K            11032017            100
K            11102017            200
K            11112017            200
R            11032016            200
R            11032017            100
R            11042017            500

I wanted to group the TRANSACTION_DT into 7 days by candidate. In other words, 10292017 (or 10/29/2017), 10302017, 10312017, 11012017, 11022017, 11032017, and 11042017 would be grouped and the transaction amount for that group will be summed up.

I wanted this to give:

CAND_NAME   TRANSACTION_WK_START   TRANSACTION_AMT
K            10292017            700
K            11052017            400
R            10302016            200
R            10292017            600

Note for R, the date 11032016 and 11032017 are different, and I don't want them to be grouped together.

So far I have

df.new <- df %>%
  group_by(TRANSACTION_DT,CAND_NAME) %>%
  summarize(TRANSACTION_AMT = sum(TRANSACTION_AMT))

Body:
Here is a potential solution.  Covert Transaction_dt to a date and then create a sequence of weeks.  In this case I am using the earliest date in the data.  This might be a problem since it may not start at the beginning of the week. If so, it would be a matter of defining the sequence to start from a known acceptable beginning. Then it is just a matter of cut and grouping.

df<-structure(list(CAND_NAME = structure(c(1L, 1L, 1L, 1L, 1L, 2L,
            2L, 2L), .Label = c("K", "R"), class = "factor"), TRANSACTION_DT = c(10312017L,
             11032017L, 11032017L, 11102017L, 11112017L, 11032016L, 11032017L,
             11042017L), TRANSACTION_AMT = c(100L, 500L, 100L, 200L, 200L,
              200L, 100L, 500L)), .Names = c("CAND_NAME", "TRANSACTION_DT",
              "TRANSACTION_AMT"), class = "data.frame", row.names = c(NA, -8L))

#convert to dates
df$date<-as.Date(as.character(df$TRANSACTION_DT), format="%m%d%Y")
#define the breaks
breaks<-seq(from=min(df$date), to=max(df$date)+7, by = "week")
#define the cut points
df$breaks<-cut(df$date, breaks)

library(dplyr)
df %>%
  group_by(breaks,CAND_NAME) %>%
  summarize(TRANSACTION_AMT = sum(TRANSACTION_AMT))

#     breaks CAND_NAME TRANSACTION_AMT
#      <fctr>    <fctr>           <int>
#1 2016-11-03         R             200
#2 2017-10-26         K             100
#3 2017-11-02         K             600
#4 2017-11-02         R             600
#5 2017-11-09         K             400


问:
Converting a list of strings to a list of int for machine learning
I have a table with a column corresponding to the education level : "phd", "undergrad", etc.

I would like to change those features to 0, 1, 2..... in order to use the data as an input of a machine learning algorithm.

Is there a way in Python to automatically map those string features to integers?

答:
It's called a dict (dictionary).  Something like this:

```<code>edu_level = {
    "phd": 0;
    "master": 1;
    "undergrad":2,
    ...
}
</code>```

Look up how to work with dictionaries, perhaps using keys "Python dictionary tutorial".

Body:
It's called a dict (dictionary).  Something like this:

edu_level = {
    "phd": 0;
    "master": 1;
    "undergrad":2,
    ...
}

Look up how to work with dictionaries, perhaps using keys "Python dictionary tutorial".


问:
Make HTML5 video poster be same size as video itself
Does anyone know how to resize the HTML5 video poster such that it fits the exact dimensions of the video itself?

here's a jsfiddle which shows the problem: http://jsfiddle.net/zPacg/7/

here's that code:

HTML:

```<code><video controls width="100%" height="100%"  poster="http://www.wpclipart.com/blanks/buttons/glossy_buttons/glossy_button_blank_orange_rectangle.png">
  <source src="http://demo.inwebson.com/html5-video/iceage4.mp4" type="video/mp4" />
  <source src="http://demo.inwebson.com/html5-video/iceage4.ogg" type="video/ogg" />
  <source src="http://demo.inwebson.com/html5-video/iceage4.webm" type="video/webm" />
</video>
</code>```

CSS:

```<code>video{
border:1px solid red;
}
</code>```

Notice that the orange rectangle doesn't scale to the red border of the video.

Also, just adding the CSS below doesn't work either as it rescales the video along with the poster:

```<code>video[poster]{
height:100%;
width:100%;
}
</code>```

答:
<video src="videofile.webm" poster="posterimage.jpg" controls preload="metadata">
    Sorry, your browser doesn't support embedded videos.
</video>
```

<p><strong>Cover</strong></p>

<pre class="lang-css prettyprint-override"><code>video{
   object-fit: cover; /*to cover all the box*/
}
</code>```

Fill

video{
   object-fit: fill; /*to add black content at top and bottom*/
   object-position: 0 -14px; /* to center our image*/
}
```

Note that the video controls are over our image, so our image is not completly showed. If you are using object-fit cover, edit your image on a visual app as photoshop and add a margin bottom content.

Body:
Does anyone know how to resize the HTML5 video poster such that it fits the exact dimensions of the video itself?

here's a jsfiddle which shows the problem: http://jsfiddle.net/zPacg/7/

here's that code:

HTML:

<video controls width="100%" height="100%"  poster="http://www.wpclipart.com/blanks/buttons/glossy_buttons/glossy_button_blank_orange_rectangle.png">
  <source src="http://demo.inwebson.com/html5-video/iceage4.mp4" type="video/mp4" />
  <source src="http://demo.inwebson.com/html5-video/iceage4.ogg" type="video/ogg" />
  <source src="http://demo.inwebson.com/html5-video/iceage4.webm" type="video/webm" />
</video>

CSS:

video{
border:1px solid red;
}

Notice that the orange rectangle doesn't scale to the red border of the video.

Also, just adding the CSS below doesn't work either as it rescales the video along with the poster:

video[poster]{
height:100%;
width:100%;
}

Body:
<video src="videofile.webm" poster="posterimage.jpg" controls preload="metadata">
    Sorry, your browser doesn't support embedded videos.
</video>

Cover

video{
   object-fit: cover; /*to cover all the box*/
}

Fill

video{
   object-fit: fill; /*to add black content at top and bottom*/
   object-position: 0 -14px; /* to center our image*/
}

Note that the video controls are over our image, so our image is not completly showed. If you are using object-fit cover, edit your image on a visual app as photoshop and add a margin bottom content.


问:
Get current position in stream from net/html tokenizer
I'm trying to figure out if there's a way to get the current character position of a tag using the golang.org/x/net/html tokenizer library?

Simplified code looks like:

```<code>func LookForForm(body string) {
    reader := strings.NewReader(body)
    tokenizer := html.NewTokenizer(reader)
    idx := 0
    lastIdx := 0
    for {
        token := tokenizer.Next()
        lastIdx = idx
        idx = int(reader.Size()) - int(reader.Len())
        switch token {
        case html.ErrorToken:
            return
        case html.StartTagToken:
            t := tokenizer.Token()
            tagName := strings.ToLower(t.Data)
            if tagName == "form" {
                fmt.Printf("found at form at %d\n", lastIdx)
                return
            }
        }
    }
}
</code>```

This doesn't work (I think) because reader is not reading character-by-character but by chunks so my calculation of Size - Len is invalid.  tokenizer maintains two private span structs ( https://github.com/golang/net/blob/master/html/token.go line 147) but I am unaware of how to access them.

One possible solution that just occurred to me is to make a "reader" that only reads a single character at a time so my Size and Len calculations are always correct. But, that seems like a hack and any suggestions would be appreciated.

答:
A non-buffering reader ended up working ok for me. The implementation of the reader looks something like:

```<code>package rule

import (
    "errors"
    "io"
    "unicode/utf8"
)

type Reader struct {
    s        string
    i        int64
    z        int64
    prevRune int64 // index of the previously read rune or -1
}

func (r *Reader) String() string {
    return r.s
}

func (r *Reader) Len() int {
    if r.i >= r.z {
        return 0
    }
    return int(r.z - r.i)
}

func (r *Reader) Size() int64 {
    return r.z
}

func (r *Reader) Pos() int64 {
    return r.i
}

func (r *Reader) Read(b []byte) (int, error) {
    if r.i >= r.z {
        return 0, io.EOF
     }

    r.prevRune = -1
    b[0] = r.s[r.i]
    r.i += 1
    return 1, nil
}
</code>```

Then the loop for the tokenizer is fairly easy to calculate:

```<code>    reader := NewReader(body)
    tokenizer := html.NewTokenizer(reader)
    idx := 0
    lastIdx := 0
tokenLoop:
    for {
        token := tokenizer.Next()
        switch token {
        case html.ErrorToken:
            break tokenLoop
        case html.EndTagToken, html.TextToken, html.CommentToken, html.SelfClosingTagToken:
            lastIdx = int(reader.Pos())
        case html.StartTagToken:
            t := tokenizer.Token()
            tagName := strings.ToLower(t.Data)
            idx = int(reader.Pos())
            if tagName == "form" {
                fmt.Printf("found at form at %d\n", lastIdx)
                return
            }
        }
    }
</code>```

Body:
I'm trying to figure out if there's a way to get the current character position of a tag using the golang.org/x/net/html tokenizer library?

Simplified code looks like:

func LookForForm(body string) {
    reader := strings.NewReader(body)
    tokenizer := html.NewTokenizer(reader)
    idx := 0
    lastIdx := 0
    for {
        token := tokenizer.Next()
        lastIdx = idx
        idx = int(reader.Size()) - int(reader.Len())
        switch token {
        case html.ErrorToken:
            return
        case html.StartTagToken:
            t := tokenizer.Token()
            tagName := strings.ToLower(t.Data)
            if tagName == "form" {
                fmt.Printf("found at form at %d\n", lastIdx)
                return
            }
        }
    }
}

This doesn't work (I think) because reader is not reading character-by-character but by chunks so my calculation of Size - Len is invalid.  tokenizer maintains two private span structs ( https://github.com/golang/net/blob/master/html/token.go line 147) but I am unaware of how to access them.

One possible solution that just occurred to me is to make a "reader" that only reads a single character at a time so my Size and Len calculations are always correct. But, that seems like a hack and any suggestions would be appreciated.

Body:
A non-buffering reader ended up working ok for me. The implementation of the reader looks something like:

package rule

import (
    "errors"
    "io"
    "unicode/utf8"
)

type Reader struct {
    s        string
    i        int64
    z        int64
    prevRune int64 // index of the previously read rune or -1
}

func (r *Reader) String() string {
    return r.s
}

func (r *Reader) Len() int {
    if r.i >= r.z {
        return 0
    }
    return int(r.z - r.i)
}

func (r *Reader) Size() int64 {
    return r.z
}

func (r *Reader) Pos() int64 {
    return r.i
}

func (r *Reader) Read(b []byte) (int, error) {
    if r.i >= r.z {
        return 0, io.EOF
     }

    r.prevRune = -1
    b[0] = r.s[r.i]
    r.i += 1
    return 1, nil
}

Then the loop for the tokenizer is fairly easy to calculate:

    reader := NewReader(body)
    tokenizer := html.NewTokenizer(reader)
    idx := 0
    lastIdx := 0
tokenLoop:
    for {
        token := tokenizer.Next()
        switch token {
        case html.ErrorToken:
            break tokenLoop
        case html.EndTagToken, html.TextToken, html.CommentToken, html.SelfClosingTagToken:
            lastIdx = int(reader.Pos())
        case html.StartTagToken:
            t := tokenizer.Token()
            tagName := strings.ToLower(t.Data)
            idx = int(reader.Pos())
            if tagName == "form" {
                fmt.Printf("found at form at %d\n", lastIdx)
                return
            }
        }
    }


问:
how to avoid losing the completed fields in a view
I have 2 controllers with 2 views. view A contains several input text, checkbox, text fields etc. Clicking on a  on this form redirects me to view B. view B has a return to view  A.

How can I do so that when I return to view A, I do not miss the information on the form I previously filled out?
I'm not using ng-model because I just want to know how not to lose sight data. I do not think this matters or does it?

I understand the ngStorage and ng-model. but I want to know if there is any easier solution than saving the values field by field ?. something like cache: true

```<code>var myApp = angular.module('myApp', ['ui.router'])
.config(function ($stateProvider) {

    $stateProvider.state('A', {
        url: "/A",
        template: '<input type="text"><br><input type="checkbox"><br><input type="radio"><br><a ui-sref="B">NEXT</a>',
        controller: function ($scope) {
            console.log("A");
        }
    }).state('B', {
        url: "/B",
        template: '<a ui-sref="A">BACK</a>',
        controller: function ($scope) {
            console.log("B");
        }
    });
})

.controller('MainCtrl', function ($scope, $state) {
 $state.go("A");
});
</code>```

http://jsfiddle.net/rw645c89/

答:
why don't you use service to preserve data between states?

http://jsfiddle.net/b41uo73t/

```<code>var myApp = angular.module('myApp', ['ui.router'])
.config(function ($stateProvider) {

$stateProvider.state('A', {
    url: "/A",
    template: '<input type="text" ng-model="mainService.inputValue"><br><input type="checkbox" ng-model="mainService.checkboxValue_1"><br><input type="radio" ng-model="mainService.checkboxValue_2"><br><a ui-sref="B">NEXT</a>',
    controller: function ($scope, MainService) {
        console.log("A");
        $scope.mainService = MainService;
    }
}).state('B', {
    url: "/B",
    template: '<a ui-sref="A">BACK</a>',
    controller: function ($scope) {
        console.log("B");
    }
});
})

.controller('MainCtrl', function ($scope, $state) {
 $state.go("A");
})

.service('MainService', function() {
 this.inputValue = "";
  this.checkboxValue_1 = false;
    this.checkboxValue_2 = false;

});
</code>```

Body:
I have 2 controllers with 2 views. view A contains several input text, checkbox, text fields etc. Clicking on a  on this form redirects me to view B. view B has a return to view  A.

How can I do so that when I return to view A, I do not miss the information on the form I previously filled out?
I'm not using ng-model because I just want to know how not to lose sight data. I do not think this matters or does it?

I understand the ngStorage and ng-model. but I want to know if there is any easier solution than saving the values field by field ?. something like cache: true

var myApp = angular.module('myApp', ['ui.router'])
.config(function ($stateProvider) {

    $stateProvider.state('A', {
        url: "/A",
        template: '<input type="text">
<input type="checkbox">
<input type="radio">
NEXT',
        controller: function ($scope) {
            console.log("A");
        }
    }).state('B', {
        url: "/B",
        template: 'BACK',
        controller: function ($scope) {
            console.log("B");
        }
    });
})

.controller('MainCtrl', function ($scope, $state) {
 $state.go("A");
});

http://jsfiddle.net/rw645c89/

Body:
why don't you use service to preserve data between states?

http://jsfiddle.net/b41uo73t/

var myApp = angular.module('myApp', ['ui.router'])
.config(function ($stateProvider) {

$stateProvider.state('A', {
    url: "/A",
    template: '<input type="text" ng-model="mainService.inputValue"><br><input type="checkbox" ng-model="mainService.checkboxValue_1"><br><input type="radio" ng-model="mainService.checkboxValue_2"><br><a ui-sref="B">NEXT</a>',
    controller: function ($scope, MainService) {
        console.log("A");
        $scope.mainService = MainService;
    }
}).state('B', {
    url: "/B",
    template: '<a ui-sref="A">BACK</a>',
    controller: function ($scope) {
        console.log("B");
    }
});
})

.controller('MainCtrl', function ($scope, $state) {
 $state.go("A");
})

.service('MainService', function() {
 this.inputValue = "";
  this.checkboxValue_1 = false;
    this.checkboxValue_2 = false;

});


问:
How to say Hystrix not to trigger fallback for some of the exceptions in Hystrix command
We were using the Hystrix functionality by directly extending the HystrixCommand class. But for some of the business exceptions, Hystrix's fallback method is being triggered.

I don't want to trigger the Hystrix fallback for some of the business specific exceptions. How I can achieve it without annotation based?

答:
If you wrap your logic in a try/catch and re-throw any exceptions in a HystrixBadRequestException then it will not trigger the fallback.

```<code>@Override
protected Object run() throws Exception {
    try {
        return //call goes here
    }
    catch (Throwable e) {
        //We wrap any exceptions in a HystrixBadRequestException because this way any other errors will not
        //trip the short circuit
        throw new HystrixBadRequestException("Exception thrown hystrix call", e);
    }
}
</code>```

From the docs:
http://netflix.github.io/Hystrix/javadoc/com/netflix/hystrix/exception/HystrixBadRequestException.html

An exception representing an error with provided arguments or state rather than an execution failure.
Unlike all other exceptions thrown by a HystrixCommand this will not trigger fallback, not count against failure metrics and thus not trigger the circuit breaker.

NOTE: This should only be used when an error is due to user input such as IllegalArgumentException otherwise it defeats the purpose of fault-tolerance and fallback behavior.

Body:
If you wrap your logic in a try/catch and re-throw any exceptions in a HystrixBadRequestException then it will not trigger the fallback.

@Override
protected Object run() throws Exception {
    try {
        return //call goes here
    }
    catch (Throwable e) {
        //We wrap any exceptions in a HystrixBadRequestException because this way any other errors will not
        //trip the short circuit
        throw new HystrixBadRequestException("Exception thrown hystrix call", e);
    }
}

From the docs:
http://netflix.github.io/Hystrix/javadoc/com/netflix/hystrix/exception/HystrixBadRequestException.html

An exception representing an error with provided arguments or state rather than an execution failure.
Unlike all other exceptions thrown by a HystrixCommand this will not trigger fallback, not count against failure metrics and thus not trigger the circuit breaker.

NOTE: This should only be used when an error is due to user input such as IllegalArgumentException otherwise it defeats the purpose of fault-tolerance and fallback behavior.


问:
Create a "continuous" matrix operator
Following this previous question:
Add 0 or 1 in a df depending on conditions from another df

I have now a similar purpose but a bit different. I have df1 but with a third column "value":

```<code>file_name  loc                        num
rep1       chr1:62161618:62162663:-   3
rep2       chr1:62161618:62162669:-   5
...
</code>```

I would like to generate a df2 matrix with file_name as rows and loc as columns. Finally I want to fill the matrix df2 with the values from num and 0 for the rest, something like:

```<code>     chr1:62161618:62162663:-    chr1:62161618:62162669:-...
rep1           3                            0
rep2           0                            5
...
</code>```

Thanks!

Title: Create a "continuous" matrix operator

Body:
Following this previous question:
Add 0 or 1 in a df depending on conditions from another df

I have now a similar purpose but a bit different. I have df1 but with a third column "value":

file_name  loc                        num
rep1       chr1:62161618:62162663:-   3
rep2       chr1:62161618:62162669:-   5
...

I would like to generate a df2 matrix with file_name as rows and loc as columns. Finally I want to fill the matrix df2 with the values from num and 0 for the rest, something like:

     chr1:62161618:62162663:-    chr1:62161618:62162669:-...
rep1           3                            0
rep2           0                            5
...

Thanks!

Body:
Try tidyr's spread:

df <- data.frame(file_name = c("rep1", "rep2"),
           loc = c("chr1:62161618:62162663:-", "chr1:62161618:62162669:-"),
           num = c(3,5))

library(tidyr)
df <- spread(df, key = loc, value = num, fill = 0)
row.names(df) <- df$file_name
df <- df[,-1]

     chr1:62161618:62162663:- chr1:62161618:62162669:-
rep1                        3                        0
rep2                        0                        5


问:
Open android Gallery App from react native app
My application requires opening an image, stored locally in the document directories using the android gallery app.Is this possible in react native using linking.</p>

答: So my requirement was to download an image on a button click an then open the same image using the android gallery , I achieved the same using react-native-fetch-blob which facilitates both downloading a file and opening it with the corresponding apps. P.S: you could also open the gallery using linking, provided you have the content url rather than file url.</p>