问:
Swift Wait for Callback to finish before method return
I'm using Siesta REST API client for swift. I'm logging into an external API (successfully) and get the result from the siesta request object. The request has two callbacks - onSuccess and onFailure.

If the login was successful I set a token in the keychain and then return the result to the view controller - which segues to a new view controller if successful.

However, as I'm assuming the callback is used asynchronously, my function is not returning the correct result.

```<code> @IBAction func normalLoginButton(_ sender: UIButton) {

    //do normal login
    let standardLogin = StandardLogin()
    let credentials = ["email" : "john@example.com", "password": "password" ]
    let loginResult = standardLogin.login(params: credentials)
    print(loginResult)
    if loginResult {
        performSegue(withIdentifier: "showSuccessfulLoginView", sender: self)
    }

 }

 func login(params : Dictionary<String,String>) -> Bool{
    var loginSuccess = false
    let loginRequest = wrApi.makePostRequest(route: "login", params:params)

    loginRequest
        .onSuccess { data in
            print("succes")
            self.setJwtToken(jsonData: data.content)
            loginSuccess = true
        }
        .onFailure { error in print("an error occured")
    }

    return loginSuccess

}
</code>```

My question is basically how do I wait for the callback to finish before returning my loginSuccess Boolean?

I'm pretty new to swift, so any help would be appreciated.

答:
login is acsync function, so you can't use return
Try closure:

```<code>   func login(params : Dictionary<String,String>, handleFinish:((isOK:Bool,param: Type?)->())){
       var loginSuccess = false
    let loginRequest = wrApi.makePostRequest(route: "login", params:params)

    loginRequest
        .onSuccess { data in
            print("succes")
            self.setJwtToken(jsonData: data.content)
            loginSuccess = true
            handleFinish(isOK: true, param :data.content )
        }
        .onFailure { error in
                       print("an error occured")
                        handleFinish(isOK: false, param :nil )
    }

   }
</code>```

and call it:

```<code>login(param) { (isOK, param) in
  if isOK{
   print("login success: \(param)")
 }
</code>```

}

Body:
I'm using Siesta REST API client for swift. I'm logging into an external API (successfully) and get the result from the siesta request object. The request has two callbacks - onSuccess and onFailure.

If the login was successful I set a token in the keychain and then return the result to the view controller - which segues to a new view controller if successful.

However, as I'm assuming the callback is used asynchronously, my function is not returning the correct result.

 @IBAction func normalLoginButton(_ sender: UIButton) {

    //do normal login
    let standardLogin = StandardLogin()
    let credentials = ["email" : "john@example.com", "password": "password" ]
    let loginResult = standardLogin.login(params: credentials)
    print(loginResult)
    if loginResult {
        performSegue(withIdentifier: "showSuccessfulLoginView", sender: self)
    }

 }

 func login(params : Dictionary<String,String>) -> Bool{
    var loginSuccess = false
    let loginRequest = wrApi.makePostRequest(route: "login", params:params)

    loginRequest
        .onSuccess { data in
            print("succes")
            self.setJwtToken(jsonData: data.content)
            loginSuccess = true
        }
        .onFailure { error in print("an error occured")
    }

    return loginSuccess

}

My question is basically how do I wait for the callback to finish before returning my loginSuccess Boolean?

I'm pretty new to swift, so any help would be appreciated.

Body:
login is acsync function, so you can't use return
Try closure:

   func login(params : Dictionary<String,String>, handleFinish:((isOK:Bool,param: Type?)->())){
       var loginSuccess = false
    let loginRequest = wrApi.makePostRequest(route: "login", params:params)

    loginRequest
        .onSuccess { data in
            print("succes")
            self.setJwtToken(jsonData: data.content)
            loginSuccess = true
            handleFinish(isOK: true, param :data.content )
        }
        .onFailure { error in
                       print("an error occured")
                        handleFinish(isOK: false, param :nil )
    }

   }

and call it:

login(param) { (isOK, param) in
  if isOK{
   print("login success: \(param)")
 }

}


来源: stackexchange

问:
how to add 2 classes with delay in jquery
I trying to create animation with jquery.
When I click yellow box it will move to center container(.radius), after that the box will change as container width(remove .radius add .full).
is that posible to adding 2 classes in single event with jquery?
or is there any otherway to do it?
thank you

