问:
Get HTTP status 404 for /j_spring_security_check with GWT
I'm attempting to get Spring Security working, and failing utterly.  No matter what I try, I can't get j_spring_security_check to be valid.

Error:

HTTP Status 404 - /j_spring_security_check

  type Status report

  message /j_spring_security_check

  description The requested resource is not available.

Login.html file:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>My App</title>
    <link rel="shortcut icon" type="image/x-icon" href="img/favicon.ico">

    <form method = "post" action="/j_spring_security_check">
      Username:
      <input type = "text" name = "username" />

      Password:
      <input type = "password" name = "password" />

      <input type = "submit" value = "Login" />
    </form>

```

<p><code>web.xml</code>:</p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /META-INF/application*.xml
        </param-value>
    </context-param>

    <!-- Creates the Spring Container -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

  <!-- Servlets -->
  <servlet>
    <servlet-name>MyServlet</servlet-name>
    <servlet-class>com.me.portal.server.MyPortalServiceImpl</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/MyPortal/MyPortal</url-pattern>
  </servlet-mapping>

  <!-- Default page to serve -->
  <welcome-file-list>
    <welcome-file>Login.html</welcome-file>
  </welcome-file-list>

</web-app>
</code>```

application.security.xml:

<?xml version = "1.0" encoding = "UTF-8"?>
<beans:beans xmlns = "http://www.springframework.org/schema/security"
             xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
             xmlns:beans = "http://www.springframework.org/schema/beans"
             xmlns:util = "http://www.springframework.org/schema/util"
             xsi:schemaLocation = "http://www.springframework.org/schema/beans
                                 http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
                                 http://www.springframework.org/schema/util
                                 http://www.springframework.org/schema/util/spring-util-4.3.xsd
                                 http://www.springframework.org/schema/security
                                 http://www.springframework.org/schema/security/spring-security-3.2.xsd">

    <http auto-config = 'true' use-expressions = "false" entry-point-ref = "customAuthenticationEntryPoint">
        <intercept-url pattern = "/j_spring_security_check" access = "IS_AUTHENTICATED_ANONYMOUSLY"/>
        <intercept-url pattern = "/login" access = "IS_AUTHENTICATED_ANONYMOUSLY"/>
        <intercept-url pattern = "/Login.html" access = "IS_AUTHENTICATED_ANONYMOUSLY" />
        <intercept-url pattern = "/img/favicon.ico" access = "IS_AUTHENTICATED_ANONYMOUSLY" />
        <intercept-url pattern = "/**" access = "IS_AUTHENTICATED_FULLY" />
        <logout logout-success-url = "/Login.html" />
        <form-login login-page = "/Login.html" default-target-url = "/index.gwt.html" always-use-default-target = "true"
                    login-processing-url = "/j_spring_security_check" username-parameter = "username" password-parameter = "password"
                    authentication-success-handler-ref = "customAuthenticationSuccessHandler"
                    authentication-failure-handler-ref="customAuthenticationFailureHandler"/>

        <session-management invalid-session-url = "/Login.html"
                            session-authentication-error-url = "/Login.html"
                            session-fixation-protection = "newSession">
            <concurrency-control max-sessions = "1" error-if-maximum-exceeded = "false" />
        </session-management>
    </http>

    <ldap-server {Our settings} />

    <authentication-manager alias = "authenticationManager">
        <ldap-authentication-provider
                {Our LDAP Info}
        </ldap-authentication-provider>
    </authentication-manager>

    <beans:bean id = "customAuthenticationEntryPoint" class = "com.me.portal.server.security.CustomAuthenticationEntryPoint"/>

    <beans:bean id = "customAuthenticationSuccessHandler" class = "com.me.portal.server.security.CustomAuthenticationSuccessHandler"/>

    <beans:bean id = "customAuthenticationFailureHandler" class = "com.me.portal.server.security.CustomAuthenticationFailureHandler"/>

</beans:beans>
```

<p>Spring JARs used:</p>

```spring-aop-4.3.2.RELEASE.jar
spring-beans-4.3.2.RELEASE.jar
spring-context-4.3.2.RELEASE.jar
spring-core-4.3.2.RELEASE.jar
spring-expression-4.3.2.RELEASE.jar
spring-ldap-core-2.3.1.RELEASE.jar
spring-security-config-3.2.7.RELEASE.jar
spring-security-core-3.2.7.RELEASE.jar
spring-security-ldap-3.2.7.RELEASE.jar
spring-security-web-3.2.7.RELEASE.jar
spring-tx-4.3.2.RELEASE.jar
spring-web-4.3.2.RELEASE.jar
```

<p>As requested, Headers:
<img src="https://i.stack.imgur.com/25pax.png" alt="Headers for the failure"></p>

<p>Response:</p>

```<!DOCTYPE html>
<title>Apache Tomcat/8.0.22 - Error report</title>

HTTP Status 404 - /j_spring_security_check

type Status report

message /j_spring_security_check

description The requested resource is not available.

Apache Tomcat/8.0.22

```

答:
I don't know if this is a GWT problem, or a Tomcat problem, but the solution is here:

```<code><form method = "post" action="/MyPortal/j_spring_security_check">
</code>```

I had to add the path to "/MyPortal" in order for j_spring_security_check to be found.

Body:
I'm attempting to get Spring Security working, and failing utterly.  No matter what I try, I can't get j_spring_security_check to be valid.

Error:

HTTP Status 404 - /j_spring_security_check

  type Status report

  message /j_spring_security_check

  description The requested resource is not available.

Login.html file:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>My App</title>
    <link rel="shortcut icon" type="image/x-icon" href="img/favicon.ico">

    <form method = "post" action="/j_spring_security_check">
      Username:
      <input type = "text" name = "username" />

      Password:
      <input type = "password" name = "password" />

      <input type = "submit" value = "Login" />
    </form>

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /META-INF/application*.xml
        </param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

  <servlet>
    <servlet-name>MyServlet</servlet-name>
    <servlet-class>com.me.portal.server.MyPortalServiceImpl</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/MyPortal/MyPortal</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file>Login.html</welcome-file>
  </welcome-file-list>

</web-app>

application.security.xml:

<?xml version = "1.0" encoding = "UTF-8"?>
<beans:beans xmlns = "http://www.springframework.org/schema/security"
             xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
             xmlns:beans = "http://www.springframework.org/schema/beans"
             xmlns:util = "http://www.springframework.org/schema/util"
             xsi:schemaLocation = "http://www.springframework.org/schema/beans
                                 http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
                                 http://www.springframework.org/schema/util
                                 http://www.springframework.org/schema/util/spring-util-4.3.xsd
                                 http://www.springframework.org/schema/security
                                 http://www.springframework.org/schema/security/spring-security-3.2.xsd">

    <http auto-config = 'true' use-expressions = "false" entry-point-ref = "customAuthenticationEntryPoint">
        <intercept-url pattern = "/j_spring_security_check" access = "IS_AUTHENTICATED_ANONYMOUSLY"/>
        <intercept-url pattern = "/login" access = "IS_AUTHENTICATED_ANONYMOUSLY"/>
        <intercept-url pattern = "/Login.html" access = "IS_AUTHENTICATED_ANONYMOUSLY" />
        <intercept-url pattern = "/img/favicon.ico" access = "IS_AUTHENTICATED_ANONYMOUSLY" />
        <intercept-url pattern = "/**" access = "IS_AUTHENTICATED_FULLY" />
        <logout logout-success-url = "/Login.html" />
        <form-login login-page = "/Login.html" default-target-url = "/index.gwt.html" always-use-default-target = "true"
                    login-processing-url = "/j_spring_security_check" username-parameter = "username" password-parameter = "password"
                    authentication-success-handler-ref = "customAuthenticationSuccessHandler"
                    authentication-failure-handler-ref="customAuthenticationFailureHandler"/>

        <session-management invalid-session-url = "/Login.html"
                            session-authentication-error-url = "/Login.html"
                            session-fixation-protection = "newSession">
            <concurrency-control max-sessions = "1" error-if-maximum-exceeded = "false" />
        </session-management>
    </http>

    <ldap-server {Our settings} />

    <authentication-manager alias = "authenticationManager">
        <ldap-authentication-provider
                {Our LDAP Info}
        </ldap-authentication-provider>
    </authentication-manager>

    <beans:bean id = "customAuthenticationEntryPoint" class = "com.me.portal.server.security.CustomAuthenticationEntryPoint"/>

    <beans:bean id = "customAuthenticationSuccessHandler" class = "com.me.portal.server.security.CustomAuthenticationSuccessHandler"/>

    <beans:bean id = "customAuthenticationFailureHandler" class = "com.me.portal.server.security.CustomAuthenticationFailureHandler"/>

</beans:beans>

Spring JARs used:

spring-aop-4.3.2.RELEASE.jar
spring-beans-4.3.2.RELEASE.jar
spring-context-4.3.2.RELEASE.jar
spring-core-4.3.2.RELEASE.jar
spring-expression-4.3.2.RELEASE.jar
spring-ldap-core-2.3.1.RELEASE.jar
spring-security-config-3.2.7.RELEASE.jar
spring-security-core-3.2.7.RELEASE.jar
spring-security-ldap-3.2.7.RELEASE.jar
spring-security-web-3.2.7.RELEASE.jar
spring-tx-4.3.2.RELEASE.jar
spring-web-4.3.2.RELEASE.jar

As requested, Headers:

Response:

<!DOCTYPE html>
<title>Apache Tomcat/8.0.22 - Error report</title>

HTTP Status 404 - /j_spring_security_check

type Status report

message /j_spring_security_check

description The requested resource is not available.

Apache Tomcat/8.0.22

Body:
I don't know if this is a GWT problem, or a Tomcat problem, but the solution is here:

<form method = "post" action="/MyPortal/j_spring_security_check">

I had to add the path to "/MyPortal" in order for j_spring_security_check to be found.


来源: stackexchange

问:
Css overlapping div with multiple children
I need help to fix a couple of things in the grid. You can see the website here (just click on search button and scroll down to see the items).

1) the 6 columns overlap each other when they're all clicked (screen 1 and 2). Try to click on each of them to reproduce this.I'd like the to stick in the original position. basically the div with text and audio player should just replace the image (onclick)

html sample

```<code><div class="row">
            <div class="col-sm-4">
                <img id="img1" onclick="play(1)" src="data/img/portfolio/fox.jpg" class="img-responsive img-animals" alt="Fox">
                <div class="inner_text_img" id="inner1">
                    <h3>Red Fox - <a class="stopsound" onclick="stop(1)">X</a></h3>
                    <p>lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum</p>
                    <audio class="audio_player" id="audio1" src="data/sound/animals/fox.mp3" type="audio/mpeg"></audio>
                </div>
            </div>
            <div class="col-sm-4">
              ....
