问:
How can I solve "crontab: your UID isn't in the passwd file. bailing out."?
Hi I'm using Docker and whenever to write cron schedule rules, but when I run whenever --update-crontab in my docker container this errors is showing to me.

```<code>crontab: your UID isn't in the passwd file.
bailing out.
[fail] Couldn't write crontab; try running `whenever' with no options to ensure your schedule file is valid.
</code>```

Dockerfile

```<code>FROM ruby:2.4.1-slim
RUN apt-get update && apt-get -y install cron
ENV RAILS_ENV production

ENV INSTALL_PATH /app

RUN mkdir -p $INSTALL_PATH
WORKDIR $INSTALL_PATH

COPY Gemfile Gemfile.lock ./
RUN bundle install --binstubs --jobs 20 --retry 5

COPY . .
RUN chown -R nobody:nogroup /app
USER nobody

# use docker run -it --entrypoint="" demo "ls -la" to skip
EXPOSE 3000

CMD puma -C config/puma.rb
</code>```

Docker Version: Docker version 17.05.0-ce, build 89658be

My Docker compose file

```<code>  chatbot_web:
    container_name: chatbot_web
    depends_on:
      - postgres
      - chatbot_redis
      - chatbot_lita
    user: "1000:1000"
    build: .
    image: dpe/chatbot
    ports:
      - '3000:3000'
    volumes:
      - '.:/app'
    restart: always
</code>```

How can I solve this?

EDIT:
When I use:

```<code>host$ docker run -it dpe/chatbot bash
container $ whenever --update-cron
[write] crontab file updated
</code>```

Works, but when I use:

```<code>host$ docker exec -it chatbot_web bash
I have no name!@352c6a7500d2:/app$ whenever --update-cron
crontab: your UID isn't in the passwd file.
bailing out.
[fail] Couldn't write crontab; try running `whenever' with no options to ensure your schedule file is valid.
</code>```

Don't Work =(

答:
To fix I use same user in Dockerfile and docker-compose

Dockerfile

```<code>RUN chown -R nobody:nogroup /app
USER nobody
</code>```

Docker Compose

```<code>  chatbot_web:
    user: "nobody:nogroup"
</code>```

Body:
Hi I'm using Docker and whenever to write cron schedule rules, but when I run whenever --update-crontab in my docker container this errors is showing to me.

crontab: your UID isn't in the passwd file.
bailing out.
[fail] Couldn't write crontab; try running `whenever' with no options to ensure your schedule file is valid.

Dockerfile

FROM ruby:2.4.1-slim
RUN apt-get update && apt-get -y install cron
ENV RAILS_ENV production

ENV INSTALL_PATH /app

RUN mkdir -p $INSTALL_PATH
WORKDIR $INSTALL_PATH

COPY Gemfile Gemfile.lock ./
RUN bundle install --binstubs --jobs 20 --retry 5

COPY . .
RUN chown -R nobody:nogroup /app
USER nobody

# use docker run -it --entrypoint="" demo "ls -la" to skip
EXPOSE 3000

CMD puma -C config/puma.rb

Docker Version: Docker version 17.05.0-ce, build 89658be

My Docker compose file

  chatbot_web:
    container_name: chatbot_web
    depends_on:
      - postgres
      - chatbot_redis
      - chatbot_lita
    user: "1000:1000"
    build: .
    image: dpe/chatbot
    ports:
      - '3000:3000'
    volumes:
      - '.:/app'
    restart: always

How can I solve this?

EDIT:
When I use:

host$ docker run -it dpe/chatbot bash
container $ whenever --update-cron
[write] crontab file updated

Works, but when I use:

host$ docker exec -it chatbot_web bash
I have no name!@352c6a7500d2:/app$ whenever --update-cron
crontab: your UID isn't in the passwd file.
bailing out.
[fail] Couldn't write crontab; try running `whenever' with no options to ensure your schedule file is valid.

Don't Work =(

Body:
To fix I use same user in Dockerfile and docker-compose

Dockerfile

RUN chown -R nobody:nogroup /app
USER nobody

Docker Compose

  chatbot_web:
    user: "nobody:nogroup"


来源: stackexchange

问:
Optional route data with default value in MVC
I have this routing:

```<code>app.UseMvc(routes =>
            {
                routes.MapRoute(
                name: "default",
                template: "{culture=en-US}/{controller=Home}/{action=Index}/{p1?}/{p2?}");
            });
</code>```

The last two items are optional and actually they don't exist in most of pages and is for a specific page (That also I want it to be the landing page) however its not letting to define values for optional parameters.

I tried {p1?=somevalue} and I got an error telling me that ? must be the last character. {p1=somevalue?} doesn't work either.

答:
Shouldn't it be:

```<code>routes.MapRoute(
    name: "default",
    url: "{culture}/{controller}/{action}/{p1}/{p2}",
    defaults: new
    {
        culture = "en-US",
        controller = "Home",
        action = "Index",
        p1 = UrlParameter.Optional,
        p2 = UrlParameter.Optional
    }
);
</code>```

Then your method signature would be something like this to set defaults:

```<code>public ActionResult Index(var p1 = defaultValue, var p2 = defaultValue)
</code>```

As far as I know, you wouldn't be able to set defaults site wide, only for each action they apply to.

Whereas you look like you're trying to use the RouteAttribute which works the way you have attempted:

```<code>[HttpGet("{p1:var?}{p2:var?}"]
public ActionResult Index(var p1 = defaultValue, var p2 = defaultValue)
</code>```

Please note: I've used var as I don't know what your method signatures are and defaultValue because I don't know your defaults.

ContentLicense: CC BY-SA 3.0

Body:
I have this routing:

app.UseMvc(routes =>
            {
                routes.MapRoute(
                name: "default",
                template: "{culture=en-US}/{controller=Home}/{action=Index}/{p1?}/{p2?}");
            });

The last two items are optional and actually they don't exist in most of pages and is for a specific page (That also I want it to be the landing page) however its not letting to define values for optional parameters.

I tried {p1?=somevalue} and I got an error telling me that ? must be the last character. {p1=somevalue?} doesn't work either.

Body:
Shouldn't it be:

routes.MapRoute(
    name: "default",
    url: "{culture}/{controller}/{action}/{p1}/{p2}",
    defaults: new
    {
        culture = "en-US",
        controller = "Home",
        action = "Index",
        p1 = UrlParameter.Optional,
        p2 = UrlParameter.Optional
    }
);

Then your method signature would be something like this to set defaults:

public ActionResult Index(var p1 = defaultValue, var p2 = defaultValue)

As far as I know, you wouldn't be able to set defaults site wide, only for each action they apply to.

Whereas you look like you're trying to use the RouteAttribute which works the way you have attempted:

[HttpGet("{p1:var?}{p2:var?}"]
public ActionResult Index(var p1 = defaultValue, var p2 = defaultValue)

Please note: I've used var as I don't know what your method signatures are and defaultValue because I don't know your defaults.


问:
Convert Ruby Date to Integer
How can I convert a Ruby Date to an integer?</p>

ContentLicense: CC BY-SA 2.5

Title: Convert Ruby Date to Integer

Body:
t = Time.now
# => 2010-12-20 11:20:31 -0700

# Seconds since epoch
t.to_i
#=> 1292869231

require 'date'
d = Date.today
#=> #<Date: 2010-12-20 (4911101/2,0,2299161)>

epoch = Date.new(1970,1,1)
#=> #<Date: 1970-01-01 (4881175/2,0,2299161)>

d - epoch
#=> (14963/1)

# Days since epoch
(d - epoch).to_i
#=> 14963

# Seconds since epoch
d.to_time.to_i
#=> 1292828400


问:
Stata : distinct values, count and histogram
I am new to Stata and still learning.
I have a var shaped like that :

```<code>+-------+
| Phase |
+-------+
| I     |
+-------+
| I     |
+-------+
| II    |
+-------+
| III   |
+-------+
| II    |
+-------+
</code>```

My goal is to draw a histogram with the possible value (I,II,III) (x-axis) and the number of each (2,2,1) (y-axis).

I though I could make a loop and store the number of each possible in an array but arrays does not seem to be implemented in Stata.

Is the any kind of function that do what I want already implemented or I have to write a function to distinct the value, then count them, then draw the histogram ?

Thank you.

/edit :

```<code>processed.p |
       hase |      Freq.     Percent        Cum.
------------+-----------------------------------
          I |        266        0.92        0.92
       I/II |      1,006        3.50        4.42
         II |     10,867       37.76       42.18
     II/III |        344        1.20       43.37
        III |      9,248       32.13       75.51
         IV |      6,984       24.27       99.77
         NA |         65        0.23      100.00
------------+-----------------------------------
      Total |     28,780      100.00
</code>```

I found a way of counting distinct values.

Body:
I am new to Stata and still learning.
I have a var shaped like that :

+-------+
| Phase |
+-------+
| I     |
+-------+
| I     |
+-------+
| II    |
+-------+
| III   |
+-------+
| II    |
+-------+

My goal is to draw a histogram with the possible value (I,II,III) (x-axis) and the number of each (2,2,1) (y-axis).

I though I could make a loop and store the number of each possible in an array but arrays does not seem to be implemented in Stata.

Is the any kind of function that do what I want already implemented or I have to write a function to distinct the value, then count them, then draw the histogram ?

Thank you.

/edit :

processed.p |
       hase |      Freq.     Percent        Cum.
------------+-----------------------------------
          I |        266        0.92        0.92
       I/II |      1,006        3.50        4.42
         II |     10,867       37.76       42.18
     II/III |        344        1.20       43.37
        III |      9,248       32.13       75.51
         IV |      6,984       24.27       99.77
         NA |         65        0.23      100.00
------------+-----------------------------------
      Total |     28,780      100.00

I found a way of counting distinct values.

Body:
I found the solution :

tab processedphase, matcell(x)

in order to obtain

processed.p |
       hase |      Freq.     Percent        Cum.
------------+-----------------------------------
          I |        266        0.92        0.92
       I/II |      1,006        3.50        4.42
         II |     10,867       37.76       42.18
     II/III |        344        1.20       43.37
        III |      9,248       32.13       75.51
         IV |      6,984       24.27       99.77
         NA |         65        0.23      100.00
------------+-----------------------------------
      Total |     28,780      100.00

then :

matrix list x
svmat x


问:
WebAPI returns corrupted, incomplete file
I want to return an image from WebApi endpoint. This is my method:

```<code>[System.Web.Http.HttpGet]
public HttpResponseMessage GetAttachment(string id)
{
    string dirPath = HttpContext.Current.Server.MapPath(Constants.ATTACHMENT_FOLDER);
    string path = string.Format($"{dirPath}\\{id}.jpg");

    try
    {
        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        var stream = new FileStream(path, FileMode.Open, FileAccess.Read);

        var content = new StreamContent(stream);
        result.Content = content;
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = Path.GetFileName(path) };
        return result;
    }
    catch (FileNotFoundException ex)
    {
        _log.Warn($"Image {path} was not found on the server.");
        return Request.CreateResponse(HttpStatusCode.NotFound, "Invalid image ID");
    }
}
</code>```

Unfortunately, the file that is downloaded is incomplete. The message in consuming Android app is:

java.io.EOFException: source exhausted prematurely

答:
The problem is most likely that your Android client thinks the download is over before it actually is.

To easily fix this, you can use this method instead which will return the entire file at once (rather than streaming it):

```<code>result.Content = new ByteArrayContent(File.ReadAllBytes(path));
</code>```

Body:
I want to return an image from WebApi endpoint. This is my method:

[System.Web.Http.HttpGet]
public HttpResponseMessage GetAttachment(string id)
{
    string dirPath = HttpContext.Current.Server.MapPath(Constants.ATTACHMENT_FOLDER);
    string path = string.Format($"{dirPath}\\{id}.jpg");

    try
    {
        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        var stream = new FileStream(path, FileMode.Open, FileAccess.Read);

        var content = new StreamContent(stream);
        result.Content = content;
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = Path.GetFileName(path) };
        return result;
    }
    catch (FileNotFoundException ex)
    {
        _log.Warn($"Image {path} was not found on the server.");
        return Request.CreateResponse(HttpStatusCode.NotFound, "Invalid image ID");
    }
}