$(document).ready(function(){
  var go = $('.expand');

  function erase(){
    $(go).removeClass('radius');
    //$(go).addClass('full');
  }
  $(go).on('click', function(){
    $(this).addClass('radius').delay(500, erase);
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.boxContainer {
  position: relative;
  overflow: hidden;
  width: 1170px;
  height: 800px;
  border: 3px solid #cecece;
  margin: 0 auto;
  padding: 0 15px;
}

.expand {
  position: absolute;
  top: 5px;
  left: 5px;
  width: 50px;
  height: 50px;
  background-color: yellow;
  cursor: pointer;
  transition: 300ms all ease-in-out;
}

.radius {
  top: 50%;
  left: 50%;
}

.full{
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}</code>```

```

答:
To achieve what you need you can use setTimeout() to delay amending the classes for 500ms. Try this:

var $go = $('.expand');

$go.on('click', function() {
  $(this).addClass('radius')
  setTimeout(function() {
    $go.removeClass('radius').addClass('full');
  }, 500);
});
```

<p>That being said, a much better solution would be to do it all in CSS by using keyframes:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$('.expand').on('click', function() {
  $(this).addClass('animate')
});</code>```

.boxContainer {
  position: relative;
  overflow: hidden;
  width: 1170px;
  height: 800px;
  border: 3px solid #cecece;
  margin: 0 auto;
  padding: 0 15px;
}

.expand {
  position: absolute;
  top: 5px;
  left: 5px;
  width: 50px;
  height: 50px;
  background-color: yellow;
  cursor: pointer;
  transition: 300ms all ease-in-out;
}

@keyframes expand {
  50% {
    width: 50px;
    height: 50px;
    top: 50%;
    left: 50%;
  }
  100% {
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
  }
}

.animate {
  animation: expand 1s forwards;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="boxContainer">
  <div class="expand"></div>
</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I trying to create animation with jquery.
When I click yellow box it will move to center container(.radius), after that the box will change as container width(remove .radius add .full).
is that posible to adding 2 classes in single event with jquery?
or is there any otherway to do it?
thank you

$(document).ready(function(){
  var go = $('.expand');

  function erase(){
    $(go).removeClass('radius');
    //$(go).addClass('full');
  }
  $(go).on('click', function(){
    $(this).addClass('radius').delay(500, erase);
  });

});

.boxContainer {
  position: relative;
  overflow: hidden;
  width: 1170px;
  height: 800px;
  border: 3px solid #cecece;
  margin: 0 auto;
  padding: 0 15px;
}

.expand {
  position: absolute;
  top: 5px;
  left: 5px;
  width: 50px;
  height: 50px;
  background-color: yellow;
  cursor: pointer;
  transition: 300ms all ease-in-out;
}

.radius {
  top: 50%;
  left: 50%;
}

.full{
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}

Body:
To achieve what you need you can use setTimeout() to delay amending the classes for 500ms. Try this:

var $go = $('.expand');

$go.on('click', function() {
  $(this).addClass('radius')
  setTimeout(function() {
    $go.removeClass('radius').addClass('full');
  }, 500);
});

That being said, a much better solution would be to do it all in CSS by using keyframes:

$('.expand').on('click', function() {
  $(this).addClass('animate')
});

.boxContainer {
  position: relative;
  overflow: hidden;
  width: 1170px;
  height: 800px;
  border: 3px solid #cecece;
  margin: 0 auto;
  padding: 0 15px;
}

.expand {
  position: absolute;
  top: 5px;
  left: 5px;
  width: 50px;
  height: 50px;
  background-color: yellow;
  cursor: pointer;
  transition: 300ms all ease-in-out;
}

@keyframes expand {
  50% {
    width: 50px;
    height: 50px;
    top: 50%;
    left: 50%;
  }
  100% {
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
  }
}

.animate {
  animation: expand 1s forwards;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="boxContainer">
  <div class="expand"></div>
</div>


问:
Add margin to pdf page
I have a pdf book that is not showing up completely. I have attached a screenshot of acrobat's print preview showing what the issue is. As you can see there is more conentent on the left of the page that is not showing up.

I have tried:
Changing the paper size
Changing the dimensions to "fit"
Opening in Google docs
Opening in mac's preview
Opening in Google Books.

Any ideas of what I can try

答:
As a late answer and when using Linux, one can use the command line tool "pdfjam".

Add margins to pages

Desired result: remove 0.5 cm from top and bottom of page, add 2 cm to right margin. Keep page size (important)

```<code>pdfjam --fitpaper true --trim "0cm 0.5cm -2cm 0.5cm" input.pdf -o output.pdf
</code>```

Negative numbers in the trim-argument means "add", while a positive means "remove".

The four numbers within the trim-arguments relates to the left, bottom, right and top margin

If fitpaper is set to false the trim will move the content around the page and not resize the page.

You can add "--frame true" to see what's going on.

Move content to the left

Desired result: make right margin 1 cm larger and left margin 1 cm smaller

```<code>pdfjam --offset "-1cm 0cm" input.pdf -o output.pdf
</code>```

The command below will move the content of the page 1 cm from right to left.

pdfjam and documentation

Documentation about pdfjam can be found here: http://www2.warwick.ac.uk/fac/sci/statistics/staff/academic-research/firth/software/pdfjam

The combination of pdfinfo, pdftk and pdfjam can be used to modify PDFs quickly on a more advanced level.

Title: Add margin to pdf page

Body:
As a late answer and when using Linux, one can use the command line tool "pdfjam".

Add margins to pages

Desired result: remove 0.5 cm from top and bottom of page, add 2 cm to right margin. Keep page size (important)

pdfjam --fitpaper true --trim "0cm 0.5cm -2cm 0.5cm" input.pdf -o output.pdf

Negative numbers in the trim-argument means "add", while a positive means "remove".

The four numbers within the trim-arguments relates to the left, bottom, right and top margin

If fitpaper is set to false the trim will move the content around the page and not resize the page.

You can add "--frame true" to see what's going on.

Move content to the left

Desired result: make right margin 1 cm larger and left margin 1 cm smaller

pdfjam --offset "-1cm 0cm" input.pdf -o output.pdf

The command below will move the content of the page 1 cm from right to left.

pdfjam and documentation

Documentation about pdfjam can be found here: http://www2.warwick.ac.uk/fac/sci/statistics/staff/academic-research/firth/software/pdfjam

The combination of pdfinfo, pdftk and pdfjam can be used to modify PDFs quickly on a more advanced level.


问:
UIDatePicker outputs different formats of string of date between simulator and iPhone
I ran the UIDatePicker on my iPhone and on the simulator, they both show output in different formats?

How can i solve the problem? Is there a format that can work around? I know it is because of NSLocale. as I want my app not only to work on one country. I need save the date to the server for searching and comparing. Therefore, I need a format to work around.

Thanks.

答:
The date format displayed on a UIDatePicker is, as you say, dependant on the locale of the device. The simulator is set to en_US by default, I assume your device is different.

Do NOT force user to us a standard format - the date should be displayed in the picker in their device's locale format - using a standard format will be confusing for most of your users. For example, a user in USA would expect to see their dates as MM/DD/YY, in UK DD/MM/YY, in South Africa as YY/MM/DD. If you force a standard format it will be wrong for most of your users. See http://en.wikipedia.org/wiki/Date_format_by_country

Regardless of what format is displayed in a UIDatePicker, the date selected by the user and is just a Date object. This does NOT have a format, it is just a point in time.

If you're comparing / searching dates, never use a formatted date string. Use Date, Calendar, etc methods.

If you print the value of a Date object, it will format it using the current locale (but that is just how it's displayed, the date itself has no format)

See Apple docs for more Date info

If you want to send your selected date to the server in a fixed format, you should use DateFormatter and set the format/locale to whatever your require. Apple's recommendation is the use en_US_POSIX as the locale. Only use this internally, when converting your date to a format for sending to the server - this shouldn't be seen by the user.

From Apple docs…

```<code>let RFC3339DateFormatter = DateFormatter()
RFC3339DateFormatter.locale = Locale(localeIdentifier: "en_US_POSIX")
RFC3339DateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
RFC3339DateFormatter.timeZone = TimeZone(forSecondsFromGMT: 0)

/* 39 minutes and 57 seconds after the 16th hour of December 19th, 1996 with an offset of -08:00 from UTC (Pacific Standard Time) */
let string = "1996-12-19T16:39:57-08:00"
let date = RFC3339DateFormatter.dateFromString(string)
</code>```

In iOS 10+, this has been simplified - you can just use the ISO8601DateFormatter class

Body:
The date format displayed on a UIDatePicker is, as you say, dependant on the locale of the device. The simulator is set to en_US by default, I assume your device is different.

Do NOT force user to us a standard format - the date should be displayed in the picker in their device's locale format - using a standard format will be confusing for most of your users. For example, a user in USA would expect to see their dates as MM/DD/YY, in UK DD/MM/YY, in South Africa as YY/MM/DD. If you force a standard format it will be wrong for most of your users. See http://en.wikipedia.org/wiki/Date_format_by_country

Regardless of what format is displayed in a UIDatePicker, the date selected by the user and is just a Date object. This does NOT have a format, it is just a point in time.

If you're comparing / searching dates, never use a formatted date string. Use Date, Calendar, etc methods.

If you print the value of a Date object, it will format it using the current locale (but that is just how it's displayed, the date itself has no format)

See Apple docs for more Date info

If you want to send your selected date to the server in a fixed format, you should use DateFormatter and set the format/locale to whatever your require. Apple's recommendation is the use en_US_POSIX as the locale. Only use this internally, when converting your date to a format for sending to the server - this shouldn't be seen by the user.

From Apple docs…

let RFC3339DateFormatter = DateFormatter()
RFC3339DateFormatter.locale = Locale(localeIdentifier: "en_US_POSIX")
RFC3339DateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
RFC3339DateFormatter.timeZone = TimeZone(forSecondsFromGMT: 0)

/* 39 minutes and 57 seconds after the 16th hour of December 19th, 1996 with an offset of -08:00 from UTC (Pacific Standard Time) */
let string = "1996-12-19T16:39:57-08:00"
let date = RFC3339DateFormatter.dateFromString(string)

In iOS 10+, this has been simplified - you can just use the ISO8601DateFormatter class


问:
How do you get a Cronjob executing a PHP script to run longer than 30 seconds?
How can I rewrite this into a cron that will run every day for longer than 30 seconds? Also, do I need to edit the .htaccess or php.ini file in the cron.php directory to say something? Over the browser it runs just fine for longer than 30 seconds; over the shell, it runs just fine too. But as a cron set task, it dies after 30 seconds. I'm on 1and1 share hosting.

```<code>0 12 * * * php5 /this/is/the/file/cron.php
</code>```

答:
```<code>ini_set('max_execution_time', 600);
</code>```

Add this to the top of your php file and it will run for 600 seconds. Anything more is not recommended but you can have a go if you want.

Body:
How can I rewrite this into a cron that will run every day for longer than 30 seconds? Also, do I need to edit the .htaccess or php.ini file in the cron.php directory to say something? Over the browser it runs just fine for longer than 30 seconds; over the shell, it runs just fine too. But as a cron set task, it dies after 30 seconds. I'm on 1and1 share hosting.

0 12 * * * php5 /this/is/the/file/cron.php

Body:
ini_set('max_execution_time', 600);

Add this to the top of your php file and it will run for 600 seconds. Anything more is not recommended but you can have a go if you want.


问:
How can I invoke a Model's method from view in a Xamarin PCL project
I'd like to call a method that is located in a class LoginViewModel but it is inacessible. How can I render it accessible from the Login.xaml.cs code behind so that i can call the Connexion() method ?

Login.xaml

```<code><Button
            StyleId="btn_connexion"
            Text="Connexion"
                Clicked="Connexion_click" />
</code>```

Login.xaml.cs

```<code>private void Connexion_click(object sender, EventArgs e)
        {
           //here is where i'd like to call the connexion method
        }
</code>```

LoginViewModel.cs

```<code>public async Task Connexion()
        {

            List<Visiteur> listeTest = CreerListeVisiteurDur();
            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
            {
                foreach (Visiteur unVisiteur in listeTest)
                {
                    string login = unVisiteur.login;
                    string pass = unVisiteur.mdp;

                    if (login == username && pass == password)
                    {
                        App.Current.MainPage = new CreerVisite();
                    }

                }
            }
</code>```

答:
I think you should use "Binding" with Command, not Clicked

something like

```<code><Button
            StyleId="btn_connexion"
            Text="Connexion"
                Command="{Binding OpenPageCommand}" />
</code>```

and in your ViewModel something like

```<code>    this.OpenPageCommand = new Command(async () => {
        try {
                        List<Visiteur> listeTest = CreerListeVisiteurDur();
    if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
    {
        foreach (Visiteur unVisiteur in listeTest)
        {
            string login = unVisiteur.login;
            string pass = unVisiteur.mdp;

            if (login == username && pass == password)
            {
                App.Current.MainPage = new CreerVisite();
            }

        }
    }

        }
        catch (Exception ex) {
            await Application.Current.MainPage.DisplayAlert("Attention", ex.Message, "Ok");
        }
    });
</code>```

Body:
I'd like to call a method that is located in a class LoginViewModel but it is inacessible. How can I render it accessible from the Login.xaml.cs code behind so that i can call the Connexion() method ?

Login.xaml

<Button
            StyleId="btn_connexion"
            Text="Connexion"
                Clicked="Connexion_click" />

Login.xaml.cs

private void Connexion_click(object sender, EventArgs e)
        {
           //here is where i'd like to call the connexion method
        }

LoginViewModel.cs

public async Task Connexion()
        {

            List<Visiteur> listeTest = CreerListeVisiteurDur();
            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
            {
                foreach (Visiteur unVisiteur in listeTest)
                {
                    string login = unVisiteur.login;
                    string pass = unVisiteur.mdp;

                    if (login == username && pass == password)
                    {
                        App.Current.MainPage = new CreerVisite();
                    }

                }
            }

Body:
I think you should use "Binding" with Command, not Clicked

something like

<Button
            StyleId="btn_connexion"
            Text="Connexion"
                Command="{Binding OpenPageCommand}" />

and in your ViewModel something like

    this.OpenPageCommand = new Command(async () => {
        try {
                        List<Visiteur> listeTest = CreerListeVisiteurDur();
    if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
    {
        foreach (Visiteur unVisiteur in listeTest)
        {
            string login = unVisiteur.login;
            string pass = unVisiteur.mdp;

            if (login == username && pass == password)
            {
                App.Current.MainPage = new CreerVisite();
            }

        }
    }

        }
        catch (Exception ex) {
            await Application.Current.MainPage.DisplayAlert("Attention", ex.Message, "Ok");
        }
    });


问:
Spring JavaConfig and Tomcat 8
I have a Spring 4 web application (webapp-module.war) working and running locally in eclipse using Java 8, tomcat 8 and JavaConfig (no web.xml):

But when I deploy to tomcat 8 (same version I am using locally in eclipse) on a remote Ubuntu server I get:

I verified host and port which are correct. There is no error in the log (/var/lib/tomcat8/logs/catalina.out)

```<code>Jun 21, 2016 10:32:44 PM org.apache.catalina.startup.HostConfig undeploy
INFO: Undeploying context [/webapp-module]
Jun 21, 2016 10:32:44 PM org.apache.catalina.startup.HostConfig deployWAR
INFO: Deploying web application archive /var/lib/tomcat8/webapps/webapp-module.war
Jun 21, 2016 10:32:46 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Jun 21, 2016 10:32:46 PM org.apache.catalina.startup.HostConfig deployWAR
INFO: Deployment of web application archive /var/lib/tomcat8/webapps/webapp-module.war has finished in 1,870 ms
root@vmi63860:/var/lib/tomcat8/logs#
</code>```

The access log contains:

```<code>root@vmi63860:/var/log/tomcat8# cat localhost_access_log.2016-06-22.txt
xx.xxx.xxx.xx - - [22/Jun/2016:22:36:00 +0200] "GET /webapp-module/ HTTP/1.1" 404 1040
xx.xxx.xxx.xx - - [22/Jun/2016:22:36:00 +0200] "GET /favicon.ico HTTP/1.1" 404 1034
xx.xxx.xxx.xx - - [22/Jun/2016:22:36:50 +0200] "GET /webapp-module/hello HTTP/1.1" 404 1050
</code>```

Where xx.xxx.xxx.xx is the IP of my local machine from where I try to access the web app in my browser.

I took a look at:
Spring Java Config: Tomcat deploy without web.xml but it does not really provide a solution.

Details on my project below:

Sources

Config.java

```<code>@Configuration // Marks this class as configuration
// Specifies which package to scan
@ComponentScan("com.samples")
// Enables Spring's annotations
@EnableWebMvc
public class Config {

  @Bean
  public UrlBasedViewResolver setupViewResolver() {
    UrlBasedViewResolver resolver = new UrlBasedViewResolver();
    resolver.setPrefix("/WEB-INF/jsp/");
    resolver.setSuffix(".jsp");
    resolver.setViewClass(JstlView.class);
    return resolver;
  }

}
</code>```

WebInitializer.java

```<code>public class WebInitializer implements WebApplicationInitializer {

  @Override
  public void onStartup(ServletContext servletContext) throws ServletException {

    AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
    ctx.register(Config.class);
    ctx.setServletContext(servletContext);

    Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
    servlet.addMapping("/");
    servlet.setLoadOnStartup(1);

  }

}
</code>```

HelloController.java

```<code>@Controller
public class HelloController {

  @RequestMapping("/")
  public String home() {
    return "index";
  }

  @RequestMapping("/hello")
  public String showhello(ModelMap model) {
    model.addAttribute("message", "Hello Spring MVC Framework!");
    return "hello";
  }

}
</code>```

答:
Sorry previously I was too hasty

It seems that spring context is not at all loaded.

I guess the problem is in this piece of code:

```<code>public class WebInitializer implements WebApplicationInitializer {

  @Override
  public void onStartup(ServletContext servletContext) throws ServletException {

    AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
    ctx.register(Config.class);
    ctx.setServletContext(servletContext);

    Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
    servlet.addMapping("/");
    servlet.setLoadOnStartup(1);

  }

}
</code>```

You used ctx.register(Config.class);

In any case I always used this kind of initialization:

```<code>public class AppInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        // Create the 'root' Spring application context
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.scan("com.spring");
        rootContext.setConfigLocations(new String[]{"com.spring.config.WebAppContextConfig", "com.spring.config.AppConfig"});
        // Manages the lifecycle of the root application context
        servletContext.addListener(new ContextLoaderListener(rootContext));

        // Declare dispatcher servlet. Handles requests into the application
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher",
                new DispatcherServlet(rootContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");

    }

}
</code>```

As you can see I used rootContext.setConfigLocations in order to specify where to find the spring configuration classes

In any case Here you can find a working sample I successfully deployed it on tomcat 8.0.39 and 8.5.4

Hope it's useful

Angelo

Title: Spring JavaConfig and Tomcat 8

Body:
I have a Spring 4 web application (webapp-module.war) working and running locally in eclipse using Java 8, tomcat 8 and JavaConfig (no web.xml):

But when I deploy to tomcat 8 (same version I am using locally in eclipse) on a remote Ubuntu server I get:

I verified host and port which are correct. There is no error in the log (/var/lib/tomcat8/logs/catalina.out)

Jun 21, 2016 10:32:44 PM org.apache.catalina.startup.HostConfig undeploy
INFO: Undeploying context [/webapp-module]
Jun 21, 2016 10:32:44 PM org.apache.catalina.startup.HostConfig deployWAR
INFO: Deploying web application archive /var/lib/tomcat8/webapps/webapp-module.war
Jun 21, 2016 10:32:46 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Jun 21, 2016 10:32:46 PM org.apache.catalina.startup.HostConfig deployWAR
INFO: Deployment of web application archive /var/lib/tomcat8/webapps/webapp-module.war has finished in 1,870 ms
root@vmi63860:/var/lib/tomcat8/logs#

The access log contains:

root@vmi63860:/var/log/tomcat8# cat localhost_access_log.2016-06-22.txt
xx.xxx.xxx.xx - - [22/Jun/2016:22:36:00 +0200] "GET /webapp-module/ HTTP/1.1" 404 1040
xx.xxx.xxx.xx - - [22/Jun/2016:22:36:00 +0200] "GET /favicon.ico HTTP/1.1" 404 1034
xx.xxx.xxx.xx - - [22/Jun/2016:22:36:50 +0200] "GET /webapp-module/hello HTTP/1.1" 404 1050

Where xx.xxx.xxx.xx is the IP of my local machine from where I try to access the web app in my browser.

I took a look at:
Spring Java Config: Tomcat deploy without web.xml but it does not really provide a solution.

Details on my project below:

Sources

Config.java

@Configuration // Marks this class as configuration
// Specifies which package to scan
@ComponentScan("com.samples")
// Enables Spring's annotations
@EnableWebMvc
public class Config {

  @Bean
  public UrlBasedViewResolver setupViewResolver() {
    UrlBasedViewResolver resolver = new UrlBasedViewResolver();
    resolver.setPrefix("/WEB-INF/jsp/");
    resolver.setSuffix(".jsp");
    resolver.setViewClass(JstlView.class);
    return resolver;
  }

}

WebInitializer.java

public class WebInitializer implements WebApplicationInitializer {

  @Override
  public void onStartup(ServletContext servletContext) throws ServletException {

    AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
    ctx.register(Config.class);
    ctx.setServletContext(servletContext);

    Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
    servlet.addMapping("/");
    servlet.setLoadOnStartup(1);

  }

}

HelloController.java

@Controller
public class HelloController {

  @RequestMapping("/")
  public String home() {
    return "index";
  }

  @RequestMapping("/hello")
  public String showhello(ModelMap model) {
    model.addAttribute("message", "Hello Spring MVC Framework!");
    return "hello";
  }

}

Body:
Sorry previously I was too hasty

It seems that spring context is not at all loaded.

I guess the problem is in this piece of code:

public class WebInitializer implements WebApplicationInitializer {

  @Override
  public void onStartup(ServletContext servletContext) throws ServletException {

    AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
    ctx.register(Config.class);
    ctx.setServletContext(servletContext);

    Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
    servlet.addMapping("/");
    servlet.setLoadOnStartup(1);

  }

}

You used ctx.register(Config.class);

In any case I always used this kind of initialization:

public class AppInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        // Create the 'root' Spring application context
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.scan("com.spring");
        rootContext.setConfigLocations(new String[]{"com.spring.config.WebAppContextConfig", "com.spring.config.AppConfig"});
        // Manages the lifecycle of the root application context
        servletContext.addListener(new ContextLoaderListener(rootContext));

        // Declare dispatcher servlet. Handles requests into the application
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher",
                new DispatcherServlet(rootContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");

    }

}

As you can see I used rootContext.setConfigLocations in order to specify where to find the spring configuration classes

In any case Here you can find a working sample I successfully deployed it on tomcat 8.0.39 and 8.5.4

Hope it's useful

Angelo


问:
Facebook Marketing API - Cannot Create Ad-Set
I'm new to the facebook marketing API.
I was able to create a campaign.

But it seems I cannot create Adset.

I've tried posting with Javascript to the Adset:
https://graph.facebook.com/v2.8/act_156221465583672/adsets

with this payload:

```<code>    var targeting = {
        "age_max": 43,
        "age_min": 18,
        "geo_locations": { "countries": ["US"] }
    };

   var campaignId = "520337003094784508";

    var promotedObject = {
        'application_id': 2242592062246511
    };
</code>```

and post body:

```<code>    {
        "access_token": accessToken,
        "name": "testNirAd",
        "lifetime_budget": "8000",
        "autobid": "true",
        "start_time": new Date("October 13, 2017 00:00:00"),
        "end_time": new Date("November 13, 2017 00:00:00"),
        "optimization_goal": "POST_ENGAGEMENT",
        "billing_event": "IMPRESSIONS",
        "daily_budget": "2000",
        "campaign_id": campaignId,
        "targeting": JSON.stringify(targeting),
        "status": "PAUSED"
    }
</code>```

But I get this error:

```<code>     {
         "error": {
         "message": "Invalid parameter",
         "type": "OAuthException",
         "code": 100,
         "error_data": {
         "blame_field_specs": [
             [
                "name"
             ]
         ]
       },
       "error_subcode": 2061015,
       "is_transient": false,
       "error_user_title": "Required Field Is Missing",
       "error_user_msg": "The name field is required. Please complete the
       field to continue.",
      "fbtrace_id": "HFg4HmwbQhG"
   }
</code>```

}

Which is strange because I have a name field.

Then I've tried the same with the Javascript SDK
https://github.com/lucascosta/facebook-js-ads-sdk, with the same payload data,
and this time I get:
       {
             code:1
             fbtrace_id:"DcXmP0Wr82Q"
             message:"An unknown error has occurred."
             type:"OAuthException"
       }

Please can anybody help?

答:
Tried also with different, less parameters, with Curl, and got the same results:

```<code>curl /
-F 'name=MyFirstTest'  /
-F 'billing_event=IMPRESSIONS' /
-F 'bid_amount=2' /
-F 'daily_budget=1000' /
-F 'campaign_id=120330000094784508' /
-F 'targeting={"geo_locations":{"countries":["US"]}}' /
-F 'start_time=2017-10-14T16:06:09+0000' /
-F 'end_time=2017-11-21T16:06:09+0000' /
-F 'status=PAUSED' /
-F 'access_token= EAAf0hSLb7osBAEgUpUtkGydJ9mmfZCzYumfNVxDFUjBFtx7C8aos3x
LbzjwkZBEbgXkWAT75OvIy6HXNTFBEqN1ca1aVvWT3RQAAKAAi6jYyncTG3m9ae0MkZAM9gZDZD'
/https://graph.facebook.com/v2.8/act_116221225224746/adsets
</code>```

And got:

```<code>{"error":{"message":"Invalid
parameter","type":"OAuthException","code":100,"error_data":
{"blame_field_specs":[["name"]]},"error_subcode":2061015,"is_transient":
false,"error_user_title":"Required Field Is Missing","error_user_msg":"The
name field is required. Please complete the field to
continue.","fbtrace_id":"AeI4nngXTmj"}}
</code>```

fbtrace_id:  AeI4nngXTmj

By the way, I'm using a sandbox account.

Thanks!

Body:
I'm new to the facebook marketing API.
I was able to create a campaign.

But it seems I cannot create Adset.

I've tried posting with Javascript to the Adset:
https://graph.facebook.com/v2.8/act_156221465583672/adsets

with this payload:

    var targeting = {
        "age_max": 43,
        "age_min": 18,
        "geo_locations": { "countries": ["US"] }
    };

   var campaignId = "520337003094784508";

    var promotedObject = {
        'application_id': 2242592062246511
    };

and post body:

    {
        "access_token": accessToken,
        "name": "testNirAd",
        "lifetime_budget": "8000",
        "autobid": "true",
        "start_time": new Date("October 13, 2017 00:00:00"),
        "end_time": new Date("November 13, 2017 00:00:00"),
        "optimization_goal": "POST_ENGAGEMENT",
        "billing_event": "IMPRESSIONS",
        "daily_budget": "2000",
        "campaign_id": campaignId,
        "targeting": JSON.stringify(targeting),
        "status": "PAUSED"
    }

But I get this error:

     {
         "error": {
         "message": "Invalid parameter",
         "type": "OAuthException",
         "code": 100,
         "error_data": {
         "blame_field_specs": [
             [
                "name"
             ]
         ]
       },
       "error_subcode": 2061015,
       "is_transient": false,
       "error_user_title": "Required Field Is Missing",
       "error_user_msg": "The name field is required. Please complete the
       field to continue.",
      "fbtrace_id": "HFg4HmwbQhG"
   }

}

Which is strange because I have a name field.

Then I've tried the same with the Javascript SDK
https://github.com/lucascosta/facebook-js-ads-sdk, with the same payload data,
and this time I get:
       {
             code:1
             fbtrace_id:"DcXmP0Wr82Q"
             message:"An unknown error has occurred."
             type:"OAuthException"
       }

Please can anybody help?

Body:
Tried also with different, less parameters, with Curl, and got the same results:

curl /
-F 'name=MyFirstTest'  /
-F 'billing_event=IMPRESSIONS' /
-F 'bid_amount=2' /
-F 'daily_budget=1000' /
-F 'campaign_id=120330000094784508' /
-F 'targeting={"geo_locations":{"countries":["US"]}}' /
-F 'start_time=2017-10-14T16:06:09+0000' /
-F 'end_time=2017-11-21T16:06:09+0000' /
-F 'status=PAUSED' /
-F 'access_token= EAAf0hSLb7osBAEgUpUtkGydJ9mmfZCzYumfNVxDFUjBFtx7C8aos3x
LbzjwkZBEbgXkWAT75OvIy6HXNTFBEqN1ca1aVvWT3RQAAKAAi6jYyncTG3m9ae0MkZAM9gZDZD'
/https://graph.facebook.com/v2.8/act_116221225224746/adsets

And got:

{"error":{"message":"Invalid
parameter","type":"OAuthException","code":100,"error_data":
{"blame_field_specs":[["name"]]},"error_subcode":2061015,"is_transient":
false,"error_user_title":"Required Field Is Missing","error_user_msg":"The
name field is required. Please complete the field to
continue.","fbtrace_id":"AeI4nngXTmj"}}

fbtrace_id:  AeI4nngXTmj

By the way, I'm using a sandbox account.

Thanks!


问:
Error when adding rows to OutputBuffer in parallel
I am facing a problem an it really drives me insane: I have to handle a bunch of XML files (something like 70k a day) and wrote a Sourcecomponent which does a pretty good job in transforming (XSL) and loading the files (Yes, I tried the XML Source; No, it does not fullfill my needs). However, I designed the source component in order to first load a certain amount of data into  memory tables and after this amount is reached send the data from the tables to the OutputBuffer and in order to speed things up a little, I do this by Parallel.For. The first part - the loading and transforming - works pretty fine and I can load an example set of 200 files in a few seconds. But when it comes to OutputBuffer.AddRow, the program crashes, reporting errors of various types (wrong data type, etc.). If I send the content of the data tables separately, everything seems to work. Any idea, why OutputBuffer.AddRow crashes when it is called from within Parallel.For???

答:
What is typeof OutputBuffer? very likely, a type not thread safe, requiring some syncronization when calling a method on it.
Can you try locking the access to it? instead of

```<code>OutputBuffer.AddRow(...)
</code>```

something like

```<code>lock(OutputBuffer)
{
    OutputBuffer.AddRow(...);
}
</code>```

Body:
What is typeof OutputBuffer? very likely, a type not thread safe, requiring some syncronization when calling a method on it.
Can you try locking the access to it? instead of

OutputBuffer.AddRow(...)

something like

lock(OutputBuffer)
{
    OutputBuffer.AddRow(...);
}


问:
Laravel: Custom login path doesn't work
I set my login path to be 123. Here's how I did it:

In routes/web.php, I posted this:

```<code>// Authentication Routes...
Route::get('123', 'Auth\LoginController@showLoginForm')->name('login');
Route::post('123', 'Auth\LoginController@login');
Route::post('logout', 'Auth\LoginController@logout')->name('logout');

// Registration Routes...
Route::get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
Route::post('register', 'Auth\RegisterController@register');

// Password Reset Routes...
Route::get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
Route::post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
Route::get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
Route::post('password/reset', 'Auth\ResetPasswordController@reset');
</code>```

I deleted the default Auth::routes(); line in the same file.

Like it should, localhost:8000/login generates this error:

```<code>NotFoundHttpException in RouteCollection.php line 161:
</code>```

But, when I type localhost:8000/123, I get:

```<code>ReflectionException in RouteSignatureParameters.php line 39:
Method App\Http\Controllers\HomeController::index() does not exist
</code>```

after getting redirected to localhost:8000/home.

So there is some sort of weird redirect going on here. /home doesn't exist, so probably that is the direct reason for the error. But why does it redirect at all? It should go to the login page!

Help please.

答:
It looks like you have cached routes to me.

php artisan cache:clear

php artisan route:cache

Should remove any cached routes created by the Auth::routes(); function.

The redirect takes place because of a setting in Http/Controllers/Auth/LoginController

```<code> protected $redirectTo = '/home';
</code>```

Title: Laravel: Custom login path doesn't work

Body:
I set my login path to be 123. Here's how I did it:

In routes/web.php, I posted this:

// Authentication Routes...
Route::get('123', 'Auth\LoginController@showLoginForm')->name('login');
Route::post('123', 'Auth\LoginController@login');
Route::post('logout', 'Auth\LoginController@logout')->name('logout');

// Registration Routes...
Route::get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
Route::post('register', 'Auth\RegisterController@register');

// Password Reset Routes...
Route::get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
Route::post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
Route::get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
Route::post('password/reset', 'Auth\ResetPasswordController@reset');

I deleted the default Auth::routes(); line in the same file.

Like it should, localhost:8000/login generates this error:

NotFoundHttpException in RouteCollection.php line 161:

But, when I type localhost:8000/123, I get:

ReflectionException in RouteSignatureParameters.php line 39:
Method App\Http\Controllers\HomeController::index() does not exist

after getting redirected to localhost:8000/home.

So there is some sort of weird redirect going on here. /home doesn't exist, so probably that is the direct reason for the error. But why does it redirect at all? It should go to the login page!

Help please.

Body:
It looks like you have cached routes to me.

php artisan cache:clear

php artisan route:cache

Should remove any cached routes created by the Auth::routes(); function.

The redirect takes place because of a setting in Http/Controllers/Auth/LoginController

 protected $redirectTo = '/home';


问:
Leaflet angularjs on zoomend rootscope not changing
on map zoomend I am trying to call a function which sets the $rootscope to some value. If I am trying to call the same function directly or through different function it is setting the $rootscope. I am able to see the changed value of rootscope variable in console.log but it is not reflecting on html

```<code>map.on('zoomend',function(e){
    if(map._zoom<11){
        clearVillageLayer();
    }
});

function clearVillageLayer(){
    setSummaryData("Summary");
}

function setSummaryData(loc){
    $rootScope.rwsSummaryData = data[loc];
    console.log($rootScope.rwsSummaryData);
}
</code>```

the data variable is already set

答:
You need to call $apply every time you do some manipulations width scope outside of angular (like in leaflet handler). Like this:

```<code>$rootScope.$apply(function(loc) {
  $rootScope.rwsSummaryData = data[loc];
  console.log($rootScope.rwsSummaryData);
});
</code>```

You need this, to tell angular that scope is updated, so it could run $digest cycle, and update the view.

Body:
on map zoomend I am trying to call a function which sets the $rootscope to some value. If I am trying to call the same function directly or through different function it is setting the $rootscope. I am able to see the changed value of rootscope variable in console.log but it is not reflecting on html

map.on('zoomend',function(e){
    if(map._zoom<11){
        clearVillageLayer();
    }
});

function clearVillageLayer(){
    setSummaryData("Summary");
}

function setSummaryData(loc){
    $rootScope.rwsSummaryData = data[loc];
    console.log($rootScope.rwsSummaryData);
}

the data variable is already set

Body:
You need to call $apply every time you do some manipulations width scope outside of angular (like in leaflet handler). Like this:

$rootScope.$apply(function(loc) {
  $rootScope.rwsSummaryData = data[loc];
  console.log($rootScope.rwsSummaryData);
});

You need this, to tell angular that scope is updated, so it could run $digest cycle, and update the view.


问:
get err timestamp when scan into strct in golang
what did I do:
1.exec sql query and get err timestamp data when scan to struct after db ddl.
sql:
SELECT state,round,remark,ctime FROM archive_track WHERE aid=? ORDER BY id DESC
struct:

```<code>type Archive struct {
    Timestamp time.Time `json:"timestamp"`
    State int `json:"state"`
    Round int `json:"round"`
    Remark string `json:"remark,omitempty"`
}
</code>```

go code:

```<code>a:=&Archive{}
 rows.Scan(&a.State, &a.Round, &a.Remark, &a.Timestamp)
</code>```

mysql table info:

```<code>CREATE TABLE `archive_track` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT ,
  `aid` int(11) NOT NULL DEFAULT '0' ,
  `state` tinyint(11) DEFAULT NULL,
  `round` tinyint(4) NOT NULL DEFAULT '0' ,
  `remark` text COMMENT '其他信息',
  `ctime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ,
  `mtime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ,
  `attribute` mediumint(8) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `ix_aid` (`aid`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
</code>```

table data:

| id | aid |state | round  |remark | ctime | mtime | attribute |

|:---|---|---|---| ---| ---|--- | ---:|

| 1  | 1   | 1  | 1| ""  | 2017-03-27 17:07:10 | 2017-03-27 17:07:10 | 0|

I can get correct data first:

&a{aid:1,state:1,round:1 ,ctime:1490605630}
but get err data after db ttl(modify state(tinyint) to state(int) ):

&a{aid:0,state:0,round:0,ctime:-62135596800}.

db ttl:

alter table archive_track modify state int

I can't get correct data anymore until I restart the program.
after I restart ,I can get correct data and err data don't appear anymore ,but why.It make me confuse.

Configuration

*Driver version (or git SHA):QD6LqgLz2JMxXqns8TaxtK9AuHs=

*Go version:go1.7.4

Server version: E.g. MySQL 5.6,

*Server OS:Linux version 3.16.0-4-amd64

答:
If you're using gomysql as your database driver, then it seems to be that you don't have the parseTime DSN parameter enabled for the driver when you connect to your database.

By default, gomysql does not scan the Go type time.Time into a struct, but it's implemented as a DSN parameter. Try this connection string:

```<code>connectionString := fmt.Sprintf(`%s:%s@tcp(%s:%s)/%s?parseTime=true`,
        DBUsername,
        DBPassword,
        DBHost,
        DBHostPort,
        DBName)
</code>```

Body:
what did I do:
1.exec sql query and get err timestamp data when scan to struct after db ddl.
sql:
SELECT state,round,remark,ctime FROM archive_track WHERE aid=? ORDER BY id DESC
struct:

type Archive struct {
    Timestamp time.Time `json:"timestamp"`
    State int `json:"state"`
    Round int `json:"round"`
    Remark string `json:"remark,omitempty"`
}

go code:

a:=&Archive{}
 rows.Scan(&a.State, &a.Round, &a.Remark, &a.Timestamp)

mysql table info:

CREATE TABLE `archive_track` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT ,
  `aid` int(11) NOT NULL DEFAULT '0' ,
  `state` tinyint(11) DEFAULT NULL,
  `round` tinyint(4) NOT NULL DEFAULT '0' ,
  `remark` text COMMENT '其他信息',
  `ctime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ,
  `mtime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ,
  `attribute` mediumint(8) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `ix_aid` (`aid`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

table data:

| id | aid |state | round  |remark | ctime | mtime | attribute |

|:---|---|---|---| ---| ---|--- | ---:|

| 1  | 1   | 1  | 1| ""  | 2017-03-27 17:07:10 | 2017-03-27 17:07:10 | 0|

I can get correct data first:

&a{aid:1,state:1,round:1 ,ctime:1490605630}
but get err data after db ttl(modify state(tinyint) to state(int) ):

&a{aid:0,state:0,round:0,ctime:-62135596800}.

db ttl:

alter table archive_track modify state int

I can't get correct data anymore until I restart the program.
after I restart ,I can get correct data and err data don't appear anymore ,but why.It make me confuse.

Configuration

*Driver version (or git SHA):QD6LqgLz2JMxXqns8TaxtK9AuHs=

*Go version:go1.7.4

Server version: E.g. MySQL 5.6,

*Server OS:Linux version 3.16.0-4-amd64

Body:
If you're using gomysql as your database driver, then it seems to be that you don't have the parseTime DSN parameter enabled for the driver when you connect to your database.

By default, gomysql does not scan the Go type time.Time into a struct, but it's implemented as a DSN parameter. Try this connection string:

connectionString := fmt.Sprintf(`%s:%s@tcp(%s:%s)/%s?parseTime=true`,
        DBUsername,
        DBPassword,
        DBHost,
        DBHostPort,
        DBName)


问:
Anybody interested in possible operation/use of quantum computers?
I went through a period of being interested in how quantum computers work and what they might be good for if they ever become practical. I know they are talked about for code-breaking. I was interested is using them for validating software by essentially trying all possible inputs (in parallel) and seeing if any error states are reached.

I know it's a bit of a blue-sky question, but I wonder if others are interested in quantum computers, how they might work, and what they would be useful for.

Added: Just for fun, let me throw out a mini-tutorial:

Suppose you've got N bits of memory to play with. Suppose you can load those bits (or some of them) with your input data. Then suppose there is a finite sequence of operations you can do on them (without using any additional memory) leaving the answer in them.

To do this with a quantum computer, it is only necessary that you make sure that the entire computation is reversible, by reserving some of the bits to record branches you took, so you can undo them. If you do that, then all the operations can be written as simple unitary matrix transformations on the N bits. (A unitary transform is a pure rotation in the N-dimensional coordinate system.) So performing the computation consists of applying a succession of pure rotations on the bit-vector.

If you do this, then if the N-bit vector is in a quantum computer, it can be initialized into a state where all 2^N (or fewer) possible inputs are superimposed at the same time in "parallel universes". Then if you do the computation, it is doing them all at the same time.

Now all you have to do to see if one of the inputs gives you a particular answer is to let it run to a particular state. If you halt it and examine the state, what it does is choose one of the universes at random and throw away all the rest. So what the Grover algorithm lets you do is, without halting it, accentuate the probability of the universes with the answer state. Then you run it forward, then backward, then forward, and so on for a number of iterations until the answer universe has very high probability. Then if you examine it, you have a high probability of seeing the answer you want.

Whew...

答:
During my Symbolic AI module at university I was asked to give a small presentation to the class on a certain subject, my subject being AI Applications. My subject in this presentation was Quantum Computing in AI.

If the information I write here is out-of-date/wrong/poor don't be too angry. I'm only a second-year CS student at a crappy university that is relying on his memory for most of these details.

The power of Quantum Computing appears to be its ability to work on things incredibly fast (due to its perceived states if I remember correctly). This will obviously completely change security, as white and black-hat hackers will jump on the opportunity to develop and stress-test the various methods of secure systems. If you're interested in Physics then this is the subject for you! If you want to read more about how Quantum Computers can be used in security by using Algorithms to factorise large numbers read this paper by Peter Shor.

Its power comes from the Qubit and a technique known as Quantum Interference. I could spend all day talking about it, but it'd be better for you to read about the double-slit experiment to see how quantum computing works.

The conventional computer compromises of logic gates, whilst quantum computers have their own. As many of these computers have been built (hard-wired) to solve certain problems there are a multitude of different QLG (Quantum Logic Gates) proposed for different problems. Functionally, Quantum Networks are formed using these gates in a method known as Gate Arrays. If you require more information on this then the Ekert paper is the way to go.

Please note that the traditional way to represent the super-positions is as unit contra-variant vectors (one per Qubit) in an 2^n-dimension Hilbert space (where n is the number of Qubits). The gates are defined as rotating these universes and inevitably transforming the Qubit. One such gate is the Hadamard Gate.

Quantum AI has a bright future, but not for a long time. Many academics see Quantum Computing as the distant future of Computing, similarly to how Charles Babbage viewed his machine.

Sorry if this answer got a bit out of hand.

OwnerDisplayName: Mike Dunlavey

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Mike Dunlavey

OwnerDisplayName: EnderMB


问:
How to parse JSON with Gson, when there is no @SerializedName
I have the following JSON document:

```<code>{
  "1786042": {},
  "2064178": {
    "initialImportDate": "2015-11-13T12:22:53.585",
    "hideCrossedOutPrice": false,
    "salesCount": 0,
  },
  ...
}
</code>```

How can I get access to the list of products, which are defined by id and not a name, that could be deserialized?

答:
You can use TypeToken here:

I am assuming a class named Product, which contains properties like initialImportDate, hideCrossedOutPrice etc.

Now You can use TypeToken to deserialize this json, like this:

```<code>Type productMap = new TypeToken<Map<Integer, Product> >() {}.getType();
Map<Integer, Product> result= gson.fromJson(jsonString, productMap);
</code>```

Body:
I have the following JSON document:

{
  "1786042": {},
  "2064178": {
    "initialImportDate": "2015-11-13T12:22:53.585",
    "hideCrossedOutPrice": false,
    "salesCount": 0,
  },
  ...
}

How can I get access to the list of products, which are defined by id and not a name, that could be deserialized?

Body:
You can use TypeToken here:

I am assuming a class named Product, which contains properties like initialImportDate, hideCrossedOutPrice etc.

Now You can use TypeToken to deserialize this json, like this:

Type productMap = new TypeToken<Map<Integer, Product> >() {}.getType();
Map<Integer, Product> result= gson.fromJson(jsonString, productMap);


问:
Cutting down repeating code in Sass functions
I'm working on an HTML boilerplate that uses a lot of Sass to create a maintainable and easy to use code base. Part of that are a few functions:

// Returns the scale value found at $key.
@function get-type-scale($key) {
    $value: map-get($type-scale, $key);

    @if $value != null {
        @return $value;
    }

    @else {
        @warn "Unfortunately, `#{$key}` is not defined in the `$type-scale` map.";
    }
}

// Returns the line-height value found at $key.
@function get-line-height($key) {
    $value: map-get($line-heights, $key);

    @if $value != null {
        @return $value;
    }

    @else {
        @warn "Unfortunately, `#{$key}` is not defined in the `$line-heights` map.";
    }
}

// etc... I have 2 more functions like this where only the $map changes.```
</div>
</div>
</p>

<p>These functions then get called in a few mixins, like this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>// Sets font-size and line-height based on the $level.
@mixin set-type($level: 0) {
    font-size: get-type-scale($level);
    line-height: get-line-height($level);
}</code>```

While this works just fine, I don't like the fact that I'm repeating a lot of code in the functions. I've tried writing a generic function that receives a map name as a parameter, but I cannot use interpolation in map-get().

Is there a way to make the function code more elegant and as DRY as possible?

I appreciate any insights. Cheers!

答:
I've tried writing a generic function that receives a map name as a parameter, but I cannot use interpolation in map-get().

Unfortunately, it is not possible to create variable names from the names of other variables at all (only from its values). Furthermore, a variable only knows its value(s) and not its name which is another issue we are facing when it comes to define the variable warning messages.

I come up with a little improvement that reduces the amount of duplicated code and keeps the ease of use of the high-level function calls. Criticism of having to pass a third variable to the generic function is justified, but I simply couldn't find a clean way to avoid it.

$line-heights: (
  0: 1em,
  1: 2em
);

$type-scale: (
  0: 1em,
  1: 2em
);

// Returns the scale value found at $key.
@function get-type-scale($key) {
    @return get-value-or-warn($type-scale, $key, 'type-scale');
}

// Returns the line-height value found at $key.
@function get-line-height($key) {
    @return get-value-or-warn($line-heights, $key, 'line-heights');
}

@function get-value-or-warn($map, $key, $map-name) {
    $value: map-get($map, $key);

    @if $value != null {
        @return $value;
    }

    @else {
        @warn "Unfortunately, `#{$key}` is not defined in the `$#{$map-name}` map.";
    }
}

// Sets font-size and line-height based on the $level.
@mixin set-type($level: 0) {
    font-size: get-type-scale($level);
    line-height: get-line-height($level);
}```

Body:
I'm working on an HTML boilerplate that uses a lot of Sass to create a maintainable and easy to use code base. Part of that are a few functions:

// Returns the scale value found at $key.
@function get-type-scale($key) {
    $value: map-get($type-scale, $key);

    @if $value != null {
        @return $value;
    }

    @else {
        @warn "Unfortunately, `#{$key}` is not defined in the `$type-scale` map.";
    }
}

// Returns the line-height value found at $key.
@function get-line-height($key) {
    $value: map-get($line-heights, $key);

    @if $value != null {
        @return $value;
    }

    @else {
        @warn "Unfortunately, `#{$key}` is not defined in the `$line-heights` map.";
    }
}

// etc... I have 2 more functions like this where only the $map changes.

These functions then get called in a few mixins, like this:

// Sets font-size and line-height based on the $level.
@mixin set-type($level: 0) {
    font-size: get-type-scale($level);
    line-height: get-line-height($level);
}

While this works just fine, I don't like the fact that I'm repeating a lot of code in the functions. I've tried writing a generic function that receives a map name as a parameter, but I cannot use interpolation in map-get().

Is there a way to make the function code more elegant and as DRY as possible?

I appreciate any insights. Cheers!


问:
TextInput as ItemRenderer in DataGrid :Scroll Issue
I use textInput as ItemRenderer for all columns of a  datagrid.I need to set editability of  first  row as false.I did it on creationComplete of the itemRenderer.Also tried overriding upDateDislayList.
 It works fine for the first row.But some other rows also get their editability changed to false.Also on scroll many rows get their editability changed.Please help.

```<code>  override public function set data(value:Object):void
    {
        super.data = value;
      if(listData.owner.name == "headCountGrid")
      {
      if(data != null && qbpHttpServ.rowDataHcGridArr != null)
          {
             if(data["column1Data"] == qbpHttpServ.rowDataHcGridArr[0]["column1Data"])
          {
          this.editable = false;
          }
          }
     }
    }
    override protected function updateDisplayList(unscaledWidth:Number,unscaledHeight:Number):void{
     super.updateDisplayList(unscaledWidth,unscaledHeight);
     var g:Graphics = graphics;
     g.clear();
    }
</code>```

答: Do you know that items in lists are reused? Make sure they are controlled entirely by set data() function. Pass editability flag with data.</p>

Body:
I use textInput as ItemRenderer for all columns of a  datagrid.I need to set editability of  first  row as false.I did it on creationComplete of the itemRenderer.Also tried overriding upDateDislayList.
 It works fine for the first row.But some other rows also get their editability changed to false.Also on scroll many rows get their editability changed.Please help.

  override public function set data(value:Object):void
    {
        super.data = value;
      if(listData.owner.name == "headCountGrid")
      {
      if(data != null && qbpHttpServ.rowDataHcGridArr != null)
          {
             if(data["column1Data"] == qbpHttpServ.rowDataHcGridArr[0]["column1Data"])
          {
          this.editable = false;
          }
          }
     }
    }
    override protected function updateDisplayList(unscaledWidth:Number,unscaledHeight:Number):void{
     super.updateDisplayList(unscaledWidth,unscaledHeight);
     var g:Graphics = graphics;
     g.clear();
    }


问:
'java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException:'
Problem 1:
I am importing the project on maven in eclipse on  my System and i found the problem while running with the port number .

Solution 1:
I changed the port number from 8080 because it was currently used by oracle10g.
Now while performing the run operation-
'tomcat7:run -Dmaven.tomcat.port=8083'

Problem 2:
NEXT an Exception occured ...

I got this Exception followed by many more exceptions and couldn't find the exact cause of this .
AS This code was runnig fine on another System.

EXCEPTION

```<code>SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[/NSBTPortal1]]
    at java.util.concurrent.FutureTask.report(Unknown Source)
    at java.util.concurrent.FutureTask.get(Unknown Source)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:800)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[/NSBTPortal1]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    ... 6 more
Caused by: java.lang.ClassCastException: org.springframework.web.SpringServletContainerInitializer cannot be cast to javax.servlet.ServletContainerInitializer
    at org.apache.catalina.startup.ContextConfig.getServletContainerInitializer(ContextConfig.java:1670)
    at org.apache.catalina.startup.ContextConfig.getServletContainerInitializers(ContextConfig.java:1652)
    at org.apache.catalina.startup.ContextConfig.processServletContainerInitializers(ContextConfig.java:1562)
    at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1270)
    at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:878)
    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:376)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5322)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more

Mar 30, 2017 10:26:42 PM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost]]
    at java.util.concurrent.FutureTask.report(Unknown Source)
    at java.util.concurrent.FutureTask.get(Unknown Source)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:302)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:732)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.startup.Tomcat.start(Tomcat.java:341)
    at org.apache.tomcat.maven.plugin.tomcat7.run.AbstractRunMojo.startContainer(AbstractRunMojo.java:1238)
    at org.apache.tomcat.maven.plugin.tomcat7.run.AbstractRunMojo.execute(AbstractRunMojo.java:592)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:862)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:286)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:197)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1131)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:800)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 17.003 s
[INFO] Finished at: 2017-03-30T22:26:42+05:30
[INFO] Final Memory: 12M/80M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.tomcat.maven:tomcat7-maven-plugin:2.2:run (default-cli) on project NSBTPortal1: Could not start Tomcat: Failed to start component [StandardServer[-1]]: Failed to start component [StandardService[Tomcat]]: Failed to start component [StandardEngine[Tomcat]]: A child container failed during start -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
</code>```

答:
You have a error in your project deployed on tomcat.
org.springframework.web.SpringServletContainerInitializer cannot be cast to javax.servlet.ServletContainerInitializer

Perhaps you imported javax.servlet in you pom.xml.If so, you can provide provided scope like blow.

pom.xml

Body:
Problem 1:
I am importing the project on maven in eclipse on  my System and i found the problem while running with the port number .

Solution 1:
I changed the port number from 8080 because it was currently used by oracle10g.
Now while performing the run operation-
'tomcat7:run -Dmaven.tomcat.port=8083'

Problem 2:
NEXT an Exception occured ...

I got this Exception followed by many more exceptions and couldn't find the exact cause of this .
AS This code was runnig fine on another System.

EXCEPTION

SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[/NSBTPortal1]]
    at java.util.concurrent.FutureTask.report(Unknown Source)
    at java.util.concurrent.FutureTask.get(Unknown Source)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:800)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[/NSBTPortal1]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    ... 6 more
Caused by: java.lang.ClassCastException: org.springframework.web.SpringServletContainerInitializer cannot be cast to javax.servlet.ServletContainerInitializer
    at org.apache.catalina.startup.ContextConfig.getServletContainerInitializer(ContextConfig.java:1670)
    at org.apache.catalina.startup.ContextConfig.getServletContainerInitializers(ContextConfig.java:1652)
    at org.apache.catalina.startup.ContextConfig.processServletContainerInitializers(ContextConfig.java:1562)
    at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1270)
    at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:878)
    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:376)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5322)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more