</code>```

css

```<code>audio{
  width: 100%;
}

.inner_text_img{
  max-width: 360px;
  max-height: 260px;
}
.col-sm-4:hover img{
  opacity: 0.5;
}

.inner_text_img{
  width: 100%;
  height: 100%;
  color: red;
  position: absolute;
  color: #2C3E50;
  top:0px;
  left:0px;
  display:none;
}

.inner_text_img{
    background-color: #f3f3f3;
}
</code>```

js to switch div and start/stop the audio

```<code>function play(n) {

    var audio = document.getElementById("audio" + n);
    var inner_el = document.getElementById("inner" + n);
    var img = document.getElementById("img" + n);

    if (audio.paused) {
        img.style.display = 'none';
        inner_el.style.display = 'block';
        audio.controls = true;
        audio.play();
        audio.loop = true;
    } else {
        img.style.display = 'block';
        inner_el.style.display = 'none';
        audio.controls = false;
        audio.pause();
    }
}

function stop(n) {
    var audio = document.getElementById("audio" + n);
    var inner_el = document.getElementById("inner" + n);
    var img = document.getElementById("img" + n);

    img.style.display = 'block';
    inner_el.style.display = 'none';
    audio.controls = false;
    audio.pause();

}
</code>```

edited to one question

thank you!

答: remove the position: absolute in .inner_text_img {} style

ContentLicense: CC BY-SA 3.0

Body:
I need help to fix a couple of things in the grid. You can see the website here (just click on search button and scroll down to see the items).

1) the 6 columns overlap each other when they're all clicked (screen 1 and 2). Try to click on each of them to reproduce this.I'd like the to stick in the original position. basically the div with text and audio player should just replace the image (onclick)

html sample

Red Fox - X

lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum

                    <audio class="audio_player" id="audio1" src="data/sound/animals/fox.mp3" type="audio/mpeg"></audio>

              ....

css

audio{
  width: 100%;
}

.inner_text_img{
  max-width: 360px;
  max-height: 260px;
}
.col-sm-4:hover img{
  opacity: 0.5;
}

.inner_text_img{
  width: 100%;
  height: 100%;
  color: red;
  position: absolute;
  color: #2C3E50;
  top:0px;
  left:0px;
  display:none;
}

.inner_text_img{
    background-color: #f3f3f3;
}

js to switch div and start/stop the audio

function play(n) {

    var audio = document.getElementById("audio" + n);
    var inner_el = document.getElementById("inner" + n);
    var img = document.getElementById("img" + n);

    if (audio.paused) {
        img.style.display = 'none';
        inner_el.style.display = 'block';
        audio.controls = true;
        audio.play();
        audio.loop = true;
    } else {
        img.style.display = 'block';
        inner_el.style.display = 'none';
        audio.controls = false;
        audio.pause();
    }
}

function stop(n) {
    var audio = document.getElementById("audio" + n);
    var inner_el = document.getElementById("inner" + n);
    var img = document.getElementById("img" + n);

    img.style.display = 'block';
    inner_el.style.display = 'none';
    audio.controls = false;
    audio.pause();

}

edited to one question

thank you!


问:
Removing empty lists from csv file in Python 3
I have been working on code that takes rows from csv file and transfer them into the lists of integers for further mathematical operations. However, if a row turns out to be empty, it causes problems. Also, the user will not know which row is empty, so the solution should be general rather than pointing at a row and removing it. Here is the code:

```<code>import csv
import statistics as st

def RepresentsInt(i):
    try:
       int(i)
       return True
    except ValueError:
       return False
l = []

with open('Test.csv', 'r') as f:
    reader = csv.reader(f, delimiter=',')

    for row in reader:
        l.append([int(r) if RepresentsInt(r) else 0 for r in row])

    for row in l:

        row=[x for x in row if x!=0]
        row.sort()
        print(row)
</code>```

I've tried l=[row for row in l if row!=[]] and ...

```<code>if row==[]:
    l.remove(row)
</code>```

... but both do nothing, and there is no error code for either. Here is my csv file:

```<code>1,2,5,4
2,3
43,65,34,56,7

0,5
7,8,9,6,5

33,45,65,4
</code>```

If I run the code, I will get [] for row 4 and 6 (which are empty).

答:
It is unclear what you are doing with the statistics module, but the following program should you what you asked for. The pprint module is imported to make displaying the generated table easier to read. If this answer solves the problem presented in your question but you are having difficulty somewhere else, make sure you open another question targeted at the new problem.

```<code>#! /usr/bin/env python3
import csv
import pprint

def main():
    table = []
    # Add rows to table.
    with open('Test.csv', newline='') as file:
        table.extend(csv.reader(file))
    # Convert table cells to numbers.
    for index, row in enumerate(table):
        table[index] = [int(value) if value.isdigit() else 0 for value in row]
    # Remove zeros from the rows.
    for index, row in enumerate(table):
        table[index] = [value for value in row if value]
    # Remove empty rows and display the table.
    table = [row for row in table if row]
    pprint.pprint(table)

if __name__ == '__main__':
    main()
</code>```

Body:
I have been working on code that takes rows from csv file and transfer them into the lists of integers for further mathematical operations. However, if a row turns out to be empty, it causes problems. Also, the user will not know which row is empty, so the solution should be general rather than pointing at a row and removing it. Here is the code:

import csv
import statistics as st

def RepresentsInt(i):
    try:
       int(i)
       return True
    except ValueError:
       return False
l = []

with open('Test.csv', 'r') as f:
    reader = csv.reader(f, delimiter=',')

    for row in reader:
        l.append([int(r) if RepresentsInt(r) else 0 for r in row])

    for row in l:

        row=[x for x in row if x!=0]
        row.sort()
        print(row)

I've tried l=[row for row in l if row!=[]] and ...

if row==[]:
    l.remove(row)

... but both do nothing, and there is no error code for either. Here is my csv file:

1,2,5,4
2,3
43,65,34,56,7

0,5
7,8,9,6,5

33,45,65,4

If I run the code, I will get [] for row 4 and 6 (which are empty).

Body:
It is unclear what you are doing with the statistics module, but the following program should you what you asked for. The pprint module is imported to make displaying the generated table easier to read. If this answer solves the problem presented in your question but you are having difficulty somewhere else, make sure you open another question targeted at the new problem.

#! /usr/bin/env python3
import csv
import pprint

def main():
    table = []
    # Add rows to table.
    with open('Test.csv', newline='') as file:
        table.extend(csv.reader(file))
    # Convert table cells to numbers.
    for index, row in enumerate(table):
        table[index] = [int(value) if value.isdigit() else 0 for value in row]
    # Remove zeros from the rows.
    for index, row in enumerate(table):
        table[index] = [value for value in row if value]
    # Remove empty rows and display the table.
    table = [row for row in table if row]
    pprint.pprint(table)

if __name__ == '__main__':
    main()


问:
AsyncSocket and Notifications - memory leak
I have a memory leak in the following scenario. I read data at every 30 seconds, use SBJSONParser to transform it to a dictionary, add a notification and after that use the data to bind it to a tableview:

```<code>// Read data and send notification
-(void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    NSString *content = [[NSString alloc] initWithData:[data subDataWithRange:NSMakeRange(0, [data length] - 2)] encoding: NSUTF8StringEncoding];

    // Line where leaks appear
    NSMutableDictionary* dict = [[NSMutableDictionary alloc] initWithDictionary:[content JSONValue]];

    [content release];

    // Post notification
    [[NSNotificationCenter defaultCenter] postNotificationName:@"BindData" object:nil userInfo:dict];

     [dict release];
}
</code>```

On a CustomViewController I have the observer:

```<code>[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bindData) name:@"BindData" object:nil];
</code>```

and the bindData method:

```<code>-(void)bindData:(NSNotification*)notification
{
    NSAutoreleasePool* pool = [[NSAutoReleasePool alloc] init];

    NSMutableArray* customers = [notification.userInfo objectForKey:@"Customers"];
    for (NSDictionary* customer in customers)
    {
         Company* company = [[Company alloc] init];
         company.name = [customer objectForKey:@"CompanyName"];
         NSLog(@"Company name = %@", company.name);
         [company release];
    }

    [pool drain];
}
</code>```

The problem is: when I set company.name = something from that dictionary, I get a memory leak on the line:  NSMutableDictionary* dict = [[NSMutableDictionary alloc] initWithDictionary:[content JSONValue]]; which keeps increasing since I'm reading at every 30 seconds.

I appreciate any help you can give. Thanks.

答:
dict is leaking because you are using alloc and init (thus increasing its retain count by 1), but never releasing it. Since the dictionary will no longer be needed after the notification has been posted, you can safely release it on the following line, like so:

```<code>// Post notification
[[NSNotificationCenter defaultCenter] postNotificationName:@"BindData" object:nil userInfo:dict]
[dict release];
</code>```

See the Memory Management Programming Guide for more details.

ContentLicense: CC BY-SA 2.5

Body:
I have a memory leak in the following scenario. I read data at every 30 seconds, use SBJSONParser to transform it to a dictionary, add a notification and after that use the data to bind it to a tableview:

// Read data and send notification
-(void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    NSString *content = [[NSString alloc] initWithData:[data subDataWithRange:NSMakeRange(0, [data length] - 2)] encoding: NSUTF8StringEncoding];

    // Line where leaks appear
    NSMutableDictionary* dict = [[NSMutableDictionary alloc] initWithDictionary:[content JSONValue]];

    [content release];

    // Post notification
    [[NSNotificationCenter defaultCenter] postNotificationName:@"BindData" object:nil userInfo:dict];

     [dict release];
}

On a CustomViewController I have the observer:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bindData) name:@"BindData" object:nil];

and the bindData method:

-(void)bindData:(NSNotification*)notification
{
    NSAutoreleasePool* pool = [[NSAutoReleasePool alloc] init];

    NSMutableArray* customers = [notification.userInfo objectForKey:@"Customers"];
    for (NSDictionary* customer in customers)
    {
         Company* company = [[Company alloc] init];
         company.name = [customer objectForKey:@"CompanyName"];
         NSLog(@"Company name = %@", company.name);
         [company release];
    }

    [pool drain];
}

The problem is: when I set company.name = something from that dictionary, I get a memory leak on the line:  NSMutableDictionary* dict = [[NSMutableDictionary alloc] initWithDictionary:[content JSONValue]]; which keeps increasing since I'm reading at every 30 seconds.

I appreciate any help you can give. Thanks.

Body:
dict is leaking because you are using alloc and init (thus increasing its retain count by 1), but never releasing it. Since the dictionary will no longer be needed after the notification has been posted, you can safely release it on the following line, like so:

// Post notification
[[NSNotificationCenter defaultCenter] postNotificationName:@"BindData" object:nil userInfo:dict]
[dict release];

See the Memory Management Programming Guide for more details.


问:
Return an F# record type as JSON in Azure Functions
I'm creating a simple azure function in F#. At the end, I'm returning a record type as JSON. I'm doing something like this:

```<code>let y = {Gender = "Woman"; Frequency = 17; Percentage = 100.0}
req.CreateResponse(HttpStatusCode.OK, y);
</code>```

When I call the function from Postman I'm getting this JSON
{"Gender@":"Woman","Frequency@":17,"Percentage@":100}

It looks like that this is caused by the default serializer (Serializing F# Record type to JSON includes '@' character after each property).

Then I tried to use Newtonsoft.Json. Now, the code looks like this:

```<code>req.CreateResponse(HttpStatusCode.OK, JsonConvert.SerializeObject(y));
</code>```

But now I'm getting this using postman:

```<code>"{\"Gender\":\"Woman\",\"Frequency\":17,\"Percentage\":100}"
</code>```

I'd like to get this response:
{"Gender":"Woman","Frequency":17,"Percentage":100}

How can I get this JSON response? Is there any other way apart from specifying DataMemberAttribute?

Thanks

答:
I don't think you can use JSON.Net (would be nice) because the AzureFunctions infrastructure seems to the Data Contract Serializers

I have just implemented the fix as per Serializing F# Record type to JSON includes '@' character after each property and it works for me if a bit clunkier than you may hope.

I was also struggling to fix this and you got me going in the right direction - Thanks

```<code>#r "System.Runtime.Serialization"

