问:
Debug Ionic 3 code on the device
I am testing Ionic 3, so far everything works as it should. I would wish to debug the TS code on the ionic lab so i added the next configuration in package.json:

```<code>"config": {
    "ionic_source_map": "source-map"
}
</code>```

After this, i was able to see the code and debug it(in chrome devTools), but when i execute the same test on the phone i am not able to see the .Ts files and debug it. Anyone has any idea which configuration or how to make them also visible on the phone?

答:
You can use Chrome Inspector to debug Ionic app from the phone.

Prerequisites:

For Windows, install the necessary USB drivers.

A USB cable to connect your device.

Chrome for Android installed and running on your device.

USB debugging enabled on your device.

Debugging:

In Chrome, go to chrome://inspect in the URL bar.

Click inspect in your app’s WebView on your device.

Title: Debug Ionic 3 code on the device

Body:
I am testing Ionic 3, so far everything works as it should. I would wish to debug the TS code on the ionic lab so i added the next configuration in package.json:

"config": {
    "ionic_source_map": "source-map"
}

After this, i was able to see the code and debug it(in chrome devTools), but when i execute the same test on the phone i am not able to see the .Ts files and debug it. Anyone has any idea which configuration or how to make them also visible on the phone?


来源: stackexchange

问:
Error: invalid_request Missing required parameter: client_id in golang
I'm having difficulty authenticating using Google OAuth2.

I've obtainedd client ID and secret from google developer console, and I came up with this code :

```<code>package main

    import (
        "fmt"
        "golang.org/x/oauth2"
        "golang.org/x/oauth2/google"
        "io/ioutil"
        "net/http"
        "os"
    )

    const htmlIndex = `<html><body>
    <a href="/GoogleLogin">Log in with Google</a>
    </body></html>
    `

    func init() {
        // Setup Google's example test keys
        os.Setenv("CLIENT_ID", "somrestring-otherstring.apps.googleusercontent.com")
        os.Setenv("SECRET_KEY", "alongcharachterjumble")
    }

    var (
        googleOauthConfig = &oauth2.Config{
            RedirectURL:  "http://127.0.0.1:8080/auth",  //defined in Google console
            ClientID:     os.Getenv("CLIENT_ID"),
            ClientSecret: os.Getenv("SECRET_KEY"),
            Scopes: []string{"https://www.googleapis.com/auth/userinfo.profile",
                "https://www.googleapis.com/auth/userinfo.email"},
            Endpoint: google.Endpoint,
        }
        // Some random string, random for each request
        oauthStateString = "random"
    )

    func main() {
        http.HandleFunc("/", handleMain)
        http.HandleFunc("/GoogleLogin", handleGoogleLogin)
        http.HandleFunc("/GoogleCallback", handleGoogleCallback)
        fmt.Println(http.ListenAndServe(":8080", nil))
    }

    func handleMain(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, htmlIndex)
        fmt.Println("another request made")
    }

    func handleGoogleLogin(w http.ResponseWriter, r *http.Request) {
        url := googleOauthConfig.AuthCodeURL(oauthStateString)
        http.Redirect(w, r, url, http.StatusTemporaryRedirect)
    }

    func handleGoogleCallback(w http.ResponseWriter, r *http.Request) {
        state := r.FormValue("state")
        if state != oauthStateString {
            fmt.Printf("invalid oauth state, expected '%s', got '%s'\n", oauthStateString, state)
            http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
            return
        }

        code := r.FormValue("code")
        token, err := googleOauthConfig.Exchange(oauth2.NoContext, code)
        if err != nil {
            fmt.Println("Code exchange failed with '%s'\n", err)
            http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
            return
        }

        response, err := http.Get("https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + token.AccessToken)

        defer response.Body.Close()
        contents, err := ioutil.ReadAll(response.Body)
        fmt.Fprintf(w, "Content: %s\n", contents)
    }
</code>```

But I get this error from google:

That’s an error.

Error: invalid_request

Missing required parameter: client_id

Learn more

Request Details client_id= redirect_uri=http://127.0.0.1:8080/auth
  response_type=code
  scope=https://www.googleapis.com/auth/userinfo.profile
  https://www.googleapis.com/auth/userinfo.email state=random

What's wrong here? How can I fix it?

答:
The error message indicates that ClientID is not initialized.

That looks consistent with the code, since var declarations are executed before the init functions.

So when your var requests os.Getenv("CLIENT_ID") the value is blank since init has not executed yet.

From the documentation:

A package with no imports is initialized by assigning initial values to all its package-level variables followed by calling all init functions in the order they appear in the source, possibly in multiple files, as presented to the compiler

https://golang.org/ref/spec#Package_initialization

To fix this, either put the string directly in the var initialization, or trigger the initialization from the init after you set the values.

Like:

```<code>var (
    googleOauthConfig *oauth2.Config
)

func init() {
     // init ENV
     // initialize the variable using ENV values
     googleOauthConfig = &oauth2.Config{ ... }
}
</code>```

Alternatively, you can set those ENV values at the OS level before executing the actual Go program.

ContentLicense: CC BY-SA 3.0

Body:
I'm having difficulty authenticating using Google OAuth2.

I've obtainedd client ID and secret from google developer console, and I came up with this code :