Mar 30, 2017 10:26:42 PM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost]]
    at java.util.concurrent.FutureTask.report(Unknown Source)
    at java.util.concurrent.FutureTask.get(Unknown Source)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:302)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:732)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.startup.Tomcat.start(Tomcat.java:341)
    at org.apache.tomcat.maven.plugin.tomcat7.run.AbstractRunMojo.startContainer(AbstractRunMojo.java:1238)
    at org.apache.tomcat.maven.plugin.tomcat7.run.AbstractRunMojo.execute(AbstractRunMojo.java:592)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:862)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:286)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:197)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1131)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:800)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 17.003 s
[INFO] Finished at: 2017-03-30T22:26:42+05:30
[INFO] Final Memory: 12M/80M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.tomcat.maven:tomcat7-maven-plugin:2.2:run (default-cli) on project NSBTPortal1: Could not start Tomcat: Failed to start component [StandardServer[-1]]: Failed to start component [StandardService[Tomcat]]: Failed to start component [StandardEngine[Tomcat]]: A child container failed during start -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException


问:
Passing index value from select to inside php block in one page html
I have two select dropdown. Example:If i select index 3 in the first
 select option,the display of the 2nd select option should stop at
 index 3.What is the best way of doing it.See my current code below.</p>

```<code><label class="control-label">SY1:</label>
<select class="form-control" name="pri_sy" id="pri_sy" onchange="">
<?php
    $null = 'Null';
    $choose = 'Choose School Year';
    $Present = 'Present';
    echo '<option value='.$null.'>' .$choose.'</option>';
    echo '<option value='.$Present.'>' .$Present.'</option>';
    for($i=date('Y');  $i > date('Y')-27; $i--){
        $x = $i +1;
        $y = $i;
        echo '<option value='.$y.'-'.$x.'>'.$y.'-'.$x.'</option>';
    }?>
</select>

Result:
[0]Choose School Year
[1] Present
[2] 2017-2018
[3] 2016-2017   if selected index[3] / How can i pass 3 in my 2nd for loop?
   2015-2016   for($i=date('Y');  $i > date('Y')-3; $i--)/See below php code..
[5]2014-2015
[6]2013-2014
and so on ...

<label class="control-label">SY2:</label>
    <select class="form-control" name="sec_sy" id="sec_sy" onchange="">
    <?php
        $null = 'Null';
        $choose = 'Choose School Year';
        $Present = 'Present';
        echo '<option value='.$null.'>' .$choose.'</option>';
        echo '<option value='.$Present.'>' .$Present.'</option>';
        for($i=date('Y');  $i > date('Y')-3; $i--){
            $x = $i +1;
            $y = $i;
            echo '<option value='.$y.'-'.$x.'>'.$y.'-'.$x.'</option>';
        }?>
    </select>

Expected Result:
Choose School Year
Present
2017-2018
2016-2017
2015-2016

<script type="text/javascript">

$('.form-control').on('change', function(e) {
  var pri_sy = $("#pri_sy").find("option:selected").index();
  var sec_sy   = $("#sec_sy").find("option:selected").index();
  var sen_high_sy = $("#sen_high_sy").find("option:selected").index();
  var college_sy = $("#college_sy").find("option:selected").index();

  var isPri = $(this).is("#pri_sy");
  var isSec = $(this).is("#sec_sy");
  var isSenHigh = $(this).is("#sen_high_sy");
  var isCollege = $(this).is("#college_sy");
  //console.log("from:"+fromIdx,"to:"+toIdx);
  if (isPri) {
    alert('a');
    $('#sec_sy').val(pri_sy);
    alert(pri_sy);
       // $('#sec_sy').each(function(pri_sy, sec_sy) {
      // $(sec_sy).attr('disabled', pri_sy < sec_sy);
     });
  }
}).change();
</script>
</code>```