open System.Runtime.Serialization

[<DataContract>]
type SearchItem = {
    [<field: DataMember(Name="Gender")>]
    Gender: string
    [<field: DataMember(Name="Frequency")>]
    Frequency: int
    [<field: DataMember(Name="Percentage")>]
    Percentage: float
}
</code>```

Body:
I'm creating a simple azure function in F#. At the end, I'm returning a record type as JSON. I'm doing something like this:

let y = {Gender = "Woman"; Frequency = 17; Percentage = 100.0}
req.CreateResponse(HttpStatusCode.OK, y);

When I call the function from Postman I'm getting this JSON
{"Gender@":"Woman","Frequency@":17,"Percentage@":100}

It looks like that this is caused by the default serializer (Serializing F# Record type to JSON includes '@' character after each property).

Then I tried to use Newtonsoft.Json. Now, the code looks like this:

req.CreateResponse(HttpStatusCode.OK, JsonConvert.SerializeObject(y));

But now I'm getting this using postman:

"{\"Gender\":\"Woman\",\"Frequency\":17,\"Percentage\":100}"

I'd like to get this response:
{"Gender":"Woman","Frequency":17,"Percentage":100}

How can I get this JSON response? Is there any other way apart from specifying DataMemberAttribute?

Thanks

Body:
I don't think you can use JSON.Net (would be nice) because the AzureFunctions infrastructure seems to the Data Contract Serializers

I have just implemented the fix as per Serializing F# Record type to JSON includes '@' character after each property and it works for me if a bit clunkier than you may hope.

I was also struggling to fix this and you got me going in the right direction - Thanks

#r "System.Runtime.Serialization"

open System.Runtime.Serialization

[<DataContract>]
type SearchItem = {
    [<field: DataMember(Name="Gender")>]
    Gender: string
    [<field: DataMember(Name="Frequency")>]
    Frequency: int
    [<field: DataMember(Name="Percentage")>]
    Percentage: float
}


问:
How can I insert a character after every 2 characters?
I want to insert a slash after every two characters, but just for the first two instances. The following regex inserts after every occurrence. Does anyone know how to limit it to two occurrences? The amount will be entered by the user through an input element. So if a user entered 30032017 it would be something like the following.

```<code>function insertSlash(val) {
    return val.match(new RegExp('.{1,2}', 'g')).join("/");
}

insertSlash(input);
</code>```

so for the first character the user would enter 3. On the next input it will be 0. this should then insert a slash.

this should then return 30/03/2017.

答:
```<code>function insertSlash(val) {
    return val.substr(0,2)+"/"+val.substr(2,2)+"/"+val.substr(4,4)
}

insertSlash('30032017');
</code>```

Body:
I want to insert a slash after every two characters, but just for the first two instances. The following regex inserts after every occurrence. Does anyone know how to limit it to two occurrences? The amount will be entered by the user through an input element. So if a user entered 30032017 it would be something like the following.

function insertSlash(val) {
    return val.match(new RegExp('.{1,2}', 'g')).join("/");
}

insertSlash(input);

so for the first character the user would enter 3. On the next input it will be 0. this should then insert a slash.

this should then return 30/03/2017.


问:
Unnecessary else statements: Is there any disadvantage to using ELSE IF when just IF can be used?
Consider the speed of the following examples (please ignore that this example is completely ridiculous):

```<code>int multiply(int a, int b) {
  if (a == 0 || b == 0) {
    return 0;
  }
  if (a == b) {
    return pow(a, 2);
  }
  return a*b;
}
</code>```

versus

```<code>int multiply(int a, int b) {
  if (a == 0 || b == 0) {
    return 0;
  } else if (a == b) {
    return pow(a, 2);
  } else {
    return a*b;
  }
}
</code>```

Obviously, it's not really necessary here, but when I'm working with complex operations, I find it a lot easier to read when formatted as the latter.  Does it take any longer to run in the second configuration?  Will I be sacrificing anything?

答:
In this particular case, no compiler I'm aware of would fail to
generate the exact same output for both. However, in the general
case:

Write for readability and maintainability

Profile profile profile

Optimize only where you find bottlenecks

Test your optimization using more profiling

The fourth part is important, hardware have many surprising
optimizations builtin, it's not at all intuitive what will
be faster.

Body:
Consider the speed of the following examples (please ignore that this example is completely ridiculous):

int multiply(int a, int b) {
  if (a == 0 || b == 0) {
    return 0;
  }
  if (a == b) {
    return pow(a, 2);
  }
  return a*b;
}

versus

int multiply(int a, int b) {
  if (a == 0 || b == 0) {
    return 0;
  } else if (a == b) {
    return pow(a, 2);
  } else {
    return a*b;
  }
}

Obviously, it's not really necessary here, but when I'm working with complex operations, I find it a lot easier to read when formatted as the latter.  Does it take any longer to run in the second configuration?  Will I be sacrificing anything?


问:
How to display submenu on dropdown using positioning and CSS?
I have this simple navigation menu for my design. But the problem is I can't display the sub menu when hovered. Is there any way to solve this? Or does my CSS has some missing styles?

nav ul {list-style-type: none; overflow: hidden; background: #000; position: relative;}
nav li {float: left;}
nav li > a {padding: 15px 15px; display: inline-block; text-decoration: none; color: white; text-align: center;}
nav li > a:hover {background: violet;}

nav ul ul { position: absolute; background: green; top: 100%;}
nav ul ul li > a:hover {color: red;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>sample UL</title>
    <style media="screen">

    </style>
  </head>
  <body>
    <nav>
      <ul>
        <li>Home</li>
        <li>Menu 1</li>
        <ul>
          <li>submenu 1</li>
          <li>submenu 2</li>
        </ul>
      </ul>
    </nav>
  </body>
</html></code>```

答:
Just try this one. You could learn from it.

<!DOCTYPE html>

Home

News

    Dropdown

      Link 1
      Link 2
      Link 3

Dropdown Menu inside a Navigation Bar

Hover over the "Dropdown" link to see the dropdown menu.

```

Body:
I have this simple navigation menu for my design. But the problem is I can't display the sub menu when hovered. Is there any way to solve this? Or does my CSS has some missing styles?

nav ul {list-style-type: none; overflow: hidden; background: #000; position: relative;}
nav li {float: left;}
nav li > a {padding: 15px 15px; display: inline-block; text-decoration: none; color: white; text-align: center;}
nav li > a:hover {background: violet;}

nav ul ul { position: absolute; background: green; top: 100%;}
nav ul ul li > a:hover {color: red;}

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>sample UL</title>

Home

Menu 1

submenu 1

submenu 2

Body:
Just try this one. You could learn from it.

<!DOCTYPE html>
<html>
<head>
<style>
ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

li {
    float: left;
}

li a, .dropbtn {
    display: inline-block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

li a:hover, .dropdown:hover .dropbtn {
    background-color: red;
}

li.dropdown {
    display: inline-block;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {
    display: block;
}
</style>
</head>
<body>

<ul>
  <li><a href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li class="dropdown">
    <a href="javascript:void(0)" class="dropbtn">Dropdown</a>
    <div class="dropdown-content">
      <a href="#">Link 1</a>
      <a href="#">Link 2</a>
      <a href="#">Link 3</a>
    </div>
  </li>
</ul>

<h3>Dropdown Menu inside a Navigation Bar</h3>
<p>Hover over the "Dropdown" link to see the dropdown menu.</p>

</body>
</html>


问:
How to use proxies with Indy TIdWhois?
I cannot figure out how to use proxies with TIdWhois. Does anybody have a clue for me?

Following Remy's description, I use the following code:

```<code>w:=TIdWhois.Create(nil);
p:=TIdConnectThroughHttpProxy.Create(nil);
io:=TIdIOHandlerStack.Create(nil);
p.Host:=<proxy-ip>
p.port:=<proxy-port>
io.TransparentProxy:=p;
w.io:=io;
w.host:=<whois-server>
w.port:=43;
w.WHoIs(<domain>);
</code>```

Monitoring the ports, it still use my real IP for the request.

What am I doing wrong?

答:
Indy 10 natively supports two types of proxies:

HTTP, via the
TIdConnectThroughHttpProxy component.

SOCKS 4/4a/5, via the TIdSocksInfo
component.

To use either one of them, you need to:

Assign a
TIdIOHandlerSocket-derived component, such as TIdIOHandlerStack, to the
client's IOHandler property.

Assign the desired proxy component to the TIdIOHandlerSocket.TransparentProxy property, set its Host and Port properties to the Host/Port of the desired proxy server, and enable it accordingly (via the TIdConnectThroughHttpProxy.Enabled or TIdSocksInfo.Version property).

Set the client's Host
and Port properties to the Host/Port of the target server, and then Connect() and use the client normally.

Title: How to use proxies with Indy TIdWhois?

Body:
I cannot figure out how to use proxies with TIdWhois. Does anybody have a clue for me?

Following Remy's description, I use the following code:

w:=TIdWhois.Create(nil);
p:=TIdConnectThroughHttpProxy.Create(nil);
io:=TIdIOHandlerStack.Create(nil);
p.Host:=<proxy-ip>
p.port:=<proxy-port>
io.TransparentProxy:=p;
w.io:=io;
w.host:=<whois-server>
w.port:=43;
w.WHoIs(<domain>);

Monitoring the ports, it still use my real IP for the request.

What am I doing wrong?


问:
Fragments inside Activity - with Toolbar and Action buttons (similar to Windows windows)
I would like to have an Activity populated with Fragments. Every Fragment behaves as a windows in Windows OS - it has its Toolbar with title and action buttons:

Fragment:

```<code>    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Show Toolbar in Fragment
        setHasOptionsMenu(true);

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_entries_list, container, false);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);

        inflater.inflate(R.menu.menu_common, menu);
    }