Unfortunately, the file that is downloaded is incomplete. The message in consuming Android app is:

java.io.EOFException: source exhausted prematurely

Body:
The problem is most likely that your Android client thinks the download is over before it actually is.

To easily fix this, you can use this method instead which will return the entire file at once (rather than streaming it):

result.Content = new ByteArrayContent(File.ReadAllBytes(path));


问:
Spring Boot JPA repositories custom query
http://spring.io/guides/gs/accessing-data-jpa/

Referred the above link to define a custom query.

We have a developed a Spring boot web service CRUD application but we are facing the following exception when we add a custom query.

```<code> org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'EmployeeController': Unsatisfied dependency expressed through field 'EmployeeService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'EmployeeServiceImpl': Unsatisfied dependency expressed through field 'EmployeeRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'EmployeeRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property name found for type Employee!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'EmployeeServiceImpl': Unsatisfied dependency expressed through field 'EmployeeRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'EmployeeRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property name found for type Employee!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'EmployeeRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property name found for type Employee!
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property name found for type Employee!
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:77) ~[spring-data-commons-1.13.4.RELEASE.jar:naat org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:309) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:272) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
</code>```

This was the repository interface that I have defined. Defined a custom query.

```<code>package com.example.rest.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.rest.model.Employee;
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
Employee findByName(String employeeName);}
</code>```

This is my service interface

```<code>package com.example.rest.service;
import java.util.List;
import com.example.rest.model.Employee;
public interface EmployeeService {

Employee save(Employee employee);
Employee getById(Long employeeId);
void delete(Long employeeId);
List<Employee> findAll();
Employee findByName(String employeeName); }
</code>```

This is my Service Implementation class

```<code>package com.example.rest.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.rest.model.Employee;
import com.example.rest.repository.EmployeeRepository;

@Service
public class EmployeeServiceImpl implements EmployeeService {

@Autowired
EmployeeRepository employeeRepository;

@Override
public Employee save(Employee employee) {
    // TODO Auto-generated method stub
    return employeeRepository.save(employee);
}

@Override
public Employee getById(Long employeeId) {
    // TODO Auto-generated method stub
    return employeeRepository.getOne(employeeId);
}

@Override
public void delete(Long employeeId) {
    // TODO Auto-generated method stub
    employeeRepository.delete(employeeId);
}

@Override
public List<Employee> findAll() {
    // TODO Auto-generated method stub
    return employeeRepository.findAll();
}

@Override
public Employee findByName(String employeeName) {
    // TODO Auto-generated method stub
    return employeeRepository.findByName(employeeName);
}}
</code>```

Without custom query my application works fine.
Let me know where I have made a mistake.

I have added the model class

```<code>package com.example.rest.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="testF")
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(nullable=false, unique=true)
private Long employeeId;

@Column(nullable=false, unique=true)
private String employeeName;

@Column(nullable=false)
private String emailId;

@Column(nullable=false)
private Long salary;

public Employee() {
}

public Employee(Long employeeId, String employeeName, String emailId, Long salary) {
this.employeeId = employeeId;
this.employeeName = employeeName;
this.emailId = emailId;
this.salary = salary;
}

public Long getEmployeeId() {
return employeeId;
}

public void setEmployeeId(Long employeeId) {
this.employeeId = employeeId;
}

public String getEmployeeName() {
return employeeName;
}

public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}

public String getEmailId() {
return emailId;
}

public void setEmailId(String emailId) {
this.emailId = emailId;
}

public Long getSalary() {
return salary;
}

public void setSalary(Long salary) {
this.salary = salary;
}

@Override
public String toString() {
return "Employee [employeeId=" + employeeId + ", employeeName=" + employeeName + ", emailId=" + emailId
+ ", salary=" + salary + "]";
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((employeeId == null) ? 0 : employeeId.hashCode());
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (employeeId == null) {
if (other.employeeId != null)
return false;
} else if (!employeeId.equals(other.employeeId))
return false;
return true;
}}
</code>```

答:
you don't have field 'name' in class Employee.

spring data try created query for search Employee with field name.

```<code>Employee findByName(String employeeName);}
</code>```

Body:
http://spring.io/guides/gs/accessing-data-jpa/

Referred the above link to define a custom query.

We have a developed a Spring boot web service CRUD application but we are facing the following exception when we add a custom query.

 org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'EmployeeController': Unsatisfied dependency expressed through field 'EmployeeService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'EmployeeServiceImpl': Unsatisfied dependency expressed through field 'EmployeeRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'EmployeeRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property name found for type Employee!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'EmployeeServiceImpl': Unsatisfied dependency expressed through field 'EmployeeRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'EmployeeRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property name found for type Employee!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'EmployeeRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property name found for type Employee!
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property name found for type Employee!
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:77) ~[spring-data-commons-1.13.4.RELEASE.jar:naat org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:309) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:272) ~[spring-data-commons-1.13.4.RELEASE.jar:na]

This was the repository interface that I have defined. Defined a custom query.

package com.example.rest.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.rest.model.Employee;
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
Employee findByName(String employeeName);}

This is my service interface

package com.example.rest.service;
import java.util.List;
import com.example.rest.model.Employee;
public interface EmployeeService {

Employee save(Employee employee);
Employee getById(Long employeeId);
void delete(Long employeeId);
List<Employee> findAll();
Employee findByName(String employeeName); }

This is my Service Implementation class

package com.example.rest.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.rest.model.Employee;
import com.example.rest.repository.EmployeeRepository;

@Service
public class EmployeeServiceImpl implements EmployeeService {

@Autowired
EmployeeRepository employeeRepository;

@Override
public Employee save(Employee employee) {
    // TODO Auto-generated method stub
    return employeeRepository.save(employee);
}

@Override
public Employee getById(Long employeeId) {
    // TODO Auto-generated method stub
    return employeeRepository.getOne(employeeId);
}

@Override
public void delete(Long employeeId) {
    // TODO Auto-generated method stub
    employeeRepository.delete(employeeId);
}

@Override
public List<Employee> findAll() {
    // TODO Auto-generated method stub
    return employeeRepository.findAll();
}

@Override
public Employee findByName(String employeeName) {
    // TODO Auto-generated method stub
    return employeeRepository.findByName(employeeName);
}}

Without custom query my application works fine.
Let me know where I have made a mistake.

I have added the model class

package com.example.rest.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="testF")
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(nullable=false, unique=true)
private Long employeeId;

@Column(nullable=false, unique=true)
private String employeeName;

@Column(nullable=false)
private String emailId;

@Column(nullable=false)
private Long salary;

public Employee() {
}

public Employee(Long employeeId, String employeeName, String emailId, Long salary) {
this.employeeId = employeeId;
this.employeeName = employeeName;
this.emailId = emailId;
this.salary = salary;
}

public Long getEmployeeId() {
return employeeId;
}

public void setEmployeeId(Long employeeId) {
this.employeeId = employeeId;
}

public String getEmployeeName() {
return employeeName;
}

public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}

public String getEmailId() {
return emailId;
}

public void setEmailId(String emailId) {
this.emailId = emailId;
}

public Long getSalary() {
return salary;
}

public void setSalary(Long salary) {
this.salary = salary;
}

@Override
public String toString() {
return "Employee [employeeId=" + employeeId + ", employeeName=" + employeeName + ", emailId=" + emailId
+ ", salary=" + salary + "]";
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((employeeId == null) ? 0 : employeeId.hashCode());
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (employeeId == null) {
if (other.employeeId != null)
return false;
} else if (!employeeId.equals(other.employeeId))
return false;
return true;
}}

Body:
you don't have field 'name' in class Employee.

spring data try created query for search Employee with field name.

Employee findByName(String employeeName);}