答:
When the page load, extract the options from the second select and clear the second select. Then when an index is selected, compute the options from your extraction (here the X first options) and then insert them in the second select.

EDIT:

Either you have the two select with all the options. Then in Javascript you get the options from the second and clear it. Then when the first select change, you insert the good values in the second.

Or you use an input hidden with a text containing the values for the second select (ex 'value1;value2'). Then you get the value in javascript and split it (here on the ':'). Then you update the second select when the first change.

Body:
I have two select dropdown. Example:If i select index 3 in the first
 select option,the display of the 2nd select option should stop at
 index 3.What is the best way of doing it.See my current code below.

SY1:
<select class="form-control" name="pri_sy" id="pri_sy" onchange="">
<?php
    $null = 'Null';
    $choose = 'Choose School Year';
    $Present = 'Present';
    echo '<option value='.$null.'>' .$choose.'</option>';
    echo '<option value='.$Present.'>' .$Present.'</option>';
    for($i=date('Y');  $i > date('Y')-27; $i--){
        $x = $i +1;
        $y = $i;
        echo '<option value='.$y.'-'.$x.'>'.$y.'-'.$x.'</option>';
    }?>
</select>

Result:
[0]Choose School Year
[1] Present
[2] 2017-2018
[3] 2016-2017   if selected index[3] / How can i pass 3 in my 2nd for loop?
   2015-2016   for($i=date('Y');  $i > date('Y')-3; $i--)/See below php code..