</code>```

Question:

How to change the title of the Fragment?

How to display three-dot actions button?

Edit:

I have now modified menu_common.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_categories"
        android:title="Categories"
        android:visible="true"
        app:showAsAction="never"/>
    <item
        android:id="@+id/action_settings"
        android:title="Settings"/>
</menu>
</code>```

Fragment

```<code>@Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        ViewGroup view = (ViewGroup) inflater.inflate(
                R.layout.fragment_entries_list, container, false);

        // Toolbar
        Toolbar toolbar = (Toolbar) view.findViewById(R.id.tb_actions);
        toolbar.setTitle("Bar");
        toolbar.showOverflowMenu();
        setHasOptionsMenu(true);

        // Inflate the layout for this fragment
        return view;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.menu_common, menu);
    }
</code>```

Edit 2:

This is what I want to achieve:

答:
How to change the title of the Fragment?

Include Toolbar in your fragment and call toolbar.setTitle(String).

How to display three-dot actions button?

As you can see in this answer:

```<code>toolbar.showOverflowMenu();
</code>```

Body:
I would like to have an Activity populated with Fragments. Every Fragment behaves as a windows in Windows OS - it has its Toolbar with title and action buttons:

Fragment:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Show Toolbar in Fragment
        setHasOptionsMenu(true);

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_entries_list, container, false);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);

        inflater.inflate(R.menu.menu_common, menu);
    }

Question:

How to change the title of the Fragment?

How to display three-dot actions button?

Edit:

I have now modified menu_common.xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_categories"
        android:title="Categories"
        android:visible="true"
        app:showAsAction="never"/>
    <item
        android:id="@+id/action_settings"
        android:title="Settings"/>
</menu>

Fragment

@Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        ViewGroup view = (ViewGroup) inflater.inflate(
                R.layout.fragment_entries_list, container, false);

        // Toolbar
        Toolbar toolbar = (Toolbar) view.findViewById(R.id.tb_actions);
        toolbar.setTitle("Bar");
        toolbar.showOverflowMenu();
        setHasOptionsMenu(true);

        // Inflate the layout for this fragment
        return view;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.menu_common, menu);
    }

Edit 2:

This is what I want to achieve:

Body:
How to change the title of the Fragment?

Include Toolbar in your fragment and call toolbar.setTitle(String).

How to display three-dot actions button?

As you can see in this answer:

toolbar.showOverflowMenu();


问:
Mule xpath function
I have an xml like below

```<code><wd:report xmlns:wd="foo">
  <wd:id>abc</wd:id>
  <wd:id>def</wd:id>
  <wd:id>ghi</wd:id>
</wd:report>
</code>```

I am using an xpath 2 function to concatenate the wd:id elements as below

```<code>#[xpath3('string-join(//wd:id)')]
</code>```

and this works except that I need to have a semicolon delimiter between the strings like abc;def;ghi. So when I use the below function

```<code>#[xpath3('string-join(//wd:id, ';')')]
</code>```

I get an xpath parsing exception saying an unexpected token ) found . How can I avoid the error? Thanks.

Regards,
Hari

答:
your expression should look like this:#[xpath3('string-join(//wd:id, ";")')]

important part is " vs '

Title: Mule xpath function

Body:
I have an xml like below

<wd:report xmlns:wd="foo">
  <wd:id>abc</wd:id>
  <wd:id>def</wd:id>
  <wd:id>ghi</wd:id>
</wd:report>

I am using an xpath 2 function to concatenate the wd:id elements as below

#[xpath3('string-join(//wd:id)')]

and this works except that I need to have a semicolon delimiter between the strings like abc;def;ghi. So when I use the below function

#[xpath3('string-join(//wd:id, ';')')]

I get an xpath parsing exception saying an unexpected token ) found . How can I avoid the error? Thanks.

Regards,
Hari


问:
Create column of truth values
I have a data frame which looks like this:

```<code>    date      people_count
0   30/03/17  6

1   31/03/17  4

2   1/04/17   7

3   2/04/17   9
</code>```

How can you create a new column which indicates if the date is a weekend(1), or if the date is a weekday(0)?

Something like this:

```<code>    date      people_count   weekend
0   30/03/17  6              0

1   31/03/17  4              0

2   1/04/17   7              1

3   2/04/17   9              1
</code>```

So far I have created a column which stores the day number(0-6), from DateTimeIndex.dayofweek:

```<code>df = pd.read_csv('myfile.csv', encoding = 'ISO-8859-1')

df['weekend'] = pd.DatetimeIndex(df['date']).dayofweek
</code>```

But I am unsure of how to evaluate these values and replace them with 1 for weekends, and 0 for weekdays. How can I do this?

答:
First, you may have to specify the date format -- I get

```<code>In [31]: pd.DatetimeIndex(df['date'])
Out[31]: DatetimeIndex(['2017-03-30', '2017-03-31', '2017-01-04', '2017-02-04'], dtype='datetime64[ns]', name='date', freq=None)
</code>```

from your input and I don't think that's what you wanted.  Once you have that, though, it's easy to compute, whether as a bool column or an int column, using the .dt accessor:

```<code>In [48]: pd.to_datetime(df["date"], format="%d/%m/%y")
Out[48]:
0   2017-03-30
1   2017-03-31
2   2017-04-01
3   2017-04-02
Name: date, dtype: datetime64[ns]

In [49]: (pd.to_datetime(df["date"], format="%d/%m/%y").dt.weekday >= 5)
Out[49]:
0    False
1    False
2     True
3     True
Name: date, dtype: bool

In [50]: (pd.to_datetime(df["date"], format="%d/%m/%y").dt.weekday >= 5).astype(int)
Out[50]:
0    0
1    0
2    1
3    1
Name: date, dtype: int64
</code>```

Title: Create column of truth values

Body:
I have a data frame which looks like this:

    date      people_count
0   30/03/17  6

1   31/03/17  4

2   1/04/17   7

3   2/04/17   9

How can you create a new column which indicates if the date is a weekend(1), or if the date is a weekday(0)?

Something like this:

    date      people_count   weekend
0   30/03/17  6              0

1   31/03/17  4              0

2   1/04/17   7              1

3   2/04/17   9              1

So far I have created a column which stores the day number(0-6), from DateTimeIndex.dayofweek:

df = pd.read_csv('myfile.csv', encoding = 'ISO-8859-1')

df['weekend'] = pd.DatetimeIndex(df['date']).dayofweek

But I am unsure of how to evaluate these values and replace them with 1 for weekends, and 0 for weekdays. How can I do this?

Body:
First, you may have to specify the date format -- I get

In [31]: pd.DatetimeIndex(df['date'])
Out[31]: DatetimeIndex(['2017-03-30', '2017-03-31', '2017-01-04', '2017-02-04'], dtype='datetime64[ns]', name='date', freq=None)

from your input and I don't think that's what you wanted.  Once you have that, though, it's easy to compute, whether as a bool column or an int column, using the .dt accessor:

In [48]: pd.to_datetime(df["date"], format="%d/%m/%y")
Out[48]:
0   2017-03-30
1   2017-03-31
2   2017-04-01
3   2017-04-02
Name: date, dtype: datetime64[ns]

In [49]: (pd.to_datetime(df["date"], format="%d/%m/%y").dt.weekday >= 5)
Out[49]:
0    False
1    False
2     True
3     True
Name: date, dtype: bool

In [50]: (pd.to_datetime(df["date"], format="%d/%m/%y").dt.weekday >= 5).astype(int)
Out[50]:
0    0
1    0
2    1
3    1
Name: date, dtype: int64


问:
How to send reminder to attendee of the appointment (not the owner of shared calendar) 24 hr before the appointment time in outlook 2013?
I am creating a windows application in C# for setting appointments in a shared calendar for my team. I am the owner of the calendar. I have written the code to set the appointment and set reminder time as 24 hrs before the meeting. But instead of sending reminder to attendee it is sending reminder to me. I am using Microsoft.Office.Interop.Outlook for this. Here is the code that I used:

```<code>Outlook.Application oApp = new Outlook.Application();

// Get the NameSpace and Logon information.
Outlook.NameSpace oNS = oApp.GetNamespace("mapi");

// Get the Calendar folder.
Outlook.Recipient rcip = oNS.CreateRecipient("abc@domain.com");
Outlook.MAPIFolder oSharedCal = oNS.GetSharedDefaultFolder(rcip, Outlook.OlDefaultFolders.olFolderCalendar);
Outlook.MAPIFolder oShiftCal = oSharedCal.Folders["Sample"];
// Get the Items (Appointments) collection from the Calendar folder.
Outlook.Items oItems = oSharedCal.Items;
Outlook.AppointmentItem oAppt = (Outlook.AppointmentItem)oItems.Add();

// Set Appointment properties.
oAppt.Subject = Subject;
oAppt.Start = start;
oAppt.End = end;
oAppt.RequiredAttendees = email;
oAppt.ReminderMinutesBeforeStart = 24 * 60;
oAppt.ReminderSet = true;
oAppt.BusyStatus = Outlook.OlBusyStatus.olFree;

//Show the item to pause.
oAppt.Save();
oAppt.Send();
</code>```

Can anyone help me with this?

答: Reminders cannot be set for attendees, they are for your copy of the appointment in the calendar you create it in.  Attendees can set a reminder for themselves when the accept the meeting request.</p>

Body:
I am creating a windows application in C# for setting appointments in a shared calendar for my team. I am the owner of the calendar. I have written the code to set the appointment and set reminder time as 24 hrs before the meeting. But instead of sending reminder to attendee it is sending reminder to me. I am using Microsoft.Office.Interop.Outlook for this. Here is the code that I used:

Outlook.Application oApp = new Outlook.Application();

// Get the NameSpace and Logon information.
Outlook.NameSpace oNS = oApp.GetNamespace("mapi");

// Get the Calendar folder.
Outlook.Recipient rcip = oNS.CreateRecipient("abc@domain.com");
Outlook.MAPIFolder oSharedCal = oNS.GetSharedDefaultFolder(rcip, Outlook.OlDefaultFolders.olFolderCalendar);
Outlook.MAPIFolder oShiftCal = oSharedCal.Folders["Sample"];
// Get the Items (Appointments) collection from the Calendar folder.
Outlook.Items oItems = oSharedCal.Items;
Outlook.AppointmentItem oAppt = (Outlook.AppointmentItem)oItems.Add();