问:
Obj-C - POST JSON data to server?
Sorry for the newb question, but I am tearing my hair out over this one. I can successfully POST data to my endpoint URL via a program like FireFox's POSTER. However, I'm trying to post that same JSON data from my app to my endpoint URL (Drupal services push_notifications end point), and for some reason it will not POST successfully. Here is the code that I'm using:

ViewController.m

```<code>NSString *urlString1 = @"http://app.com/endpoint001/push_notifications";
 NSDictionary *jsonBodyDict = @{@"token":postDeviceID, @"type":@"ios"};
 NSData *jsonBodyData = [NSJSONSerialization dataWithJSONObject:jsonBodyDict options:kNilOptions error:nil];
 // watch out: error is nil here, but you never do that in production code. Do proper checks!

 NSString *urlString2 = [NSString stringWithFormat:@"http://app.com/endpoint001/push_notifications?token=%@&type=%@",
                         postDeviceID,@"ios"];

 NSMutableURLRequest *request = [NSMutableURLRequest new];
 request.HTTPMethod = @"POST";

 // for alternative 1:
 [request setURL:[NSURL URLWithString:urlString1]];
 [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
 [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
 [request setHTTPBody:jsonBodyData];
 [request addValue:csrfToken forHTTPHeaderField:@"X-CSRF-Token"];

 // for alternative 2:
 [request setURL:[NSURL URLWithString:urlString2]];
 // no body needed, though that ultimately depends on your server. Also, I didn't test this for lack of a backend :)

 NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
 NSURLSession *session = [NSURLSession sessionWithConfiguration:config
                                                       delegate:nil
                                                  delegateQueue:[NSOperationQueue mainQueue]];
 NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                         completionHandler:^(NSData * _Nullable data,
                                                             NSURLResponse * _Nullable response,
                                                             NSError * _Nullable error) {
                                             NSLog(@"Yay, done! Check for errors in response!");

                                             NSHTTPURLResponse *asHTTPResponse = (NSHTTPURLResponse *) response;
                                             NSLog(@"The response is: %@", asHTTPResponse);
                                             // set a breakpoint on the last NSLog and investigate the response in the debugger

                                             // if you get data, you can inspect that, too. If it's JSON, do one of these:
                                             NSDictionary *forJSONObject = [NSJSONSerialization JSONObjectWithData:data
                                                                                options:kNilOptions
                                                                                error:nil];
                                             // or
                                             NSArray *forJSONArray = [NSJSONSerialization JSONObjectWithData:data
                                                                                options:kNilOptions
                                                                                error:nil];

                                             NSLog(@"One of these might exist - object: %@ \n array: %@", forJSONObject, forJSONArray);

                                         }];
 [task resume];
</code>```

Note: I've put this code in AFTER my user already successfully logs in, so I'm not sure starting a whole new connection is necessary? How can I POST my data to the server if a session and CSRF Token already exists? What should my code look like? Whoever answers this question is going on my Christmas list... O_O

NSLog Response:

```<code>2017-07-17 17:31:11.421281-0700 app[977:206852] Yay, done! Check for errors in response!
2017-07-17 17:31:11.422198-0700 app[977:206852] The response is: <NSHTTPURLResponse: 0x170239b40> { URL: http://app.com/endpoint001/push_notifications?token=9526687d594944513b0wabf704eae3223f0de9bf69136a0aae3ab046863474b1&type=ios } { status code: 401, headers {
    "Cache-Control" = "no-cache, must-revalidate";
    Connection = "keep-alive";
    "Content-Type" = "application/json";
    Date = "Tue, 18 Jul 2017 00:14:35 GMT";
    Expires = "Sun, 19 Nov 1978 05:00:00 GMT";
    Server = Apache;
    "Transfer-Encoding" = Identity;
    Vary = Accept;
    "X-Content-Type-Options" = nosniff;
} }
2017-07-17 17:31:27.172085-0700 app[977:207024] XPC connection interrupted
2017-07-17 17:31:27.172311-0700 app[977:206852] One of these might exist - object: (
    "CSRF validation failed"
)
 array: (
    "CSRF validation failed"
)
</code>```

答:
All the Answers are good but i am posting a method , for i proper implementation  of posting JSON data to POST API

POST Method

```<code>    -(void)postServiceAPI:(NSString*)url andParameters:(NSString *)parameterString andCompletionHandler:(void(^)(NSData *data,NSError *error,BOOL networkError))compilationHandler
        {

     // Checking the Network availability : You can skip this check
             Reachability *netConnectionReach = [Reachability reachabilityWithHostname:@"www.google.com"];
            NetworkStatus internetStatus = [netConnectionReach currentReachabilityStatus];

            if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN))
            {

                dispatch_async(dispatch_get_main_queue(), ^{

                    compilationHandler(nil,nil,TRUE);
                });

            }
            else
            {
                NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
                configuration.timeoutIntervalForRequest = 30.0;
                configuration.timeoutIntervalForResource = 60.0;
                configuration.requestCachePolicy =  NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
                _session = [NSURLSession sessionWithConfiguration:configuration];

                NSURL *urlStr = [NSURL URLWithString:url];
                NSData *postData = [parameterString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
                NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];
                NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlStr
                                                                       cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0];
                [request setHTTPMethod:@"POST"];
                [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
                [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

             // You can also set  " application/json"

  // This will solve your problem
                [ request setValue:@"Your_Token" forHTTPHeaderField:@"your_key_for_token"];

                [request setHTTPBody:postData];

                [[_session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
                  {
                      if (error)
                      {
                          dispatch_async(dispatch_get_main_queue(), ^{

                              compilationHandler(nil,error,nil);
                          });
                      }
                      else
                      {
                          dispatch_async(dispatch_get_main_queue(), ^{

                              compilationHandler(data,nil,nil);
                          });
                      }

                  }]resume];

            }

        }
</code>```

Uses:

```<code>   NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
  [dict setObject:postDeviceID forKey:@"token"];
  [dict setObject:@"iOS" forKey:@"type"];

NSData * JsonData =[NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];

    NSString *urlStr = @"http://myurl.com/endpoint01/push_notifications"
    NSString *parameterJsonString= [[NSString alloc] initWithData:JsonData encoding:NSUTF8StringEncoding];

// If you Don't want to create Dictionary than just send your Parameter JSon what you have made , please make sure if json is correct or not

 //parameterJsonString = [NSString stringWithFormat:@"token=%@&type=%@",postDeviceID,@"ios"];

    NSLog(@"URL:%@ Request :\n\n  %@",urlStr,parameterJsonString);

 [self postServiceAPI:urlStr andParameters:parameterJsonString andCompletionHandler:^(NSData *data, NSError *error, BOOL networkError) {

            // If Data Retrun By API is not nil

        if (data)
        {
            // Here is your Response
            NSDictionary *dicData=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

        }
        else
        {

            // Show Alert When data is Not Recived from API
              if (networkError)
                {
                    // No Internet Connection
                }
                else
                {
                    // Network Error

                    NSLog(@"Network Error : %@",error.description);

                }

        }
 }];
</code>```

i hope this will help you

Title: Obj-C - POST JSON data to server?

Body:
Sorry for the newb question, but I am tearing my hair out over this one. I can successfully POST data to my endpoint URL via a program like FireFox's POSTER. However, I'm trying to post that same JSON data from my app to my endpoint URL (Drupal services push_notifications end point), and for some reason it will not POST successfully. Here is the code that I'm using:

ViewController.m

NSString *urlString1 = @"http://app.com/endpoint001/push_notifications";
 NSDictionary *jsonBodyDict = @{@"token":postDeviceID, @"type":@"ios"};
 NSData *jsonBodyData = [NSJSONSerialization dataWithJSONObject:jsonBodyDict options:kNilOptions error:nil];
 // watch out: error is nil here, but you never do that in production code. Do proper checks!

 NSString *urlString2 = [NSString stringWithFormat:@"http://app.com/endpoint001/push_notifications?token=%@&type=%@",
                         postDeviceID,@"ios"];

 NSMutableURLRequest *request = [NSMutableURLRequest new];
 request.HTTPMethod = @"POST";

 // for alternative 1:
 [request setURL:[NSURL URLWithString:urlString1]];
 [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
 [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
 [request setHTTPBody:jsonBodyData];
 [request addValue:csrfToken forHTTPHeaderField:@"X-CSRF-Token"];

 // for alternative 2:
 [request setURL:[NSURL URLWithString:urlString2]];
 // no body needed, though that ultimately depends on your server. Also, I didn't test this for lack of a backend :)

 NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
 NSURLSession *session = [NSURLSession sessionWithConfiguration:config
                                                       delegate:nil
                                                  delegateQueue:[NSOperationQueue mainQueue]];
 NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                         completionHandler:^(NSData * _Nullable data,
                                                             NSURLResponse * _Nullable response,
                                                             NSError * _Nullable error) {
                                             NSLog(@"Yay, done! Check for errors in response!");

                                             NSHTTPURLResponse *asHTTPResponse = (NSHTTPURLResponse *) response;
                                             NSLog(@"The response is: %@", asHTTPResponse);
                                             // set a breakpoint on the last NSLog and investigate the response in the debugger

                                             // if you get data, you can inspect that, too. If it's JSON, do one of these:
                                             NSDictionary *forJSONObject = [NSJSONSerialization JSONObjectWithData:data
                                                                                options:kNilOptions
                                                                                error:nil];
                                             // or
                                             NSArray *forJSONArray = [NSJSONSerialization JSONObjectWithData:data
                                                                                options:kNilOptions
                                                                                error:nil];

                                             NSLog(@"One of these might exist - object: %@ \n array: %@", forJSONObject, forJSONArray);

                                         }];
 [task resume];

Note: I've put this code in AFTER my user already successfully logs in, so I'm not sure starting a whole new connection is necessary? How can I POST my data to the server if a session and CSRF Token already exists? What should my code look like? Whoever answers this question is going on my Christmas list... O_O

NSLog Response:

2017-07-17 17:31:11.421281-0700 app[977:206852] Yay, done! Check for errors in response!
2017-07-17 17:31:11.422198-0700 app[977:206852] The response is: <NSHTTPURLResponse: 0x170239b40> { URL: http://app.com/endpoint001/push_notifications?token=9526687d594944513b0wabf704eae3223f0de9bf69136a0aae3ab046863474b1&type=ios } { status code: 401, headers {
    "Cache-Control" = "no-cache, must-revalidate";
    Connection = "keep-alive";
    "Content-Type" = "application/json";
    Date = "Tue, 18 Jul 2017 00:14:35 GMT";
    Expires = "Sun, 19 Nov 1978 05:00:00 GMT";
    Server = Apache;
    "Transfer-Encoding" = Identity;
    Vary = Accept;
    "X-Content-Type-Options" = nosniff;
} }
2017-07-17 17:31:27.172085-0700 app[977:207024] XPC connection interrupted
2017-07-17 17:31:27.172311-0700 app[977:206852] One of these might exist - object: (
    "CSRF validation failed"
)
 array: (
    "CSRF validation failed"
)