package main

    import (
        "fmt"
        "golang.org/x/oauth2"
        "golang.org/x/oauth2/google"
        "io/ioutil"
        "net/http"
        "os"
    )

    const htmlIndex = `
    Log in with Google

    `

    func init() {
        // Setup Google's example test keys
        os.Setenv("CLIENT_ID", "somrestring-otherstring.apps.googleusercontent.com")
        os.Setenv("SECRET_KEY", "alongcharachterjumble")
    }

    var (
        googleOauthConfig = &oauth2.Config{
            RedirectURL:  "http://127.0.0.1:8080/auth",  //defined in Google console
            ClientID:     os.Getenv("CLIENT_ID"),
            ClientSecret: os.Getenv("SECRET_KEY"),
            Scopes: []string{"https://www.googleapis.com/auth/userinfo.profile",
                "https://www.googleapis.com/auth/userinfo.email"},
            Endpoint: google.Endpoint,
        }
        // Some random string, random for each request
        oauthStateString = "random"
    )

    func main() {
        http.HandleFunc("/", handleMain)
        http.HandleFunc("/GoogleLogin", handleGoogleLogin)
        http.HandleFunc("/GoogleCallback", handleGoogleCallback)
        fmt.Println(http.ListenAndServe(":8080", nil))
    }

    func handleMain(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, htmlIndex)
        fmt.Println("another request made")
    }

    func handleGoogleLogin(w http.ResponseWriter, r *http.Request) {
        url := googleOauthConfig.AuthCodeURL(oauthStateString)
        http.Redirect(w, r, url, http.StatusTemporaryRedirect)
    }

    func handleGoogleCallback(w http.ResponseWriter, r *http.Request) {
        state := r.FormValue("state")
        if state != oauthStateString {
            fmt.Printf("invalid oauth state, expected '%s', got '%s'\n", oauthStateString, state)
            http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
            return
        }

        code := r.FormValue("code")
        token, err := googleOauthConfig.Exchange(oauth2.NoContext, code)
        if err != nil {
            fmt.Println("Code exchange failed with '%s'\n", err)
            http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
            return
        }

        response, err := http.Get("https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + token.AccessToken)

        defer response.Body.Close()
        contents, err := ioutil.ReadAll(response.Body)
        fmt.Fprintf(w, "Content: %s\n", contents)
    }

But I get this error from google:

That’s an error.

Error: invalid_request

Missing required parameter: client_id

Learn more

Request Details client_id= redirect_uri=http://127.0.0.1:8080/auth
  response_type=code
  scope=https://www.googleapis.com/auth/userinfo.profile
  https://www.googleapis.com/auth/userinfo.email state=random

What's wrong here? How can I fix it?

Body:
The error message indicates that ClientID is not initialized.

That looks consistent with the code, since var declarations are executed before the init functions.

So when your var requests os.Getenv("CLIENT_ID") the value is blank since init has not executed yet.

From the documentation:

A package with no imports is initialized by assigning initial values to all its package-level variables followed by calling all init functions in the order they appear in the source, possibly in multiple files, as presented to the compiler

https://golang.org/ref/spec#Package_initialization

To fix this, either put the string directly in the var initialization, or trigger the initialization from the init after you set the values.

Like:

var (
    googleOauthConfig *oauth2.Config
)

func init() {
     // init ENV
     // initialize the variable using ENV values
     googleOauthConfig = &oauth2.Config{ ... }
}

Alternatively, you can set those ENV values at the OS level before executing the actual Go program.


问:
How to append properties of another object to a json object without copying all the properties in the target json object
So here is the scenario, I have a class which is being serialized to a json object:

```<code>public classA
{
    [JsonProperty("A")]
        public string A { get; set; }

    [JsonProperty("B")]
        public string B { get; set; }
}
</code>```

I am serializing it to a json string like below:

```<code>var serializedObject = JsonConvert.SerializeObject(new classA
        {
            A = "stingAAAA",
            B = "stringBBBBB"
        });
</code>```

Now, I have another class:

```<code>public classB
{
    [JsonProperty("C")]
    public string C { get; set; }

[JsonProperty("D")]
    public string D { get; set; }
}
</code>```

I want to append the properties of ClassB object to the json string being generated but without copying all the properties (C and D) to ClassA. So basically the final json string should treat properties of ClassB object as if they were the properties of ClassA itsef. Is it even possible?

答:
I see 2 solutions:

1.Create dictionary with values from both objects

2.Create new class with 2 properties (classA and classB)

```<code>var a = new classA { A = "stingAAAA", B = "stringBBBBB" };
var b = new classB { C = "CCC", D = "DDD" };
</code>```

1:

```<code>var dictA = a.GetType().GetProperties().ToDictionary(x => x.GetCustomAttributes(false).OfType<JsonPropertyAttribute>().FirstOrDefault()?.PropertyName ?? x.Name, y => y.GetValue(a));
var dictB = b.GetType().GetProperties().ToDictionary(x => x.GetCustomAttributes(false).OfType<JsonPropertyAttribute>().FirstOrDefault()?.PropertyName ?? x.Name, y => y.GetValue(b));

var result = new[] { dictA, dictB }.SelectMany(dict => dict)
                .ToDictionary(pair => pair.Key, pair => pair.Value);

var res = JsonConvert.SerializeObject(result);
// Result: {"A":"stingAAAA","B":"stringBBBBB","C":"CCC","D2":"DDD"}
</code>```

2:

```<code>var newClass = new { ClassA = a, ClassB = b };
var res2 = JsonConvert.SerializeObject(newClass);
// Result: {"ClassA":{"A":"stingAAAA","B":"stringBBBBB"},"ClassB":{"C":"CCC","D2":"DDD"}}
</code>```

Both however have disadvantages.

1 - there will be problem if both classA and classB would have properties with the same name (or JsonPropertyAttribute)

2 - you result will have 2 properties and all properties you need will be inside of them.

Body:
So here is the scenario, I have a class which is being serialized to a json object:

public classA
{
    [JsonProperty("A")]
        public string A { get; set; }

    [JsonProperty("B")]
        public string B { get; set; }
}

I am serializing it to a json string like below:

var serializedObject = JsonConvert.SerializeObject(new classA
        {
            A = "stingAAAA",
            B = "stringBBBBB"
        });

Now, I have another class:

public classB
{
    [JsonProperty("C")]
    public string C { get; set; }

[JsonProperty("D")]
    public string D { get; set; }
}

I want to append the properties of ClassB object to the json string being generated but without copying all the properties (C and D) to ClassA. So basically the final json string should treat properties of ClassB object as if they were the properties of ClassA itsef. Is it even possible?

Body:
I see 2 solutions:

1.Create dictionary with values from both objects

2.Create new class with 2 properties (classA and classB)

var a = new classA { A = "stingAAAA", B = "stringBBBBB" };
var b = new classB { C = "CCC", D = "DDD" };

1:

var dictA = a.GetType().GetProperties().ToDictionary(x => x.GetCustomAttributes(false).OfType<JsonPropertyAttribute>().FirstOrDefault()?.PropertyName ?? x.Name, y => y.GetValue(a));
var dictB = b.GetType().GetProperties().ToDictionary(x => x.GetCustomAttributes(false).OfType<JsonPropertyAttribute>().FirstOrDefault()?.PropertyName ?? x.Name, y => y.GetValue(b));

var result = new[] { dictA, dictB }.SelectMany(dict => dict)
                .ToDictionary(pair => pair.Key, pair => pair.Value);

var res = JsonConvert.SerializeObject(result);
// Result: {"A":"stingAAAA","B":"stringBBBBB","C":"CCC","D2":"DDD"}

2:

var newClass = new { ClassA = a, ClassB = b };
var res2 = JsonConvert.SerializeObject(newClass);
// Result: {"ClassA":{"A":"stingAAAA","B":"stringBBBBB"},"ClassB":{"C":"CCC","D2":"DDD"}}

Both however have disadvantages.

1 - there will be problem if both classA and classB would have properties with the same name (or JsonPropertyAttribute)

2 - you result will have 2 properties and all properties you need will be inside of them.


问:
Spring-Boot ignores @Qualifier annotation
I am migrating an active Spring web app to spring boot(1.4.2).

The beans are defined in an XML as it is being loaded with @ImportResource.

4 of the beans that I am starting are an instance of the same object BasicDataSource.

To tell spring which one to load I have set an ID for each one and using @Qualifier to bind the correct bean to the variable.

But it seems to be that Spring ignores my @Qualifier and throwing "No qualifying bean of type 'javax.sql.DataSource' available: expected single matching bean but found 4: DataSource1, DataSource2, DataSource3, DataSource4"

P.S - Note that the class that has the @Qualifier is an abstract class, and the class that is failing to instantiate is an extending class, however @Qualifier has @Inherited.

XML

```<code><beans
    xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:task="http://www.springframework.org/schema/task"
xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
   http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.2.xsd
   http://www.springframework.org/schema/jee
   http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
   http://www.springframework.org/schema/task
   http://www.springframework.org/schema/task/spring-task-3.2.xsd
   http://www.springframework.org/schema/cache
   http://www.springframework.org/schema/cache/spring-cache-3.2.xsd
   http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring
   http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.1.xsd">

<context:load-time-weaver aspectj-weaving="on"/>
<cache:annotation-driven mode="aspectj"/>
<context:property-override location="file:/app/config/dataSourceOverride.cfg"/>
<context:annotation-config />

<bean id="DataSource1" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <property name="userId" value="4" />
</bean>

<bean id="DataSource2" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <property name="userId" value="3" />
</bean>

<bean id="DataSource3" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <property name="userId" value="2" />
</bean>

<bean id="DataSource4" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <property name="userId" value="1" />
</bean>
</code>```

Spring boot app main

```<code>package com.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportResource;

@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan("com.app")
@ImportResource("com/app/startup/spring.xml")
public class SpringBootServer {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootServer.class, args);

    }
}
</code>```

Abstract Class

```<code>public abstract class GenericDao {

    public GenericDao() {

    }

    private Logger logger = LoggerFactory.getLogger(GenericDao.class);

    @Autowired
    @Qualifier("DataSource1")
    protected BasicDataSource dataSource1Impl;

    @Autowired
    @Qualifier("DataSource2")
    protected BasicDataSource dataSource2Impl;

    @Autowired
    @Qualifier("DataSource3")
    protected BasicDataSource dataSource3Impl;

    @Autowired
    @Qualifier("DataSource4")
    protected BasicDataSource dataSource4Impl;
}
</code>```

Solid Calss

```<code>@Component("widgetsDao")
public class WidgetsDao extends GenericDao {

##Some methods##

}
</code>```

Exception

```<code>***************************
APPLICATION FAILED TO START
***************************

Description:

Field dataSource1Impl in com.app.dal.GenericDao required a single bean, but 4 were found:
    - DataSource1: defined in class path resource [com/app/startup/app-spring.xml]
    - DataSource2: defined in class path resource [com/app/startup/app-spring.xml]
    - DataSource3: defined in class path resource [com/app/startup/app-spring.xml]
    - DataSource4: defined in class path resource [com/app/startup/app-spring.xml]

Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed
</code>```

What could possibly make spring to ignore my @Qualifier annotation??

Thanks Ahead.

答:
I was seeing the same error when using multiple data sources, and after making one of the data source beans "primary" the issue seemed to be resolved and I was then able to autowire the correct bean with the @Qualifier annotation.

The Spring Boot documentation here agrees with that, saying that when using multiple data sources, one of the data source beans must be primary.

I configured my beans in Java using @Bean annotation, and so I used @Primary annotation to make one primary.  But if you're configuring in XML it looks like the  element in XML does have an optional "primary" attribute that could be used if configuring the beans in XML.

Body:
I am migrating an active Spring web app to spring boot(1.4.2).

The beans are defined in an XML as it is being loaded with @ImportResource.

4 of the beans that I am starting are an instance of the same object BasicDataSource.

To tell spring which one to load I have set an ID for each one and using @Qualifier to bind the correct bean to the variable.

But it seems to be that Spring ignores my @Qualifier and throwing "No qualifying bean of type 'javax.sql.DataSource' available: expected single matching bean but found 4: DataSource1, DataSource2, DataSource3, DataSource4"

P.S - Note that the class that has the @Qualifier is an abstract class, and the class that is failing to instantiate is an extending class, however @Qualifier has @Inherited.

XML

<beans
    xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:task="http://www.springframework.org/schema/task"
xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
   http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.2.xsd
   http://www.springframework.org/schema/jee
   http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
   http://www.springframework.org/schema/task
   http://www.springframework.org/schema/task/spring-task-3.2.xsd
   http://www.springframework.org/schema/cache
   http://www.springframework.org/schema/cache/spring-cache-3.2.xsd
   http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring
   http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.1.xsd">

<context:load-time-weaver aspectj-weaving="on"/>
<cache:annotation-driven mode="aspectj"/>
<context:property-override location="file:/app/config/dataSourceOverride.cfg"/>
<context:annotation-config />

<bean id="DataSource1" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <property name="userId" value="4" />
</bean>

<bean id="DataSource2" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <property name="userId" value="3" />
</bean>

<bean id="DataSource3" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <property name="userId" value="2" />
</bean>

<bean id="DataSource4" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <property name="userId" value="1" />
</bean>

Spring boot app main

package com.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportResource;

@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan("com.app")
@ImportResource("com/app/startup/spring.xml")
public class SpringBootServer {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootServer.class, args);

    }
}

Abstract Class

public abstract class GenericDao {

    public GenericDao() {

    }

    private Logger logger = LoggerFactory.getLogger(GenericDao.class);

    @Autowired
    @Qualifier("DataSource1")
    protected BasicDataSource dataSource1Impl;

    @Autowired
    @Qualifier("DataSource2")
    protected BasicDataSource dataSource2Impl;

    @Autowired
    @Qualifier("DataSource3")
    protected BasicDataSource dataSource3Impl;

    @Autowired
    @Qualifier("DataSource4")
    protected BasicDataSource dataSource4Impl;
}

Solid Calss

@Component("widgetsDao")
public class WidgetsDao extends GenericDao {

##Some methods##

}