// Set Appointment properties.
oAppt.Subject = Subject;
oAppt.Start = start;
oAppt.End = end;
oAppt.RequiredAttendees = email;
oAppt.ReminderMinutesBeforeStart = 24 * 60;
oAppt.ReminderSet = true;
oAppt.BusyStatus = Outlook.OlBusyStatus.olFree;

//Show the item to pause.
oAppt.Save();
oAppt.Send();

Can anyone help me with this?


答:
If you want to treat your date string like an actual Date you could do something like this:

const dateString = "30032017"
const date = new Date(dateString.slice(4), dateString.slice(3,4), dateString.slice(0,2))

const formattedDateString = date.getUTCFullYear() +"/"+ date.getUTCMonth() +"/"+ date.getUTCDate()

console.log(formattedDateString)```

This would allow you to do any intermediary date manipulation (adding/subtracting days/months/years) if you so desired.

Title: How can I insert a character after every 2 characters?

Body:
If you want to treat your date string like an actual Date you could do something like this:

const dateString = "30032017"
const date = new Date(dateString.slice(4), dateString.slice(3,4), dateString.slice(0,2))

const formattedDateString = date.getUTCFullYear() +"/"+ date.getUTCMonth() +"/"+ date.getUTCDate()

console.log(formattedDateString)

This would allow you to do any intermediary date manipulation (adding/subtracting days/months/years) if you so desired.


答:
There are quite a few errors in your code. The most critical one is the top: 100% on the submenu container, which moves it out of the visible area.

Apart from that it's important to define the submenu header li as position: relative and the submenu ul itself by default display: none and on hover display: block. And put the submenu container into the li that serves as its header. See my code below:

nav ul {
  list-style-type: none;
  background: #000;
}

nav li {
  display: inline-block;
  position: relative;
}

nav li>a {
  padding: 15px 15px;
  display: inline-block;
  text-decoration: none;
  color: white;
  text-align: center;
}

nav li>a:hover {
  background: violet;
}
nav ul li ul {
  display: none;
  position: absolute;
  top: 45px;
  left: 0px;
  width: 100px;
  overflow: visible;
  padding: 0;
}
nav ul li:hover ul {
  display: block;
}
nav ul ul li {
  background: green;
  display: block;
}
nav ul ul li>a:hover {
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>sample UL</title>
  <style media="screen">

  </style>
</head>

<body>
  <nav>
    <ul>
      <li>Home</li>
      <li>Menu 1
        <ul>
          <li>submenu 1</li>
          <li>submenu 2</li>
        </ul>
      </li>
    </ul>
  </nav>
</body>

</html></code>```

Title: How to display submenu on dropdown using positioning and CSS?

Body:
There are quite a few errors in your code. The most critical one is the top: 100% on the submenu container, which moves it out of the visible area.

Apart from that it's important to define the submenu header li as position: relative and the submenu ul itself by default display: none and on hover display: block. And put the submenu container into the li that serves as its header. See my code below:

nav ul {
  list-style-type: none;
  background: #000;
}

nav li {
  display: inline-block;
  position: relative;
}

nav li>a {
  padding: 15px 15px;
  display: inline-block;
  text-decoration: none;
  color: white;
  text-align: center;
}

nav li>a:hover {
  background: violet;
}
nav ul li ul {
  display: none;
  position: absolute;
  top: 45px;
  left: 0px;
  width: 100px;
  overflow: visible;
  padding: 0;
}
nav ul li:hover ul {
  display: block;
}
nav ul ul li {
  background: green;
  display: block;
}
nav ul ul li>a:hover {
  color: red;
}

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>sample UL</title>
  <style media="screen">

  </style>
</head>

<body>
  <nav>
    <ul>
      <li><a href="#">Home</a></li>
      <li><a href="#">Menu 1</a>
        <ul>
          <li><a href="#">submenu 1</a></li>
          <li><a href="#">submenu 2</a></li>
        </ul>
      </li>
    </ul>
  </nav>
</body>

</html>


问:
String split comma and parenthisis-JAVA
Convert the string:
"(id,created,employee(id,firstname,employeeType(id), lastname),location)"
to the following output
id
created
employee
- id
- firstname
- employeeType
-- id
- lastname
location

is there any optimistic solution available with using regular expression

答:
```<code>public static void main(String[] args) {
    String a = "(id,created,employee(id,firstname," +
             "employeeType(id), lastname),location)";
    StringTokenizer tok = new StringTokenizer(a, "(), ");
    System.out.println("StringTokenizer example");
    while (tok.hasMoreElements()) {
        String b = (String)tok.nextElement();
        System.out.println(b);
    }
    System.out.println("Split example");
    String[] array = a.split("(),");
    for (String ii: array) {
         System.out.println(ii);
    }

 }
}
</code>```

Outputs

```<code>StringTokenizer example
id
created
employee
id
firstname
employeeType
id
lastname
location
Split example
(id
created
employee(id
firstname
employeeType(id)
lastname)
location)
</code>```

You can add the hyphens.

Title: String split comma and parenthisis-JAVA

Body:
public static void main(String[] args) {
    String a = "(id,created,employee(id,firstname," +
             "employeeType(id), lastname),location)";
    StringTokenizer tok = new StringTokenizer(a, "(), ");
    System.out.println("StringTokenizer example");
    while (tok.hasMoreElements()) {
        String b = (String)tok.nextElement();
        System.out.println(b);
    }
    System.out.println("Split example");
    String[] array = a.split("(),");
    for (String ii: array) {
         System.out.println(ii);
    }

 }
}

Outputs

StringTokenizer example
id
created
employee
id
firstname
employeeType
id
lastname
location
Split example
(id
created
employee(id
firstname
employeeType(id)
lastname)
location)

You can add the hyphens.


问:
Nil value in virtual attribute not caught by Rails validation?
I have this Rails model:

```<code>class Profile < ActiveRecord::Base

  validates :number_format, :inclusion => { :in => ["1,000.00", "1.000,00"] }

  def number_format=(format)
    self.currency_delimiter = format[1]
    self.currency_separator = format[5]
  end

  def number_format
    "1#{currency_delimiter}000#{currency_separator}00"
  end

end
</code>```

The problem is that when I test it with RSpec...

```<code>it "is invalid without a number_format" do
  expect(FactoryGirl.build(:profile, :number_format => nil).errors_on(:number_format).size).to eq(1)
end
</code>```

...I get this error:

1) Profile number_format is invalid without a number_format
       Failure/Error: expect(FactoryGirl.build(:profile, :number_format => nil).errors_on(:number_format).size).to eq(1)

```<code>   expected: 1
        got: 0
</code>```

How is this possible?

I thought nil won't get validated due to the validation method I put in place.

答: If you are using virtual attributes, I think the errors are saved to :base. You should check expect(FactoryGirl.build(:profile, :number_format => nil).errors.size).to eq(1).

Body:
I have this Rails model:

class Profile < ActiveRecord::Base

  validates :number_format, :inclusion => { :in => ["1,000.00", "1.000,00"] }

  def number_format=(format)
    self.currency_delimiter = format[1]
    self.currency_separator = format[5]
  end

  def number_format
    "1#{currency_delimiter}000#{currency_separator}00"
  end

end

The problem is that when I test it with RSpec...

it "is invalid without a number_format" do
  expect(FactoryGirl.build(:profile, :number_format => nil).errors_on(:number_format).size).to eq(1)
end

...I get this error:

1) Profile number_format is invalid without a number_format
       Failure/Error: expect(FactoryGirl.build(:profile, :number_format => nil).errors_on(:number_format).size).to eq(1)

   expected: 1
        got: 0

How is this possible?

I thought nil won't get validated due to the validation method I put in place.


问:
Error with Tuple in C# 2008
I have made a program in C# 2010 and my code contains a Tuple, but when I put my program into C# 2008 it does not recognise it, and comes up with the error of:

"The type of namespace name 'Tuple' could not be found"

So I don't know how to make this work, this is the line of code in which the error occurs:

```<code>private List<Tuple<Point, Point>> lines = new List<Tuple<Point, Point>>();
</code>```

Please help.

EDIT

Basically this is my code at the moment which doesn't compile due to the error:

```<code>public partial class Form1 : Form
{
    private bool isMoving = false;
    private Point mouseDownPosition = Point.Empty;
    private Point mouseMovePosition = Point.Empty;
    private List<Tuple<Point, Point>> lines = new List<Tuple<Point, Point>>();
    public Form1()
    {
        InitializeComponent();
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        var g = e.Graphics;
        if (isMoving)
        {
            g.Clear(pictureBox1.BackColor);
            g.DrawLine(Pens.Black, mouseDownPosition, mouseMovePosition);
            foreach (var line in lines)
            {
                g.DrawLine(Pens.Black, line.Item1, line.Item2);
            }
        }
    }

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        isMoving = true;
        mouseDownPosition = e.Location;
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (isMoving)
        {
            mouseMovePosition = e.Location;
            pictureBox1.Invalidate();
        }
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        if (isMoving)
        {
            lines.Add(Tuple.Create(mouseDownPosition, mouseMovePosition));
        }
        isMoving = false;
    }
}
</code>```

So I need a way of changing or making the Tuple work in VS C# 2008 as well as 2010,

Thanks

答: Tuple is only available in .NET 4, which isn't supported by VS2008.

Title: Error with Tuple in C# 2008

Body:
I have made a program in C# 2010 and my code contains a Tuple, but when I put my program into C# 2008 it does not recognise it, and comes up with the error of:

"The type of namespace name 'Tuple' could not be found"

So I don't know how to make this work, this is the line of code in which the error occurs:

private List<Tuple<Point, Point>> lines = new List<Tuple<Point, Point>>();

Please help.

EDIT

Basically this is my code at the moment which doesn't compile due to the error:

public partial class Form1 : Form
{
    private bool isMoving = false;
    private Point mouseDownPosition = Point.Empty;
    private Point mouseMovePosition = Point.Empty;
    private List<Tuple<Point, Point>> lines = new List<Tuple<Point, Point>>();
    public Form1()
    {
        InitializeComponent();
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        var g = e.Graphics;
        if (isMoving)
        {
            g.Clear(pictureBox1.BackColor);
            g.DrawLine(Pens.Black, mouseDownPosition, mouseMovePosition);
            foreach (var line in lines)
            {
                g.DrawLine(Pens.Black, line.Item1, line.Item2);
            }
        }
    }

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        isMoving = true;
        mouseDownPosition = e.Location;
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (isMoving)
        {
            mouseMovePosition = e.Location;
            pictureBox1.Invalidate();
        }
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        if (isMoving)
        {
            lines.Add(Tuple.Create(mouseDownPosition, mouseMovePosition));
        }
        isMoving = false;
    }
}

So I need a way of changing or making the Tuple work in VS C# 2008 as well as 2010,

Thanks


问:
Print the contents of the file
I am trying to print the contents of my file byte by byte. However, I do get the compiler error "invalid type argument of unary *(have int)