Body:
All the Answers are good but i am posting a method , for i proper implementation  of posting JSON data to POST API

POST Method

    -(void)postServiceAPI:(NSString*)url andParameters:(NSString *)parameterString andCompletionHandler:(void(^)(NSData *data,NSError *error,BOOL networkError))compilationHandler
        {

     // Checking the Network availability : You can skip this check
             Reachability *netConnectionReach = [Reachability reachabilityWithHostname:@"www.google.com"];
            NetworkStatus internetStatus = [netConnectionReach currentReachabilityStatus];

            if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN))
            {

                dispatch_async(dispatch_get_main_queue(), ^{

                    compilationHandler(nil,nil,TRUE);
                });

            }
            else
            {
                NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
                configuration.timeoutIntervalForRequest = 30.0;
                configuration.timeoutIntervalForResource = 60.0;
                configuration.requestCachePolicy =  NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
                _session = [NSURLSession sessionWithConfiguration:configuration];

                NSURL *urlStr = [NSURL URLWithString:url];
                NSData *postData = [parameterString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
                NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];
                NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlStr
                                                                       cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0];
                [request setHTTPMethod:@"POST"];
                [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
                [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

             // You can also set  " application/json"

  // This will solve your problem
                [ request setValue:@"Your_Token" forHTTPHeaderField:@"your_key_for_token"];

                [request setHTTPBody:postData];

                [[_session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
                  {
                      if (error)
                      {
                          dispatch_async(dispatch_get_main_queue(), ^{

                              compilationHandler(nil,error,nil);
                          });
                      }
                      else
                      {
                          dispatch_async(dispatch_get_main_queue(), ^{

                              compilationHandler(data,nil,nil);
                          });
                      }

                  }]resume];

            }

        }

Uses:

   NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
  [dict setObject:postDeviceID forKey:@"token"];
  [dict setObject:@"iOS" forKey:@"type"];

NSData * JsonData =[NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];

    NSString *urlStr = @"http://myurl.com/endpoint01/push_notifications"
    NSString *parameterJsonString= [[NSString alloc] initWithData:JsonData encoding:NSUTF8StringEncoding];

// If you Don't want to create Dictionary than just send your Parameter JSon what you have made , please make sure if json is correct or not

 //parameterJsonString = [NSString stringWithFormat:@"token=%@&type=%@",postDeviceID,@"ios"];

    NSLog(@"URL:%@ Request :\n\n  %@",urlStr,parameterJsonString);

 [self postServiceAPI:urlStr andParameters:parameterJsonString andCompletionHandler:^(NSData *data, NSError *error, BOOL networkError) {

            // If Data Retrun By API is not nil

        if (data)
        {
            // Here is your Response
            NSDictionary *dicData=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

        }
        else
        {

            // Show Alert When data is Not Recived from API
              if (networkError)
                {
                    // No Internet Connection
                }
                else
                {
                    // Network Error

                    NSLog(@"Network Error : %@",error.description);

                }

        }
 }];

i hope this will help you


问:
Error in Intent Service in Android
I am trying to fetch some for Location Address using IntentService but ended up with error leading to app crash. Please help me.

Here is the Stacktrace:

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'void android.os.ResultReceiver.send(int, android.os.Bundle)' on a null object reference
        at com.example.ajender.sample2.FetchAddressIntentService.deliverResultToReceiver(FetchAddressIntentService.java:91)
        at com.example.ajender.sample2.FetchAddressIntentService.onHandleIntent(FetchAddressIntentService.java:81)
        at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.os.HandlerThread.run(HandlerThread.java:61)
