问:
AJAX Form Submitting (Only on Firefox)
I am running an AJAX contact form on my website (www.chrisanstey.co.uk), which is not submitting only in Firefox, but works absolute fine in every other browser. The form is uses the following PHP file:

```<code><?php

$to = "me@somewhere.com"; //This is the email address you want to send the email to

if(!isset($_GET['action']))
{
die("You must not access this page directly!"); //Just to stop people from visiting contact.php normally
}

/* Now lets trim up the input before sending it */

$name = trim($_GET['name']); //The senders name
$email = trim($_GET['email']); //The senders email address
$subject = "A message sent from " . $name . " on Chris Anstey's portfolio"; //The senders subject
$message = trim($_GET['msg']); //The senders message

mail($to,$subject,$message,"From: ".$email.""); //a very simple send

echo 'contactarea|<p>Thank you '.$name.' for your message, I will reply to you as soon as I can.</p>'; //now lets update the "contactarea" div on the contact.html page. The contactarea| tell's the javascript which div to update.
?>
</code>```

and also the following javascript file:

```<code>function createRequestObject() {
    var ro;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer"){
        ro = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
        ro = new XMLHttpRequest();
    }
    return ro;
}

var http = createRequestObject();

function sendemail() {
 var msg = document.contactform.msg.value;
 var name = document.contactform.name.value;
 var email = document.contactform.email.value;
 document.contactform.send.disabled=true;
 document.contactform.send.value='Sending....';

    http.open('get', 'contact.php?msg='+msg+'&name='+name+'&email='+email+'&action=send');
    http.onreadystatechange = handleResponse;
    http.send(null);
}

function handleResponse() {
    if(http.readyState == 4){
        var response = http.responseText;
        var update = new Array();

        if(response.indexOf('|' != -1)) {
            update = response.split('|');
            document.getElementById(update[0]).innerHTML = update[1];

        }
    }
}
</code>```

The form is within a Wordpress page, being called on the template by the following HTML:

```<code><div id="contactarea">
<form name="contactform" id="contactform">
<p>Full Name:<br />
    <span class="wpcf7-form-control-wrap your-name"><input type="text" name="name"></span></p>
<p>Email:<br />
    <span class="wpcf7-form-control-wrap your-email"><input type="text" name="email"></span></p>
<p>Message:<br />
    <span class="wpcf7-form-control-wrap your-message"><textarea name="msg" rows="6" id="textarea"></textarea></span></p>
<p><input type="submit" value="Send Email" name="send" id="submitbutton" onClick="sendemail();"></p>
</form>
</div>
</code>```

If anyone has any idea or has encountered similar problems with AJAX not working within Firefox, please could you reply. Any help would be much appreciated!

答:
i've tested it in firefox and the ajax call works fine... i dont think that's the problem.. try installing firebug addon on firefox so we could see what's the error message

EDIT:
if i understood correctly from your comment, the page changes when you click on the submit button, and you dont want that... if that's it, then just change the onClick attribute on your submit button to this

```<code>onClick="sendemail();return false;"
</code>```

or change your input submit to a input button... that's because when you click on a submit button, the form is sended even if you have a onClick event, so the return false should stop it... it's the same with links when you want to prevent the default event

Good luck

Title: AJAX Form Submitting (Only on Firefox)

Body:
I am running an AJAX contact form on my website (www.chrisanstey.co.uk), which is not submitting only in Firefox, but works absolute fine in every other browser. The form is uses the following PHP file:

<?php

$to = "me@somewhere.com"; //This is the email address you want to send the email to

if(!isset($_GET['action']))
{
die("You must not access this page directly!"); //Just to stop people from visiting contact.php normally
}

/* Now lets trim up the input before sending it */

$name = trim($_GET['name']); //The senders name
$email = trim($_GET['email']); //The senders email address
$subject = "A message sent from " . $name . " on Chris Anstey's portfolio"; //The senders subject
$message = trim($_GET['msg']); //The senders message

mail($to,$subject,$message,"From: ".$email.""); //a very simple send

echo 'contactarea|
Thank you '.$name.' for your message, I will reply to you as soon as I can.
'; //now lets update the "contactarea" div on the contact.html page. The contactarea| tell's the javascript which div to update.
?>

and also the following javascript file:

function createRequestObject() {
    var ro;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer"){
        ro = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
        ro = new XMLHttpRequest();
    }
    return ro;
}

var http = createRequestObject();

function sendemail() {
 var msg = document.contactform.msg.value;
 var name = document.contactform.name.value;
 var email = document.contactform.email.value;
 document.contactform.send.disabled=true;
 document.contactform.send.value='Sending....';

    http.open('get', 'contact.php?msg='+msg+'&name='+name+'&email='+email+'&action=send');
    http.onreadystatechange = handleResponse;
    http.send(null);
}

function handleResponse() {
    if(http.readyState == 4){
        var response = http.responseText;
        var update = new Array();

        if(response.indexOf('|' != -1)) {
            update = response.split('|');
            document.getElementById(update[0]).innerHTML = update[1];

        }
    }
}

The form is within a Wordpress page, being called on the template by the following HTML:

<form name="contactform" id="contactform">

Full Name:

    <input type="text" name="name">

Email:

    <input type="text" name="email">

Message:

    <textarea name="msg" rows="6" id="textarea"></textarea>

<input type="submit" value="Send Email" name="send" id="submitbutton" onClick="sendemail();">

</form>

If anyone has any idea or has encountered similar problems with AJAX not working within Firefox, please could you reply. Any help would be much appreciated!

Body:
i've tested it in firefox and the ajax call works fine... i dont think that's the problem.. try installing firebug addon on firefox so we could see what's the error message

EDIT:
if i understood correctly from your comment, the page changes when you click on the submit button, and you dont want that... if that's it, then just change the onClick attribute on your submit button to this

onClick="sendemail();return false;"

or change your input submit to a input button... that's because when you click on a submit button, the form is sended even if you have a onClick event, so the return false should stop it... it's the same with links when you want to prevent the default event

Good luck


来源: stackexchange

问:
Why does my Spring Boot App always shutdown immediately after starting?
This is my first Spring Boot code. Unfortunately, it always shuts down. I was expecting it to run continuously so that my web client can get some data from the browser.

```<code>package hello;
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;

@Controller
@EnableAutoConfiguration
public class SampleController {

    @RequestMapping("/")
    @ResponseBody
    String home() {
        return "Hello World!";
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(SampleController.class, args);
    }
}

[@localhost initial]$ java -jar build/libs/gs-spring-boot-0.1.0.jar

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::            (v1.0.0.RC4)

2014-03-13 09:20:24.805  INFO 14650 --- [           main] hello.SampleController                   : Starting SampleController on localhost.localdomain with PID 14650 (/home/xxx/dev/gs-spring-boot/initial/build/libs/gs-spring-boot-0.1.0.jar started by xxx)
2014-03-13 09:20:25.002  INFO 14650 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@b9eec: startup date [Thu Mar 13 09:20:24 EDT 2014]; root of context hierarchy
2014-03-13 09:20:28.833  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Registering beans for JMX exposure on startup
2014-03-13 09:20:30.148  INFO 14650 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 0
2014-03-13 09:20:30.154  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'requestMappingEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=requestMappingEndpoint]
2014-03-13 09:20:30.316  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'environmentEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=environmentEndpoint]
2014-03-13 09:20:30.335  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'healthEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=healthEndpoint]
2014-03-13 09:20:30.351  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'beansEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=beansEndpoint]
2014-03-13 09:20:30.376  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'infoEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=infoEndpoint]
2014-03-13 09:20:30.400  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'metricsEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=metricsEndpoint]
2014-03-13 09:20:30.413  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'traceEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=traceEndpoint]
2014-03-13 09:20:30.428  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'dumpEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=dumpEndpoint]
2014-03-13 09:20:30.450  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'autoConfigurationAuditEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=autoConfigurationAuditEndpoint]
2014-03-13 09:20:30.465  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'shutdownEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=shutdownEndpoint]
2014-03-13 09:20:30.548  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'configurationPropertiesReportEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=configurationPropertiesReportEndpoint]
2014-03-13 09:20:30.589  INFO 14650 --- [           main] hello.SampleController                   : Started SampleController in 7.396 seconds (JVM running for 9.569)
2014-03-13 09:20:30.608  INFO 14650 --- [       Thread-2] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@b9eec: startup date [Thu Mar 13 09:20:24 EDT 2014]; root of context hierarchy
2014-03-13 09:20:30.610  INFO 14650 --- [       Thread-2] o.s.c.support.DefaultLifecycleProcessor  : Stopping beans in phase 0
2014-03-13 09:20:30.624  INFO 14650 --- [       Thread-2] o.s.b.a.e.jmx.EndpointMBeanExporter      : Unregistering JMX-exposed beans on shutdown
</code>```

Please advise.

Thanks

P.S. build.gradle is the fault.

```<code>dependencies {
    // tag::jetty[]
    compile("org.springframework.boot:spring-boot-starter-web") {
        **exclude module: "spring-boot-starter-tomcat"**
    }
</code>```

Once I took off the above line in bold, everything works. My application context now is correct. Thanks Dave

```<code>  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::            (v1.0.0.RC4)

2014-03-13 13:58:08.965  INFO 7307 --- [           main] hello.Application                        : Starting
 Application on  with PID 7307 (/ladev/home/xxx/dev/gs-spring-boot/initial/build/libs/gs-spring-boo
t-0.1.0.jar started by xxx)
2014-03-13 13:58:09.021  INFO 7307 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshi
ng org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@45490eb5: startup
 date [Thu Mar 13 13:58:09 MDT 2014]; root of context hierarchy
2014-03-13 13:58:09.653  INFO 7307 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overridi
ng bean definition for bean 'beanNameViewResolver': replacing [Root bean: class [null]; scope=; abstract=fal
se; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanNam
e=org.springframework.boot.actuate.autoconfigure.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration;
 factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class
 path resource [org/springframework/boot/actuate/autoconfigure/ErrorMvcAutoConfiguration$WhitelabelErrorView
Configuration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3;
 dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconf
igure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; in
itMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/au
toconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]
</code>```

答:
I had the same problem but when I removed the below dependency it worked fine

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency>