my code is :

```<code> void print_the_file ()
    {
       void *file_hndl;
       UINT32 file_size = 2048;
       UINT8 *hndl;
       file_hndl = fopen("my_bin_file.bin", "r") ;
       if ( file_hndl == NULL )
       {
          printf("file open failed");
       }
       hndl = (UINT8*)file_hndl;
     /* print the contents */
      for ( UINT32 i = 0; i< 2048; i++ )
    {
        printf ("%02x", *hndl[i] );
    }
   }
</code>```

Please advise me where i am going wrong and right way to print the contents of the file.

答:
fopen returns a FILE * so your file_hndl should be of that type. Whilst you're checking the return value from fopen to print out an error message, you then ignore it and continue on trying to read from the file.

You're not actually reading from the file though - you need to call other functions such as fgetc to do that. But using fopen/fgetc is probably not want you want anyway as you're trying to read in a binary file. For that you want to use open and read.

The code below does what you're actually trying to do.

```<code>#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>

void print_the_file(void)
    {
    int file_desc;
    char a_byte;
    size_t err;

    file_desc=open("my_bin_file.bin",O_RDONLY,S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
    if(file_desc==-1)
        {
        printf("file open failed\n");
        return;
        }
    do
        {
        err=read(file_desc,&a_byte,1);
        if(err>0)
            {
            printf("%02x",a_byte);
            }
        }
    while(err>0);
    }
</code>```

Title: Print the contents of the file

Body:
I am trying to print the contents of my file byte by byte. However, I do get the compiler error "invalid type argument of unary *(have int)

my code is :

 void print_the_file ()
    {
       void *file_hndl;
       UINT32 file_size = 2048;
       UINT8 *hndl;
       file_hndl = fopen("my_bin_file.bin", "r") ;
       if ( file_hndl == NULL )
       {
          printf("file open failed");
       }
       hndl = (UINT8*)file_hndl;
     /* print the contents */
      for ( UINT32 i = 0; i< 2048; i++ )
    {
        printf ("%02x", *hndl[i] );
    }
   }

Please advise me where i am going wrong and right way to print the contents of the file.

Body:
fopen returns a FILE * so your file_hndl should be of that type. Whilst you're checking the return value from fopen to print out an error message, you then ignore it and continue on trying to read from the file.

You're not actually reading from the file though - you need to call other functions such as fgetc to do that. But using fopen/fgetc is probably not want you want anyway as you're trying to read in a binary file. For that you want to use open and read.

The code below does what you're actually trying to do.

#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>

void print_the_file(void)
    {
    int file_desc;
    char a_byte;
    size_t err;

    file_desc=open("my_bin_file.bin",O_RDONLY,S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
    if(file_desc==-1)
        {
        printf("file open failed\n");
        return;
        }
    do
        {
        err=read(file_desc,&a_byte,1);
        if(err>0)
            {
            printf("%02x",a_byte);
            }
        }
    while(err>0);
    }


问:
setting progress to progress bar while downloading a file
i am developing an app in which a user can read pdf books online/offline. If he has pdf reader installed then the book gets downloaded from the server and gets opened in that pdf reader but if he don't have a pdf reader installed then in that case pdf is opened online(using google docs link).

Now, when downloading a pdf file i want to display a progress dialog to the user but don't know how to set the percentage of file being downloaded ..I've searched for this but all the solutions given are for http connection.In my case it would be in a different manner i guess. So kindly check my code and then suggest me a way to do so. Thanks in advance.

PDFtools.java

```<code>public class PDFtools {
    static Context mContext;
     public PDFtools(Context mContext) {
           PDFtools.mContext = mContext;
     }

    private static final String GOOGLE_DRIVE_PDF_READER_PREFIX = "http://drive.google.com/viewer?url=";
    private static final String PDF_MIME_TYPE = "application/pdf";
    private static final String HTML_MIME_TYPE = "text/html";

    /**
     * If a PDF reader is installed, download the PDF file and open it in a reader.
     * Otherwise ask the user if he/she wants to view it in the Google Drive online PDF reader.<br />
     * <br />
     * <b>BEWARE:</b> This method
     * @param context
     * @param pdfUrl
     * @return
     */

    public static void showPDFUrl( final Context context, final String pdfUrl ) {
        if ( isPDFSupported( context ) ) {
            downloadAndOpenPDF(context, pdfUrl);
        } else {
            askToOpenPDFThroughGoogleDrive( context, pdfUrl );
        }
    }

    /**
     * Downloads a PDF with the Android DownloadManager and opens it with an installed PDF reader app.
     * @param context
     * @param pdfUrl
     */
    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public static void downloadAndOpenPDF(final Context context, final String pdfUrl) {
        // Get filename
        final String filename = pdfUrl.substring( pdfUrl.lastIndexOf( "/" ) + 1 );
        // The place where the downloaded PDF file will be put
        final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), filename );
        if ( tempFile.exists() ) {
            // If we have downloaded the file before, just go ahead and show it.
            openPDF( context, Uri.fromFile( tempFile ) );
            return;
        }

        // Show progress dialog while downloading
        final ProgressDialog progress = ProgressDialog.show( context, context.getString( R.string.pdf_show_local_progress_title ), context.getString( R.string.pdf_show_local_progress_title), true );

        // Create the download request
        DownloadManager.Request r = new DownloadManager.Request( Uri.parse( pdfUrl ) );
        r.setDestinationInExternalFilesDir( context, Environment.DIRECTORY_DOWNLOADS, filename );

        final DownloadManager dm = (DownloadManager) context.getSystemService( Context.DOWNLOAD_SERVICE );

        BroadcastReceiver onComplete = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if ( !progress.isShowing() ) {
                    return;
                }

                context.unregisterReceiver( this );

                progress.dismiss();
                long downloadId = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID, -1 );
                Cursor c = dm.query( new DownloadManager.Query().setFilterById( downloadId ) );

                if ( c.moveToFirst() ) {
                    int status = c.getInt( c.getColumnIndex( DownloadManager.COLUMN_STATUS ) );
                    if ( status == DownloadManager.STATUS_SUCCESSFUL ) {
                        openPDF( context, Uri.fromFile( tempFile ) );
                    }
                }
                c.close();
            }
        };
        context.registerReceiver( onComplete, new IntentFilter( DownloadManager.ACTION_DOWNLOAD_COMPLETE ) );

        // Enqueue the request
        dm.enqueue( r );
    }

    /**
     * Show a dialog asking the user if he wants to open the PDF through Google Drive
     * @param context
     * @param pdfUrl
     */
    public static void askToOpenPDFThroughGoogleDrive( final Context context, final String pdfUrl ) {
        new AlertDialog.Builder( context )
            .setTitle("PDF reader not installed!")
            .setMessage( "Do you want to open it with Google Drive ?" )
            .setNegativeButton( "No", null )
            .setPositiveButton( "Yes", new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    openPDFThroughGoogleDrive(context, pdfUrl);
                }
            })
            .show();
    }

    /**
     * Launches a browser to view the PDF through Google Drive
     * @param context
     * @param pdfUrl
     */
    public static void openPDFThroughGoogleDrive(final Context context, final String pdfUrl) {
        Intent i = new Intent( Intent.ACTION_VIEW );
        i.setDataAndType(Uri.parse(GOOGLE_DRIVE_PDF_READER_PREFIX + pdfUrl ), HTML_MIME_TYPE );
        context.startActivity( i );
    }
    /**
     * Open a local PDF file with an installed reader
     * @param context
     * @param localUri
     */
    public static final void openPDF(Context context, Uri localUri ) {
        Intent i = new Intent( Intent.ACTION_VIEW );
        i.setDataAndType( localUri, PDF_MIME_TYPE );
        context.startActivity( i );
    }
    /**
     * Checks if any apps are installed that supports reading of PDF files.
     * @param context
     * @return
     */
    public static boolean isPDFSupported( Context context ) {
        Intent i = new Intent( Intent.ACTION_VIEW );
        final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), "test.pdf" );
        i.setDataAndType( Uri.fromFile( tempFile ), PDF_MIME_TYPE );
        return context.getPackageManager().queryIntentActivities( i, PackageManager.MATCH_DEFAULT_ONLY ).size() > 0;
    }

}
</code>```

答:
This can be achieved by performing a query to the download manager.
It's pretty straightforward, you probably want to query for the columns
COLUMN_BYTES_DOWNLOADED_SO_FAR and COLUMN_TOTAL_SIZE_BYTES.

After getting those numbers you should set the actual progress in the progress bar by calling ProgressDialog.setProgress.

An example of how to make the query can be found here

Body:
i am developing an app in which a user can read pdf books online/offline. If he has pdf reader installed then the book gets downloaded from the server and gets opened in that pdf reader but if he don't have a pdf reader installed then in that case pdf is opened online(using google docs link).

Now, when downloading a pdf file i want to display a progress dialog to the user but don't know how to set the percentage of file being downloaded ..I've searched for this but all the solutions given are for http connection.In my case it would be in a different manner i guess. So kindly check my code and then suggest me a way to do so. Thanks in advance.

PDFtools.java

public class PDFtools {
    static Context mContext;
     public PDFtools(Context mContext) {
           PDFtools.mContext = mContext;
     }

    private static final String GOOGLE_DRIVE_PDF_READER_PREFIX = "http://drive.google.com/viewer?url=";
    private static final String PDF_MIME_TYPE = "application/pdf";
    private static final String HTML_MIME_TYPE = "text/html";

    /**
     * If a PDF reader is installed, download the PDF file and open it in a reader.
     * Otherwise ask the user if he/she wants to view it in the Google Drive online PDF reader.

     *

     * BEWARE: This method
     * @param context
     * @param pdfUrl
     * @return
     */

    public static void showPDFUrl( final Context context, final String pdfUrl ) {
        if ( isPDFSupported( context ) ) {
            downloadAndOpenPDF(context, pdfUrl);
        } else {
            askToOpenPDFThroughGoogleDrive( context, pdfUrl );
        }
    }

    /**
     * Downloads a PDF with the Android DownloadManager and opens it with an installed PDF reader app.
     * @param context
     * @param pdfUrl
     */
    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public static void downloadAndOpenPDF(final Context context, final String pdfUrl) {
        // Get filename
        final String filename = pdfUrl.substring( pdfUrl.lastIndexOf( "/" ) + 1 );
        // The place where the downloaded PDF file will be put
        final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), filename );
        if ( tempFile.exists() ) {
            // If we have downloaded the file before, just go ahead and show it.
            openPDF( context, Uri.fromFile( tempFile ) );
            return;
        }

        // Show progress dialog while downloading
        final ProgressDialog progress = ProgressDialog.show( context, context.getString( R.string.pdf_show_local_progress_title ), context.getString( R.string.pdf_show_local_progress_title), true );

        // Create the download request
        DownloadManager.Request r = new DownloadManager.Request( Uri.parse( pdfUrl ) );
        r.setDestinationInExternalFilesDir( context, Environment.DIRECTORY_DOWNLOADS, filename );

        final DownloadManager dm = (DownloadManager) context.getSystemService( Context.DOWNLOAD_SERVICE );

        BroadcastReceiver onComplete = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if ( !progress.isShowing() ) {
                    return;
                }

                context.unregisterReceiver( this );

                progress.dismiss();
                long downloadId = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID, -1 );
                Cursor c = dm.query( new DownloadManager.Query().setFilterById( downloadId ) );

                if ( c.moveToFirst() ) {
                    int status = c.getInt( c.getColumnIndex( DownloadManager.COLUMN_STATUS ) );
                    if ( status == DownloadManager.STATUS_SUCCESSFUL ) {
                        openPDF( context, Uri.fromFile( tempFile ) );
                    }
                }
                c.close();
            }
        };
        context.registerReceiver( onComplete, new IntentFilter( DownloadManager.ACTION_DOWNLOAD_COMPLETE ) );

        // Enqueue the request
        dm.enqueue( r );
    }

    /**
     * Show a dialog asking the user if he wants to open the PDF through Google Drive
     * @param context
     * @param pdfUrl
     */
    public static void askToOpenPDFThroughGoogleDrive( final Context context, final String pdfUrl ) {
        new AlertDialog.Builder( context )
            .setTitle("PDF reader not installed!")
            .setMessage( "Do you want to open it with Google Drive ?" )
            .setNegativeButton( "No", null )
            .setPositiveButton( "Yes", new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    openPDFThroughGoogleDrive(context, pdfUrl);
                }
            })
            .show();
    }

    /**
     * Launches a browser to view the PDF through Google Drive
     * @param context
     * @param pdfUrl
     */
    public static void openPDFThroughGoogleDrive(final Context context, final String pdfUrl) {
        Intent i = new Intent( Intent.ACTION_VIEW );
        i.setDataAndType(Uri.parse(GOOGLE_DRIVE_PDF_READER_PREFIX + pdfUrl ), HTML_MIME_TYPE );
        context.startActivity( i );
    }
    /**
     * Open a local PDF file with an installed reader
     * @param context
     * @param localUri
     */
    public static final void openPDF(Context context, Uri localUri ) {
        Intent i = new Intent( Intent.ACTION_VIEW );
        i.setDataAndType( localUri, PDF_MIME_TYPE );
        context.startActivity( i );
    }
    /**
     * Checks if any apps are installed that supports reading of PDF files.
     * @param context
     * @return
     */
    public static boolean isPDFSupported( Context context ) {
        Intent i = new Intent( Intent.ACTION_VIEW );
        final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), "test.pdf" );
        i.setDataAndType( Uri.fromFile( tempFile ), PDF_MIME_TYPE );
        return context.getPackageManager().queryIntentActivities( i, PackageManager.MATCH_DEFAULT_ONLY ).size() > 0;
    }

}