Exception

***************************
APPLICATION FAILED TO START
***************************

Description:

Field dataSource1Impl in com.app.dal.GenericDao required a single bean, but 4 were found:
    - DataSource1: defined in class path resource [com/app/startup/app-spring.xml]
    - DataSource2: defined in class path resource [com/app/startup/app-spring.xml]
    - DataSource3: defined in class path resource [com/app/startup/app-spring.xml]
    - DataSource4: defined in class path resource [com/app/startup/app-spring.xml]

Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

What could possibly make spring to ignore my @Qualifier annotation??

Thanks Ahead.


问:
Is it better to rotate an arrow-icon or to use separate icons for right and left arrow?
In Android, i have an Arrow-Right icon (SVG). I also need an Arrow-Left icon. Is it better to use Arrow-Right and rotate it by 180° or use a separate drawable?

I imagine that rotating one icon is more efficient than loading a second drawable, but what if i have to use the icon hundreds of times in my activity?

Also, what if i have to use a bigger image (a .png file > 1MB)?

答: I'm guessing, if it's really an icon, it'll be small.  So small that I probably would just add the rotated version.  If you were to rotate it programmatically, you could cache it, of course.  If you were worried about the size of your app, you could rotate the image and save it into the app's disk cache so that you don't have to do each time.  At least I'd avoid having to rotate the image hundreds of times in the activity (or app).</p>


问:
Calculate time since user input and multiply times hourly rate in JS
I'm trying to create a simple time/salary tracker.
The user inputs time they started work and then a counter counts up the numbers of hours and minutes since clock-in and also the amount of money made in that time
It should also update the time and salary every 1s (setInterval(function, 1000))
I've been trying to get it right but can't seem to get the Date() working like I want it, would appreciate a nudge in the right direction
Thanks</p>

```<code><!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

<input id="input" type="time">
<button onclick="live()">run</button>
<!---->
<p id="output">Output</p>
<script>
       function live() {
           var seconds = 60;
           var minutes = seconds * 60;
           var hours = minutes * 60;

           var rate = 75;

           var input = document.getElementById('input');
           var output = document.getElementById('output');

           var now = new Date();
           var clock_in = input.value;

           var elapsed = now.toString();

           output.innerHTML = now.getHours() + " " +  now.getMinutes() + " " + now.getSeconds() + " " + now.getMilliseconds();
       }
</script>
</body>
</html>
</code>```

答:
I modified your code to accept a date too, you can find a demo working here

Basically the problem is that you need to have a valid Date Object

Explained without inputs the basic code works like this

```<code>// Init Time - valid Object time
var initTime = new Date(2017, 06, 5) // today Date, month start with 0

// time now
var now = new Date()

// diference in millisecond
var diference = now - initTime;

// rate scale
var rate = 75;
var scale = 75/3600000 // millisecond in a hour

// money
var money = scale * diference;
</code>```

Body:
I'm trying to create a simple time/salary tracker.
The user inputs time they started work and then a counter counts up the numbers of hours and minutes since clock-in and also the amount of money made in that time
It should also update the time and salary every 1s (setInterval(function, 1000))
I've been trying to get it right but can't seem to get the Date() working like I want it, would appreciate a nudge in the right direction
Thanks

<!doctype html>

    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

<input id="input" type="time">
<button onclick="live()">run</button>

Output

Body:
I modified your code to accept a date too, you can find a demo working here

Basically the problem is that you need to have a valid Date Object

Explained without inputs the basic code works like this

// Init Time - valid Object time
var initTime = new Date(2017, 06, 5) // today Date, month start with 0

// time now
var now = new Date()

// diference in millisecond
var diference = now - initTime;

// rate scale
var rate = 75;
var scale = 75/3600000 // millisecond in a hour

// money
var money = scale * diference;


问:
Breaking a form with a partial
I have this form made by rails scaffold:

```<code><%= form_for(@archive) do |f| %>
  <% if @archive.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@archive.errors.count, "error") %> prohibited this archive from being saved:</h2>

      <ul>
      <% @archive.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :objective %><br>
    <%= f.cktext_area :objective %>
  </div>
  <div class="field">
    <%= f.label :settings %><br>
    <%= f.cktext_area :settings %>
  </div>
  <div class="field">
    <%= f.label :related_documents %><br>
    <%= f.cktext_area :related_documents %>
  </div>
  <div class="field">
    <%= f.label :responsability %><br>
    <%= f.cktext_area :responsability %>
  </div>
  <div class="field">
    <%= f.label :material_needed %><br>
    <%= f.cktext_area :material_needed %>
  </div>
  <div class="field">
    <%= f.label :description %><br>
    <%= f.cktext_area :description %>
  </div>
  <div class="field">
    <%= f.label :preventive_measures %><br>
    <%= f.cktext_area :preventive_measures %>
  </div>
  <div class="field">
    <%= f.label :corrective_actions %><br>
    <%= f.cktext_area :corrective_actions %>
  </div>
  <div class="field">
    <%= f.label :execution %><br>
    <%= f.cktext_area :execution %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>
</code>```

And I wanted to separate the fields, I wanted to use partials because it keeps repeating, what changes is the name of the field, I wanted to render the partial form of a field and pass the field name. Because of the fact that I'm going to use the custom ckeditor, and I'll keep repeating on the form, it may give the error chance. Am I right to think that? Is my idea correct? If so, how can I do to pass the field? Will this influence something in the database?
I wanted to do something like this.

form:

```<code><%= form_for(@archive) do |f| %>
  <% if @archive.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@archive.errors.count, "error") %> prohibited this archive from being saved:</h2>

      <ul>
      <% @archive.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

<%= render partial 'fields', 'field_name' %>

 <!-- Call many times and pass the field name -->

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>
</code>```

partial:

```<code>  <div class="field">
    <%= f.label :field_name%><br>
    <%= f.cktext_area :field_name %>
  </div>
</code>```

答:
You can pass various arguments when calling a partial. You can do something like this :-

<%= render partial 'fields', locals: { f: f, field_name: :body } %>

Here f is the form object and :body will be the field_name you want to pass when calling the partial.

You can even pass multiple fields in an array and iterate over them in the partial.

<%= render partial 'fields', locals: { f: f, field_names: [:body, :bio] } %>

Your partial code will look something like this -

```<code><% field_names.each do |field_name| %>
    <div class="field">
        <%= f.label field_name%><br>
        <%= f.text_area :field_name %>
    </div>
<% end %>
</code>```

You can do the same in your main file too instead of calling so many partails. As it is not considered a good practise.

Title: Breaking a form with a partial

Body:
I have this form made by rails scaffold:

<%= form_for(@archive) do |f| %>
  <% if @archive.errors.any? %>

<%= pluralize(@archive.errors.count, "error") %> prohibited this archive from being saved:

      <% @archive.errors.full_messages.each do |message| %>

<%= message %>

      <% end %>

  <% end %>

    <%= f.label :objective %>

    <%= f.cktext_area :objective %>

    <%= f.label :settings %>

    <%= f.cktext_area :settings %>

    <%= f.label :related_documents %>

    <%= f.cktext_area :related_documents %>

    <%= f.label :responsability %>

    <%= f.cktext_area :responsability %>

    <%= f.label :material_needed %>

    <%= f.cktext_area :material_needed %>

    <%= f.label :description %>

    <%= f.cktext_area :description %>

    <%= f.label :preventive_measures %>

    <%= f.cktext_area :preventive_measures %>

    <%= f.label :corrective_actions %>

    <%= f.cktext_area :corrective_actions %>

    <%= f.label :execution %>

    <%= f.cktext_area :execution %>

    <%= f.submit %>

<% end %>

And I wanted to separate the fields, I wanted to use partials because it keeps repeating, what changes is the name of the field, I wanted to render the partial form of a field and pass the field name. Because of the fact that I'm going to use the custom ckeditor, and I'll keep repeating on the form, it may give the error chance. Am I right to think that? Is my idea correct? If so, how can I do to pass the field? Will this influence something in the database?
I wanted to do something like this.

form:

<%= form_for(@archive) do |f| %>
  <% if @archive.errors.any? %>

<%= pluralize(@archive.errors.count, "error") %> prohibited this archive from being saved:

      <% @archive.errors.full_messages.each do |message| %>

<%= message %>

      <% end %>

  <% end %>

<%= render partial 'fields', 'field_name' %>

    <%= f.submit %>

<% end %>

partial:

    <%= f.label :field_name%>

    <%= f.cktext_area :field_name %>

Body:
You can pass various arguments when calling a partial. You can do something like this :-

<%= render partial 'fields', locals: { f: f, field_name: :body } %>

Here f is the form object and :body will be the field_name you want to pass when calling the partial.

You can even pass multiple fields in an array and iterate over them in the partial.

<%= render partial 'fields', locals: { f: f, field_names: [:body, :bio] } %>

Your partial code will look something like this -

<% field_names.each do |field_name| %>
    <div class="field">
        <%= f.label field_name%><br>
        <%= f.text_area :field_name %>
    </div>
<% end %>

You can do the same in your main file too instead of calling so many partails. As it is not considered a good practise.


问:
MySQL query ! What's wrong here?
Please tell me what is wrong here :</p>

```<code>INSERT INTO `tbl_verkauf_am`(`fld_kdnr`, `fld_artikelnummer`, `fld_artikelbez1`, `fld_saal_lst`, `fld_anzahl`, `fld_preis`) VALUES
(900000, (SELECT `id`, `fld_besch_0`, `fld_class` FROM `tbl_saal_koord` WHERE `id` < 20300), 1, 50)
</code>```

答:
Remove the values keyword and put all in one select