[5]2014-2015
[6]2013-2014
and so on ...

SY2:
    <select class="form-control" name="sec_sy" id="sec_sy" onchange="">
    <?php
        $null = 'Null';
        $choose = 'Choose School Year';
        $Present = 'Present';
        echo '<option value='.$null.'>' .$choose.'</option>';
        echo '<option value='.$Present.'>' .$Present.'</option>';
        for($i=date('Y');  $i > date('Y')-3; $i--){
            $x = $i +1;
            $y = $i;
            echo '<option value='.$y.'-'.$x.'>'.$y.'-'.$x.'</option>';
        }?>
    </select>

Expected Result:
Choose School Year
Present
2017-2018
2016-2017
2015-2016


问:
File Exists and Exception Handling in U-Sql
Two questions

How to check file exists or not before EXTRACT?
we have scenario where new inputs file is generated every day for catalog data. we need to merge new input with d-1 file. before merge we what to make sure that new input file exists at source location

does u-sql supports try...catch block?

答:
FILE.EXISTS() always returns True when executed locally. However, it works when executing against Azure Data Lake.

Tried MSDN example and the following returns True, True

```<code>DECLARE @filepath_good = "/Samples/Data/SearchLog.tsv";
DECLARE @filepath_bad = "/Samples/Data/zzz.tsv";

@result =
    SELECT  FILE.EXISTS(@filepath_good) AS exists_good,
            FILE.EXISTS(@filepath_bad) AS exists_bad
    FROM (VALUES (1)) AS T(dummy);

OUTPUT @result
TO "/Output/FileExists.txt"
USING Outputters.Csv();
</code>```