</code>```

Here is FetchAddressIntentService:

```<code>public class FetchAddressIntentService extends IntentService {
private static String TAG="Fetch-address-Service";
protected ResultReceiver mReceiver;

/**
 * Creates an IntentService.  Invoked by your subclass's constructor.
 *
 * @param name Used to name the worker thread, important only for debugging.
 */
public FetchAddressIntentService(String name) {
    super(name);
}
public FetchAddressIntentService(){
    super("FetchAddressIntentService");
}

@Override
protected void onHandleIntent(Intent intent) {
    String errorMessage = "";
    Geocoder geocoder = new Geocoder(this, Locale.getDefault());
    Location location = intent.getParcelableExtra(
            Constants.LOCATION_DATA_EXTRA);
    mReceiver=intent.getParcelableExtra(Constants.RECEIVER);
    Log.e(TAG,"1-----");
    List<Address> addresses = null;

    try {
        addresses = geocoder.getFromLocation(
                location.getLatitude(),
                location.getLongitude(),
                // In this sample, get just a single address.
                1);
    } catch (IOException ioException) {
        // Catch network or other I/O problems.
        errorMessage = "service_not_available";
        Log.e(TAG, errorMessage, ioException);
    } catch (IllegalArgumentException illegalArgumentException) {
        // Catch invalid latitude or longitude values.
        errorMessage = "invalid_lat_long_used";
        Log.e(TAG, errorMessage + ". " +
                "Latitude = " + location.getLatitude() +
                ", Longitude = " +
                location.getLongitude(), illegalArgumentException);
    }
    // Handle case where no address was found.
    if (addresses == null || addresses.size()  == 0) {
        if (errorMessage.isEmpty()) {
            errorMessage = "no_address_found";
            Log.e(TAG, errorMessage);
        }
        deliverResultToReceiver(Constants.FAILURE_RESULT, errorMessage);
    } else {
        Address address = addresses.get(0);
        ArrayList<String> addressFragments = new ArrayList<String>();

        // Fetch the address lines using getAddressLine,
        // join them, and send them to the thread.
        for(int i = 0; i < address.getMaxAddressLineIndex(); i++) {
            addressFragments.add(address.getAddressLine(i));
        }
        Log.i(TAG, "address_found");
        deliverResultToReceiver(Constants.SUCCESS_RESULT,
                TextUtils.join(System.getProperty("line.separator"),
                        addressFragments));
    }

}

private void deliverResultToReceiver(int resultCode, String message) {
    Bundle bundle = new Bundle();
    bundle.putString(Constants.RESULT_DATA_KEY, message);
    Log.e(TAG, "2-----");
    mReceiver.send(resultCode, bundle);
    Log.e(TAG, "3-----");
}
</code>```

This service should have to send back bundle with Result Receiver and result code but not happening....

答:
What happens in case of IntentService is that you have three components that are playing role: MainActivity (that will call the intent service), IntentService (which is responsible for handling the intent) and the last ResultReceiver which receives the result after the intent has been handled (or operated).

As evident from the Log you have not initialized or assigned any value to ResultReceiver mReceiver
You should initialize mResultReceiver by declaring a class let us call it AddressResultReceiver which extends ResultReceiver and has a parameterized constructor that accepts a single parameter as Handler object and overrides the onReceiveResult() method like the following:

```<code>    AddressResultReceiver(Handler handler) {
        super(handler);
    }

    //Result from intent service
    @Override
    public void onReceiveResult(int resultCode, Bundle bundle) {
       ...
    }
</code>```

Now you have successfully obtained two of three components: MainActivity for starting an intent request and ResultReceiver for receiving the result. Let us now make our IntentService by defining a class in the project hierarchy and extending it with IntentService and overriding its method onHandleIntent(Intent intent)():

```<code>public class FetchAddressIntentService extends IntentService {
     public FetchAddressIntentService() {
        super("FetchAddressIntentService");
     }
     @Override
     protected void onHandleIntent(Intent intent) {...}
}
</code>```

So we are now good to go to get the things up and working. Now write the following code in your MainActivity:

```<code>  //Initializing the reference with AddressResultReceiver object
  mResultReceiver = new AddressResultReceiver(new Handler());
  ...
  //Setting the IntentService to FetchAddressIntentService
  Intent intent = new Intent(this, FetchAddressIntentService.class);

  /*passing the receiver object to the service so as to let it know where to
    publish results*/
  intent.putExtra(Constants.RECEIVER, mResultReceiver);
  ...
  //starting the service
  startService(intent);
</code>```

Now your deliverResult(int, String) would no longer throw NullPointerException. For more information visit IntentService and ResultReceiver. Hope it helps! :)

Title: Error in Intent Service in Android

Body:
I am trying to fetch some for Location Address using IntentService but ended up with error leading to app crash. Please help me.

Here is the Stacktrace:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.os.ResultReceiver.send(int, android.os.Bundle)' on a null object reference
        at com.example.ajender.sample2.FetchAddressIntentService.deliverResultToReceiver(FetchAddressIntentService.java:91)
        at com.example.ajender.sample2.FetchAddressIntentService.onHandleIntent(FetchAddressIntentService.java:81)
        at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.os.HandlerThread.run(HandlerThread.java:61)

Here is FetchAddressIntentService:

public class FetchAddressIntentService extends IntentService {
private static String TAG="Fetch-address-Service";
protected ResultReceiver mReceiver;

/**
 * Creates an IntentService.  Invoked by your subclass's constructor.
 *
 * @param name Used to name the worker thread, important only for debugging.
 */
public FetchAddressIntentService(String name) {
    super(name);
}
public FetchAddressIntentService(){
    super("FetchAddressIntentService");
}

@Override
protected void onHandleIntent(Intent intent) {
    String errorMessage = "";
    Geocoder geocoder = new Geocoder(this, Locale.getDefault());
    Location location = intent.getParcelableExtra(
            Constants.LOCATION_DATA_EXTRA);
    mReceiver=intent.getParcelableExtra(Constants.RECEIVER);
    Log.e(TAG,"1-----");
    List<Address> addresses = null;

    try {
        addresses = geocoder.getFromLocation(
                location.getLatitude(),
                location.getLongitude(),
                // In this sample, get just a single address.
                1);
    } catch (IOException ioException) {
        // Catch network or other I/O problems.
        errorMessage = "service_not_available";
        Log.e(TAG, errorMessage, ioException);
    } catch (IllegalArgumentException illegalArgumentException) {
        // Catch invalid latitude or longitude values.
        errorMessage = "invalid_lat_long_used";
        Log.e(TAG, errorMessage + ". " +
                "Latitude = " + location.getLatitude() +
                ", Longitude = " +
                location.getLongitude(), illegalArgumentException);
    }
    // Handle case where no address was found.
    if (addresses == null || addresses.size()  == 0) {
        if (errorMessage.isEmpty()) {
            errorMessage = "no_address_found";
            Log.e(TAG, errorMessage);
        }
        deliverResultToReceiver(Constants.FAILURE_RESULT, errorMessage);
    } else {
        Address address = addresses.get(0);
        ArrayList<String> addressFragments = new ArrayList<String>();

        // Fetch the address lines using getAddressLine,
        // join them, and send them to the thread.
        for(int i = 0; i < address.getMaxAddressLineIndex(); i++) {
            addressFragments.add(address.getAddressLine(i));
        }
        Log.i(TAG, "address_found");
        deliverResultToReceiver(Constants.SUCCESS_RESULT,
                TextUtils.join(System.getProperty("line.separator"),
                        addressFragments));
    }

}

private void deliverResultToReceiver(int resultCode, String message) {
    Bundle bundle = new Bundle();
    bundle.putString(Constants.RESULT_DATA_KEY, message);
    Log.e(TAG, "2-----");
    mReceiver.send(resultCode, bundle);
    Log.e(TAG, "3-----");
}

This service should have to send back bundle with Result Receiver and result code but not happening....

Body:
What happens in case of IntentService is that you have three components that are playing role: MainActivity (that will call the intent service), IntentService (which is responsible for handling the intent) and the last ResultReceiver which receives the result after the intent has been handled (or operated).

As evident from the Log you have not initialized or assigned any value to ResultReceiver mReceiver
You should initialize mResultReceiver by declaring a class let us call it AddressResultReceiver which extends ResultReceiver and has a parameterized constructor that accepts a single parameter as Handler object and overrides the onReceiveResult() method like the following:

    AddressResultReceiver(Handler handler) {
        super(handler);
    }

    //Result from intent service
    @Override
    public void onReceiveResult(int resultCode, Bundle bundle) {
       ...
    }

Now you have successfully obtained two of three components: MainActivity for starting an intent request and ResultReceiver for receiving the result. Let us now make our IntentService by defining a class in the project hierarchy and extending it with IntentService and overriding its method onHandleIntent(Intent intent)():

public class FetchAddressIntentService extends IntentService {
     public FetchAddressIntentService() {
        super("FetchAddressIntentService");
     }
     @Override
     protected void onHandleIntent(Intent intent) {...}
}

So we are now good to go to get the things up and working. Now write the following code in your MainActivity:

  //Initializing the reference with AddressResultReceiver object
  mResultReceiver = new AddressResultReceiver(new Handler());
  ...
  //Setting the IntentService to FetchAddressIntentService
  Intent intent = new Intent(this, FetchAddressIntentService.class);

  /*passing the receiver object to the service so as to let it know where to
    publish results*/
  intent.putExtra(Constants.RECEIVER, mResultReceiver);
  ...
  //starting the service
  startService(intent);

Now your deliverResult(int, String) would no longer throw NullPointerException. For more information visit IntentService and ResultReceiver. Hope it helps! :)


问:
Android TableLayout not behaving like a table
Given this layout XML snippet:

```<code>    <TableLayout
        android:id="@+id/review_ltpv_table"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:stretchColumns="*">

        <!-- TODO: This row's cells don't line up with the rows below. Fix. -->
        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/review_text_view_look"
                android:text="@string/review_look"
                android:textAppearance="@style/TextBody" />

            <TextView
                android:id="@+id/review_text_view_taste"
                android:text="@string/review_taste"
                android:textAppearance="@style/TextBody" />

            <TextView
                android:id="@+id/review_text_view_portion"
                android:text="@string/review_portion"
                android:textAppearance="@style/TextBody" />

            <TextView
                android:id="@+id/review_text_view_value"
                android:text="@string/review_value"
                android:textAppearance="@style/TextBody" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="0dp" >

            <ToggleButton
                android:id="@+id/review_look_positive"
                style="@style/ButtonPositive"
                android:onClick="onLookPositive"
                android:textOn="@null"
                android:textOff="@null" />

            <ToggleButton
                android:id="@+id/review_taste_positive"
                style="@style/ButtonPositive"
                android:onClick="onTastePositive"
                android:textOn="@null"
                android:textOff="@null" />

            <ToggleButton
                android:id="@+id/review_portion_positive"
                style="@style/ButtonPositive"
                android:onClick="onPortionPositive"
                android:textOn="@null"
                android:textOff="@null" />

            <ToggleButton
                android:id="@+id/review_value_positive"
                style="@style/ButtonPositive"
                android:onClick="onValuePositive"
                android:textOn="@null"
                android:textOff="@null" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="0dp" >

            <ToggleButton
                android:id="@+id/review_look_negative"
                style="@style/ButtonNegative"
                android:onClick="onLookNegative"
                android:textOn="@null"
                android:textOff="@null" />

            <ToggleButton
                android:id="@+id/review_taste_negative"
                style="@style/ButtonNegative"
                android:onClick="onTasteNegative"
                android:textOn="@null"
                android:textOff="@null" />

            <ToggleButton
                android:id="@+id/review_portion_negative"
                style="@style/ButtonNegative"
                android:onClick="onPortionNegative"
                android:textOn="@null"
                android:textOff="@null" />

            <ToggleButton
                android:id="@+id/review_value_negative"
                style="@style/ButtonNegative"
                android:onClick="onValueNegative"
                android:textOn="@null"
                android:textOff="@null" />
        </TableRow>

    </TableLayout>
</code>```

I see this:

Why do the vertical borders between the cells in the top row not line up with those in the rows below? This is not a table!

If I remove android:stretchColumns="*" from the layout tag it looks even worse - the cells in the top row just bunch up on the left.

If I add android:layout_weight="1" to the TextViews it makes no difference.

This is API level 22.

答:
I think you do not use the "weight" correctly, I would suggest to try to change your first row to :

```<code>    <TableRow
        android:weightSum="4">

        <TextView
            android:id="@+id/review_text_view_look"
            android:text="@string/review_look"
            android:layout_weight="1"
            android:textAppearance="@style/TextBody" />

        <TextView
            android:id="@+id/review_text_view_taste"
            android:text="@string/review_taste"
            android:layout_weight="1"
            android:textAppearance="@style/TextBody" />

        <TextView
            android:id="@+id/review_text_view_portion"
            android:text="@string/review_portion"
            android:layout_weight="1"
            android:textAppearance="@style/TextBody" />

        <TextView
            android:id="@+id/review_text_view_value"
            android:text="@string/review_value"
            android:layout_weight="1"
            android:textAppearance="@style/TextBody" />
    </TableRow>
</code>```

So every cells have the same weight and will be of the same size

Body:
Given this layout XML snippet:

    <TableLayout
        android:id="@+id/review_ltpv_table"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:stretchColumns="*">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/review_text_view_look"
                android:text="@string/review_look"
                android:textAppearance="@style/TextBody" />

            <TextView
                android:id="@+id/review_text_view_taste"
                android:text="@string/review_taste"
                android:textAppearance="@style/TextBody" />

            <TextView
                android:id="@+id/review_text_view_portion"
                android:text="@string/review_portion"
                android:textAppearance="@style/TextBody" />

            <TextView
                android:id="@+id/review_text_view_value"
                android:text="@string/review_value"
                android:textAppearance="@style/TextBody" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="0dp" >

            <ToggleButton
                android:id="@+id/review_look_positive"
                style="@style/ButtonPositive"
                android:onClick="onLookPositive"
                android:textOn="@null"
                android:textOff="@null" />

            <ToggleButton
                android:id="@+id/review_taste_positive"
                style="@style/ButtonPositive"
                android:onClick="onTastePositive"
                android:textOn="@null"
                android:textOff="@null" />

            <ToggleButton
                android:id="@+id/review_portion_positive"
                style="@style/ButtonPositive"
                android:onClick="onPortionPositive"
                android:textOn="@null"
                android:textOff="@null" />

            <ToggleButton
                android:id="@+id/review_value_positive"
                style="@style/ButtonPositive"
                android:onClick="onValuePositive"
                android:textOn="@null"
                android:textOff="@null" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="0dp" >

            <ToggleButton
                android:id="@+id/review_look_negative"
                style="@style/ButtonNegative"
                android:onClick="onLookNegative"
                android:textOn="@null"
                android:textOff="@null" />

            <ToggleButton
                android:id="@+id/review_taste_negative"
                style="@style/ButtonNegative"
                android:onClick="onTasteNegative"
                android:textOn="@null"
                android:textOff="@null" />

            <ToggleButton
                android:id="@+id/review_portion_negative"
                style="@style/ButtonNegative"
                android:onClick="onPortionNegative"
                android:textOn="@null"
                android:textOff="@null" />

            <ToggleButton
                android:id="@+id/review_value_negative"
                style="@style/ButtonNegative"
                android:onClick="onValueNegative"
                android:textOn="@null"
                android:textOff="@null" />
        </TableRow>

    </TableLayout>

I see this:

Why do the vertical borders between the cells in the top row not line up with those in the rows below? This is not a table!

If I remove android:stretchColumns="*" from the layout tag it looks even worse - the cells in the top row just bunch up on the left.

If I add android:layout_weight="1" to the TextViews it makes no difference.

This is API level 22.

Body:
I think you do not use the "weight" correctly, I would suggest to try to change your first row to :

    <TableRow
        android:weightSum="4">

        <TextView
            android:id="@+id/review_text_view_look"
            android:text="@string/review_look"
            android:layout_weight="1"
            android:textAppearance="@style/TextBody" />

        <TextView
            android:id="@+id/review_text_view_taste"
            android:text="@string/review_taste"
            android:layout_weight="1"
            android:textAppearance="@style/TextBody" />

        <TextView
            android:id="@+id/review_text_view_portion"
            android:text="@string/review_portion"
            android:layout_weight="1"
            android:textAppearance="@style/TextBody" />

        <TextView
            android:id="@+id/review_text_view_value"
            android:text="@string/review_value"
            android:layout_weight="1"
            android:textAppearance="@style/TextBody" />
    </TableRow>

So every cells have the same weight and will be of the same size


问:
Can't hold session values
I have written a code for a login page and user page. When the user provides the correct username and password, my code creates a session variable rid and then redirects the user to user page.

But I am facing a weird problem, the session variable remains in the login page but when the code redirects to user page is says Notice: Undefined variable: _SESSION in /var/www/Avatar/test1.php on line 6.

Just to check if session is working properly I tries to output $_SESSION['rid'] on both the pages, it displays the rid on the login page, but on the user page I get the above error.

So I have created two sample pages test.php and test1.php. I am creating a session variable in test.php and then trying to display in in test1.php.

test.php :

```<code><?php
     $result=session_start();
     $_SESSION["Searock"]="Searock";
     echo $result;
     echo $_SESSION["Searock"];
?>
<html>
     <body>
          <a href="test1.php">next</a>
     </body>
</html>
</code>```

Output :

1 Searock next

test1.php :

```<code><?php
    echo $_SESSION["Searock"];
?>
</code>```

Output :

Notice: Undefined variable: _SESSION
  in /var/www/Avatar/test1.php on line 2

I don't know whether the problem is in my code or is it in PHP enviroment variables.

Heres a screen shot of phpinfo.

Can someone point me in a right direction ?

Thanks.

答:
You need to call session_start() on each page. This will either begin a new session or resume a previously saved session. Do this before trying to access any $_SESSION variables and you should be good to go.

Update

Looks like I was beaten to it!

Title: Can't hold session values

Body:
I have written a code for a login page and user page. When the user provides the correct username and password, my code creates a session variable rid and then redirects the user to user page.

But I am facing a weird problem, the session variable remains in the login page but when the code redirects to user page is says Notice: Undefined variable: _SESSION in /var/www/Avatar/test1.php on line 6.

Just to check if session is working properly I tries to output $_SESSION['rid'] on both the pages, it displays the rid on the login page, but on the user page I get the above error.

So I have created two sample pages test.php and test1.php. I am creating a session variable in test.php and then trying to display in in test1.php.

test.php :

<?php
     $result=session_start();
     $_SESSION["Searock"]="Searock";
     echo $result;
     echo $_SESSION["Searock"];
?>

          next

Output :

1 Searock next

test1.php :

<?php
    echo $_SESSION["Searock"];
?>

Output :

Notice: Undefined variable: _SESSION
  in /var/www/Avatar/test1.php on line 2

I don't know whether the problem is in my code or is it in PHP enviroment variables.

Heres a screen shot of phpinfo.

Can someone point me in a right direction ?

Thanks.


问:
Retrieve sent message with EWS Managed API
I'm trying to send a message using EWS Managed API, and I need to confirm message was sent and register some info (ex. the date & time it was sent). However, I get an exception as shown below. My question is: how can I retrieve the EmailMessage object for the sent message, after it was sent?

Thank you very much!

```<code>Private Sub NovaMensagemToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NovaMensagemToolStripMenuItem.Click
    Dim em As New EmailMessage(serviceClient.Service)
    em.Subject = "Test"
    em.Body = "This is a test."
    em.ToRecipients.Add("mytestmail@test.com")
    em.SendAndSaveCopy(WellKnownFolderName.SentItems)
    em.Load() 'Exception: System.InvalidOperationException: This operation can't be performed because this service object doesn't have an Id.
    MsgBox(em.DateTimeSent)
End Sub
</code>```

答:
Apparently, all it takes is to save a draft before sending:</p>

```<code>Private Sub NovaMensagemToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NovaMensagemToolStripMenuItem.Click
    Dim em As New EmailMessage(serviceClient.Service)
    em.Subject = "Test"
    em.Body = "This is a test."
    em.ToRecipients.Add("mytestmail@test.com")
    em.Save(WellKnownFolderName.Drafts) '<--- added this
    em.SendAndSaveCopy(WellKnownFolderName.SentItems)
    em.Load() 'no exception now
    MsgBox(em.DateTimeSent)
End Sub
</code>```

Body:
I'm trying to send a message using EWS Managed API, and I need to confirm message was sent and register some info (ex. the date & time it was sent). However, I get an exception as shown below. My question is: how can I retrieve the EmailMessage object for the sent message, after it was sent?

Thank you very much!

Private Sub NovaMensagemToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NovaMensagemToolStripMenuItem.Click
    Dim em As New EmailMessage(serviceClient.Service)
    em.Subject = "Test"
    em.Body = "This is a test."
    em.ToRecipients.Add("mytestmail@test.com")
    em.SendAndSaveCopy(WellKnownFolderName.SentItems)
    em.Load() 'Exception: System.InvalidOperationException: This operation can't be performed because this service object doesn't have an Id.
    MsgBox(em.DateTimeSent)
End Sub

Body:
Apparently, all it takes is to save a draft before sending:

Private Sub NovaMensagemToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NovaMensagemToolStripMenuItem.Click
    Dim em As New EmailMessage(serviceClient.Service)
    em.Subject = "Test"
    em.Body = "This is a test."
    em.ToRecipients.Add("mytestmail@test.com")
    em.Save(WellKnownFolderName.Drafts) '<--- added this
    em.SendAndSaveCopy(WellKnownFolderName.SentItems)
    em.Load() 'no exception now
    MsgBox(em.DateTimeSent)
End Sub


问:
What is semantics?
So there are copy semantics, move semantics and maybe more semantics that I don't know of. I have read articles about both but I still do not really get have a good definition of "semantics". As the name suggests, move semantics have something to do with moving things but why is it called move semantics?

The more clear version: What is the meaning of semantics in the context of programming? Example: Move and copy semantics.

答:
Semantics is about the meaning of something. move-semantic is about the meaning of moving objects. Specifically, in this context, it tells you what it means to move something in C++.
The semantic of moving is all about everything that is involved during a move operation.

read move-semantic as: what does it mean, what are the implications (and how do you achieve it ) of moving an object in a C++ program?

The following is a good answer that might help: What are move semantics?

Title: What is semantics?


问:
Laravel TokenMismatchException caused in routes/web.php
I am learning Routing in Laravel 5.4 by viewing a tutorial created by DevDojo. Using the following codes in routes/web.php will emerge the TokenMismatchException error and my code does not work after I press the submit button:

```<code>Route::post('test', function () {
    return 'Printed by the route responsible for test post action.';
});

Route::get('test', function () {
    echo '<form method="post" action="test">';
    echo '<input type="submit">';
    echo '</form>';
});
</code>```

I searched this same forum here and also the other places on the net like laravel.io or laracasts.com and everyone is talking about problems that occur when Laravel tries to detect the session of the request that is getting made.

I tried to fix the problem by adding the following lines to the Route::get rules but the issue does not get fixed:

```<code>echo '<input type="hidden" name="_method" value="post">';
echo '<input type="hidden" name="_token" value="csrf_field();">';
</code>```

I hope you help me fix it by telling me how to properly use csrf_field(), csrf_token() or anything else needed here in the route file.

Thank you very much in advance.

答:
csrf_token() just gives you the token.

csrf_field() builds the entire input field for you.

example:

{{ csrf_token() }}  // Outputs: SomeRandomString

{{ csrf_field() }}  // Outputs: <input type="hidden" name="_token" value="SomeRandomString">

in your question:
use

```<code><input type="hidden" name="_token" value="csrf_token();">;
</code>```

instead of

```<code><input type="hidden" name="_token" value="csrf_field();">;
</code>```

on the other hand

you could use

```<code>echo csrf_field();
</code>```

OR

```<code>{{ csrf_field() }}
</code>```

Body:
I am learning Routing in Laravel 5.4 by viewing a tutorial created by DevDojo. Using the following codes in routes/web.php will emerge the TokenMismatchException error and my code does not work after I press the submit button:

Route::post('test', function () {
    return 'Printed by the route responsible for test post action.';
});

Route::get('test', function () {
    echo '<form method="post" action="test">';
    echo '<input type="submit">';
    echo '</form>';
});

I searched this same forum here and also the other places on the net like laravel.io or laracasts.com and everyone is talking about problems that occur when Laravel tries to detect the session of the request that is getting made.

I tried to fix the problem by adding the following lines to the Route::get rules but the issue does not get fixed:

echo '<input type="hidden" name="_method" value="post">';
echo '<input type="hidden" name="_token" value="csrf_field();">';

I hope you help me fix it by telling me how to properly use csrf_field(), csrf_token() or anything else needed here in the route file.

Thank you very much in advance.

Body:
csrf_token() just gives you the token.

csrf_field() builds the entire input field for you.

example:

{{ csrf_token() }}  // Outputs: SomeRandomString

{{ csrf_field() }}  // Outputs: <input type="hidden" name="_token" value="SomeRandomString">

in your question:
use

<input type="hidden" name="_token" value="csrf_token();">;

instead of

<input type="hidden" name="_token" value="csrf_field();">;

on the other hand

you could use

echo csrf_field();

OR

{{ csrf_field() }}


问:
How do I display duration in milliseconds as a properly formatted string?
I'm using Ruby 2.4.  I want to convert milliseconds to a readable hours, minutes, and seconds format.  SO I have this method

```<code>  def time_as_str(time_in_ms)
    regex = /^(0*:?)*0*/
    Time.at(time_in_ms.to_f/1000).utc.strftime("%H:%M:%S.%1N").sub!(regex, '')
  end
</code>```

The problem is, if my value in milliseconds is a day or greater, this function doesn't display the correct values.  FOr instance, if I pass

```<code>2.4.0 :009 > TimeFormattingHelper.time_as_str(86400000)
 => ".0"
</code>```

86400000 is a day in milliseconds (unless I've miscalculated).  So I would expect the value to be "24:00:00".  How do I correct the above to display the time formatted properly?

答:
Some basic info:

a second = 1000 milliseconds

a minute = 1000 × 60 milliseconds

an hour = 1000 × 60 × 60 milliseconds

Now, you can try below method:

```<code>def get_duration_hrs_and_mins(duration)
  duration = duration.to_i

  h = duration / (1000 * 60 * 60)
  m = duration / (1000 * 60) % 60
  s = duration / (1000.to_f) % 60

  h = zero_to_nil(h)
  m = zero_to_nil(m) if h.nil?

  arr = [h, m, s].map { |e| format_val(e) }

  arr.compact.join(':')
end

def format_val(e)
  case
  when e.nil?
    nil
  when e.zero?
    '00'
  when e.round(0) == e
    sprintf("%2d", e)
  else
    e.round(3)
  end
end

def zero_to_nil(val)
  val.zero? ? nil : val
end
</code>```

Some output from rails console:

```<code>puts get_duration_hrs_and_mins(86400000)
# => 24:00:00
puts get_duration_hrs_and_mins(150400)
# => 2:30.4
puts get_duration_hrs_and_mins(150401)
# => 2:30.401
puts get_duration_hrs_and_mins(1500)
# => 1.5
puts get_duration_hrs_and_mins(864000)
# => 14:24
</code>```

Body:
I'm using Ruby 2.4.  I want to convert milliseconds to a readable hours, minutes, and seconds format.  SO I have this method

  def time_as_str(time_in_ms)
    regex = /^(0*:?)*0*/
    Time.at(time_in_ms.to_f/1000).utc.strftime("%H:%M:%S.%1N").sub!(regex, '')
  end

The problem is, if my value in milliseconds is a day or greater, this function doesn't display the correct values.  FOr instance, if I pass

2.4.0 :009 > TimeFormattingHelper.time_as_str(86400000)
 => ".0"

86400000 is a day in milliseconds (unless I've miscalculated).  So I would expect the value to be "24:00:00".  How do I correct the above to display the time formatted properly?

Body:
Some basic info:

a second = 1000 milliseconds

a minute = 1000 × 60 milliseconds

an hour = 1000 × 60 × 60 milliseconds

Now, you can try below method:

def get_duration_hrs_and_mins(duration)
  duration = duration.to_i

  h = duration / (1000 * 60 * 60)
  m = duration / (1000 * 60) % 60
  s = duration / (1000.to_f) % 60

  h = zero_to_nil(h)
  m = zero_to_nil(m) if h.nil?

  arr = [h, m, s].map { |e| format_val(e) }

  arr.compact.join(':')
end

def format_val(e)
  case
  when e.nil?
    nil
  when e.zero?
    '00'
  when e.round(0) == e
    sprintf("%2d", e)
  else
    e.round(3)
  end
end

def zero_to_nil(val)
  val.zero? ? nil : val
end

Some output from rails console:

puts get_duration_hrs_and_mins(86400000)
# => 24:00:00
puts get_duration_hrs_and_mins(150400)
# => 2:30.4
puts get_duration_hrs_and_mins(150401)
# => 2:30.401
puts get_duration_hrs_and_mins(1500)
# => 1.5
puts get_duration_hrs_and_mins(864000)
# => 14:24


问:
Openpyxl: How to copy a row after checking if a cell contains specific value
I have a worksheet that is updated every week with thousands of rows and would need to transfer rows from this worksheet after filtering. I am using the current code to find the cells which has the value I need and then transfer the entire row to another sheet but after saving the file, I get the "IndexError: list index out of range" exception.

The code I use is as follows:

```<code>import openpyxl

wb1 = openpyxl.load_workbook('file1.xlsx')
wb2 = openpyxl.load_workbook('file2.xlsx')

ws1 = wb1.active
ws2 = wb2.active

for row in ws1.iter_rows():
    for cell in row:
        if cell.value == 'TrueValue':
            n = 'A' + str(cell.row) + ':' + ('GH' + str(cell.row))
            for row2 in ws1.iter_rows(n):
                ws2.append(row2)

wb2.save("file2.xlsx")
</code>```

The original code I used that used to work is below and has to be modified because of the large files which causes MS Excel not to open them (over 40mb).

```<code>n = 'A3' + ':' + ('GH'+ str(ws1.max_row))
for row in ws1.iter_rows(n):
    ws2.append(row)
</code>```

Thanks.

答:
Use a list to hold the items in each column for the particular row.
Then append the list to your ws2.

```<code>...

def iter_rows(ws,n):  #produce the list of items in the particular row
        for row in ws.iter_rows(n):
            yield [cell.value for cell in row]

for row in ws1.iter_rows():
    for cell in row:
        if cell.value == 'TrueValue':
            n = 'A' + str(cell.row) + ':' + ('GH' + str(cell.row))
            list_to_append = list(iter_rows(ws1,n))
            for items in list_to_append:
                ws2.append(items)
</code>```

Body:
I have a worksheet that is updated every week with thousands of rows and would need to transfer rows from this worksheet after filtering. I am using the current code to find the cells which has the value I need and then transfer the entire row to another sheet but after saving the file, I get the "IndexError: list index out of range" exception.

The code I use is as follows:

import openpyxl

wb1 = openpyxl.load_workbook('file1.xlsx')
wb2 = openpyxl.load_workbook('file2.xlsx')

ws1 = wb1.active
ws2 = wb2.active

for row in ws1.iter_rows():
    for cell in row:
        if cell.value == 'TrueValue':
            n = 'A' + str(cell.row) + ':' + ('GH' + str(cell.row))
            for row2 in ws1.iter_rows(n):
                ws2.append(row2)

wb2.save("file2.xlsx")

The original code I used that used to work is below and has to be modified because of the large files which causes MS Excel not to open them (over 40mb).

n = 'A3' + ':' + ('GH'+ str(ws1.max_row))
for row in ws1.iter_rows(n):
    ws2.append(row)

Thanks.

Body:
Use a list to hold the items in each column for the particular row.
Then append the list to your ws2.

...

def iter_rows(ws,n):  #produce the list of items in the particular row
        for row in ws.iter_rows(n):
            yield [cell.value for cell in row]

for row in ws1.iter_rows():
    for cell in row:
        if cell.value == 'TrueValue':
            n = 'A' + str(cell.row) + ':' + ('GH' + str(cell.row))
            list_to_append = list(iter_rows(ws1,n))
            for items in list_to_append:
                ws2.append(items)


答:
Unless session.auto_start is enabled, you need to call session_start explicitly on every page you want the session to be available.

So call session_start in test1.php and check whether $_SESSION["Searock"] exists before accessing it:

```<code><?php
    session_start();
    if (isset($_SESSION["Searock"])) {
        echo $_SESSION["Searock"];
    }
?>
</code>```

Title: Can't hold session values

Body:
Unless session.auto_start is enabled, you need to call session_start explicitly on every page you want the session to be available.

So call session_start in test1.php and check whether $_SESSION["Searock"] exists before accessing it:

<?php
    session_start();
    if (isset($_SESSION["Searock"])) {
        echo $_SESSION["Searock"];
    }
?>


问:
Adding Third party library to Laravel
I have an RSA algorithm Library giving to me by a payment gateway and When I do a

```<code>include (app_path().'/PaymentGateway/Crypt/RSA.php');
</code>```

this and try to make an object as $rsa = new Crypt_RSA(); this it gives me and error saying

```<code>Class 'App\Http\Controllers\Crypt_RSA' not found
</code>```

I tried including it in web.php and making an object it worked the problem occur when I try to include it in a Controller.

答:
On default, everything included in the app folder of your laravel project is autoloaded, that is described in the composer.json of your project:

```<code>...
"autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },
...
</code>```

The only thing you will need to do is simply use the namespace:

```<code>use App/Path/To/Third/Party/plugin/Class;
</code>```

If, however, the plugin is placed outside of the scope of App, then simply add it to the psr-4 autoloader:

```<code>    "psr-4": {
        "ProjectRootNs\\": "projects/myproject/"
    }
</code>```

Title: Adding Third party library to Laravel

Body:
I have an RSA algorithm Library giving to me by a payment gateway and When I do a

include (app_path().'/PaymentGateway/Crypt/RSA.php');

this and try to make an object as $rsa = new Crypt_RSA(); this it gives me and error saying

Class 'App\Http\Controllers\Crypt_RSA' not found

I tried including it in web.php and making an object it worked the problem occur when I try to include it in a Controller.

Body:
On default, everything included in the app folder of your laravel project is autoloaded, that is described in the composer.json of your project:

...
"autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },
...

The only thing you will need to do is simply use the namespace:

use App/Path/To/Third/Party/plugin/Class;

If, however, the plugin is placed outside of the scope of App, then simply add it to the psr-4 autoloader:

    "psr-4": {
        "ProjectRootNs\\": "projects/myproject/"
    }


问:
error receiving JSON is badly formatted or it contains invalid character php curl
JSON is badly formatted or it contains invalid character, tried few suggestions but still receiving same error please help on this following is my json posting using curl

complete curl request

```<code>    $url='https://sandbox.interswitchng.com/api/v2/quickteller/payments/transfers';
     $postdata='{
            "mac":"9F4E4F53C57BE63E1F08D8F07A7BC1A9461E4A7D5304043DAA1EF54BD727B6CDE148F4FBFC5E2AD8C4A60F78DFA76304DE671FBEB70657B1628F14B6B6BAA5E1",
            "beneficiary":{
                "firstname":"chi",
                "lastname":"chi",
                "othernames":"chi"
                },
            "initiatingEntityCode":"FIB",
            "initiation":{
                "amount":"100000",
                "channel":"7",
                "currencyCode":"566",
                "paymentMethodCode":"CA"
            },
            "sender":{
                "email":"isw@interswitch.com",
                "lastname":"Phil colins",
                "othernames":"Phil colins",
                "phone":"08124888436"
            },
            "termination":{
                "accountReceivable":{
                    "accountNumber":"0012000887",
                    "accountType":"10"
                },
                "amount":"100000",
                "countryCode":"NG",
                "currencyCode":"566",
                "entityCode":"058",
                "paymentMethodCode":"AC"
            },
            "transferCode":"1016858652542545"
     }';

    $data=json_encode(json_decode($postdata));
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_SSLVERSION, 6);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type:application/json'
    ));

    $result = curl_exec($ch);

    echo curl_getinfo($ch) . '<br/>';
    echo curl_errno($ch) . '<br/>';
    echo curl_error($ch) . '<br/>';

    var_dump($result);