```<code>INSERT INTO tbl_verkauf_am (fld_kdnr, fld_artikelnummer, fld_artikelbez1, fld_saal_lst, fld_anzahl, fld_preis)
SELECT 900000, id, fld_besch_0, fld_class, 1, 50
FROM tbl_saal_koord
WHERE id < 20300
</code>```

Title: MySQL query ! What's wrong here?

Body:
Please tell me what is wrong here :

INSERT INTO `tbl_verkauf_am`(`fld_kdnr`, `fld_artikelnummer`, `fld_artikelbez1`, `fld_saal_lst`, `fld_anzahl`, `fld_preis`) VALUES
(900000, (SELECT `id`, `fld_besch_0`, `fld_class` FROM `tbl_saal_koord` WHERE `id` < 20300), 1, 50)

Body:
Remove the values keyword and put all in one select

INSERT INTO tbl_verkauf_am (fld_kdnr, fld_artikelnummer, fld_artikelbez1, fld_saal_lst, fld_anzahl, fld_preis)
SELECT 900000, id, fld_besch_0, fld_class, 1, 50
FROM tbl_saal_koord
WHERE id < 20300


问:
Symfony 3.3.2 Doctrine EntityRepository constructor argument
I'm newbie on Symfony. I am trying to update an old project under symfony 2.6 to symfony 3.3.

After multiple bug fixes I am stuck on a point: I have an Error in my EntityRepository.php file with the constructor.

```<code>Type error: Too few arguments to function Doctrine\ORM\EntityRepository::__construct(), 1 passed in /Users/.../var/cache/dev/appDevDebugProjectContainer.php on line 3434 and exactly 2 expected
</code>```

I understand the error, but my EntityRepository file not contain any __construct method. Should I fix something between Symfony 2 and 3 for the consructor to work?

Thanks a lot.

Here is my MilestoneRepository.php file:

```<code>namespace MilestonesBundle\Entity\Repository;

use DateTime;

use Doctrine\ORM\EntityRepository;

use Milestones\Entity\Factory\MilestoneFactoryInterface;
use Milestones\Entity\Repository\MilestoneRepositoryInterface;

class MilestoneRepository extends EntityRepository implements MilestoneFactoryInterface, MilestoneRepositoryInterface
{
    protected $current = false;

    /**
     * @see MilestoneFactoryInterface
     */
    public function create()
    {
        $class = $this->getClassName();

        return new $class;
    }

    public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
    {
        if (!$orderBy) {
            $orderBy['startsAt'] = 'ASC';
        }

        return parent::findBy($criteria, $orderBy, $limit, $offset);
    }

    /**
     * @see MilestoneRepositoryInterface
     */
    public function findCurrent()
    {
        $now = new DateTime;

        if ($this->current === false) {
            $this->current = $this->createQueryBuilder('m')
                ->where('m.startsAt <= :now')
                ->andWhere('(m.endsAt IS NULL OR :now < m.endsAt)')
                ->setParameter('now', $now->format('Y-m-d'))
                ->orderBy('m.startsAt', 'ASC')
                ->setMaxResults(1)
                ->getQuery()
                ->getOneOrNullResult()
            ;
        }

        return $this->current;
    }

    /**
     * @see MilestoneRepositoryInterface
     */
    public function isOpen()
    {
        $current = $this->findCurrent();

        return $current && $current->isStart();
    }
}
</code>```

And here is my EntityRepository.php file:

```<code>namespace Common\Doctrine\ORM;

use Doctrine\ORM\EntityRepository as BaseEntityRepository;
use Doctrine\ORM\QueryBuilder;

class EntityRepository extends BaseEntityRepository
{
    protected $alias = 'x';

    public function add($entity)
    {
        $em = $this->getEntityManager();
        $em->persist($entity);
        $em->flush();
    }

    public function remove($entity)
    {
        $em = $this->getEntityManager();
        $em->remove($entity);
        $em->flush();
    }

    public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null, $result = true)
    {
        $alias   = $this->alias;
        $builder = $this->createQueryBuilder($alias);

        $this->applyCriteria($builder, $alias, $criteria);
        $this->applyOrderBy($builder, $alias, $orderBy);
        $this->applyLimit($builder, $limit);
        $this->applyOffset($builder, $offset);

        if (!$result) {
            return $builder;
        }

        return $builder->getQuery()->getResult();
    }

    public function findOneBy(array $criteria, array $orderBy = null, $result = true)
    {
        $alias   = $this->alias;
        $builder = $this->createQueryBuilder($alias);

        $this->applyCriteria($builder, $alias, $criteria);
        $this->applyOrderBy($builder, $alias, $orderBy);

        if (!$result) {
            return $builder;
        }

        return $builder->getQuery()->getOneOrNullResult();
    }

    protected function applyCriteria(QueryBuilder $builder, $alias, array $criteria)
    {
        $map = $this->getCriteriaMap();

        foreach ($criteria as $property => $value) {
            if (array_key_exists($property, $map)) {
                call_user_func_array($map[$property], [$builder, $alias, $property, $value]);
            } else {
                $this->applyDefaultCriterion($builder, $alias, $property, $value);
            }
        }
    }

    protected function getCriteriaMap()
    {
        return [];
    }

    protected function applyDefaultCriterion($builder, $alias, $property, $value)
    {
        if (null === $value) {
            $builder->andWhere($alias.'.'.$property.' IS NULL');
        } else {
            $parameter = 'p_' . uniqid();
            $builder->andWhere($alias.'.'.$property.' = :'.$parameter);
            $builder->setParameter($parameter, $value);
        }
    }

    /**
     * Apply order by
     *
     * @param  QueryBuilder $builder
     * @param  string       $alias
     * @param  array|null   $orderBy
     * @return void
     */
    protected function applyOrderBy(QueryBuilder $builder, $alias, array $orderBy = null)
    {
        if (empty($orderBy)) {
            $orderBy = $this->getDefaultOrder();
        }

        $map = $this->getOrderingMap();

        foreach ($orderBy as $property => $direction) {
            if (array_key_exists($property, $map)) {
                call_user_func_array($map[$property], [$builder, $alias, $property, $direction]);
            } else {
                $this->applyDefaultOrder($builder, $alias, $property, $direction);
            }
        }
    }

    protected function getDefaultOrder()
    {
        return [];
    }

    protected function getOrderingMap()
    {
        return [];
    }

    protected function applyDefaultOrder(QueryBuilder $builder, $alias, $property, $direction)
    {
        $builder->orderBy($alias.'.'.$property, $direction);
    }

    protected function applyLimit(QueryBuilder $builder, $limit = null)
    {
        if ($limit) {
            $builder->setMaxResults($limit);
        }
    }

    protected function applyOffset(QueryBuilder $builder, $offset = null)
    {
        if ($offset) {
            $builder->setFirstResult($offset);
        }
    }
}
</code>```

I think I'm accessing through a service, with this:

```<code>services:

# Factories

milestones.factory.milestone:
    alias: milestones.repository.milestone
    arguments: [ MilestonesBundle\Entity\Milestone ]

# Repositories

milestones.repository.milestone:
    class: MilestonesBundle\Entity\Repository\MilestoneRepository
    factory_service: doctrine.orm.default_entity_manager
    factory_method: getRepository
    arguments: [ MilestonesBundle\Entity\Milestone ]
</code>```

答:
replace this code:

```<code>milestones.repository.milestone:
    class: MilestonesBundle\Entity\Repository\MilestoneRepository
    factory_service: doctrine.orm.default_entity_manager
    factory_method: getRepository
    arguments: [ MilestonesBundle\Entity\Milestone ]
</code>```

with this one:

```<code>milestones.repository.milestone:
     class: MilestonesBundle\Entity\Repository\MilestoneRepository
     factory: ['@doctrine.orm.entity_manager', getRepository]
     arguments: [ MilestonesBundle\Entity\Milestone ]
</code>```

factory method - getRepository

Body:
I'm newbie on Symfony. I am trying to update an old project under symfony 2.6 to symfony 3.3.

After multiple bug fixes I am stuck on a point: I have an Error in my EntityRepository.php file with the constructor.

Type error: Too few arguments to function Doctrine\ORM\EntityRepository::__construct(), 1 passed in /Users/.../var/cache/dev/appDevDebugProjectContainer.php on line 3434 and exactly 2 expected

I understand the error, but my EntityRepository file not contain any __construct method. Should I fix something between Symfony 2 and 3 for the consructor to work?

Thanks a lot.

Here is my MilestoneRepository.php file:

namespace MilestonesBundle\Entity\Repository;

use DateTime;

use Doctrine\ORM\EntityRepository;

use Milestones\Entity\Factory\MilestoneFactoryInterface;
use Milestones\Entity\Repository\MilestoneRepositoryInterface;

class MilestoneRepository extends EntityRepository implements MilestoneFactoryInterface, MilestoneRepositoryInterface
{
    protected $current = false;

    /**
     * @see MilestoneFactoryInterface
     */
    public function create()
    {
        $class = $this->getClassName();

        return new $class;
    }

    public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
    {
        if (!$orderBy) {
            $orderBy['startsAt'] = 'ASC';
        }

        return parent::findBy($criteria, $orderBy, $limit, $offset);
    }

    /**
     * @see MilestoneRepositoryInterface
     */
    public function findCurrent()
    {
        $now = new DateTime;

        if ($this->current === false) {
            $this->current = $this->createQueryBuilder('m')
                ->where('m.startsAt <= :now')
                ->andWhere('(m.endsAt IS NULL OR :now < m.endsAt)')
                ->setParameter('now', $now->format('Y-m-d'))
                ->orderBy('m.startsAt', 'ASC')
                ->setMaxResults(1)
                ->getQuery()
                ->getOneOrNullResult()
            ;
        }

        return $this->current;
    }