I have Microsoft Azure Data Lake Tools for Visual Studio version 2.2.5000.0

Body:
FILE.EXISTS() always returns True when executed locally. However, it works when executing against Azure Data Lake.

Tried MSDN example and the following returns True, True

DECLARE @filepath_good = "/Samples/Data/SearchLog.tsv";
DECLARE @filepath_bad = "/Samples/Data/zzz.tsv";

@result =
    SELECT  FILE.EXISTS(@filepath_good) AS exists_good,
            FILE.EXISTS(@filepath_bad) AS exists_bad
    FROM (VALUES (1)) AS T(dummy);

OUTPUT @result
TO "/Output/FileExists.txt"
USING Outputters.Csv();

I have Microsoft Azure Data Lake Tools for Visual Studio version 2.2.5000.0


问:
PHP: manipulate array making value as key recursively
I got this array:

```<code>array:2 [▼
  0 => array:1 [▼
    0 => array:7 [▼
     "id" => "1"
     "producer" => "Samsung"
     "model" => "LE22B541C4W"
     "category" => "1"
     "production_date" => "2009-05-08"
     "status" => "Discontinued"
     "type" => "LCD"
     ]
  ]
  1 => array:1 [▼
    0 => array:7 [▼
     "id" => "2"
     "producer" => "Samsung"
     "model" => "P24FHD"
     "category" => "1"
     "production_date" => "0000-00-00"
     "status" => "Discontinued"
     "type" => "LCD"
    ]
  ]
 [...]
]
</code>```