```

it started working again.

ContentLicense: CC BY-SA 3.0

Body:
This is my first Spring Boot code. Unfortunately, it always shuts down. I was expecting it to run continuously so that my web client can get some data from the browser.

package hello;
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;

@Controller
@EnableAutoConfiguration
public class SampleController {

    @RequestMapping("/")
    @ResponseBody
    String home() {
        return "Hello World!";
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(SampleController.class, args);
    }
}

[@localhost initial]$ java -jar build/libs/gs-spring-boot-0.1.0.jar

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::            (v1.0.0.RC4)

2014-03-13 09:20:24.805  INFO 14650 --- [           main] hello.SampleController                   : Starting SampleController on localhost.localdomain with PID 14650 (/home/xxx/dev/gs-spring-boot/initial/build/libs/gs-spring-boot-0.1.0.jar started by xxx)
2014-03-13 09:20:25.002  INFO 14650 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@b9eec: startup date [Thu Mar 13 09:20:24 EDT 2014]; root of context hierarchy
2014-03-13 09:20:28.833  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Registering beans for JMX exposure on startup
2014-03-13 09:20:30.148  INFO 14650 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 0
2014-03-13 09:20:30.154  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'requestMappingEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=requestMappingEndpoint]
2014-03-13 09:20:30.316  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'environmentEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=environmentEndpoint]
2014-03-13 09:20:30.335  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'healthEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=healthEndpoint]
2014-03-13 09:20:30.351  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'beansEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=beansEndpoint]
2014-03-13 09:20:30.376  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'infoEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=infoEndpoint]
2014-03-13 09:20:30.400  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'metricsEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=metricsEndpoint]
2014-03-13 09:20:30.413  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'traceEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=traceEndpoint]
2014-03-13 09:20:30.428  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'dumpEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=dumpEndpoint]
2014-03-13 09:20:30.450  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'autoConfigurationAuditEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=autoConfigurationAuditEndpoint]
2014-03-13 09:20:30.465  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'shutdownEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=shutdownEndpoint]
2014-03-13 09:20:30.548  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'configurationPropertiesReportEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=configurationPropertiesReportEndpoint]
2014-03-13 09:20:30.589  INFO 14650 --- [           main] hello.SampleController                   : Started SampleController in 7.396 seconds (JVM running for 9.569)
2014-03-13 09:20:30.608  INFO 14650 --- [       Thread-2] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@b9eec: startup date [Thu Mar 13 09:20:24 EDT 2014]; root of context hierarchy
2014-03-13 09:20:30.610  INFO 14650 --- [       Thread-2] o.s.c.support.DefaultLifecycleProcessor  : Stopping beans in phase 0
2014-03-13 09:20:30.624  INFO 14650 --- [       Thread-2] o.s.b.a.e.jmx.EndpointMBeanExporter      : Unregistering JMX-exposed beans on shutdown

Please advise.

Thanks

P.S. build.gradle is the fault.

dependencies {
    // tag::jetty[]
    compile("org.springframework.boot:spring-boot-starter-web") {
        **exclude module: "spring-boot-starter-tomcat"**
    }

Once I took off the above line in bold, everything works. My application context now is correct. Thanks Dave

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::            (v1.0.0.RC4)

2014-03-13 13:58:08.965  INFO 7307 --- [           main] hello.Application                        : Starting
 Application on  with PID 7307 (/ladev/home/xxx/dev/gs-spring-boot/initial/build/libs/gs-spring-boo
t-0.1.0.jar started by xxx)
2014-03-13 13:58:09.021  INFO 7307 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshi
ng org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@45490eb5: startup
 date [Thu Mar 13 13:58:09 MDT 2014]; root of context hierarchy
2014-03-13 13:58:09.653  INFO 7307 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overridi
ng bean definition for bean 'beanNameViewResolver': replacing [Root bean: class [null]; scope=; abstract=fal
se; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanNam
e=org.springframework.boot.actuate.autoconfigure.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration;
 factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class
 path resource [org/springframework/boot/actuate/autoconfigure/ErrorMvcAutoConfiguration$WhitelabelErrorView
Configuration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3;
 dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconf
igure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; in
itMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/au
toconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]

Body:
I had the same problem but when I removed the below dependency it worked fine

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency>

it started working again.

ContentLicense: CC BY-SA 4.0


问:
Background image not showing in browser
I have a question. I am pretty new to coding and I am trying to make my own website. I want to add a background image to my website but the image is not showing up. I have tried several things but without luck. I have added code of what I have done in my html file. I hope someone can help me with this and point me in the right direction.

This is what my html file looks like:

<!DOCTYPE html>

     <link rel="stylesheet" type="text/css" href="./Lusofly virtual.css" />
     <title>Lusofly Virtual</title>

Lusofly Virtual

HOME

COMMUNITY

CONTACT

PILOT AREA

```

Thanks in advance

答:
In your CSS code, you set the image as the background of an HTML element with ID mydiv, but there is no such element in your HTML code. That's why your image isn't visible.

Just add

 to your HTML code, and you should see your image :

#mydiv {
    background-image: url('https://i.stack.imgur.com/0Cbf1.png');
    background-repeat:no-repeat;
    background-size:contain;
    height:200px;
    width:1200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
    <div class="container">
        <div id="mydiv"></div>
        <div class="logo">
            <h1>Lusofly Virtual</h1>
        </div>
        <div class="nav">
            <ul>
                <li>HOME</li>
                <li>COMMUNITY</li>
                <li>CONTACT</li>
                <li>PILOT AREA</li>
            </ul>
        </div>
    </div>
</div></code>```

Title: Background image not showing in browser

Body:
I have a question. I am pretty new to coding and I am trying to make my own website. I want to add a background image to my website but the image is not showing up. I have tried several things but without luck. I have added code of what I have done in my html file. I hope someone can help me with this and point me in the right direction.

This is what my html file looks like:

<!DOCTYPE html>

     <link rel="stylesheet" type="text/css" href="./Lusofly virtual.css" />
     <title>Lusofly Virtual</title>

Lusofly Virtual

HOME

COMMUNITY

CONTACT

PILOT AREA

Thanks in advance

Body:
In your CSS code, you set the image as the background of an HTML element with ID mydiv, but there is no such element in your HTML code. That's why your image isn't visible.

Just add <div id="mydiv"></div> to your HTML code, and you should see your image :

#mydiv {
    background-image: url('https://i.stack.imgur.com/0Cbf1.png');
    background-repeat:no-repeat;
    background-size:contain;
    height:200px;
    width:1200px;
}

<div class="header">
    <div class="container">
        <div id="mydiv"></div>
        <div class="logo">
            <h1><a href="#">Lusofly Virtual</a></h1>
        </div>
        <div class="nav">
            <ul>
                <li><a href="#">HOME</a></li>
                <li><a href="#">COMMUNITY</a></li>
                <li><a href="#">CONTACT</a></li>
                <li><a href="#">PILOT AREA</a></li>
            </ul>
        </div>
    </div>
</div>


问:
MS Access SQL Update table a based on Value in table b joined by ID
I am having an issue to make an update query making the update based on values other table. The problem is also that the other table has a To Many relation with the one I try to update.

Table A

```<code>ID   isTrue  hasOption1 hasOption2 hasOption3
1
2
3
4
5
6
7
</code>```

Table B

```<code>ID          OptionType
1           type1
1           type2
2           type2
1           type3
2           type1
6           type3
</code>```

The Update needs to set in table A whether the ID has Any option, and set Y or N for the optionTypes like the below;

Table A after update:

```<code>ID   isTrue  hasOption1 hasOption2 hasOption3
1    Y         Y          Y          Y
2    Y         Y          Y          N
3    N         N          N          N
4    N         N          N          N
5    N         N          N          N
6    Y         N          N          Y
7    N         N          N          N
</code>```

It is probably a matter of syntax which I don't know for example how to make Update with a Join. Or would it be simpler to do several queries in VBA?

答:
This Query is for Sql Server same will also work in MS Access.</p>

```<code>update TableA set   isTrue= case when (B.OptionType='type1') then 'Y' else 'N' end,
                hasOption1=case when (B.OptionType='type2') then 'Y' else 'N' end,
                hasOption2=case when (B.OptionType='type3') then 'Y' else 'N' end,
                hasOption3=case when (B.OptionType='type4') then 'Y' else 'N' end from TableA AS A  inner join tableb As B on A.ID=B.ID
</code>```

Body:
I am having an issue to make an update query making the update based on values other table. The problem is also that the other table has a To Many relation with the one I try to update.

Table A

ID   isTrue  hasOption1 hasOption2 hasOption3
1
2
3
4
5
6
7

Table B

ID          OptionType
1           type1
1           type2
2           type2
1           type3
2           type1
6           type3

The Update needs to set in table A whether the ID has Any option, and set Y or N for the optionTypes like the below;

Table A after update:

ID   isTrue  hasOption1 hasOption2 hasOption3
1    Y         Y          Y          Y
2    Y         Y          Y          N
3    N         N          N          N
4    N         N          N          N
5    N         N          N          N
6    Y         N          N          Y
7    N         N          N          N

It is probably a matter of syntax which I don't know for example how to make Update with a Join. Or would it be simpler to do several queries in VBA?

Body:
This Query is for Sql Server same will also work in MS Access.

update TableA set   isTrue= case when (B.OptionType='type1') then 'Y' else 'N' end,
                hasOption1=case when (B.OptionType='type2') then 'Y' else 'N' end,
                hasOption2=case when (B.OptionType='type3') then 'Y' else 'N' end,
                hasOption3=case when (B.OptionType='type4') then 'Y' else 'N' end from TableA AS A  inner join tableb As B on A.ID=B.ID


问:
using multiple return statements in a c++ function
I was wondering if it might be sort of advantageous for a c++ compiler if there's only one return statement in a function. one of my ex-bosses once told me so but I don't get the point if there would be any difference between declaring a return variable or simply having multiple return statements, e.g. in a switch-case statement.

So my question is: is there any difference, maybe in quality, performance or stack memory savings?

答:
Don't write code to suit your compiler. That changes with every compiler and compiler version. What is true today might be wrong tomorrow. Write code so it readable and shows what you intent.

As for multiple returns I highly doubt that makes any difference at all. As for trying, compiling and profiling be very aware that optimization is highly suspect to context. Multiple returns might be twice as fast in your test case but half as fast in the next function, if it shows a difference at all. To get a reliable comparison you have to test many different functions and places they are used. But if you compile the two and get the same or nearly same assembler that is a good indication that the compiler really doesn't care.


问:
Java 8 stream compare two objects and run a function on them
I've a a stream which I want to partition into smaller parts based on matching Id and then apply some proccessing logic on each of the part/element.

```<code>class BigRequest{
String bId;
List<Parts> parts;
//getters and setter here
}