    /**
     * @see MilestoneRepositoryInterface
     */
    public function isOpen()
    {
        $current = $this->findCurrent();

        return $current && $current->isStart();
    }
}

And here is my EntityRepository.php file:

namespace Common\Doctrine\ORM;

use Doctrine\ORM\EntityRepository as BaseEntityRepository;
use Doctrine\ORM\QueryBuilder;

class EntityRepository extends BaseEntityRepository
{
    protected $alias = 'x';

    public function add($entity)
    {
        $em = $this->getEntityManager();
        $em->persist($entity);
        $em->flush();
    }

    public function remove($entity)
    {
        $em = $this->getEntityManager();
        $em->remove($entity);
        $em->flush();
    }

    public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null, $result = true)
    {
        $alias   = $this->alias;
        $builder = $this->createQueryBuilder($alias);

        $this->applyCriteria($builder, $alias, $criteria);
        $this->applyOrderBy($builder, $alias, $orderBy);
        $this->applyLimit($builder, $limit);
        $this->applyOffset($builder, $offset);

        if (!$result) {
            return $builder;
        }

        return $builder->getQuery()->getResult();
    }

    public function findOneBy(array $criteria, array $orderBy = null, $result = true)
    {
        $alias   = $this->alias;
        $builder = $this->createQueryBuilder($alias);

        $this->applyCriteria($builder, $alias, $criteria);
        $this->applyOrderBy($builder, $alias, $orderBy);

        if (!$result) {
            return $builder;
        }

        return $builder->getQuery()->getOneOrNullResult();
    }

    protected function applyCriteria(QueryBuilder $builder, $alias, array $criteria)
    {
        $map = $this->getCriteriaMap();

        foreach ($criteria as $property => $value) {
            if (array_key_exists($property, $map)) {
                call_user_func_array($map[$property], [$builder, $alias, $property, $value]);
            } else {
                $this->applyDefaultCriterion($builder, $alias, $property, $value);
            }
        }
    }

    protected function getCriteriaMap()
    {
        return [];
    }

    protected function applyDefaultCriterion($builder, $alias, $property, $value)
    {
        if (null === $value) {
            $builder->andWhere($alias.'.'.$property.' IS NULL');
        } else {
            $parameter = 'p_' . uniqid();
            $builder->andWhere($alias.'.'.$property.' = :'.$parameter);
            $builder->setParameter($parameter, $value);
        }
    }

    /**
     * Apply order by
     *
     * @param  QueryBuilder $builder
     * @param  string       $alias
     * @param  array|null   $orderBy
     * @return void
     */
    protected function applyOrderBy(QueryBuilder $builder, $alias, array $orderBy = null)
    {
        if (empty($orderBy)) {
            $orderBy = $this->getDefaultOrder();
        }

        $map = $this->getOrderingMap();

        foreach ($orderBy as $property => $direction) {
            if (array_key_exists($property, $map)) {
                call_user_func_array($map[$property], [$builder, $alias, $property, $direction]);
            } else {
                $this->applyDefaultOrder($builder, $alias, $property, $direction);
            }
        }
    }

    protected function getDefaultOrder()
    {
        return [];
    }

    protected function getOrderingMap()
    {
        return [];
    }

    protected function applyDefaultOrder(QueryBuilder $builder, $alias, $property, $direction)
    {
        $builder->orderBy($alias.'.'.$property, $direction);
    }

    protected function applyLimit(QueryBuilder $builder, $limit = null)
    {
        if ($limit) {
            $builder->setMaxResults($limit);
        }
    }

    protected function applyOffset(QueryBuilder $builder, $offset = null)
    {
        if ($offset) {
            $builder->setFirstResult($offset);
        }
    }
}

I think I'm accessing through a service, with this:

services:

# Factories

milestones.factory.milestone:
    alias: milestones.repository.milestone
    arguments: [ MilestonesBundle\Entity\Milestone ]

# Repositories

milestones.repository.milestone:
    class: MilestonesBundle\Entity\Repository\MilestoneRepository
    factory_service: doctrine.orm.default_entity_manager
    factory_method: getRepository
    arguments: [ MilestonesBundle\Entity\Milestone ]

Body:
replace this code:

milestones.repository.milestone:
    class: MilestonesBundle\Entity\Repository\MilestoneRepository
    factory_service: doctrine.orm.default_entity_manager
    factory_method: getRepository
    arguments: [ MilestonesBundle\Entity\Milestone ]

with this one:

milestones.repository.milestone:
     class: MilestonesBundle\Entity\Repository\MilestoneRepository
     factory: ['@doctrine.orm.entity_manager', getRepository]
     arguments: [ MilestonesBundle\Entity\Milestone ]

factory method - getRepository


问:
Laravel 5.4: Swift_TransportException connection could not be established with host smtp.gmail.com
I'm trying to use the auth forgot password functionality but it's not working. I already turned on the access for less secure apps in gmail.</p>

```<code>.env file
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.io
MAIL_PORT=587
MAIL_USERNAME=myemail
MAIL_PASSWORD=mypass
MAIL_ENCRYPTION=tls

mail.php
'driver' => env('MAIL_DRIVER', 'smtp'),
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
'port' => env('MAIL_PORT', 587),
'from' => [
        'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
        'name' => env('MAIL_FROM_NAME', 'Example'),
    ],
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'sendmail' => '/usr/sbin/sendmail -bs',
</code>```

答:
This can be caused by the security settings on your Gmail account.
Probably you need to set the allow less secure apps to access your account.
You can read here how to do it: https://support.google.com/accounts/answer/6010255?hl=en

Also as an SMTP server use smtp.gmail.com

Body:
I'm trying to use the auth forgot password functionality but it's not working. I already turned on the access for less secure apps in gmail.

.env file
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.io
MAIL_PORT=587
MAIL_USERNAME=myemail
MAIL_PASSWORD=mypass
MAIL_ENCRYPTION=tls

mail.php
'driver' => env('MAIL_DRIVER', 'smtp'),
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
'port' => env('MAIL_PORT', 587),
'from' => [
        'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
        'name' => env('MAIL_FROM_NAME', 'Example'),
    ],
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'sendmail' => '/usr/sbin/sendmail -bs',


问:
Java generic "Collection have the same erasure" Error
I want to make the GenericCollection generic obviously. I get this error:

```<code>name clash: add(T) in GCollection and add(java.lang.Object) in
Collection have the same erasure, yet neither overrides the other
</code>```

Collection

```<code>public class Collection {
    public Object get(int i){
        return null;
    }
    public void add(Object o){ }
}
</code>```

GenericCollection

```<code>public class GenericCollection<T> extends Collection {
    public T get(int i){
        return (T) super.get(i);
    }

    public void add(T o){
        super.add(o);
    }
}
</code>```

Maybe got some ideas?

答:
I suspect your issue is that the Collection that is being extended by GenericCollection is the actual Java collection- java.util.Collection<E> and as such you're trying to override methods that already exist in the built in Java collection.

As a rule of thumb, don't completely redefine existing Java classes, because it can easily cause this behavior.

Body:
I want to make the GenericCollection generic obviously. I get this error:

name clash: add(T) in GCollection and add(java.lang.Object) in
Collection have the same erasure, yet neither overrides the other

Collection

public class Collection {
    public Object get(int i){
        return null;
    }
    public void add(Object o){ }
}

GenericCollection

public class GenericCollection<T> extends Collection {
    public T get(int i){
        return (T) super.get(i);
    }

    public void add(T o){
        super.add(o);
    }
}

Maybe got some ideas?


问:
Regex for validating a pattern in Java
I have to validate a pattern like : abc.123456789.123 (example) where I have to check for these things:

First three should be letters only of fixed length (case insensitive)

Followed by dot (.)

Numbers in range 0-9, length should be 9

Followed by dot (.) and Numbers in range 0-9, length should be 3 (optional)

Valid Example:

```<code> abc.1
 Abc.123456789
 aBc.123.123
 ABC.123456789.12
</code>```

Invalid Exmples:

```<code> abc.1.
 abc..1.123
 .123
 abc.123w45678.123
 abc.
</code>```

What I've tried :

```<code>^[a-zA-Z]{3}\\.\\d{0,9}\\.\\d{0,3}|[a-zA-Z]{3}\\.\\d{0,9}$
</code>```

As I am new in Regex, I tried the above Regex but it is failing to pass abc.1. and abc...

答:
i) first three should be letters only of fixed length (case insensitive)

Case-insensitive (Latin, unaccented) letter: [A-Za-z]

You can specify exactly three occurrences either by repeating that fragment twice more, or by using an enumerated quantifier: {3}

ii) followed by dot(.)

The dot is a regex metacharacter, so it needs to be escaped: \..  When put into a String literal, the backslash must be doubled to escape it.

iii) numbers in range 0-9,length should be 9

From your examples, I gather you mean maximum length 9.  One decimal digit would be [0-9].  Between one and nine of them would be [0-9]{1,9}.

iv) followed by dot(.) (this is optional)

v) numbers in range 0-9, length should be 3 (this is optional)

The tail of your pattern is optional, but from your examples, (iv) and (v) are not separate options but rather one joint option -- either both are present or both are absent.  Additionally, your examples suggest that you mean a maximum of three digits.  You can use the pattern components already discussed to form a sub-pattern for this part; to make it optional, group the pieces together with (?:) and make the group optional with a ? quantifier.

Putting that all together, the (a) pattern for this would be

```<code>[A-Za-z]{3}\.[0-9]{1,9}(?:\.[0-9]{1,3})?
</code>```

Or as a string,

```<code>Pattern p = Pattern.compile("[A-Za-z]{3}\\.[0-9]{1,9}(?:\\.[0-9]{1,3})?");
</code>```