问:
Javascript shorthand loading time
I was playing around so I ran into a JS shorthands. I know they, of course, do not change code however do they lower loading time since there is less data?

Testing codes such as one below in Chrome DOM inspector did not give me an answer (probably because they are one-line codes so it does not make any difference).

```<code>if (x == 0) {x=1} else {x=2}
x == 0 ? x = 1 : x = 2;
</code>```

答:
The less characters and whitespace in a file, the lower the download size of said scripts is.

Readability is also a matter of utmost importance though, and ternary operators can be confusing in certain scenarios.

I would recommend that for those cases where you expect your codebase to increase to a certain extend over time, you stick to more readable constructs and use a minification/uglification process to lower file size.

Title: Javascript shorthand loading time

Body:
I was playing around so I ran into a JS shorthands. I know they, of course, do not change code however do they lower loading time since there is less data?

Testing codes such as one below in Chrome DOM inspector did not give me an answer (probably because they are one-line codes so it does not make any difference).

if (x == 0) {x=1} else {x=2}
x == 0 ? x = 1 : x = 2;


问:
Change css classes for specified id only
I try to override some basic classes of complex control (dxList) DevExtreme, and it's work fine.

```<code>.dx-loadpanel-content {
    transform: translate(0px, 0px) !important;
    margin: auto !important;
    left: 0px !important;
    top: 0px !important;
    position: absolute !important;
}

.dx-scrollview-loadpanel {
    transform: translate(0px, 0px) !important;
    margin: auto !important;
    left: 50% !important;
    top: 50% !important;
    position: absolute !important;
}
</code>```

but it's not good idea for me, because this classes are already used on different html pages.

I want override this classes only for specified dxList by some id.
Like this:

```<code>#activitiesList .dx-loadpanel-content {
    transform: translate(0px, 0px) !important;
    margin: auto !important;
    left: 0px !important;
    top: 0px !important;
    position: absolute !important;
}

#activitiesList .dx-scrollview-loadpanel {
    transform: translate(0px, 0px) !important;
    margin: auto !important;
    left: 50% !important;
    top: 50% !important;
    position: absolute !important;
}
</code>```

but it takes no effect. whats wrong?

答: Is the class and id on the same element? Then remove the space between them like #myid.myclass if the class is for a child element inside your element that has the id use the space between them. Hope this helps you.</p>

Body:
I try to override some basic classes of complex control (dxList) DevExtreme, and it's work fine.

.dx-loadpanel-content {
    transform: translate(0px, 0px) !important;
    margin: auto !important;
    left: 0px !important;
    top: 0px !important;
    position: absolute !important;
}

.dx-scrollview-loadpanel {
    transform: translate(0px, 0px) !important;
    margin: auto !important;
    left: 50% !important;
    top: 50% !important;
    position: absolute !important;
}

but it's not good idea for me, because this classes are already used on different html pages.

I want override this classes only for specified dxList by some id.
Like this:

#activitiesList .dx-loadpanel-content {
    transform: translate(0px, 0px) !important;
    margin: auto !important;
    left: 0px !important;
    top: 0px !important;
    position: absolute !important;
}

#activitiesList .dx-scrollview-loadpanel {
    transform: translate(0px, 0px) !important;
    margin: auto !important;
    left: 50% !important;
    top: 50% !important;
    position: absolute !important;
}

but it takes no effect. whats wrong?


问:
Can an Actor handle click and key down events?
I'm trying to make an Actor handle both click and key down events. I initialized the actor (in this case, an Image) as following:

```<code>stage = new Stage();
texture = new Texture("badlogic.jpg");
Image image = new Image(texture);
image.addListener(new ClickListener() {
    @Override
    public void clicked(InputEvent event, float x, float y) {
        Gdx.app.log("Image ClickListener", "clicked");
    }

    @Override
    public boolean keyDown(InputEvent event, int keycode) {
        Gdx.app.log("Image ClickListener", "keyDown. keycode=" + keycode);
        return true;
    }
});
stage.addActor(image);
Gdx.input.setInputProcessor(stage);
</code>```

When I click on image, the clicked event is fired as expected, i.e., I see the respective log. However, no matter what key I press, the key down event does not fire. My question is: Why? Can't an Actor be able to handle both click and key down events?

答:
Create a custom class that extends the Actor class and implements the InputProcessor interface.

When you set up your game, use an InputMultiplexer:

```<code>InputMultiplexer inputMulti = new InputMultiplexer(stage);
Gdx.input.setInputProcessor( inputMulti );
</code>```

Then, in the constructor of your custom class, you can add the instance being created to the multiplexer as follows:

```<code>((InputMultiplexer)Gdx.input.getInputProcessor()).addProcessor(this);
</code>```

Handling key input functionality then becomes simpler: instead of using the addListener method and creating an anonymous inner class that extends ClickListener etc. etc., you can just use the InputProcessor methods, for example:

```<code>public boolean keyDown(int keycode)
{
    if (keycode == Keys.SPACE)
    {
        // do something
    }

    return false;
}
</code>```

This also avoids the need to set keyboard focus on the actor, which might not generalize well if you have multiple actors that need to process keyboard input.

However, one caveat to this approach is that any actor configured as an input processor will process all input events now, including touch events that do not overlap the actor, and this behavior may be undesired and/or confusing.

Body:
I'm trying to make an Actor handle both click and key down events. I initialized the actor (in this case, an Image) as following:

stage = new Stage();
texture = new Texture("badlogic.jpg");
Image image = new Image(texture);
image.addListener(new ClickListener() {
    @Override
    public void clicked(InputEvent event, float x, float y) {
        Gdx.app.log("Image ClickListener", "clicked");
    }

    @Override
    public boolean keyDown(InputEvent event, int keycode) {
        Gdx.app.log("Image ClickListener", "keyDown. keycode=" + keycode);
        return true;
    }
});
stage.addActor(image);
Gdx.input.setInputProcessor(stage);

When I click on image, the clicked event is fired as expected, i.e., I see the respective log. However, no matter what key I press, the key down event does not fire. My question is: Why? Can't an Actor be able to handle both click and key down events?

Body:
Create a custom class that extends the Actor class and implements the InputProcessor interface.

When you set up your game, use an InputMultiplexer:

InputMultiplexer inputMulti = new InputMultiplexer(stage);
Gdx.input.setInputProcessor( inputMulti );

Then, in the constructor of your custom class, you can add the instance being created to the multiplexer as follows:

((InputMultiplexer)Gdx.input.getInputProcessor()).addProcessor(this);

Handling key input functionality then becomes simpler: instead of using the addListener method and creating an anonymous inner class that extends ClickListener etc. etc., you can just use the InputProcessor methods, for example:

public boolean keyDown(int keycode)
{
    if (keycode == Keys.SPACE)
    {
        // do something
    }

    return false;
}

This also avoids the need to set keyboard focus on the actor, which might not generalize well if you have multiple actors that need to process keyboard input.

However, one caveat to this approach is that any actor configured as an input processor will process all input events now, including touch events that do not overlap the actor, and this behavior may be undesired and/or confusing.


问:
How to set a control resource dictionary in a Style in XAML?
I have a UI in Silverlight with some borders, and with a TextBlock inside that borders. There will be other TextBlocks outside borders.

```<code><Border>
    <TextBlock>This text should be centered</TextBlock>
</Border>

<Border>
    <TextBlock>This one too</TextBlock>
</Border>

<TextBlock>this one shouldn't</TextBlock>
</code>```

What I'm trying to achieve is to format all TextBlock's inside a Border, without having to set the style in every TextBlock. If it was CSS , it will be something like that : .border .textBlock { (...) }

I know i can set a style inside the scope of a border:

```<code><Border>
    <Border.Resources>
        <Style TargetType="TextBlock" BasedOn="{StaticResource DefaultTextBlockStyle}">
            <Setter Property="HorizontalAlignment" Value="Center"></Setter>
        </Style>
    </Border.Resources>
    <TextBlock>Centered Text</TextBlock>
</Border>
</code>```