Class Parts{
String pId;
String partId;
//getters and setter here
}
</code>```

I want to segregate and create a list of Parts of size 10 when the partId of different parts are same.

How to use the filter or reduce or groupingBy function to compare the two elements and put them to a list?
I've tried filter like below, doesn't take p1 variable:

```<code>big.stream().filter( p -> p.getPartId() == p1.getPartId()) //error
</code>```

Tried groupingBy like this

```<code>big.stream().collect(Collectors.groupingBy(Parts::getPartId) //error
</code>```

I want to iterate  over the filtered/reduced list a another and call another function called abc(). How can I do it using Java Streams?

pseudo:

```<code>big.getParts().stream.
//dividing logic logic
for(i < parts.size)
    abc(p)
</code>```

Thanks

答:
You might use something like this:

```<code> Map<String,List<Parts>> commonId = big.getParts().
                stream().
                collect(
                        Collectors.groupingBy(
                            Parts::getPartId,
                            Collectors.mapping(
                                Function.identity(),
                                Collectors.toList()
                            )
                        )
                );
</code>```

and after it, you will just need to iterate over the map and apply your function.
 commonId.entrySet().stream().map(entry -> apply(entry))...

Updated
We can omit Collectors.mapping(Function.identity(),Collectors.toList()) part, since it is a default behaviour of groupingBy

```<code>Map<String,List<Parts>> commonId = big.getParts().
                    stream().
                    collect(
                            Collectors.groupingBy(
                                Parts::getPartId
                            )
                    );
</code>```

Body:
I've a a stream which I want to partition into smaller parts based on matching Id and then apply some proccessing logic on each of the part/element.

class BigRequest{
String bId;
List<Parts> parts;
//getters and setter here
}

Class Parts{
String pId;
String partId;
//getters and setter here
}

I want to segregate and create a list of Parts of size 10 when the partId of different parts are same.

How to use the filter or reduce or groupingBy function to compare the two elements and put them to a list?
I've tried filter like below, doesn't take p1 variable:

big.stream().filter( p -> p.getPartId() == p1.getPartId()) //error

Tried groupingBy like this

big.stream().collect(Collectors.groupingBy(Parts::getPartId) //error

I want to iterate  over the filtered/reduced list a another and call another function called abc(). How can I do it using Java Streams?

pseudo:

big.getParts().stream.
//dividing logic logic
for(i < parts.size)
    abc(p)

Thanks

Body:
You might use something like this:

 Map<String,List<Parts>> commonId = big.getParts().
                stream().
                collect(
                        Collectors.groupingBy(
                            Parts::getPartId,
                            Collectors.mapping(
                                Function.identity(),
                                Collectors.toList()
                            )
                        )
                );

and after it, you will just need to iterate over the map and apply your function.
 commonId.entrySet().stream().map(entry -> apply(entry))...

Updated
We can omit Collectors.mapping(Function.identity(),Collectors.toList()) part, since it is a default behaviour of groupingBy

Map<String,List<Parts>> commonId = big.getParts().
                    stream().
                    collect(
                            Collectors.groupingBy(
                                Parts::getPartId
                            )
                    );


问:
How can I control the times it appears a popup in WordPress using popupmaker?
I am using Popup maker for wordpress. I need to do the following: I need the popup only appears to the user only one time each 24 hours (obviously the user must be already login in the site).

Any ideas in how can this be done?

答:
one way is using this plugin's hook and use cookie for handle your favorite hours .
i mean, attach a function to appropriate hook of popup maker and write your codes inside it .</p>


问:
Send multiple data using href in Aurelia
How to send multiple data using href in Aurelia? </p>

```<code>This works: <a href="#/candidate/upload/${cid}?t=${item.heading}">
</code>```

<p>Just need the syntax. </p>

```<code>Not working:<a href="#/candidate/upload/${cid}?t=${item.heading};s=${item.sw_casedocumentid}">
</code>```

答:
Solution: Just need to add & between the data</p>

```<code><a href="#/candidate/upload/${cid}?t=${item.heading}&s=${item.sw_casedocumentid}">
</code>```

Body:
How to send multiple data using href in Aurelia?

This works:

Just need the syntax.

Not working:

Body:
Solution: Just need to add & between the data

<a href="#/candidate/upload/${cid}?t=${item.heading}&s=${item.sw_casedocumentid}">


问:
git - rollback pushes to specific commit
I have pushed few commits on a remote branch, but realized that I made mistake and would like to roll back all changes to a particular point.

example

```<code>- pushed commit
- pushed commit
- pushed commit
- pushed commit
- point to which i want to return
- older commits ...
</code>```

My question is, is it possible to rollback all the changes and revert this branch to that point ?

On the suggested topic i found part of the answer,

please tell me if i i reverse current branch to the commit i want to return to, and the i force push it. Will this accomplish a rollback ?

答:
Simple as that:

```<code>git reset b9563df
</code>```

Just replace 'b9563df' with your commit code

Body:
I have pushed few commits on a remote branch, but realized that I made mistake and would like to roll back all changes to a particular point.

example

- pushed commit
- pushed commit
- pushed commit
- pushed commit
- point to which i want to return
- older commits ...

My question is, is it possible to rollback all the changes and revert this branch to that point ?

On the suggested topic i found part of the answer,

please tell me if i i reverse current branch to the commit i want to return to, and the i force push it. Will this accomplish a rollback ?

Body:
Simple as that:

git reset b9563df

Just replace 'b9563df' with your commit code


问:
read.table not detecting delimiters past line 6
I am trying to read a short text file using '£' as a delimiter. It correctly puts the first five lines into two columns, but then gives the error:

Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings,  :
  line 6 did not have 2 elements

The remaining lines are then all put into the first column. The first few lines of the text file I am reading has the following format:

```<code>czk11 (4).txt£ 2017-03-20 04:05:07.599+00:00  [F]  Thread 0 System not loaded, loading now, Engine Version: 1.8.11.415
czk11 (4).txt£
czk11 (4).txt£ 2017-03-20 04:05:09.130+00:00  [F]  Thread 0 System loading complete
czk11 (4).txt£
czk11 (5).txt£ 2017-03-21 04:57:24.060+00:00  [F]  Thread 0 System not loaded, loading now, Engine Version: 1.8.11.415
czk11 (5).txt£
czk11 (5).txt£ 2017-03-21 04:57:25.608+00:00  [F]  Thread 0 System loading complete
</code>```

I am currently using the following lines to read it:

```<code>dat<-file('merged.txt',encoding='UTF-16LE',open='r')
data<-read.table(dat,sep='£',fill=TRUE,header=FALSE,quote ="")
</code>```

I'm sure there is a simple answer, I just can't see what it is! Many thanks

答:
No idea what caused it, but it was a problem with the input file- added a skip=7 to the import and it works fine. I guess there's some weird character that it didn't like.

Thanks everyone for the help, good to know i'm not going crazy!

Body:
I am trying to read a short text file using '£' as a delimiter. It correctly puts the first five lines into two columns, but then gives the error:

Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings,  :
  line 6 did not have 2 elements

The remaining lines are then all put into the first column. The first few lines of the text file I am reading has the following format:

czk11 (4).txt£ 2017-03-20 04:05:07.599+00:00  [F]  Thread 0 System not loaded, loading now, Engine Version: 1.8.11.415
czk11 (4).txt£
czk11 (4).txt£ 2017-03-20 04:05:09.130+00:00  [F]  Thread 0 System loading complete
czk11 (4).txt£
czk11 (5).txt£ 2017-03-21 04:57:24.060+00:00  [F]  Thread 0 System not loaded, loading now, Engine Version: 1.8.11.415
czk11 (5).txt£
czk11 (5).txt£ 2017-03-21 04:57:25.608+00:00  [F]  Thread 0 System loading complete

I am currently using the following lines to read it:

dat<-file('merged.txt',encoding='UTF-16LE',open='r')
data<-read.table(dat,sep='£',fill=TRUE,header=FALSE,quote ="")

I'm sure there is a simple answer, I just can't see what it is! Many thanks


问:
Changing occurrences of one pattern to another
grep -R \"\/web *
gives me some occurrences which i want to change to
\"\$\/web

How can I do this?

答:
With GNU sed

```<code>sed -r 's|"(/web)|"$\1|g' *
</code>```

If your satisfied with the output, change sed -r to sed -ri to do an in-place edit

Body:
With GNU sed

sed -r 's|"(/web)|"$\1|g' *

If your satisfied with the output, change sed -r to sed -ri to do an in-place edit

ContentLicense: CC BY-SA 2.5


问:
Office.js on Outlook for Mac: Internal Error on saveAsync method
So office.js add-in support is finally out for Outlook for Mac since version 15.32.
I'm actually using the latest non-insider version 15.33, and have one issue that doesn't take place on OWA or Outlook Desktop for Windows.

When I make following call in the add-in to get the event id:

```<code>const itemCompose = Office.cast.item.toItemCompose(Office.context.mailbox.item);
itemCompose.saveAsync((result) => console.log(result));
</code>```

on OWA and Outlook Windows result.value has the event id, however on Outlook for Mac that is the result:

```<code>{
 error: Error {name: "Internal Error", message: "An internal error has occurred.", code: 5001}
 status: "failed"
 value: null
}
</code>```

is it a bug in the freshly released office.js support for Outlook for Mac, or I'm doing something wrong?

important note: it happens only if the event has some attendees, that is, if the event is an meeting. On an appointment, so an event without attendees, it works as expected.

答: Outlook for Mac doesn't support saving a meeting in compose mode, so this is expected. The Mac Outlook team knows about it.</p>

Body:
So office.js add-in support is finally out for Outlook for Mac since version 15.32.
I'm actually using the latest non-insider version 15.33, and have one issue that doesn't take place on OWA or Outlook Desktop for Windows.

When I make following call in the add-in to get the event id:

const itemCompose = Office.cast.item.toItemCompose(Office.context.mailbox.item);
itemCompose.saveAsync((result) => console.log(result));

on OWA and Outlook Windows result.value has the event id, however on Outlook for Mac that is the result:

{
 error: Error {name: "Internal Error", message: "An internal error has occurred.", code: 5001}
 status: "failed"
 value: null
}

is it a bug in the freshly released office.js support for Outlook for Mac, or I'm doing something wrong?

important note: it happens only if the event has some attendees, that is, if the event is an meeting. On an appointment, so an event without attendees, it works as expected.


问:
Using jQuery "click" function on an element echoed by php
I'm making a forum and I want the user panel to change whenever a user is logged in. So by default it says "Sign in or register." But when a user is logged in it says their name and an option to log out.

The idea is that when they click sign out jQuery will ask for a confirm and if its true they will be redirected to ?logout=true where php handles the rest.

The problem is that jQuery just won't work on the element echoed by php.

Here is the PHP:

```<code><div id="userbar">
    <span id="userPanel">User Panel</span>
    <?php
        if (isset($_SESSION['signedIn'])) {
            echo '
                <a href="#" class="logout">Sign Out</a>
                <span id="welcome">
                    Hello, <b><a href="#" class="sessName">' . $_SESSION["username"] . '
                </b></a></span>
            ';
        } else {
            echo '
                <a href="signin.php" class="signIn">Sign In</a>
                <a href="signup.php" class="register">Register</a>
            ';
        }
    ?>
</div>
</code>```

And here is the jQuery:

```<code><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>

<script type="text/javascript">

    $(".logout").click(function(){
        var exit = confirm("Are you sure you would like to sing out?");

        if (exit == true) {
            window.location("header.php?logout=true");
        }

        return false;
    });

</script>
</code>```

答:
You may add your listener on the top of your html. Try to make it this way :

```<code>$(document).ready(function() {
    $(".logout").click(function(){
        var exit = confirm("Are you sure you would like to sing out?");

        if (exit == true) {
            window.location("header.php?logout=true");
        }

        return false;
    });
});
</code>```

This way, jQuery waits until your DOM is completely loaded.

Body:
I'm making a forum and I want the user panel to change whenever a user is logged in. So by default it says "Sign in or register." But when a user is logged in it says their name and an option to log out.

The idea is that when they click sign out jQuery will ask for a confirm and if its true they will be redirected to ?logout=true where php handles the rest.

The problem is that jQuery just won't work on the element echoed by php.

Here is the PHP:

    User Panel
    <?php
        if (isset($_SESSION['signedIn'])) {
            echo '
                Sign Out

                    Hello, ' . $_SESSION["username"] . '

            ';
        } else {
            echo '
                Sign In
                Register
            ';
        }
    ?>

And here is the jQuery:

Body:
You may add your listener on the top of your html. Try to make it this way :

$(document).ready(function() {
    $(".logout").click(function(){
        var exit = confirm("Are you sure you would like to sing out?");

        if (exit == true) {
            window.location("header.php?logout=true");
        }

        return false;
    });
});

This way, jQuery waits until your DOM is completely loaded.


问:
Wildfly 10. Deploy an aplication on a specific server
I need to have an ability make several applications listen on different ports, but in the certain situation some of these applications must listen on the same port. I can change all configs, but I can't reassemble WAR files.

I've read this article "Application deployment" but still perplexed. Can it be done on standalone server? If it is possible, what configs should I make?

UPD
May be I sould change the question. Is there any way to set up a specific virtual server for an application by a deployment descriptor?

答:
To create create a different http listeners on the same wildfy instance, you will need to adjust your configuration file by adding the new http-listener.

Add, just below <http-listener name="default" socket-binding="http" redirect-socket="https" enable-http2="true"/>, in the undertow subsystem your new listener <http-listener name="customerPort" socket-binding="customerPort"/>

Then in your socket-binding-group (usually at the end of the configuration file), add the socket binding referencing customerPort above <socket-binding name="customerPort" port="2323"/>

Hope this help solve your problem.


问:
Neo4j cypher query order by with collect
In cypher query i have multiple result which i get using collect now how i can order by collect property in cypher?

```<code>MATCH(u:User)
WITH COLLECT({name:u.name,date:u.date}) AS userinfo
RETURN userinfo
</code>```

OR in the case there are multiple collections that have been merged

```<code>MATCH(u:User)-[r:CreatedBy]->(p:Project)
WITH COLLECT({name:p.name,date:p.date}) AS info
MATCH(i:Institue)-[owner:Owner]->(i:Institute)
WITH COLLECT({instituteName:i.name,date:i.date}) AS instituteinfo,info
WITH COLLECT(instituteinfo + info) AS alldata
RETURN alldata
</code>```

答:
You simply need to order the user nodes by the attribute of your choice prior to collecting them. Something like this..,

```<code>MATCH(u:User)
WITH u
ORDER BY u.name
WITH COLLECT({name:u.name,date:u.date}) AS userinfo
RETURN userinfo
</code>```

Or if you were looking to combine multiple collections and produce a single ordered collection you could recombine them something like this...

```<code>MATCH(u:User)-[r:CreatedBy]->(p:Project)
WITH COLLECT({name:p.name, date:p.date}) AS info
MATCH(i:Institue)-[owner:Owner]->(i:Institute)
WITH COLLECT({instituteName:i.name, date:i.date}) AS instituteinfo,info
WITH instituteinfo + info AS alldata
UNWIND alldata as node
WITH node
ORDER BY node.name
WITH COLLECT (DISTINCT node) as alldata
RETURN alldata
</code>```

Body:
In cypher query i have multiple result which i get using collect now how i can order by collect property in cypher?

MATCH(u:User)
WITH COLLECT({name:u.name,date:u.date}) AS userinfo
RETURN userinfo

OR in the case there are multiple collections that have been merged

MATCH(u:User)-[r:CreatedBy]->(p:Project)
WITH COLLECT({name:p.name,date:p.date}) AS info
MATCH(i:Institue)-[owner:Owner]->(i:Institute)
WITH COLLECT({instituteName:i.name,date:i.date}) AS instituteinfo,info
WITH COLLECT(instituteinfo + info) AS alldata
RETURN alldata

Body:
You simply need to order the user nodes by the attribute of your choice prior to collecting them. Something like this..,

MATCH(u:User)
WITH u
ORDER BY u.name
WITH COLLECT({name:u.name,date:u.date}) AS userinfo
RETURN userinfo

Or if you were looking to combine multiple collections and produce a single ordered collection you could recombine them something like this...

MATCH(u:User)-[r:CreatedBy]->(p:Project)
WITH COLLECT({name:p.name, date:p.date}) AS info
MATCH(i:Institue)-[owner:Owner]->(i:Institute)
WITH COLLECT({instituteName:i.name, date:i.date}) AS instituteinfo,info
WITH instituteinfo + info AS alldata
UNWIND alldata as node
WITH node
ORDER BY node.name
WITH COLLECT (DISTINCT node) as alldata
RETURN alldata


问:
Structured Data JSON-LD for Localbussiness with multiple locations query
I'm new to JSON-LD. I find the syntax fairly straightforward but my query lies more with deciding which pages it is best to add the JSON-LD to. I've spent a bit of time looking for an answer online but so far nothing has been clear.

My example:

The site is for a business that has roughly 20 branch locations across the country. Each office has a dedicated contact details page, and there is also a "contact us" page for the site as a whole.

Should I

A: Add 'Organisation' JSON-LD snippet for the organisation as a whole to the homepage of the site, and then add individual 'LocalBusiness' JSON-LD snippets to each office details page?

B: Consolidate all this into one snippet of JSON-LD that has 'Organisation' with nested 'LocalBusiness'es and place it on ALL office pages, with a separate 'Organisation' snippet for the homepage?

C: Consolidate all this into one snippet of JSON-LD that has 'Organisation' with nested 'LocalBusiness'es and place it on ALL pages sitewide?

D: None of the above... Instead you should ____________________.

I realise there may not be one correct answer for this, but any help at all in achieving what would be considered best practice, would be greatly appreciated!

Cheers

答:
Per the JSON-LD specification, it’s totally up to the authors. Consumers of your JSON-LD might of course have their own expectations.

You seem to use the vocabulary Schema.org, which is sponsored by the big Web search engine services. They are of course typically interested in your page content. The general idea of Schema.org is to mark up your existing content (+ closely related metadata).

This becomes clear when looking at the other syntaxes supported by Schema.org (Microdata and RDFa), as they define attributes that get added to existing HTML elements used for your content. So JSON-LD is the exception here, as it doesn’t get coupled with the HTML/content.

tl;dr: On a page about a branch location, provide structured data about this branch location.

It typically makes sense to provide structured data about related entities (e.g., the parent organization) in addition. This can be done by including the data and/or by referencing it via its URI (see an example). Make use of the properties the type offers (e.g., parentOrganization).


问:
A question about delegates
I am trying to read some code that I did not write. In the main body of the class, there is the following 2 lines.

```<code>// RenderingService callbacks
protected RenderingServiceResponsesDelegate renderingServiceResponsesDelegate;
public delegate void RenderingServiceResponsesDelegate(Collection<RenderingServiceResponse> responses);
</code>```

Now, I have never used delegates before in C#, but read that there is three steps (declaration, instantiation and invocation). The 2nd lines looks like the declaration and the 1st line looks like the first step in instantiation. Inside the constructor of the class, there is the following line:

```<code>//Inside the constructor
this.renderingServiceResponsesDelegate = renderingServiceResponsesDelegate;
</code>```

where renderingServiceResponsesDelegate is the parameter passed by the constructor. So that would be the second part of the instantiation. Is this correctly understood? I was confused by the order of things. Is is possible to instantiate it like that in c# before it has been declared?

答:
This is the declaration of the delegate type:

```<code>public delegate void RenderingServiceResponsesDelegate(Collection<RenderingServiceResponse> responses);
</code>```

This is the declaration of a member that is of that delegate type:

```<code> protected RenderingServiceResponsesDelegate renderingServiceResponsesDelegate;
</code>```

This is the assignment of a previously instanciated instance to that member:

```<code>this.renderingServiceResponsesDelegate = renderingServiceResponsesDelegate;
</code>```

renderingServiceResponsesDelegate points to a specific method of a object instance or a static method.

The previous instanciation could have looked like this:

```<code>SomeClassThatHasTakesTheDelegateInstance c = new SomeClassThatHasTakesTheDelegateInstance (new RenderingServiceResponsesDelegate (this.SomeMethodThatMatchesTheDelegateSignature));
</code>```

An invocation would then look like this:

```<code>this.renderingServiceResponsesDelegate(someResponses);
</code>```

Title: A question about delegates

Body:
I am trying to read some code that I did not write. In the main body of the class, there is the following 2 lines.

// RenderingService callbacks
protected RenderingServiceResponsesDelegate renderingServiceResponsesDelegate;
public delegate void RenderingServiceResponsesDelegate(Collection<RenderingServiceResponse> responses);

Now, I have never used delegates before in C#, but read that there is three steps (declaration, instantiation and invocation). The 2nd lines looks like the declaration and the 1st line looks like the first step in instantiation. Inside the constructor of the class, there is the following line:

//Inside the constructor
this.renderingServiceResponsesDelegate = renderingServiceResponsesDelegate;

where renderingServiceResponsesDelegate is the parameter passed by the constructor. So that would be the second part of the instantiation. Is this correctly understood? I was confused by the order of things. Is is possible to instantiate it like that in c# before it has been declared?

Body:
This is the declaration of the delegate type:

public delegate void RenderingServiceResponsesDelegate(Collection<RenderingServiceResponse> responses);

This is the declaration of a member that is of that delegate type:

 protected RenderingServiceResponsesDelegate renderingServiceResponsesDelegate;

This is the assignment of a previously instanciated instance to that member:

this.renderingServiceResponsesDelegate = renderingServiceResponsesDelegate;

renderingServiceResponsesDelegate points to a specific method of a object instance or a static method.

The previous instanciation could have looked like this:

SomeClassThatHasTakesTheDelegateInstance c = new SomeClassThatHasTakesTheDelegateInstance (new RenderingServiceResponsesDelegate (this.SomeMethodThatMatchesTheDelegateSignature));

An invocation would then look like this:

this.renderingServiceResponsesDelegate(someResponses);


问:
Commpering data from MongoDB in node.js
First of all, coding is new thing for me. Until now I was manual tester in Java applications.
Now, my task is learn to do "automate stuff" and I'm stuck on one problem.

I'm trying get data from MongoDB and compare it with test data. Test is a mix of Protractor and Cucumber.

I think problem is in something I don't understand or I don't know yet.

In mongoDB I have:

```<code>{
    "_id" : 123456,
    "mykey" : 2
}
</code>```

Code in IDE:

```<code>import * as chai from 'chai';
import * as chaiAsPromised from 'chai-as-promised';
chai.use(chaiAsPromised);
const expect = chai.expect;

module.exports = function () {
    this.Then(/^Data should be same$/, function (callback) {

// Connection to mongoDB

    const MongoClient = require('mongodb').MongoClient;
    MongoClient.connect('mongodb://localhost:8517/fpl').then(function(db) {

      const collection = db.collection('test');

// Test data

      const testData = [{
        _id: 123456,
        mykey: 2
      }];

// Query to DB for data

      const a = collection.find({_id: 123456}).toArray();

// "is data from DB == test data?"

      return expect(a).to.eventually.equal(testData).notify(callback);

    }).catch((err) => {
      console.log(err);
});
</code>```

As Result I got message:

```<code>Message:
 AssertionError: expected [ { _id: 123456, mykey: 2 } ] to equal [ { _id: 123456, mykey: 2 } ]

1 scenario (1 failed)
1 step (1 failed)
0m00.094s
AssertionError: expected [ { _id: 123456, mykey: 2 } ] to equal [ { _id: 123456, mykey: 2 } ]
  message: 'expected [ { _id: 123456, mykey: 2 } ] to equal [ { _id: 123456, mykey: 2 } ]',
  showDiff: true,
  actual: [ { _id: 123456, mykey: 2 } ],
  expected: [ { _id: 123456, mykey: 2 } ] }
[14:22:34] I/local - Shutting down selenium standalone server.
[14:22:34] I/launcher - 0 instance(s) of WebDriver still running
[14:22:34] I/launcher - chrome #01 failed 1 test(s)
[14:22:34] I/launcher - overall: 1 failed spec(s)
[14:22:34] E/launcher - Process exited with error code 1
</code>```

Any ideas what I'm doing wrong?

答:
Use deep flag
http://chaijs.com/api/bdd/#method_deep

```<code>collection.find({_id: 123456}).toArray(function(err, docs) {
    expect(docs).to.deep.equal(testData).notify(callback);
});
</code>```

Title: Commpering data from MongoDB in node.js

Body:
First of all, coding is new thing for me. Until now I was manual tester in Java applications.
Now, my task is learn to do "automate stuff" and I'm stuck on one problem.

I'm trying get data from MongoDB and compare it with test data. Test is a mix of Protractor and Cucumber.

I think problem is in something I don't understand or I don't know yet.

In mongoDB I have:

{
    "_id" : 123456,
    "mykey" : 2
}

Code in IDE:

import * as chai from 'chai';
import * as chaiAsPromised from 'chai-as-promised';
chai.use(chaiAsPromised);
const expect = chai.expect;

module.exports = function () {
    this.Then(/^Data should be same$/, function (callback) {

// Connection to mongoDB

    const MongoClient = require('mongodb').MongoClient;
    MongoClient.connect('mongodb://localhost:8517/fpl').then(function(db) {

      const collection = db.collection('test');

// Test data

      const testData = [{
        _id: 123456,
        mykey: 2
      }];

// Query to DB for data

      const a = collection.find({_id: 123456}).toArray();

// "is data from DB == test data?"

      return expect(a).to.eventually.equal(testData).notify(callback);

    }).catch((err) => {
      console.log(err);
});

As Result I got message:

Message:
 AssertionError: expected [ { _id: 123456, mykey: 2 } ] to equal [ { _id: 123456, mykey: 2 } ]

1 scenario (1 failed)
1 step (1 failed)
0m00.094s
AssertionError: expected [ { _id: 123456, mykey: 2 } ] to equal [ { _id: 123456, mykey: 2 } ]
  message: 'expected [ { _id: 123456, mykey: 2 } ] to equal [ { _id: 123456, mykey: 2 } ]',
  showDiff: true,
  actual: [ { _id: 123456, mykey: 2 } ],
  expected: [ { _id: 123456, mykey: 2 } ] }
[14:22:34] I/local - Shutting down selenium standalone server.
[14:22:34] I/launcher - 0 instance(s) of WebDriver still running
[14:22:34] I/launcher - chrome #01 failed 1 test(s)
[14:22:34] I/launcher - overall: 1 failed spec(s)
[14:22:34] E/launcher - Process exited with error code 1

Any ideas what I'm doing wrong?

Body:
Use deep flag
http://chaijs.com/api/bdd/#method_deep

collection.find({_id: 123456}).toArray(function(err, docs) {
    expect(docs).to.deep.equal(testData).notify(callback);
});


问:
javascript skip duplicate permutation from array
I have an array with permutations but I need to remove duplicate permutations.

Permutations for 3 different digits is always 6 ways, so 345 and 453 are the same number. 497, 479 and 749 likewise would be considered the same number.

Also, 128, 281, 812, 182, 218 and 821 are all the same number.

It means I need to keep any only one permutation from 128, 281, 812, 182, 218 and 821 all others should be removed from the array.

Like if array has 497, 479, 749, 128, 281, 812, 182, 218, 821

output should be : 497, 128

答:
You could sort the parts and maintain a hash object with the key of the sorted and joined parts.

var array = [497, 479, 749, 128, 281, 812, 182, 218, 821].map(a => a.toString().split('')),
    hash = Object.create(null),
    unique = [];

array.forEach(function (a) {
    a.sort(function (a, b) {
        return a - b;
    })
    if (!hash[a.join('')]) {
        hash[a.join('')] = true;
        unique.push(a);
    }
});

console.log(unique);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
You could sort the parts and maintain a hash object with the key of the sorted and joined parts.

var array = [497, 479, 749, 128, 281, 812, 182, 218, 821].map(a => a.toString().split('')),
    hash = Object.create(null),
    unique = [];

array.forEach(function (a) {
    a.sort(function (a, b) {
        return a - b;
    })
    if (!hash[a.join('')]) {
        hash[a.join('')] = true;
        unique.push(a);
    }
});

console.log(unique);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Convert java.lang.object to int in Java
I have a method which returns a object of type java.lang.object and I want to convert it to int. I tried this:

```<code>oldComment.get("count");
</code>```

return a java.lang.object and I want to convert it to int. I tried:

```<code>(Integer)oldComment.get("count");
Integer.valueOf(oldComment.get("count"));
Integer.parseInt(oldComment.get("count"));

con = Base.connection();
String query = "UPDATE COMMENT SET LIKES = ? WHERE POST_ID = ?";
PreparedStatement pst = con.prepareStatement(query);
pst.setObject(1, (Integer.parseInt(oldComment.get("likes").toString())) + Integer.valueOf(rateComment.getCount()));
pst.setString(2, rateComment.getPost_id());
int k = pst.executeUpdate();
</code>```

This is the code (Integer.parseInt(oldComment.get("likes").toString())) that is causing issue.

Error Stacktrace:

```<code>[qtp25844331-17] ERROR spark.http.matching.GeneralError -
java.lang.NumberFormatException: For input string: ""
        at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
        at java.lang.Integer.parseInt(Integer.java:592)
        at java.lang.Integer.parseInt(Integer.java:615)
        at com.soul.seeker.serviceImpl.CommentRatingServiceImpl.rateComment(CommentRatingServiceImpl.java:50)
        at com.soul.seeker.Application.lambda$main$12(Application.java:161)
        at spark.ResponseTransformerRouteImpl$1.handle(ResponseTransformerRouteImpl.java:47)
        at spark.http.matching.Routes.execute(Routes.java:61)
        at spark.http.matching.MatcherFilter.doFilter(MatcherFilter.java:130)
        at spark.embeddedserver.jetty.JettyHandler.doHandle(JettyHandler.java:50)
        at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:189)
        at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
        at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:119)
        at org.eclipse.jetty.server.Server.handle(Server.java:517)
        at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:308)
        at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:242)
        at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:261)
        at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95)
        at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:75)
        at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceAndRun(ExecuteProduceConsume.java:213)
        at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:147)
        at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:654)
        at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:572)
        at java.lang.Thread.run(Thread.java:745)