Depending on your requirements, you may or may not want also to anchor the pattern to start of your string (by beginning it with a ^ character) and / or to the end of the string / line (by ending it with a $ character).  If you do not anchor it to the end of the string, then you may want to append an assertion that the next character, if any, is not another digit: (?![0-9]).

Title: Regex for validating a pattern in Java

Body:
I have to validate a pattern like : abc.123456789.123 (example) where I have to check for these things:

First three should be letters only of fixed length (case insensitive)

Followed by dot (.)

Numbers in range 0-9, length should be 9

Followed by dot (.) and Numbers in range 0-9, length should be 3 (optional)

Valid Example:

 abc.1
 Abc.123456789
 aBc.123.123
 ABC.123456789.12

Invalid Exmples:

 abc.1.
 abc..1.123
 .123
 abc.123w45678.123
 abc.

What I've tried :

^[a-zA-Z]{3}\\.\\d{0,9}\\.\\d{0,3}|[a-zA-Z]{3}\\.\\d{0,9}$

As I am new in Regex, I tried the above Regex but it is failing to pass abc.1. and abc...

Body:
i) first three should be letters only of fixed length (case insensitive)

Case-insensitive (Latin, unaccented) letter: [A-Za-z]

You can specify exactly three occurrences either by repeating that fragment twice more, or by using an enumerated quantifier: {3}

ii) followed by dot(.)

The dot is a regex metacharacter, so it needs to be escaped: \..  When put into a String literal, the backslash must be doubled to escape it.

iii) numbers in range 0-9,length should be 9

From your examples, I gather you mean maximum length 9.  One decimal digit would be [0-9].  Between one and nine of them would be [0-9]{1,9}.

iv) followed by dot(.) (this is optional)

v) numbers in range 0-9, length should be 3 (this is optional)

The tail of your pattern is optional, but from your examples, (iv) and (v) are not separate options but rather one joint option -- either both are present or both are absent.  Additionally, your examples suggest that you mean a maximum of three digits.  You can use the pattern components already discussed to form a sub-pattern for this part; to make it optional, group the pieces together with (?:) and make the group optional with a ? quantifier.

Putting that all together, the (a) pattern for this would be

[A-Za-z]{3}\.[0-9]{1,9}(?:\.[0-9]{1,3})?

Or as a string,

Pattern p = Pattern.compile("[A-Za-z]{3}\\.[0-9]{1,9}(?:\\.[0-9]{1,3})?");

Depending on your requirements, you may or may not want also to anchor the pattern to start of your string (by beginning it with a ^ character) and / or to the end of the string / line (by ending it with a $ character).  If you do not anchor it to the end of the string, then you may want to append an assertion that the next character, if any, is not another digit: (?![0-9]).


问:
Help me re-understand how to use sine to oscillate a graphic in (Objective) C
I feel silly asking this but I seem to have forgotten how to use sine effectively.

I'm working on an iPad app so I'm in ObjectiveC, and I'm just trying to get a UIView to oscillate slowly. Just using position.y + sin(counter) makes it move so fast it vibrates and I can't seem to define the period to slow it down.

I've found some code samples (mostly for generating sound waves) and they all combine so many things into one line of code I can't easily pull it apart. Can anybody just explain what I should be doing?

答:
sin (and cos) take a parameter in Radians. The name counter suggests that you're not using Radians.

So, you need to determine how many oscillations per second you want. Then, you can measure the time between the last and the current animation 'frame'. A whole wave is 2PI radians, so

```<code>Y = sin(2PI * Time * OccilationsPerSecond) * Amplitude.
</code>```

ContentLicense: CC BY-SA 2.5

Body:
sin (and cos) take a parameter in Radians. The name counter suggests that you're not using Radians.

So, you need to determine how many oscillations per second you want. Then, you can measure the time between the last and the current animation 'frame'. A whole wave is 2PI radians, so

Y = sin(2PI * Time * OccilationsPerSecond) * Amplitude.


问:
Query Works in Oracle SQL Developer but not in Microsoft Query
I've spent the last two days going through Google and searching around this site for help on this but none of the suggested solutions work/make sense to me sadly. Essentially I have a code that works fine in Oracle SQL Developer that I am trying to place into an Excel workbook so that people without SQL knowledge could simply change the start/stop times in a few cells and gather the necessary information they need for their reports.

I tried testing the below code to see if it worked before I tried to link it to specific cells but sadly it failed so i have not tried setting the variables to cells yet.

The Code is as follows:

```<code>    SET NOCOUNT ON;

define start_dateA = TO_DATE('2017-07-05_00:00:00', 'YYYY-MM-DD"_"HH24:MI:SS');
define stop_dateB = TO_DATE('2017-07-05_23:59:59', 'YYYY-MM-DD"_"HH24:MI:SS');

select tdate, FRSTOL, TOSTOL,   DEVCOD, USR_ID, PRTNUM, TRNQTY
from mytable
where
tdate BETWEEN &start_dateA AND &stop_dateB
and (FRSTOL like 'A%'
OR FRSTOL like 'B%'
OR FRSTOL like 'C%'
OR FRSTOL like 'E%'
OR FRSTOL like 'F%'
OR FRSTOL like 'L%'
OR FRSTOL like 'P%'
OR FRSTOL like 'R%'
OR FRSTOL like 'T%')

order by usr_id, tdate
</code>```

The error I receive when i try to run this is ORA-00922. I'm about 95% sure there is an issue with the define statements, as when replace the variables start_dateA and stop_dateB with the actual values it works fine. Please note i will need both the date and time components for what I'm working on. Also I only have ReadOnly privileges for the server so I unable/do not have the knowledge to make changes to the tables or servers themselves.

Also not sure if I'm allowed to ask two questions but if someone could also help with how to go about setting start_dateA and &stop_dateB to specific cells as well that would be greatly appreciated as that is the hurdle I face after figuring out this step.

Thank you in advance,

答:
Rather than trying to solve the problem by writing brittle define statements, I recommend you refactor the date predicate a bit w.r.t. the define statements:</p>

```<code>define dtA=2017-07-05_00:00:00
define dtB=2017-07-05_23:59:59
define fmt='YYYY-MM-DD"_"HH24:MI:SS'

tdate between TO_DATE('&dtA', '&fmt') and TO_DATE('&dtB', '&fmt')
</code>```

Body:
I've spent the last two days going through Google and searching around this site for help on this but none of the suggested solutions work/make sense to me sadly. Essentially I have a code that works fine in Oracle SQL Developer that I am trying to place into an Excel workbook so that people without SQL knowledge could simply change the start/stop times in a few cells and gather the necessary information they need for their reports.

I tried testing the below code to see if it worked before I tried to link it to specific cells but sadly it failed so i have not tried setting the variables to cells yet.

The Code is as follows:

    SET NOCOUNT ON;

define start_dateA = TO_DATE('2017-07-05_00:00:00', 'YYYY-MM-DD"_"HH24:MI:SS');
define stop_dateB = TO_DATE('2017-07-05_23:59:59', 'YYYY-MM-DD"_"HH24:MI:SS');

select tdate, FRSTOL, TOSTOL,   DEVCOD, USR_ID, PRTNUM, TRNQTY
from mytable
where
tdate BETWEEN &start_dateA AND &stop_dateB
and (FRSTOL like 'A%'
OR FRSTOL like 'B%'
OR FRSTOL like 'C%'
OR FRSTOL like 'E%'
OR FRSTOL like 'F%'
OR FRSTOL like 'L%'
OR FRSTOL like 'P%'
OR FRSTOL like 'R%'
OR FRSTOL like 'T%')

order by usr_id, tdate

The error I receive when i try to run this is ORA-00922. I'm about 95% sure there is an issue with the define statements, as when replace the variables start_dateA and stop_dateB with the actual values it works fine. Please note i will need both the date and time components for what I'm working on. Also I only have ReadOnly privileges for the server so I unable/do not have the knowledge to make changes to the tables or servers themselves.

Also not sure if I'm allowed to ask two questions but if someone could also help with how to go about setting start_dateA and &stop_dateB to specific cells as well that would be greatly appreciated as that is the hurdle I face after figuring out this step.

Thank you in advance,

Body:
Rather than trying to solve the problem by writing brittle define statements, I recommend you refactor the date predicate a bit w.r.t. the define statements:

define dtA=2017-07-05_00:00:00
define dtB=2017-07-05_23:59:59
define fmt='YYYY-MM-DD"_"HH24:MI:SS'

tdate between TO_DATE('&dtA', '&fmt') and TO_DATE('&dtB', '&fmt')


问:
error CS0103: The name "ressourcesText" does not exist in the current context
I set up a string named ressourcesText, which will be set as the text LblRessources

This is the code for this problem :

```<code>public void ressources()
{
    string ressourcesText = "Ressources:"
                        + "\n Wood :" + wood
                        + "\n Stone : " + stone
                        + "\n Wheat : " + wheat
                        + "\n Food : " + food;
}

public void Form1_Load(object sender, EventArgs e)
{
    LblRessources.Text = ressourcesText;
}
</code>```

How can the text for LblRessources use the string ressourcesText? It usually worked this way.

答:
The issue with your code is that ressourcesText is declared locally in the ressources() function.

Variables that are declared within { } brackets are destroyed at the end of the bracket, and are called local variables.

To solve this you could make your variable global:

```<code>string ressourcesText;
public void ressources()
{
    ressourcesText = "Ressources:"
                        + "\n Wood :" + wood
                        + "\n Stone : " + stone
                        + "\n Wheat : " + wheat
                        + "\n Food : " + food;
}

public void Form1_Load(object sender, EventArgs e)
{
    LblRessources.Text = ressourcesText;
}
</code>```