</code>```

but still receiving the error
JSON is badly formatted or it contains invalid character.

答:
The JSON is valid.

You can do

```<code>print_r(json_decode($postdata));
</code>```

It will convert it to an object.

If you just want to remove the formatting, and have a one line string:

```<code>echo json_encode(json_decode($postdata));
// output:
// {"mac":"9F4E4F53C57BE63E1F08D8F07A7BC1A9461E4A7D5304043DAA1EF54BD727B6CDE148F4FBFC5E2AD8C4A60F78DFA76304DE671FBEB70657B1628F14B6B6BAA5E1","beneficiary":{"firstname":"chi","lastname":"chi","othernames":"chi"},"initiatingEntityCode":"FIB","initiation":{"amount":"100000","channel":"7","currencyCode":"566","paymentMethodCode":"CA"},"sender":{"email":"isw@interswitch.com","lastname":"Phil colins","othernames":"Phil colins","phone":"08124888436"},"termination":{"accountReceivable":{"accountNumber":"0012000887","accountType":"10"},"amount":"100000","countryCode":"NG","currencyCode":"566","entityCode":"058","paymentMethodCode":"AC"},"transferCode":"1016858652542545"}
</code>```

Body:
JSON is badly formatted or it contains invalid character, tried few suggestions but still receiving same error please help on this following is my json posting using curl

complete curl request

    $url='https://sandbox.interswitchng.com/api/v2/quickteller/payments/transfers';
     $postdata='{
            "mac":"9F4E4F53C57BE63E1F08D8F07A7BC1A9461E4A7D5304043DAA1EF54BD727B6CDE148F4FBFC5E2AD8C4A60F78DFA76304DE671FBEB70657B1628F14B6B6BAA5E1",
            "beneficiary":{
                "firstname":"chi",
                "lastname":"chi",
                "othernames":"chi"
                },
            "initiatingEntityCode":"FIB",
            "initiation":{
                "amount":"100000",
                "channel":"7",
                "currencyCode":"566",
                "paymentMethodCode":"CA"
            },
            "sender":{
                "email":"isw@interswitch.com",
                "lastname":"Phil colins",
                "othernames":"Phil colins",
                "phone":"08124888436"
            },
            "termination":{
                "accountReceivable":{
                    "accountNumber":"0012000887",
                    "accountType":"10"
                },
                "amount":"100000",
                "countryCode":"NG",
                "currencyCode":"566",
                "entityCode":"058",
                "paymentMethodCode":"AC"
            },
            "transferCode":"1016858652542545"
     }';

    $data=json_encode(json_decode($postdata));
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_SSLVERSION, 6);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type:application/json'
    ));

    $result = curl_exec($ch);

    echo curl_getinfo($ch) . '
';
    echo curl_errno($ch) . '
';
    echo curl_error($ch) . '
';

    var_dump($result);

but still receiving the error
JSON is badly formatted or it contains invalid character.

Body:
The JSON is valid.

You can do

print_r(json_decode($postdata));

It will convert it to an object.

If you just want to remove the formatting, and have a one line string:

echo json_encode(json_decode($postdata));
// output:
// {"mac":"9F4E4F53C57BE63E1F08D8F07A7BC1A9461E4A7D5304043DAA1EF54BD727B6CDE148F4FBFC5E2AD8C4A60F78DFA76304DE671FBEB70657B1628F14B6B6BAA5E1","beneficiary":{"firstname":"chi","lastname":"chi","othernames":"chi"},"initiatingEntityCode":"FIB","initiation":{"amount":"100000","channel":"7","currencyCode":"566","paymentMethodCode":"CA"},"sender":{"email":"isw@interswitch.com","lastname":"Phil colins","othernames":"Phil colins","phone":"08124888436"},"termination":{"accountReceivable":{"accountNumber":"0012000887","accountType":"10"},"amount":"100000","countryCode":"NG","currencyCode":"566","entityCode":"058","paymentMethodCode":"AC"},"transferCode":"1016858652542545"}


问:
How to analyse video frames in parallel using Matlab?
I'm working on processing large video files frame-by-frame. The processing for each frame is independent of other frames (when decompressed) and is also computationally intensive, so I figured parallel processing would be a great way to speed up my analysis. While I have taught myself the basics of using parallel loops, I'm having problems combining the specifics of parfor with VideoReader objects. In my mind I imagine the code running like this

```<code> video = VideoReader('video.mp4');
 parfor ii = 1 : 90000
     frame = read(video, ii);
     ...analysis on frame...
 end