</code>```

None of the above worked. How do I convert it?

答:
First of all, you shouldn't return java.util.Object, it's a very bad habit. If your value it's a Numeric, you should return java.lang.Number. If it's a String, you should return java.lang.String, etc.

If you don't have choice, you can convert it with this code :

```<code>// This method can throw NumberFormatException, catch it if you want
public Integer toInt(Object obj) {
    // Use intValue on a Number to improve performance
    if(obj instanceof Number) {
         return ((Number) obj).intValue();
    }

    return Integer.parseInt(obj.toString());
}
</code>```

EDIT : In your stacktrace, your program try to parse an empty String so it throws an NumberFormatException, you should catch it.

Title: Convert java.lang.object to int in Java

Body:
I have a method which returns a object of type java.lang.object and I want to convert it to int. I tried this:

oldComment.get("count");

return a java.lang.object and I want to convert it to int. I tried:

(Integer)oldComment.get("count");
Integer.valueOf(oldComment.get("count"));
Integer.parseInt(oldComment.get("count"));

con = Base.connection();
String query = "UPDATE COMMENT SET LIKES = ? WHERE POST_ID = ?";
PreparedStatement pst = con.prepareStatement(query);
pst.setObject(1, (Integer.parseInt(oldComment.get("likes").toString())) + Integer.valueOf(rateComment.getCount()));
pst.setString(2, rateComment.getPost_id());
int k = pst.executeUpdate();

This is the code (Integer.parseInt(oldComment.get("likes").toString())) that is causing issue.

Error Stacktrace:

[qtp25844331-17] ERROR spark.http.matching.GeneralError -
java.lang.NumberFormatException: For input string: ""
        at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
        at java.lang.Integer.parseInt(Integer.java:592)
        at java.lang.Integer.parseInt(Integer.java:615)
        at com.soul.seeker.serviceImpl.CommentRatingServiceImpl.rateComment(CommentRatingServiceImpl.java:50)
        at com.soul.seeker.Application.lambda$main$12(Application.java:161)
        at spark.ResponseTransformerRouteImpl$1.handle(ResponseTransformerRouteImpl.java:47)
        at spark.http.matching.Routes.execute(Routes.java:61)
        at spark.http.matching.MatcherFilter.doFilter(MatcherFilter.java:130)
        at spark.embeddedserver.jetty.JettyHandler.doHandle(JettyHandler.java:50)
        at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:189)
        at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
        at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:119)
        at org.eclipse.jetty.server.Server.handle(Server.java:517)
        at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:308)
        at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:242)
        at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:261)
        at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95)
        at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:75)
        at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceAndRun(ExecuteProduceConsume.java:213)
        at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:147)
        at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:654)
        at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:572)
        at java.lang.Thread.run(Thread.java:745)

None of the above worked. How do I convert it?

Body:
First of all, you shouldn't return java.util.Object, it's a very bad habit. If your value it's a Numeric, you should return java.lang.Number. If it's a String, you should return java.lang.String, etc.

If you don't have choice, you can convert it with this code :

// This method can throw NumberFormatException, catch it if you want
public Integer toInt(Object obj) {
    // Use intValue on a Number to improve performance
    if(obj instanceof Number) {
         return ((Number) obj).intValue();
    }

    return Integer.parseInt(obj.toString());
}

EDIT : In your stacktrace, your program try to parse an empty String so it throws an NumberFormatException, you should catch it.


问:
Unable to build unity app - issue not clear
Need help when i am trying to build my unity project its giving below error.
But i could not rectify error due to same. Any help will be useful.

Error 1

```<code>Error: Failed to add D:\jbINTEG\Temp\StagingArea\bin\classes.dex