Now this isn't necessarily good practice, because at the time of declaring your variable, it will be null, and thus can not be used until you call ressources().

Another alternative would be to return the variable through the ressources() function and calling it directly to retrieve the value, like follows:

```<code>public string ressources()
{
    string ressourcesText = "Ressources:"
                        + "\n Wood :" + wood
                        + "\n Stone : " + stone
                        + "\n Wheat : " + wheat
                        + "\n Food : " + food;
    return ressourcesText;
}

public void Form1_Load(object sender, EventArgs e)
{
    LblRessources.Text = ressources();
}
</code>```

That's somewhat safer.

You should check out these links for more info:

Local variables

C# Methods

Scopes

Body:
I set up a string named ressourcesText, which will be set as the text LblRessources

This is the code for this problem :

public void ressources()
{
    string ressourcesText = "Ressources:"
                        + "\n Wood :" + wood
                        + "\n Stone : " + stone
                        + "\n Wheat : " + wheat
                        + "\n Food : " + food;
}

public void Form1_Load(object sender, EventArgs e)
{
    LblRessources.Text = ressourcesText;
}

How can the text for LblRessources use the string ressourcesText? It usually worked this way.

Body:
The issue with your code is that ressourcesText is declared locally in the ressources() function.

Variables that are declared within { } brackets are destroyed at the end of the bracket, and are called local variables.

To solve this you could make your variable global:

string ressourcesText;
public void ressources()
{
    ressourcesText = "Ressources:"
                        + "\n Wood :" + wood
                        + "\n Stone : " + stone
                        + "\n Wheat : " + wheat
                        + "\n Food : " + food;
}

public void Form1_Load(object sender, EventArgs e)
{
    LblRessources.Text = ressourcesText;
}

Now this isn't necessarily good practice, because at the time of declaring your variable, it will be null, and thus can not be used until you call ressources().

Another alternative would be to return the variable through the ressources() function and calling it directly to retrieve the value, like follows:

public string ressources()
{
    string ressourcesText = "Ressources:"
                        + "\n Wood :" + wood
                        + "\n Stone : " + stone
                        + "\n Wheat : " + wheat
                        + "\n Food : " + food;
    return ressourcesText;
}

public void Form1_Load(object sender, EventArgs e)
{
    LblRessources.Text = ressources();
}

That's somewhat safer.

You should check out these links for more info:

Local variables

C# Methods

Scopes


问:
SDK for sony ILCE QX1L
Is it possible to attach this camera to computer through cable and get SDK so that it would be possible to control it through our own made software?

We need for automated photobooth.

If not, which camera should be used? (from cheapest with interchangeable lenses)

答: Unfortunately all of the Sony cameras that support the Camera Remote API will only work connected to the camera over wifi.</p>

Title: SDK for sony ILCE QX1L


答:
I would make a partial call with locals (f) and a collection (field_name symbols).

So i would create an array in my controller in the corresponding action like this.

Edit Actually you could create a before action: before_action :field_names, only: [:new, :edit]

```<code>def field_names
  # %i creates an array of symbols
  @field_names = %i(objectives settings related_objects ...)
end
</code>```

And then in your form you can call:

With the "as:" you can now access an instance of the @fields_names
called "field_name" in each partial

```<code> <%= render partial: "fields", collection: @field_names, as: :field_name,
 locals: {f: f} %>
</code>```

And then you can inset field_name and f in your _fields.html.erb

```<code><div class="field">
 <%= f.label field_name %><br>
 <%= f.cktext_area field_name %>
</div>
</code>```

The smart thing about collection is that it will automatically render the same number of times as there are values in the array.

Look for more in the section Local variables in the guide

Good luck! :)

Title: Breaking a form with a partial

Body:
I would make a partial call with locals (f) and a collection (field_name symbols).

So i would create an array in my controller in the corresponding action like this.

Edit Actually you could create a before action: before_action :field_names, only: [:new, :edit]

def field_names
  # %i creates an array of symbols
  @field_names = %i(objectives settings related_objects ...)
end

And then in your form you can call:

With the "as:" you can now access an instance of the @fields_names
called "field_name" in each partial

 <%= render partial: "fields", collection: @field_names, as: :field_name,
 locals: {f: f} %>

And then you can inset field_name and f in your _fields.html.erb

<div class="field">
 <%= f.label field_name %><br>
 <%= f.cktext_area field_name %>
</div>

The smart thing about collection is that it will automatically render the same number of times as there are values in the array.

Look for more in the section Local variables in the guide

Good luck! :)


问:
External CSS - Best method for different color for content area on 1/2 the site
I'm learning External CSS.

I have a CSS file that is working.  The pages use a background image and a content color.

I want to use a different content color as the background for photos--- about 1/2 of the pages in the site.  I want it to be in Ext CSS (not a page style), in case I want to change the color in the future.

What is the best practice when everything else in the CSS will be the same for all pages, except for the content color?

Please give a 'grade school' answer telling me exactly what I'll need to do.  I'm still learning terminology, so your clarity will really help me.

Thank you.

答:
The best way is use SASS and variables.

Another solution (pure css) is to create a body class to determine your theme.

Example:

```<code><body class="theme1"> or <body class="theme2">
</code>```

And set your css:

```<code>.theme1 .my-div
.theme2 .my-div
</code>```

With your theme colors

Body:
The best way is use SASS and variables.

Another solution (pure css) is to create a body class to determine your theme.

Example:

<body class="theme1"> or <body class="theme2">

And set your css:

.theme1 .my-div
.theme2 .my-div

With your theme colors


问:
Apple Mach-O Linker Error when compiling for device
I've just upgraded to xcode 4.0 and I can no longer deploy to iPhone, I get a Apple Mach-O Linker Error, it still works for the simulator though.</p>

```<code>    Ld /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Intermediates/iParcel.build/Debug-iphoneos/iParcel.build/Objects-normal/armv7/iParcel normal armv7
    cd /Users/yveswheeler/iParcel
    setenv IPHONEOS_DEPLOYMENT_TARGET 3.2
    setenv PATH "/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/g++-4.2 -arch armv7 -isysroot /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk -L/Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos -F/Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos -filelist /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Intermediates/iParcel.build/Debug-iphoneos/iParcel.build/Objects-normal/armv7/iParcel.LinkFileList -dead_strip -all_load -ObjC -lxml2 -miphoneos-version-min=3.2 -framework UIKit -framework CoreGraphics -framework QuartzCore /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20.a /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20Core.a /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20Network.a /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20Style.a /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20UI.a /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20UICommon.a /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20UINavigator.a -framework AddressBook -lz.1.2.3 -framework Foundation -framework CFNetwork -framework MobileCoreServices -framework SystemConfiguration -framework MessageUI -framework AudioToolbox -o /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Intermediates/iParcel.build/Debug-iphoneos/iParcel.build/Objects-normal/armv7/iParcel

arm-apple-darwin10-g++-4.2.1: /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20.a: No such file or directory
arm-apple-darwin10-g++-4.2.1: /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20Core.a: No such file or directory
arm-apple-darwin10-g++-4.2.1: /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20Network.a: No such file or directory
arm-apple-darwin10-g++-4.2.1: /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20Style.a: No such file or directory
arm-apple-darwin10-g++-4.2.1: /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20UI.a: No such file or directory
arm-apple-darwin10-g++-4.2.1: /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20UICommon.a: No such file or directory
arm-apple-darwin10-g++-4.2.1: /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20UINavigator.a: No such file or directory
Command /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/g++-4.2 failed with exit code 1
</code>```

答:
None of these answers helped me. Then I tried to reinstall Cocoapods:

```<code>pod deintegrate

pod install
</code>```

Problem solved!

Body:
I've just upgraded to xcode 4.0 and I can no longer deploy to iPhone, I get a Apple Mach-O Linker Error, it still works for the simulator though.

    Ld /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Intermediates/iParcel.build/Debug-iphoneos/iParcel.build/Objects-normal/armv7/iParcel normal armv7
    cd /Users/yveswheeler/iParcel
    setenv IPHONEOS_DEPLOYMENT_TARGET 3.2
    setenv PATH "/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/g++-4.2 -arch armv7 -isysroot /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk -L/Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos -F/Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos -filelist /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Intermediates/iParcel.build/Debug-iphoneos/iParcel.build/Objects-normal/armv7/iParcel.LinkFileList -dead_strip -all_load -ObjC -lxml2 -miphoneos-version-min=3.2 -framework UIKit -framework CoreGraphics -framework QuartzCore /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20.a /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20Core.a /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20Network.a /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20Style.a /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20UI.a /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20UICommon.a /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20UINavigator.a -framework AddressBook -lz.1.2.3 -framework Foundation -framework CFNetwork -framework MobileCoreServices -framework SystemConfiguration -framework MessageUI -framework AudioToolbox -o /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Intermediates/iParcel.build/Debug-iphoneos/iParcel.build/Objects-normal/armv7/iParcel

arm-apple-darwin10-g++-4.2.1: /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20.a: No such file or directory
arm-apple-darwin10-g++-4.2.1: /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20Core.a: No such file or directory
arm-apple-darwin10-g++-4.2.1: /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20Network.a: No such file or directory
arm-apple-darwin10-g++-4.2.1: /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20Style.a: No such file or directory
arm-apple-darwin10-g++-4.2.1: /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20UI.a: No such file or directory
arm-apple-darwin10-g++-4.2.1: /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20UICommon.a: No such file or directory
arm-apple-darwin10-g++-4.2.1: /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20UINavigator.a: No such file or directory
Command /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/g++-4.2 failed with exit code 1

Body:
None of these answers helped me. Then I tried to reinstall Cocoapods:

pod deintegrate