But I would still need to set this to every border in my page. So now i presente the question, can i set  in a style, in order to set it one time to affect all Borders? I tried the code bellow, but it didn't work. It didn't give me any errors, but it didn't affect the TextBlock formatting either.

```<code><Style TargetType="Border">
    <Setter Property="Resources">
        <Setter.Value>
            <ResourceDictionary>
                <Style TargetType="TextBlock">
                    <Setter Property="HorizontalAlignment" Value="Center" />
                </Style>
            </ResourceDictionary>
        </Setter.Value>
    </Setter>
</Style>
</code>```

答:
Try this:

```<code><Style TargetType="Border">
    <Style.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="HorizontalAlignment" Value="Center" />
        </Style>
    </Style.Resources>
</Style>
</code>```

This works in WPF. In Silverlight I am afraid you cannot do this though.

Body:
I have a UI in Silverlight with some borders, and with a TextBlock inside that borders. There will be other TextBlocks outside borders.

<Border>
    <TextBlock>This text should be centered</TextBlock>
</Border>

<Border>
    <TextBlock>This one too</TextBlock>
</Border>

<TextBlock>this one shouldn't</TextBlock>

What I'm trying to achieve is to format all TextBlock's inside a Border, without having to set the style in every TextBlock. If it was CSS , it will be something like that : .border .textBlock { (...) }

I know i can set a style inside the scope of a border:

<Border>
    <Border.Resources>

    </Border.Resources>
    <TextBlock>Centered Text</TextBlock>
</Border>

But I would still need to set this to every border in my page. So now i presente the question, can i set  in a style, in order to set it one time to affect all Borders? I tried the code bellow, but it didn't work. It didn't give me any errors, but it didn't affect the TextBlock formatting either.

            </ResourceDictionary>
        </Setter.Value>
    </Setter>
</Style>

Body:
Try this:

<Style TargetType="Border">
    <Style.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="HorizontalAlignment" Value="Center" />
        </Style>
    </Style.Resources>
</Style>

This works in WPF. In Silverlight I am afraid you cannot do this though.


问:
How to append unicode string to list of strings in Julia?
For integers, list comprehension can be done with:

```<code>julia> nums = [1,2,3,4]
4-element Array{Int64,1}:
 1
 2
 3
 4

julia> nums = [i+1 for i in nums]
4-element Array{Int64,1}:
 2
 3
 4
 5
</code>```

But when I tried to add a character to a string, it throws an error:

```<code>julia> s = split("the lazy fox jumps over the brown dog")
8-element Array{SubString{String},1}:
 "the"
 "lazy"
 "fox"
 "jumps"
 "over"
 "the"
 "brown"
 "dog"

julia> s2 = [word +'X' for word in s]
ERROR: syntax: invalid comprehension syntax
</code>```

And when the character is a private unicode char (http://www.fileformat.info/info/unicode/char/e000/index.htm), it throws another error:

```<code>julia> s2 = [word + u'\uE000' for word in s]
</code>```

ERROR: UndefVarError: u not defined
 in collect(::Base.Generator{Array{SubString{String},1},##3#4}) at ./array.jl:307

How to append unicode char/string to list of strings in Julia?

答:
To quickly answer your question, the correct way is

```<code>[i*"X" for i in s]
</code>```

However, please remember 'X' is  and "X" are two different things.

```<code>julia> val = 'X'
'X'
julia> typeof(val)
Char

julia> val = "X"
"X"
julia> typeof(val)
String
</code>```

This may happen initially if you have a Python background where there is no difference between the two.

Also string concatenation in Julia is done by * and not +!
You may ask as to why is that so! Well have a look at this post here

Body:
For integers, list comprehension can be done with:

julia> nums = [1,2,3,4]
4-element Array{Int64,1}:
 1
 2
 3
 4

julia> nums = [i+1 for i in nums]
4-element Array{Int64,1}:
 2
 3
 4
 5

But when I tried to add a character to a string, it throws an error:

julia> s = split("the lazy fox jumps over the brown dog")
8-element Array{SubString{String},1}:
 "the"
 "lazy"
 "fox"
 "jumps"
 "over"
 "the"
 "brown"
 "dog"

julia> s2 = [word +'X' for word in s]
ERROR: syntax: invalid comprehension syntax

And when the character is a private unicode char (http://www.fileformat.info/info/unicode/char/e000/index.htm), it throws another error:

julia> s2 = [word + u'\uE000' for word in s]

ERROR: UndefVarError: u not defined
 in collect(::Base.Generator{Array{SubString{String},1},##3#4}) at ./array.jl:307

How to append unicode char/string to list of strings in Julia?

Body:
To quickly answer your question, the correct way is

[i*"X" for i in s]

However, please remember 'X' is  and "X" are two different things.

julia> val = 'X'
'X'
julia> typeof(val)
Char

julia> val = "X"
"X"
julia> typeof(val)
String

This may happen initially if you have a Python background where there is no difference between the two.

Also string concatenation in Julia is done by * and not +!
You may ask as to why is that so! Well have a look at this post here


问:
Regex for filename if known extension
I have come up with a regex to find me all the image within a project.

```<code>(\/|\\)(.*)\.(gif|png|jpg|jpeg)
</code>```

What I am trying to do now, is find the extension (gif|jpg|etc...) and then capture the word preceeding that match (ie the filename).

I'm totally stuck on how to structure a lookbehind capture group(??)

What I am doing is looking through a large web project finding all the images that have been actually used in code, and then I'm going to clean up the image directory for ones that are no longer referenced.

答:
With Npp, you could search:

```<code>([^\/\\]+)(?=\.(gif|png|jpg|jpeg))
</code>```

or

```<code>([^\/\\]+)(?=\.(?:gif|png|jpe?g))
</code>```

to match the filename.

According to comment, you can do the find/replace with:

Ctrl+H

Find what: ^.*?([^\/\\]+\.(?:gif|png|jpe?g)).*?$

Replace with: $1

Replace all

This will remove everything in a line except the filename+extension.

Title: Regex for filename if known extension

Body:
I have come up with a regex to find me all the image within a project.

(\/|\\)(.*)\.(gif|png|jpg|jpeg)

What I am trying to do now, is find the extension (gif|jpg|etc...) and then capture the word preceeding that match (ie the filename).

I'm totally stuck on how to structure a lookbehind capture group(??)

What I am doing is looking through a large web project finding all the images that have been actually used in code, and then I'm going to clean up the image directory for ones that are no longer referenced.

Body:
With Npp, you could search:

([^\/\\]+)(?=\.(gif|png|jpg|jpeg))

or

([^\/\\]+)(?=\.(?:gif|png|jpe?g))

to match the filename.

According to comment, you can do the find/replace with:

Ctrl+H

Find what: ^.*?([^\/\\]+\.(?:gif|png|jpe?g)).*?$

Replace with: $1

Replace all

This will remove everything in a line except the filename+extension.


问:
Is there a way to create an ecommerce site using zend?
The title might be a bit misleading. As you can see, we created a site for a client. Afterwards, he decided to add ecommerce-like module wherein the user's may avail items from the site. This was not the main intention of the site but the client doesn't want a new one but rather, update the site and add an ecommerce feature.

We are planning to do it manually... I was just thinking if there's a better way of doing it? are there any tools or plugin code or way that we can do it?

答:
Ecommerce site magento

Here is a link for

http://www.magentocommerce.com/


问:
Google places radar search with a radius greater than 50,000 meters
I'm trying to find all Panera restaurants within a 200 mile radius of a certain point.

Here is the URL I have been using so far :

```<code>https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=39.52963,-119.81380&radius=321869&type=restaurant&name=panera&key=your-key-here
</code>```

However, I have found out that radius has a maximum of 30 miles. Can anyone suggest a quick workaround for me?

Thanks to all in advance.

答:
Business license with for higher usage limits.
Contact Google sales

Google place nearby search maximum 50,000 meters (31 miles) .
if you try enter more than 50,000 it not work proper.

There is another way for find all restaurants in a city.
google provide Text Search Requests

```<code>https://maps.googleapis.com/maps/api/place/textsearch/json?query=restaurants+in+Reno,NV,89501,USA&key={API_KEY}
</code>```

query = keyword + in +  city Name

for get city name using latitude longitude

```<code>http://maps.googleapis.com/maps/api/geocode/json?latlng=39.52963,-119.81380&sensor=true
</code>```

For more information how to get city name using latitude longitude

https://developers.google.com/maps/documentation/geocoding/start?csw=1#ReverseGeocoding

for more information about how to use Text Search Requests

https://developers.google.com/places/web-service/search

Body:
I'm trying to find all Panera restaurants within a 200 mile radius of a certain point.

Here is the URL I have been using so far :

https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=39.52963,-119.81380&radius=321869&type=restaurant&name=panera&key=your-key-here

However, I have found out that radius has a maximum of 30 miles. Can anyone suggest a quick workaround for me?

Thanks to all in advance.

Body:
Business license with for higher usage limits.
Contact Google sales

Google place nearby search maximum 50,000 meters (31 miles) .
if you try enter more than 50,000 it not work proper.

There is another way for find all restaurants in a city.
google provide Text Search Requests

https://maps.googleapis.com/maps/api/place/textsearch/json?query=restaurants+in+Reno,NV,89501,USA&key={API_KEY}

query = keyword + in +  city Name

for get city name using latitude longitude

http://maps.googleapis.com/maps/api/geocode/json?latlng=39.52963,-119.81380&sensor=true

For more information how to get city name using latitude longitude

https://developers.google.com/maps/documentation/geocoding/start?csw=1#ReverseGeocoding

for more information about how to use Text Search Requests

https://developers.google.com/places/web-service/search


问:
Swift: Display HTML data in a label or textView
I have some HTML data, which contains headings, paragraphs , images and lists tags.

Is there a way to display this data in one UITextView or UILabel?

答:
Swift 3</p>

```<code>extension String {

var html2AttributedString: NSAttributedString? {
    guard
        let data = data(using: String.Encoding.utf8)
        else { return nil }
    do {
        return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:String.Encoding.utf8], documentAttributes: nil)
    } catch let error as NSError {
        print(error.localizedDescription)
        return  nil
    }
}
var html2String: String {
    return html2AttributedString?.string ?? ""
 }
}
</code>```

Body:
Swift 3

extension String {

var html2AttributedString: NSAttributedString? {
    guard
        let data = data(using: String.Encoding.utf8)
        else { return nil }
    do {
        return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:String.Encoding.utf8], documentAttributes: nil)
    } catch let error as NSError {
        print(error.localizedDescription)
        return  nil
    }
}
var html2String: String {
    return html2AttributedString?.string ?? ""
 }
}