I would like to take the "ID" value of each array and make as primary key and remove the useless keys like this

```<code>array:2 [
  1 => array:7 [
    "id" => "1"
    "producer" => "Samsung"
    "model" => "LE22B541C4W"
    "category" => "1"
    "production_date" => "2009-05-08"
    "status" => "Discontinued"
    "type" => "LCD"
    ]
  2 => array:7 [
   [...]
</code>```

By now I'm just populate the array using this simple query and a for loop:

```<code>foreach ($compatibility as $compElement) {

        $sql = "SELECT * FROM product WHERE ID = '$compElement';";

        $em = $this->getDoctrine()->getManager();
        $stmt = $em->getConnection()->prepare($sql);
        $stmt->execute();
        $thisElement = $stmt->fetchAll();

        $compArray[] = $thisElement;

    }
</code>```

答:
You can do something like this if you don't want to change how you populate your array:

```<code>$result = call_user_func_array(
               'array_merge_recursive',
                $array
            );
</code>```

Output

```<code>array(2) {
  [0]=>
  array(7) {
    ["id"]=>
    string(1) "1"
    ["producer"]=>
    string(7) "Samsung"
    ["model"]=>
    string(11) "LE22B541C4W"
    ["category"]=>
    string(1) "1"
    ["production_date"]=>
    string(10) "2009-05-08"
    ["status"]=>
    string(12) "Discontinued"
    ["type"]=>
    string(3) "LCD"
  }
  [1]=>
  array(7) {
    ["id"]=>
    string(1) "2"
    ["producer"]=>
    string(7) "Samsung"
    ["model"]=>
    string(6) "P24FHD"
    ["category"]=>
    string(1) "1"
    ["production_date"]=>
    string(10) "0000-00-00"
    ["status"]=>
    string(12) "Discontinued"
    ["type"]=>
    string(3) "LCD"
  }
}
</code>```

Body:
I got this array:

array:2 [▼
  0 => array:1 [▼
    0 => array:7 [▼
     "id" => "1"
     "producer" => "Samsung"
     "model" => "LE22B541C4W"
     "category" => "1"
     "production_date" => "2009-05-08"
     "status" => "Discontinued"
     "type" => "LCD"
     ]
  ]
  1 => array:1 [▼
    0 => array:7 [▼
     "id" => "2"
     "producer" => "Samsung"
     "model" => "P24FHD"
     "category" => "1"
     "production_date" => "0000-00-00"
     "status" => "Discontinued"
     "type" => "LCD"
    ]
  ]
 [...]
]

I would like to take the "ID" value of each array and make as primary key and remove the useless keys like this