pod install

Problem solved!


问:
how to get "xyz" text from span, I tried css but protractor did not identify it
```<code><div>
<span tabindex="0" style="font-weight:bold;font-size:28pt;">xyz</span>
</div>
</code>```

how to get "xyz" text from span, I tried css but protractor did not identify it

答:
First of all your selector should look like:
div > span

You don't have [...] > td > span.

And then .getText() on that element.

Body:
xyz

how to get "xyz" text from span, I tried css but protractor did not identify it


问:
invalid operands of types 'const char [26]' and 'LPSTR '
My code is

```<code>string  str = "C:\\Users\\mardare\\Downloads\\config";
LPSTR lp = const_cast<char *>(str.c_str());
MessageBox ( NULL, "The selected folder is : "+lp, "Bye!", MB_OK );
</code>```

And when I try to build it and run i get this error

invalid operands of types 'const char [26]' and 'LPSTR'

答:
LPSTR represents a char *-type, and string literal "The ..." denotes a const char[26]. You get the error because in your expression "The selected folder is : "+lp, you try to "concatenate" them with operator +, which is not supported for members of type const char* or char *.

Operator + is, however, supported for members of type std::string; So you could work around this by, for example, the following code:

```<code>string folder = "The selected folder is : " + str;
MessageBox ( NULL, folder.c_str(), "Bye!", MB_OK );
</code>```

Body:
My code is

string  str = "C:\\Users\\mardare\\Downloads\\config";
LPSTR lp = const_cast<char *>(str.c_str());
MessageBox ( NULL, "The selected folder is : "+lp, "Bye!", MB_OK );

And when I try to build it and run i get this error

invalid operands of types 'const char [26]' and 'LPSTR'

Body:
LPSTR represents a char *-type, and string literal "The ..." denotes a const char[26]. You get the error because in your expression "The selected folder is : "+lp, you try to "concatenate" them with operator +, which is not supported for members of type const char* or char *.

Operator + is, however, supported for members of type std::string; So you could work around this by, for example, the following code:

string folder = "The selected folder is : " + str;
MessageBox ( NULL, folder.c_str(), "Bye!", MB_OK );


问:
Possible to use Camel's XSLT component with dynamic templates?
By dynamic templates, I don't mean a dynamic URI.  I mean the template itself which is assembled from pieces sitting in a database, transformed in various ways, has images inserted into it, etc.  All this is done within my Camel Routes. The finished XSLT template is sitting in an exchange property and now I want to run the message body XML through that XSLT.

Unlike the XQuery component which provides a lot of flexibility, it seems that the template file must come from only an external source with the XSLT component. Am I forced to write it out as a file first?

答:
Set the option contentCache=false then the template is re-read on each message. Then it can load eg from a file, where you can then update the file with new content as you want.

To add support for using bean or ref as the resource, so you can call a bean etc, is currently not supported but I logged a ticket so we will add that in a future release: https://issues.apache.org/jira/browse/CAMEL-11514


问:
Convert paperclip pdf from S3 to base64 (Rails)
I'm sending a base64 of a PDF to an external API endpoint in a Rails app.

This occurs regularly with different PDFs for different users. I'm currently using the Paperclip gem.

The problem is getting the PDF into a format that I can then convert to base64.

Below works if I start with a PDF locally and .read it, but not when it comes from S3.

Code:

```<code>def self.get_pdf(upload_id)

  # get URL for file in S3 (for directly accessing the PDF in browser)
  # `.generic` implemented via `has_attached_file :generic` in model
  # `.expiring_url` is paperclip syntax for generating a URL
  s3_url = Upload
      .find(upload_id)
      .generic
      .expiring_url(100)

  # open file from URL
  file = open(s3_url)

  # read file
  pdf = File.read(file)

  # convert to base64
  base64 = Base64.encode64(File.open(pdf, "rb").read)
end
</code>```

Error:

OpenURI::HTTPError (404 Not Found):

Ideally this can just occur in memory instead of actually download the file.

Streaming-in a base64 from S3 while streaming out the API request would be awesome but I don't think thats an option here.

UPDATE:

signed URLs from Cyberduck + Michael's answer will work

paperclip URLs fail + Michael's answer results in below error

Error:

The specified key does not exist.

Unfortunately I need to use Paperclip so I can generate links and download PDFs on the fly, based on the uploads table records in my db.

Is there is a technicality about paperclip links I don't understand?

答:
```<code>base64 =  Base64.encode64( get_me(s3_url).body ).gsub("\n", '')

def get_me(url)
    uri = URI(url)
    req = Net::HTTP::Get.new(uri)
    req['Any_header_you_might_need'] = 'idem'
    res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http|
      http.request(req)
    end
    return res
  end
</code>```

Body:
I'm sending a base64 of a PDF to an external API endpoint in a Rails app.

This occurs regularly with different PDFs for different users. I'm currently using the Paperclip gem.

The problem is getting the PDF into a format that I can then convert to base64.

Below works if I start with a PDF locally and .read it, but not when it comes from S3.

Code:

def self.get_pdf(upload_id)

  # get URL for file in S3 (for directly accessing the PDF in browser)
  # `.generic` implemented via `has_attached_file :generic` in model
  # `.expiring_url` is paperclip syntax for generating a URL
  s3_url = Upload
      .find(upload_id)
      .generic
      .expiring_url(100)

  # open file from URL
  file = open(s3_url)

  # read file
  pdf = File.read(file)

  # convert to base64
  base64 = Base64.encode64(File.open(pdf, "rb").read)
end

Error:

OpenURI::HTTPError (404 Not Found):

Ideally this can just occur in memory instead of actually download the file.

Streaming-in a base64 from S3 while streaming out the API request would be awesome but I don't think thats an option here.

UPDATE:

signed URLs from Cyberduck + Michael's answer will work

paperclip URLs fail + Michael's answer results in below error

Error:

The specified key does not exist.

Unfortunately I need to use Paperclip so I can generate links and download PDFs on the fly, based on the uploads table records in my db.

Is there is a technicality about paperclip links I don't understand?


问:
Jackson Adding a Custom Serializer for all fields of Type X
I have a class like this:

```<code>public class Foo {
    private Integer id;
    private FooB fooA;
    private boolean isB;
    private boolean isC;
    private int age;
    private LocalDate date1;
    private LocalDate date2;
    private LocalDate date3;
    private LocalDate date4;
}
</code>```

I want to serialize everything in this class natively except for the LocalDate fields. I have a custom serializer for that like so:

```<code>public class LocalDateSerializer extends JsonSerializer<LocalDate> {
    @Override
    public void serialize(LocalDate localDate, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
        //serialize
    }
}
</code>```

Is there a way to annotate the class Foo to say only use the serializer for objects of type LocalDate or do I have to go annotate each individual field like so:

```<code>public class Foo {
    private Integer id;
    private FooB fooA;
    private boolean isB;
    private boolean isC;
    private int age;
    @JsonSerialize(using = LocalDateSerializer.class)
    private LocalDate date1;
    @JsonSerialize(using = LocalDateSerializer.class)
    private LocalDate date2;
    @JsonSerialize(using = LocalDateSerializer.class)
    private LocalDate date3;
    @JsonSerialize(using = LocalDateSerializer.class)
    private LocalDate date4;
}
</code>```

My question is, can I consolidate that into a single class level annotation?

答:
I couldn't find a solution that uses only one annotation in the class. Probably annotating each field is the best you can get.

Another way is to configure the ObjectMapper programatically:

```<code>ObjectMapper om = new ObjectMapper();
JavaTimeModule module = new JavaTimeModule();
module.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("dd/MM/yyyy")));
om.registerModule(module);
</code>```

The addSerializer method maps all LocalDate fields to use the specified serializer. In the example above, I used the built-in com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer with a DateTimeFormatter, but of course you can replace it with any serializer you want (including your custom one).

If you don't want to (or can't) configure the ObjectMapper, then using the annotations on each field seems to be the best solution.

Body:
I have a class like this:

public class Foo {
    private Integer id;
    private FooB fooA;
    private boolean isB;
    private boolean isC;
    private int age;
    private LocalDate date1;
    private LocalDate date2;
    private LocalDate date3;
    private LocalDate date4;
}

I want to serialize everything in this class natively except for the LocalDate fields. I have a custom serializer for that like so:

public class LocalDateSerializer extends JsonSerializer<LocalDate> {
    @Override
    public void serialize(LocalDate localDate, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
        //serialize
    }
}

Is there a way to annotate the class Foo to say only use the serializer for objects of type LocalDate or do I have to go annotate each individual field like so:

public class Foo {
    private Integer id;
    private FooB fooA;
    private boolean isB;
    private boolean isC;
    private int age;
    @JsonSerialize(using = LocalDateSerializer.class)
    private LocalDate date1;
    @JsonSerialize(using = LocalDateSerializer.class)
    private LocalDate date2;
    @JsonSerialize(using = LocalDateSerializer.class)
    private LocalDate date3;
    @JsonSerialize(using = LocalDateSerializer.class)
    private LocalDate date4;
}

My question is, can I consolidate that into a single class level annotation?

Body:
I couldn't find a solution that uses only one annotation in the class. Probably annotating each field is the best you can get.

Another way is to configure the ObjectMapper programatically:

ObjectMapper om = new ObjectMapper();
JavaTimeModule module = new JavaTimeModule();
module.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("dd/MM/yyyy")));
om.registerModule(module);

The addSerializer method maps all LocalDate fields to use the specified serializer. In the example above, I used the built-in com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer with a DateTimeFormatter, but of course you can replace it with any serializer you want (including your custom one).

If you don't want to (or can't) configure the ObjectMapper, then using the annotations on each field seems to be the best solution.