</code>```

However this warns me against using read() because it will be removed in a future version, so the only alternative I know of is to use frameRead(). However frameRead uses the CurrentTime property of the VideoReader object, which increments itself (according to the fps) each time frameRead is called. This works fine for reading frames in a normal loop, but it makes parfor unhappy because each frame relies on increasing the CurrentTime according to the last. Is there a way to access independent frames in a parallel loop using readFrame or otherwise? I've tried to set the CurrentTime value in each loop by using the loop index and the frame rate like this:

```<code> video = VideoReader('video.mp4');
 fps = video.FrameRate
 results = cell(totalFrames, 1);
 parfor ii = 1 : 900000
     video.CurrentTime = ii/fps;
     frame = readFrame(video);
     results{ii} = customAnalysisFunction(frame)
 end
</code>```

In this example the parfor is underlined/flagged and the reason is provided in this message:

```<code>MATLAB runs loops in parfor functions by dividing the loop iterations into
groups,and then sending them to MATLAB workers where they run in parallel.
For MATLAB to do this in a repeatable, reliable manner, it must be able to
classify all the variables used in the loop. The code uses the indicated
variable in a way that is incompatible with classification
</code>```

What steps can I take to be able to read video frames in parallel that is compatible?

Should I just use the read function? What are the reasons why I shouldn't? Are there other video tools for Matlab?

One solution that is often suggested to me is, why don't you split up the video into separate clips? I don't want to do this because it is very slow and requires a lot of extra steps and file handling. It find it hard to believe that there isn't a solution to this problem within Matlab, so I'm looking forward to your answers!

答:
I don't expect that reading frames in parallel would work in MATLAB. The video reader is an object that has an internal state about where it is positioned. You might try to work with a copy of the object. Take a look at this:
http://mathworks.com/help/matlab/ref/matlab.mixin.copyable-class.html</p>

Body:
I'm working on processing large video files frame-by-frame. The processing for each frame is independent of other frames (when decompressed) and is also computationally intensive, so I figured parallel processing would be a great way to speed up my analysis. While I have taught myself the basics of using parallel loops, I'm having problems combining the specifics of parfor with VideoReader objects. In my mind I imagine the code running like this

 video = VideoReader('video.mp4');
 parfor ii = 1 : 90000
     frame = read(video, ii);
     ...analysis on frame...
 end

However this warns me against using read() because it will be removed in a future version, so the only alternative I know of is to use frameRead(). However frameRead uses the CurrentTime property of the VideoReader object, which increments itself (according to the fps) each time frameRead is called. This works fine for reading frames in a normal loop, but it makes parfor unhappy because each frame relies on increasing the CurrentTime according to the last. Is there a way to access independent frames in a parallel loop using readFrame or otherwise? I've tried to set the CurrentTime value in each loop by using the loop index and the frame rate like this:

 video = VideoReader('video.mp4');
 fps = video.FrameRate
 results = cell(totalFrames, 1);
 parfor ii = 1 : 900000
     video.CurrentTime = ii/fps;
     frame = readFrame(video);
     results{ii} = customAnalysisFunction(frame)
 end

In this example the parfor is underlined/flagged and the reason is provided in this message:

MATLAB runs loops in parfor functions by dividing the loop iterations into
groups,and then sending them to MATLAB workers where they run in parallel.
For MATLAB to do this in a repeatable, reliable manner, it must be able to
classify all the variables used in the loop. The code uses the indicated
variable in a way that is incompatible with classification

What steps can I take to be able to read video frames in parallel that is compatible?

Should I just use the read function? What are the reasons why I shouldn't? Are there other video tools for Matlab?

One solution that is often suggested to me is, why don't you split up the video into separate clips? I don't want to do this because it is very slow and requires a lot of extra steps and file handling. It find it hard to believe that there isn't a solution to this problem within Matlab, so I'm looking forward to your answers!