UnityEditor.HostView:OnGUI()
</code>```

Error 2

```<code>CommandInvokationFailure: Failed to build apk. See the Console for details.
C:/Program Files/Java/jdk1.8.0_121\bin\java.exe -Xmx2048M -Dcom.android.sdkmanager.toolsdir="C:/Program Files (x86)/Android/android-sdk\tools" -Dfile.encoding=UTF8 -jar "C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer/Tools\sdktools.jar" -

stderr[
Error: Failed to add D:\jbINTEG\Temp\StagingArea\bin\classes.dex
]
stdout[

]
UnityEditor.Android.Command.Run (System.Diagnostics.ProcessStartInfo psi, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.Android.AndroidSDKTools.RunCommandInternal (System.String javaExe, System.String sdkToolsDir, System.String[] sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.Android.AndroidSDKTools.RunCommandSafe (System.String javaExe, System.String sdkToolsDir, System.String[] sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.HostView:OnGUI()
</code>```

Error 3

```<code>Error building Player: CommandInvokationFailure: Failed to build apk. See the Console for details.
C:/Program Files/Java/jdk1.8.0_121\bin\java.exe -Xmx2048M -Dcom.android.sdkmanager.toolsdir="C:/Program Files (x86)/Android/android-sdk\tools" -Dfile.encoding=UTF8 -jar "C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer/Tools\sdktools.jar" -

stderr[
Error: Failed to add D:\jbINTEG\Temp\StagingArea\bin\classes.dex
]
stdout[

]
</code>```

答:
Looks like some issue with your android sdk.
you should remove it and create a clean installation/setup of the android sdk also maybe reinstall java,jre & jdk</p>

Body:
Need help when i am trying to build my unity project its giving below error.
But i could not rectify error due to same. Any help will be useful.

Error 1

Error: Failed to add D:\jbINTEG\Temp\StagingArea\bin\classes.dex

UnityEditor.HostView:OnGUI()

Error 2

CommandInvokationFailure: Failed to build apk. See the Console for details.
C:/Program Files/Java/jdk1.8.0_121\bin\java.exe -Xmx2048M -Dcom.android.sdkmanager.toolsdir="C:/Program Files (x86)/Android/android-sdk\tools" -Dfile.encoding=UTF8 -jar "C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer/Tools\sdktools.jar" -

stderr[
Error: Failed to add D:\jbINTEG\Temp\StagingArea\bin\classes.dex
]
stdout[

]
UnityEditor.Android.Command.Run (System.Diagnostics.ProcessStartInfo psi, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.Android.AndroidSDKTools.RunCommandInternal (System.String javaExe, System.String sdkToolsDir, System.String[] sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.Android.AndroidSDKTools.RunCommandSafe (System.String javaExe, System.String sdkToolsDir, System.String[] sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.HostView:OnGUI()

Error 3

Error building Player: CommandInvokationFailure: Failed to build apk. See the Console for details.
C:/Program Files/Java/jdk1.8.0_121\bin\java.exe -Xmx2048M -Dcom.android.sdkmanager.toolsdir="C:/Program Files (x86)/Android/android-sdk\tools" -Dfile.encoding=UTF8 -jar "C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer/Tools\sdktools.jar" -

stderr[
Error: Failed to add D:\jbINTEG\Temp\StagingArea\bin\classes.dex
]
stdout[

]


问:
Extension UIButton only when conforming to a protocol
I'm trying to create several extensions for UIButton so I can add some functionality easily just by adding a protocol to a custom button. It'd be a lot easier if I didn't have to override some methods in UIButton so I'm thinking I'll have to make an extension for UIButton itself.

For example, I have several protocols my custom buttons can conform to:

```<code>protocol CustomLayer { }

protocol ButtonSound { }
</code>```

So far I only managed to create an extension for UIButton without any constraints (these are simplified versions):

```<code>// Only when the button conforms to protocol CustomLayer
extension UIButton {
    override public class func layerClass() -> AnyClass { return CAShapeLayer.self }
}

// Only when the button conforms to protocol ButtonSound
extension UIButton {
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        super.touchesBegan(touches, withEvent: event)

        AudioServicesPlaySystemSound(1104)
    }
}
</code>```

I've read posts I can make an extension for the protocol itself with a where clause for the class UIButton:

```<code>extension CustomLayer where Self: UIButton { }
</code>```

But then I can't override any methods of UIButton itself.

Other suggestions like subclassing works, but certain buttons can't have the same functionality:

```<code>class A: CustomLayer { } // Can't have ButtonSound, single subclass works
class B: ButtonSound { } // Can't have CustomLayer, single subclass works

class C: CustomLayer, ButtonSound { } // Error: multiple inheritance from classes
</code>```

答:
```<code>import Foundation

protocol BackButtonDelegate {

    func BackButtonAction(sender:UIButton)
}

class NavigationBack: UIButton
{
     var delegate : BackButtonDelegate!

    override func drawRect(rect: CGRect) {
        self.frame = CGRectMake(0, 0, 60, 60)
        self.setTitle("Back", forState: .Normal)
        self.titleLabel?.font = UIFont(name: "Helvetica",size: 12)
        self.setImage(UIImage(named: "back-arrow"), forState: .Normal)

        self.addTarget(self, action: #selector(NavigationBack.click(_:)), forControlEvents: UIControlEvents.TouchUpInside)

   }
    func click(sender:UIButton)
    {
        if delegate != nil
        {
            delegate!.BackButtonAction(sender)
        }
    }

}
</code>```

Body:
I'm trying to create several extensions for UIButton so I can add some functionality easily just by adding a protocol to a custom button. It'd be a lot easier if I didn't have to override some methods in UIButton so I'm thinking I'll have to make an extension for UIButton itself.

For example, I have several protocols my custom buttons can conform to:

protocol CustomLayer { }

protocol ButtonSound { }

So far I only managed to create an extension for UIButton without any constraints (these are simplified versions):

// Only when the button conforms to protocol CustomLayer
extension UIButton {
    override public class func layerClass() -> AnyClass { return CAShapeLayer.self }
}

// Only when the button conforms to protocol ButtonSound
extension UIButton {
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        super.touchesBegan(touches, withEvent: event)

        AudioServicesPlaySystemSound(1104)
    }
}

I've read posts I can make an extension for the protocol itself with a where clause for the class UIButton:

extension CustomLayer where Self: UIButton { }

But then I can't override any methods of UIButton itself.

Other suggestions like subclassing works, but certain buttons can't have the same functionality:

class A: CustomLayer { } // Can't have ButtonSound, single subclass works
class B: ButtonSound { } // Can't have CustomLayer, single subclass works

class C: CustomLayer, ButtonSound { } // Error: multiple inheritance from classes


问:
Convert csv text from utf-16 to ascii or read in correctly
I have problems while reading text from a csv file.
An example line from the csv file looks like this:"

1477-7819-4-45-2   Angiolymphatic Invasion (H & E 400 Ã)."

I guess that the problem is the coding of the text, so I decided to change it to ASCII.

This is my python code so far:

```<code>text_path = '/some_path/filename.csv'
text_path_ascii = '/some_path/filename_ASCII.csv'

input_codec = 'UTF-16'
output_codec = 'ASCII'

for line in unicode_file:
    unicode_data = unicode_file.read().decode(input_codec)
    #here is another problem => AttributeError: 'str' object has no attribute 'decode'
    unicode_data = unicode_file.read()

ascii_file = open(text_path_ascii, 'w')
ascii_file.write(unicode_data.write(unicode_data.encode(output_codec)))
# same problem=> AttributeError: 'str' object has no attribute 'encode'
ascii_file.write(unicode_data.encode(output_codec))
</code>```

So my problem is that I don't know how to encode/decode the text.

I am even not sure if this is the right way to handle the wrong written text (yes, the text looks like the given line if you open it with any editor) correcly.

Or is there maybe an easier way to read in the csv text without "broken" characters) directly?

Thanks for Your ideas

答:
There is no decode method on str but it is on bytes

If you want to decode it. You can do it with open itself.

```<code>file = open(filename, mode, encoding='utf-8')
</code>```

Body:
I have problems while reading text from a csv file.
An example line from the csv file looks like this:"

1477-7819-4-45-2   Angiolymphatic Invasion (H & E 400 Ã)."

I guess that the problem is the coding of the text, so I decided to change it to ASCII.

This is my python code so far:

text_path = '/some_path/filename.csv'
text_path_ascii = '/some_path/filename_ASCII.csv'

input_codec = 'UTF-16'
output_codec = 'ASCII'

for line in unicode_file:
    unicode_data = unicode_file.read().decode(input_codec)
    #here is another problem => AttributeError: 'str' object has no attribute 'decode'
    unicode_data = unicode_file.read()

ascii_file = open(text_path_ascii, 'w')
ascii_file.write(unicode_data.write(unicode_data.encode(output_codec)))
# same problem=> AttributeError: 'str' object has no attribute 'encode'
ascii_file.write(unicode_data.encode(output_codec))

So my problem is that I don't know how to encode/decode the text.

I am even not sure if this is the right way to handle the wrong written text (yes, the text looks like the given line if you open it with any editor) correcly.

Or is there maybe an easier way to read in the csv text without "broken" characters) directly?

Thanks for Your ideas

Body:
There is no decode method on str but it is on bytes

If you want to decode it. You can do it with open itself.

file = open(filename, mode, encoding='utf-8')


问:
Webpack modules usage from an html page
i'm trying to use webpack to bundle a bunch of AMD modules.

Before, i used r.js bundler to bundle all my AMD modules in a huge bundle.js.

I used requirejs to get a dependency and using in it my html page:

```<code><script>
    require(["foolib"], function (foolib) {
        foolib.foo();
    });
</script
</code>```

But with webpack, i failed to reproduce the same behaviour.

The requirejs module loader can work with AMD modules but webpack generates a bundle with a different syntax that i don't understand.

How can i get my "foolib" module to use its functionalities in my page ?

答: I found a sample project which answers perfectly this question: multi-part-library</p>

Title: Webpack modules usage from an html page

Body:
i'm trying to use webpack to bundle a bunch of AMD modules.

Before, i used r.js bundler to bundle all my AMD modules in a huge bundle.js.

I used requirejs to get a dependency and using in it my html page:

But with webpack, i failed to reproduce the same behaviour.

The requirejs module loader can work with AMD modules but webpack generates a bundle with a different syntax that i don't understand.

How can i get my "foolib" module to use its functionalities in my page ?


问:
How to reposition Chrome Developer Tools
The tools are opened on the bottom of the chrome window per default. This is a rather bad choice for a wide screen display since there is plenty of empty space to the right but not much vertical space to spare. Unfortunately, I have found no way to reposition the tools. I would like to have them on the side, similar to firebug.

The only option similar to what I want is to detach the dev tools and place chrome and the tools window side-by-side. This is not very convenient for quickly alt-tabbing from the IDE to the browser and back though, so an "integrated" solution would be nice.

答: The Version 56.0.2924.87 which I am in now, Undocks the DevTools automatically if you are NOT in a desktop. Otherwise Open a NEW new Chrome tab and Inspect to Dock the DevTools back into the window.</p>


问:
Where is the implementation of values-list in SBCL?
I am trying to figure out the implementation of values-list function in SBCL.
The source code at src/code/eval.lisp looks like pretty simple, but why doesn't  it fall into infinite recursion?

```<code>(defun values-list (list)
  #!+sb-doc
  "Return all of the elements of LIST, in order, as values."
  (values-list list))
</code>```

If I define a function foo like that, it will fall into infinite recursion:

```<code>(defun foo (list)
   (foo list))
</code>```

答:
In short, because something else has already taught the compiler how to compile calls to (values-list), so the (values-list) referred to in the function body does not to refer to the function being defined.

The reason why that function definition exists at all is a little more tricky. In compiled code which calls the function directly, the compiler can just defer to whatever other bit of code handles compiling calls to that function. However, just because the compiler knows how to compile direct calls to (values-list) does not mean it is a function- it could, effectively, be just a special form or macro. That seemingly recursive definition ensures that an actual function object exists, so things like #'values-list and calls to the function at the repl (if the repl is set to use the interpreter) work as expected.

In this case, #'values-list is implemented using a virtual operation (VOP, something which the compiler can compile directly to machine instructions) on each of SBCL's target platforms, as you can see with a search through the source.

Take a look here if you want to know more about this. In that article, Paul Khoung adds support for SBCL to use the intel x86-64 popcnt instruction to compile calls to a new function #'popcnt, and as the last step he defines a function like so

```<code>(in-package "POPCNT")

(defun popcnt (x) (popcnt x))
</code>```

Which he notes

isn’t strictly necessary, but helps people who like their REPL. The
  compiler knows how to compile calls to popcnt, so we can define
  popcnt… as a call to popcnt. Our new function is now a first-class
  value that can be called from interpreted code and passed to
  higher-order functions, like the compiler’s constant-folding pass.

Body:
I am trying to figure out the implementation of values-list function in SBCL.
The source code at src/code/eval.lisp looks like pretty simple, but why doesn't  it fall into infinite recursion?

(defun values-list (list)
  #!+sb-doc
  "Return all of the elements of LIST, in order, as values."
  (values-list list))

If I define a function foo like that, it will fall into infinite recursion:

(defun foo (list)
   (foo list))

Body:
In short, because something else has already taught the compiler how to compile calls to (values-list), so the (values-list) referred to in the function body does not to refer to the function being defined.

The reason why that function definition exists at all is a little more tricky. In compiled code which calls the function directly, the compiler can just defer to whatever other bit of code handles compiling calls to that function. However, just because the compiler knows how to compile direct calls to (values-list) does not mean it is a function- it could, effectively, be just a special form or macro. That seemingly recursive definition ensures that an actual function object exists, so things like #'values-list and calls to the function at the repl (if the repl is set to use the interpreter) work as expected.

In this case, #'values-list is implemented using a virtual operation (VOP, something which the compiler can compile directly to machine instructions) on each of SBCL's target platforms, as you can see with a search through the source.

Take a look here if you want to know more about this. In that article, Paul Khoung adds support for SBCL to use the intel x86-64 popcnt instruction to compile calls to a new function #'popcnt, and as the last step he defines a function like so

(in-package "POPCNT")

(defun popcnt (x) (popcnt x))

Which he notes

isn’t strictly necessary, but helps people who like their REPL. The
  compiler knows how to compile calls to popcnt, so we can define
  popcnt… as a call to popcnt. Our new function is now a first-class
  value that can be called from interpreted code and passed to
  higher-order functions, like the compiler’s constant-folding pass.


问:
Why can't PHP on Windows see extension php_intl.dll even though it exists?
I've been trying to get the intl extension working on my test workstation (PHP 5.5.1, Apache 2.2.4, Windows 7 32-bit). It seems that no matter what I try I can't get it up and running.

I've uncommented the line "extension=php_intl.dll" in my php.ini.

I've verified the extension_dir directive is pointing at the correct directory (c:\wamp\php5.5\ext).

I've verified php_intl.dll is in c:\wamp\php5.5\ext.

I've verified that all the icu*.dll files are present in the php root directory (c:\wamp\php5.5).

I've verified that c:\wamp\php5.5 is in my PATH.

And yes, the copy of php.ini I'm editing is the correct one, the one specified by the PHPIniDir directive in httpd.conf.

I've checked the Apache error log and found this line every time I've restarted Apache:

PHP Warning:  PHP Startup: Unable to load dynamic library 'c:\wamp\php5.5\ext\php_intl.dll' - The specified module could not be found.\r\n in Unknown on line 0

I repeat myself, but c:\wamp\php5.5\ext\php_intl.dll DOES EXIST!

I'm tempted to try pointing at Windows Explorer and shouting at my computer, "LOOK! THE STINKIN' FILE IS RIGHT THERE!" Any idea why I can see the file and PHP cannot even though we're apparently looking in the same directory? Or is something else going on that I've missed?

答: This was driving me crazy. I had all the icu dlls in my path etc. In the end installing Visual C++ 2015 x86 solved it for me.


问:
Relay/Mongodb Error - Cannot Read Property of Undefined
I have this test relay-starter-kit project with an autocomplete search form that renders quotes to the browser. When I use the search form, I get an error in the browser saying "app.js:8284 Uncaught TypeError: Cannot read property 'edges' of undefined". I cant understand why its populating the search fields the first time but not on typing in the search form. Of note, if you hard code the searchTerm variable, it will render the search results. In other words, It can read the edges when its hard coded. Any guidance on this would be great. Thanks.

The schema is here
This is the component that the valid graphql query for the search term wont render to.

```<code>    import React from 'react';
    import Relay from 'react-relay';
    import { debounce } from 'lodash';
    import SearchForm from '../search-form';
    import Quote from '../quote';

    class App extends React.Component {
        constructor(props) {
        super(props)
        this.search = debounce(this.search.bind(this), 300)
      }
      search(searchTerm) {
        this.props.relay.setVariables({ searchTerm });
      }

      render() {
        return (
          <div className="quotes-library">
            <SearchForm searchAction={this.search} />
            <div className="quotes-list">
              {this.props.viewer.quotes.edges.map(edge =>
                <Quote key={edge.node.id} quote={edge.node} />
              )}
            </div>
          </div>
        )
      }
    }

    export default Relay.createContainer(App, {
      initialVariables: {
        searchTerm: '',
      },
      fragments: {
        viewer: () => Relay.QL`
          fragment on User {
                quotes(first:100, searchTerm: $searchTerm) {
                    edges {
                        node {
                            id
                            ${Quote.getFragment('quote')}
                        }
                    }
                }
            }
        `,
      },
    });
</code>```

Update: This is the query as shown in Chrome DevTools network tab. Note the 'p' input to the search form is being queried.

```<code>    query App_ViewerRelayQL($id_0:ID!) {
  node(id:$id_0) {
    ...F2
  }
}
fragment F0 on Quote {
  id,
  likesCount
}
fragment F1 on Quote {
  text,
  author,
  id,
  ...F0
}
fragment F2 on User {
  _quotes3UfnML:quotes(first:100,searchTerm:"pri") {
    edges {
      node {
        id,
        ...F1
      },
      cursor
    },
    pageInfo {
      hasNextPage,
      hasPreviousPage
    }
  },
  id
}
</code>```

Adding console.log to render() shows the searchTerm input:

```<code> app.js:17
   {
    "viewer": {
        "__dataID__": "VXNlcjox",
        "__status__": 4
    },
    "relay": {
        "pendingVariables": null,
        "route": {
            "name": "AppHomeRoute",
            "params": {},
            "queries": {}
        },
        "variables": {
            "searchTerm": "pri"
        }
    }
}
</code>```

The following error occurs at line 24 in app.js, which is {this.props.library.quotes.edges.map(edge =>
            <Quote key={edge.node.id} quote={edge.node} />
          )}:

```<code>app.js:8285 Uncaught TypeError: Cannot read property 'edges' of undefined
    at App.render (app.js:8285)
    at app.js:43197
    at measureLifeCyclePerf (app.js:42476)
    at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (app.js:43196)
    at ReactCompositeComponentWrapper._renderValidatedComponent (app.js:43223)
    at ReactCompositeComponentWrapper._updateRenderedComponent (app.js:43147)
    at ReactCompositeComponentWrapper._performComponentUpdate (app.js:43125)
    at ReactCompositeComponentWrapper.updateComponent (app.js:43046)
    at ReactCompositeComponentWrapper.receiveComponent (app.js:42948)
    at Object.receiveComponent (app.js:35341)
</code>```

UPDATE 2:

So check this out. I'm doing something wrong with my { ObjectID }.  I pulled a user and quote from the db and there is an '_id' but no 'id' property on the object. This is the output:

```<code> > db.users.find({})
{ "_id" : ObjectId("586253169465191cb812066c"), "name" : "me", "id" : ObjectId("586253169465191cb812066c"), "errors" : [ ] }
> db.quotes.find({})
{ "_id" : ObjectId("586693333ff93f3581c0ca05"), "text" : "Hi Prisc", "author" : "H. Jackson Brown", "likesCount" : 24 }
{ "_id" : ObjectId("586693333ff93f3581c0ca06"), "text" : "If opportunity doesn't knock, build a door", "author" : "Milton Berle", "likesCount" : 2 }
{ "_id" : ObjectId("586693333ff93f3581c0ca07"), "text" : "Try to be a rainbow in...", "author" : "Maya Angelou" }
</code>```

If I log the id from the globalIdFetcher(), the logged id for the Jackson Brown Quote object show two id's as expected but they are both the same and different from the one in the db. Output in console is:

```<code>{
    "viewer": {
        "__dataID__": "VXNlcjo=",
        "quotes": {
            "__dataID__": "client:6068631311_first(100),searchTerm()",
            "edges": [
                {
                    "__dataID__": "client:client:6068631311:UXVvdGU6NTg2NjkzMzMzZmY5M2YzNTgxYzBjYTA1",
                    "node": {
                        "__dataID__": "UXVvdGU6NTg2NjkzMzMzZmY5M2YzNTgxYzBjYTA1",
                        "id": "UXVvdGU6NTg2NjkzMzMzZmY5M2YzNTgxYzBjYTA1",
                        "__fragments__": {
                            "1::client": [
                                {
                                    "showLikes": false
                                }
                            ]
                        }
                    }
                },
</code>```

Any ideas on fixing this syntax?

答: Solution was to take the Quote type out of the nodeInterface so only running the top level object through the nodeInterface, let relay generate the id for the objectId from the GraphQLID or fromGlobalId as defined in the individual itemType. </p>

Body:
I have this test relay-starter-kit project with an autocomplete search form that renders quotes to the browser. When I use the search form, I get an error in the browser saying "app.js:8284 Uncaught TypeError: Cannot read property 'edges' of undefined". I cant understand why its populating the search fields the first time but not on typing in the search form. Of note, if you hard code the searchTerm variable, it will render the search results. In other words, It can read the edges when its hard coded. Any guidance on this would be great. Thanks.

The schema is here
This is the component that the valid graphql query for the search term wont render to.

    import React from 'react';
    import Relay from 'react-relay';
    import { debounce } from 'lodash';
    import SearchForm from '../search-form';
    import Quote from '../quote';

    class App extends React.Component {
        constructor(props) {
        super(props)
        this.search = debounce(this.search.bind(this), 300)
      }
      search(searchTerm) {
        this.props.relay.setVariables({ searchTerm });
      }

      render() {
        return (

            <SearchForm searchAction={this.search} />

              {this.props.viewer.quotes.edges.map(edge =>
                <Quote key={edge.node.id} quote={edge.node} />
              )}

        )
      }
    }

    export default Relay.createContainer(App, {
      initialVariables: {
        searchTerm: '',
      },
      fragments: {
        viewer: () => Relay.QL`
          fragment on User {
                quotes(first:100, searchTerm: $searchTerm) {
                    edges {
                        node {
                            id
                            ${Quote.getFragment('quote')}
                        }
                    }
                }
            }
        `,
      },
    });

Update: This is the query as shown in Chrome DevTools network tab. Note the 'p' input to the search form is being queried.

    query App_ViewerRelayQL($id_0:ID!) {
  node(id:$id_0) {
    ...F2
  }
}
fragment F0 on Quote {
  id,
  likesCount
}
fragment F1 on Quote {
  text,
  author,
  id,
  ...F0
}
fragment F2 on User {
  _quotes3UfnML:quotes(first:100,searchTerm:"pri") {
    edges {
      node {
        id,
        ...F1
      },
      cursor
    },
    pageInfo {
      hasNextPage,
      hasPreviousPage
    }
  },
  id
}

Adding console.log to render() shows the searchTerm input:

 app.js:17
   {
    "viewer": {
        "__dataID__": "VXNlcjox",
        "__status__": 4
    },
    "relay": {
        "pendingVariables": null,
        "route": {
            "name": "AppHomeRoute",
            "params": {},
            "queries": {}
        },
        "variables": {
            "searchTerm": "pri"
        }
    }
}

The following error occurs at line 24 in app.js, which is {this.props.library.quotes.edges.map(edge =>
            <Quote key={edge.node.id} quote={edge.node} />
          )}:

app.js:8285 Uncaught TypeError: Cannot read property 'edges' of undefined
    at App.render (app.js:8285)
    at app.js:43197
    at measureLifeCyclePerf (app.js:42476)
    at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (app.js:43196)
    at ReactCompositeComponentWrapper._renderValidatedComponent (app.js:43223)
    at ReactCompositeComponentWrapper._updateRenderedComponent (app.js:43147)
    at ReactCompositeComponentWrapper._performComponentUpdate (app.js:43125)
    at ReactCompositeComponentWrapper.updateComponent (app.js:43046)
    at ReactCompositeComponentWrapper.receiveComponent (app.js:42948)
    at Object.receiveComponent (app.js:35341)

UPDATE 2:

So check this out. I'm doing something wrong with my { ObjectID }.  I pulled a user and quote from the db and there is an '_id' but no 'id' property on the object. This is the output:

 > db.users.find({})
{ "_id" : ObjectId("586253169465191cb812066c"), "name" : "me", "id" : ObjectId("586253169465191cb812066c"), "errors" : [ ] }
> db.quotes.find({})
{ "_id" : ObjectId("586693333ff93f3581c0ca05"), "text" : "Hi Prisc", "author" : "H. Jackson Brown", "likesCount" : 24 }
{ "_id" : ObjectId("586693333ff93f3581c0ca06"), "text" : "If opportunity doesn't knock, build a door", "author" : "Milton Berle", "likesCount" : 2 }
{ "_id" : ObjectId("586693333ff93f3581c0ca07"), "text" : "Try to be a rainbow in...", "author" : "Maya Angelou" }

If I log the id from the globalIdFetcher(), the logged id for the Jackson Brown Quote object show two id's as expected but they are both the same and different from the one in the db. Output in console is:

{
    "viewer": {
        "__dataID__": "VXNlcjo=",
        "quotes": {
            "__dataID__": "client:6068631311_first(100),searchTerm()",
            "edges": [
                {
                    "__dataID__": "client:client:6068631311:UXVvdGU6NTg2NjkzMzMzZmY5M2YzNTgxYzBjYTA1",
                    "node": {
                        "__dataID__": "UXVvdGU6NTg2NjkzMzMzZmY5M2YzNTgxYzBjYTA1",
                        "id": "UXVvdGU6NTg2NjkzMzMzZmY5M2YzNTgxYzBjYTA1",
                        "__fragments__": {
                            "1::client": [
                                {
                                    "showLikes": false
                                }
                            ]
                        }
                    }
                },

Any ideas on fixing this syntax?


问:
How to sort a huge file which can't be loaded in memory completely. Is there any algorithm other than merge sort which can be used?
I have a huge file of numbers/String with delimiter as space. This file can't be loaded in memory as the size is 16 GB and the capacity of RAM is 8 GB.

I need the logical steps to solve this problem.

答: If the file consists of records with a unique record ID of some kind and a number of associated fields and you are only needing a subset of fields that fit in memory, then you might load the required fields into memory and sort just those?</p>