array:2 [
  1 => array:7 [
    "id" => "1"
    "producer" => "Samsung"
    "model" => "LE22B541C4W"
    "category" => "1"
    "production_date" => "2009-05-08"
    "status" => "Discontinued"
    "type" => "LCD"
    ]
  2 => array:7 [
   [...]

By now I'm just populate the array using this simple query and a for loop:

foreach ($compatibility as $compElement) {

        $sql = "SELECT * FROM product WHERE ID = '$compElement';";

        $em = $this->getDoctrine()->getManager();
        $stmt = $em->getConnection()->prepare($sql);
        $stmt->execute();
        $thisElement = $stmt->fetchAll();

        $compArray[] = $thisElement;

    }

Body:
You can do something like this if you don't want to change how you populate your array:

$result = call_user_func_array(
               'array_merge_recursive',
                $array
            );

Output

array(2) {
  [0]=>
  array(7) {
    ["id"]=>
    string(1) "1"
    ["producer"]=>
    string(7) "Samsung"
    ["model"]=>
    string(11) "LE22B541C4W"
    ["category"]=>
    string(1) "1"
    ["production_date"]=>
    string(10) "2009-05-08"
    ["status"]=>
    string(12) "Discontinued"
    ["type"]=>
    string(3) "LCD"
  }
  [1]=>
  array(7) {
    ["id"]=>
    string(1) "2"
    ["producer"]=>
    string(7) "Samsung"
    ["model"]=>
    string(6) "P24FHD"
    ["category"]=>
    string(1) "1"
    ["production_date"]=>
    string(10) "0000-00-00"
    ["status"]=>
    string(12) "Discontinued"
    ["type"]=>
    string(3) "LCD"
  }
}


问:
Missing error messages when rendering to json
Im developing an API and when trying to make RSpec request tests pass I ran into a strange behaviour/error. When trying to save an empty record through rails console i get the error messages including the missing association error.

```<code>2.3.3 :006 > Breed.create().errors.messages
 (0.2ms)  begin transaction
 (0.1ms)  rollback transaction
 => {:specie=>["must exist"], :name=>["can't be blank"]}
</code>```

But when rendering the error to json in the controller the association error disappears if I don't include the empty parameter when trying to create it from the API.
Can someone help me understand why this is happening? Thanks.

app/spec/requests/breeds_spec.rb

```<code>describe 'PUT/PATCH #update' do
  context 'when not successfull' do
    before { patch breed_path(breed_id), params: { breed: { name: '' } } }

    it "renders the errors on why the record could not be updated" do
      puts json
      expect(json['errors']).to have_key('name')
      expect(json['errors']).to have_key('specie')
    end
  end
end
# => {"errors"=>{"name"=>["can't be blank"]}}
# Failure/Error: expect(json['errors']).to have_key('specie')
</code>```

app/controllers/breeds_controller.rb

```<code>...
def create
  @breed = Breed.new(breed_params)
  if @breed.save
    render json: @breed, status: :created, location: @breed
  else
    render json: { errors: @breed.errors }, status: :unprocessable_entity
  end
end
...
</code>```

app/models/breeds.rb

```<code># == Schema Information
# Table name: breeds
#
#  name       :string
#  specie_id  :integer
class Breed < ApplicationRecord
  belongs_to :specie
  validates :name, presence: true
end
</code>```

To sum up, the question is why when saving an empty record through rails console the error looks like => {:specie=>["must exist"], :name=>["can't be blank"]} and when rendering the error to json its missing the association error => {"errors"=>{"name"=>["can't be blank"]}}

答:
In Rails 5, whenever we define a belongs_to association, it is
  required to have the associated record present by default.

see this thread

If you want it to be optional

```<code>belongs_to :specie, optional: true
</code>```

Body:
Im developing an API and when trying to make RSpec request tests pass I ran into a strange behaviour/error. When trying to save an empty record through rails console i get the error messages including the missing association error.

2.3.3 :006 > Breed.create().errors.messages
 (0.2ms)  begin transaction
 (0.1ms)  rollback transaction
 => {:specie=>["must exist"], :name=>["can't be blank"]}

But when rendering the error to json in the controller the association error disappears if I don't include the empty parameter when trying to create it from the API.
Can someone help me understand why this is happening? Thanks.

app/spec/requests/breeds_spec.rb

describe 'PUT/PATCH #update' do
  context 'when not successfull' do
    before { patch breed_path(breed_id), params: { breed: { name: '' } } }

    it "renders the errors on why the record could not be updated" do
      puts json
      expect(json['errors']).to have_key('name')
      expect(json['errors']).to have_key('specie')
    end
  end
end
# => {"errors"=>{"name"=>["can't be blank"]}}
# Failure/Error: expect(json['errors']).to have_key('specie')

app/controllers/breeds_controller.rb

...
def create
  @breed = Breed.new(breed_params)
  if @breed.save
    render json: @breed, status: :created, location: @breed
  else
    render json: { errors: @breed.errors }, status: :unprocessable_entity
  end
end
...

app/models/breeds.rb

# == Schema Information
# Table name: breeds
#
#  name       :string
#  specie_id  :integer
class Breed < ApplicationRecord
  belongs_to :specie
  validates :name, presence: true
end

To sum up, the question is why when saving an empty record through rails console the error looks like => {:specie=>["must exist"], :name=>["can't be blank"]} and when rendering the error to json its missing the association error => {"errors"=>{"name"=>["can't be blank"]}}

Body:
In Rails 5, whenever we define a belongs_to association, it is
  required to have the associated record present by default.

see this thread

If you want it to be optional

belongs_to :specie, optional: true


问:
Can't add foreign key to an existing table
I want to add foreign key to an existing table questions which has 1000 above questions of different categories in it. But when I am trying to add foreign key mysql throws error as below.

#1452 - Cannot add or update a child row: a foreign key constraint fails (question_bank.#sql-af8_1d0, CONSTRAINTcat_idFOREIGN KEY (cat_id) REFERENCESdb_category(cat_id) ON DELETE NO ACTION ON UPDATE NO ACTION)

category table db_category structure.

questions table db_questions structure.

答:
Before adding a foreign key you should ensure it fits with the actual data.
The error is simple, you have some rows on questions table with wrongs value on cat_id

Just delete that rows, or create new categories. You can check the problematic rows with:

```<code>SELECT * FROM questions WHERE cat_id NOT IN (SELECT cat_id from category)
</code>```

Body:
Before adding a foreign key you should ensure it fits with the actual data.
The error is simple, you have some rows on questions table with wrongs value on cat_id

Just delete that rows, or create new categories. You can check the problematic rows with:

SELECT * FROM questions WHERE cat_id NOT IN (SELECT cat_id from category)


问:
jQuery not triggering .click function from a jQuery generated HTML tags
I have a button on my document, upon clicking will generate certain html tags.

```<code><a type="button" name="repbut" >Reply</a> //on button click

    <script type="text/javascript"> // this script will be executed
    $(document).ready(function(){
    $('a[name=repbut]').click(function(){
        var boxid=$(this).attr("id");
        $("#"+boxid+"1").html('<ul><li><div class="comment"><div class="comment-content"><div class="comment-meta-author">Post your reply</div><br><div class="comment-body"><div class="form-group"><label>Message</label><textarea id="reep" class="form-control" rows="2"></textarea><br><span id="'+boxid+'2"></span><a type="button" name="repcom" id="test" value="'+boxid+'" class="btn btn-primary pull-right">Reply</a></div><br></div></div></div></li></ul>');
    });
    });
    </script>
</code>```

The problem is when i click the generated button nothing happens, not even alert function.

```<code><a type="button" name="repcom" id="test" class="btn btn-primary pull-right">

<script type="text/javascript">
$('a[name=repcom]').click(function(){
        alert("yes"); // not triggered
        });
</script>
</code>```

Am i doing something wrong? i am new to jQuery.
Any help is appreciated.

答:
jQuery's .click() will not work on dynamically generated html.

Use .on() instead.

```<code>$( "body" ).on( "click", "a[name=repcom]", function() {
  console.log("This Works");
});
</code>```

Body:
I have a button on my document, upon clicking will generate certain html tags.

Reply //on button click

The problem is when i click the generated button nothing happens, not even alert function.

Am i doing something wrong? i am new to jQuery.
Any help is appreciated.

Body:
jQuery's .click() will not work on dynamically generated html.

Use .on() instead.

$( "body" ).on( "click", "a[name=repcom]", function() {
  console.log("This Works");
});


问:
bash get the number of files and pass it to for loop
I am trying to get the number of files with a certain pattern in a directory and then do a for loop starting from zero to that number.

```<code>number=`ls -d *pattern_* | wc -l`%3d
for i in {001.."$number"};do
  # do something with $i
done
</code>```

the problem is that my numbers are three digits, so that is why i added %3d to the end of my number variable, but it is not working.

so if I have 20 files, the number variable in the for loop should get a leading zero 020.

答:
You really shouldn't rely on the output of ls in this way, since you can have filenames with embedded spaces, newlines and so on.

Thankfully there's a way to do this in a more reliable manner:

```<code>((i == 0))
for fspec in *pattern_* ; do
    ((i = i + 1))
    doSomethingWith "$(printf "%03d" $i)"
done
</code>```

This loop will run the exact number of times related to the file count regardless of the weirdness of said files. It will also use the correctly formatted (three-digit) argument as requested.

Body:
I am trying to get the number of files with a certain pattern in a directory and then do a for loop starting from zero to that number.

number=`ls -d *pattern_* | wc -l`%3d
for i in {001.."$number"};do
  # do something with $i
done

the problem is that my numbers are three digits, so that is why i added %3d to the end of my number variable, but it is not working.

so if I have 20 files, the number variable in the for loop should get a leading zero 020.

Body:
You really shouldn't rely on the output of ls in this way, since you can have filenames with embedded spaces, newlines and so on.

Thankfully there's a way to do this in a more reliable manner:

((i == 0))
for fspec in *pattern_* ; do
    ((i = i + 1))
    doSomethingWith "$(printf "%03d" $i)"
done

This loop will run the exact number of times related to the file count regardless of the weirdness of said files. It will also use the correctly formatted (three-digit) argument as requested.