问:
@Autowired objects are null only when testing
My question has to do with the application set-up, not mocking or using autowiring. See the answer for more details.

I'm trying to set up a Spring Boot application and I'm having issues creating unit tests. My issue is that all objects I have @Autowired are null only during unit testing. When I run the application normally I'm able to use CURL for and it works. However when I test with JUnit I get a null pointer when I try to use the @Autowired objects. I am not using a xml file to configure my beans, maybe that is my problem?

Application.java

```<code>package com.blakeparmeter.metricsapi;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 *
 * @author Blake
 */
@SpringBootApplication
@EnableAutoConfiguration
public class Application {

    public static void main(String[] args){
        SpringApplication.run(Application.class, args);
    }
}
</code>```

MetricApi.java

```<code>package com.blakeparmeter.metricsapi.api;

import com.blakeparmeter.metricsapi.beans.Metric;
import com.blakeparmeter.metricsapi.controllers.MetricController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Handles all the REST responses logic of the Metrics services.
 * Complex logic should be moved outside of this class.
 * @author Blake
 */
@RestController
@EnableAutoConfiguration
public class MetricAPI {

    @Autowired
    private MetricController metricController;

    @RequestMapping("/addMetric")
    public ResponseEntity<?> addMetric(@RequestBody Metric record){
        metricController.addMetric(record);
        return ResponseEntity.ok().build();
    }
}
</code>```

MetricController.java

```<code>package com.blakeparmeter.metricsapi.controllers;

import com.blakeparmeter.metricsapi.beans.Metric;
import org.springframework.stereotype.Controller;

/**
 *
 * @author Blake
 */
@Controller
public class MetricController {

    public Metric addMetric(Metric metric){
        System.out.println("Adding a metric!");
        return metric;
    }
}
</code>```

MetricsTest.java

```<code>package metrics;

import com.blakeparmeter.metricsapi.Application;
import com.blakeparmeter.metricsapi.api.MetricAPI;
import com.blakeparmeter.metricsapi.beans.Metric;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;

/**
 * @author Blake
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class MetricsTest {

    private MockMvc mockMvc;

    @Autowired
    ObjectMapper objectMapper;

    @Before
    public void setup() throws Exception {
        mockMvc = standaloneSetup(new MetricAPI()).build();
    }

    /**
     * Adds a valid metric
     * @throws Exception
     */
    @Test
    public void addMetricTest() throws Exception{
        mockMvc.perform(post("/addMetric")
            .contentType(MediaType.APPLICATION_JSON)
            .content(objectMapper.writeValueAsString(new Metric())))
                .andExpect(status().isOk());
    }
}
</code>```

pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.blakeparmeter</groupId>
    <artifactId>MetricsAPI</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.1.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>
    </dependencies>
</project>
</code>```

Stack trace:

```<code>Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 13.569 sec <<< FAILURE! - in metrics.MetricsTest
addMetricTest(metrics.MetricsTest)  Time elapsed: 0.174 sec  <<< ERROR!
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
    at com.blakeparmeter.metricsapi.api.MetricAPI.addMetric(MetricAPI.java:30)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
    at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155)
    at metrics.MetricsTest.addMetricTest(MetricsTest.java:47)
</code>```

答:
standaloneSetup is used for unit tests. But it seems like you are doing integrations tests, so the below code should work - I have not tested it.

Replace

```<code>@Before
public void setup() throws Exception {
    mockMvc = standaloneSetup(new MetricAPI()).build();
}
</code>```

with

```<code>@Autowired
private WebApplicationContext wac;

@Before
public void setup() throws Exception {
    mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
</code>```

and add this to your test class:

```<code>@WebAppConfiguration
</code>```

Bonus

@RunWith(SpringRunner.class) tells JUnit to run using Spring’s testing
  support. SpringRunner is the new name for SpringJUnit4ClassRunner,
  it’s just a bit easier on the eye.

Body:
My question has to do with the application set-up, not mocking or using autowiring. See the answer for more details.

I'm trying to set up a Spring Boot application and I'm having issues creating unit tests. My issue is that all objects I have @Autowired are null only during unit testing. When I run the application normally I'm able to use CURL for and it works. However when I test with JUnit I get a null pointer when I try to use the @Autowired objects. I am not using a xml file to configure my beans, maybe that is my problem?

Application.java

package com.blakeparmeter.metricsapi;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 *
 * @author Blake
 */
@SpringBootApplication
@EnableAutoConfiguration
public class Application {

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

MetricApi.java

package com.blakeparmeter.metricsapi.api;

import com.blakeparmeter.metricsapi.beans.Metric;
import com.blakeparmeter.metricsapi.controllers.MetricController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Handles all the REST responses logic of the Metrics services.
 * Complex logic should be moved outside of this class.
 * @author Blake
 */
@RestController
@EnableAutoConfiguration
public class MetricAPI {

    @Autowired
    private MetricController metricController;

    @RequestMapping("/addMetric")
    public ResponseEntity<?> addMetric(@RequestBody Metric record){
        metricController.addMetric(record);
        return ResponseEntity.ok().build();
    }
}

MetricController.java

package com.blakeparmeter.metricsapi.controllers;

import com.blakeparmeter.metricsapi.beans.Metric;
import org.springframework.stereotype.Controller;

/**
 *
 * @author Blake
 */
@Controller
public class MetricController {

    public Metric addMetric(Metric metric){
        System.out.println("Adding a metric!");
        return metric;
    }
}

MetricsTest.java

package metrics;

import com.blakeparmeter.metricsapi.Application;
import com.blakeparmeter.metricsapi.api.MetricAPI;
import com.blakeparmeter.metricsapi.beans.Metric;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;

/**
 * @author Blake
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class MetricsTest {

    private MockMvc mockMvc;

    @Autowired
    ObjectMapper objectMapper;

    @Before
    public void setup() throws Exception {
        mockMvc = standaloneSetup(new MetricAPI()).build();
    }

    /**
     * Adds a valid metric
     * @throws Exception
     */
    @Test
    public void addMetricTest() throws Exception{
        mockMvc.perform(post("/addMetric")
            .contentType(MediaType.APPLICATION_JSON)
            .content(objectMapper.writeValueAsString(new Metric())))
                .andExpect(status().isOk());
    }
}

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.blakeparmeter</groupId>
    <artifactId>MetricsAPI</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.1.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>
    </dependencies>
</project>

Stack trace:

Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 13.569 sec <<< FAILURE! - in metrics.MetricsTest
addMetricTest(metrics.MetricsTest)  Time elapsed: 0.174 sec  <<< ERROR!
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
    at com.blakeparmeter.metricsapi.api.MetricAPI.addMetric(MetricAPI.java:30)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
    at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155)
    at metrics.MetricsTest.addMetricTest(MetricsTest.java:47)

Body:
standaloneSetup is used for unit tests. But it seems like you are doing integrations tests, so the below code should work - I have not tested it.

Replace

@Before
public void setup() throws Exception {
    mockMvc = standaloneSetup(new MetricAPI()).build();
}

with

@Autowired
private WebApplicationContext wac;

@Before
public void setup() throws Exception {
    mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}

and add this to your test class:

@WebAppConfiguration

Bonus

@RunWith(SpringRunner.class) tells JUnit to run using Spring’s testing
  support. SpringRunner is the new name for SpringJUnit4ClassRunner,
  it’s just a bit easier on the eye.


来源: stackexchange

问:
Deleting head or only node in Linked List in C
I am writing a function which removes a specific node from the linked list. The function works for most cases but does not work when the node to delete is either the head node, or the only node in the linked list. I tried setting the current to equal NULL when this case happens but that creates a segmentation fault, where is my logic wrong?</p>

```<code>void deleteNodeAfter(Node *head, Node *delete) {
    bool remove = false;
    Node *current = head;
    Node *delNode = delete;
    if (current->songName == delNode->songName){
        current= NULL;
        remove = true;
    }
    while (!remove) {
        if (current->link->songName == delNode->songName) {
            current->link = delNode->link;
            remove = true;
            // free(delNode);
        } else {
            current = current->link;
        }
    }
}
</code>```

答:
If you delete the first you need to update originla list pointer:

```<code>void deleteNodeAfter(Node **head, Node *delete) {
   Node *current = *head;
   if( first ) {
     *head = (*head)->next;
     free(current);
   }
}
</code>```

You need to pass pointer to pointer to first instead of pointer to first. Using:

```<code>Node *head;
Node *after;
...
deleteNodeAfter( &head, after );
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am writing a function which removes a specific node from the linked list. The function works for most cases but does not work when the node to delete is either the head node, or the only node in the linked list. I tried setting the current to equal NULL when this case happens but that creates a segmentation fault, where is my logic wrong?

void deleteNodeAfter(Node *head, Node *delete) {
    bool remove = false;
    Node *current = head;
    Node *delNode = delete;
    if (current->songName == delNode->songName){
        current= NULL;
        remove = true;
    }
    while (!remove) {
        if (current->link->songName == delNode->songName) {
            current->link = delNode->link;
            remove = true;
            // free(delNode);
        } else {
            current = current->link;
        }
    }
}

Body:
If you delete the first you need to update originla list pointer:

void deleteNodeAfter(Node **head, Node *delete) {
   Node *current = *head;
   if( first ) {
     *head = (*head)->next;
     free(current);
   }
}

You need to pass pointer to pointer to first instead of pointer to first. Using:

Node *head;
Node *after;
...
deleteNodeAfter( &head, after );


问:
Is it correct to check cancancan abilities for each record in array?
From the DB point of view.
For example, I have 30 records on page (articles) and I want to check whether I can create "Like" or not. So, there will be 30 queries to the db to check this ability. What is the best practice to perform such ability check?

```<code><% @articles.each do |article| %>
  <% if can? :create, Like.new(user: user, article: article) %>
      <%= link_to "Like!", like_path(article) %>
  <% end %>
<% end %>
</code>```

UPDATE: Add ability.rb

```<code>class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new
    if user.admin?
      can :manage, :all
    else
      can :create, Like do |like|
        !Like.exists?(user: user, article: like.article)
      end
    end
  end
end
</code>```

答:
Abilities per se are not stored in the database. here's an example

```<code>class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user (not logged in)
    if user.admin?
      can :manage, :all
    else
      can :read, :all
    end
  end
end
</code>```

As you can see, it doesn't touch the database, since you already have a user variable, all you needed to do was ask about an attribute.

In your example, I assume you already have an 'user' loaded, and of course, you have a lot of articles already fetched.

if you cancan ability is, for example:

```<code>  user ||= User.new
  can :manage, Article do |a|
      a.user_id== user.id
    end
</code>```

then no queries are made, since you already have all the information about an article.

However, if you have to load extra information, something like

```<code>  can :manage, Article do |i|
      user.friends_articles.exists?(i.id)
    end
</code>```

then a query is made (you had to see if the article belonged to the user's friend's collection).

No matter the scenario, there is no escape from asking each article for permissions, unless of course, you load only the articles an user can 'like', then, there is no need for asking ;).

EDIT:

Let's examine your ability.rb

```<code>if user.admin?
  can :manage, :all
</code>```

User.admin?, assuming admin? is just an attribute, then it is already loaded, and no additional queries are made.

However, exists? consults the database, it searches for a like association user and articles.

```<code>  can :create, Like do |like|
    !Like.exists?(user: user, article: like.article)
</code>```

As I've said before, there's no way to avoid this, unless you do some manipulations in the @article collection.

An advanced idea I can think of is to load @articles_liked and @articles_no_like, in one database transaction, and then mixing them for display, this requires a bit of work.

Body:
From the DB point of view.
For example, I have 30 records on page (articles) and I want to check whether I can create "Like" or not. So, there will be 30 queries to the db to check this ability. What is the best practice to perform such ability check?

<% @articles.each do |article| %>
  <% if can? :create, Like.new(user: user, article: article) %>
      <%= link_to "Like!", like_path(article) %>
  <% end %>
<% end %>

UPDATE: Add ability.rb

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new
    if user.admin?
      can :manage, :all
    else
      can :create, Like do |like|
        !Like.exists?(user: user, article: like.article)
      end
    end
  end
end

Body:
Abilities per se are not stored in the database. here's an example

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user (not logged in)
    if user.admin?
      can :manage, :all
    else
      can :read, :all
    end
  end
end

As you can see, it doesn't touch the database, since you already have a user variable, all you needed to do was ask about an attribute.

In your example, I assume you already have an 'user' loaded, and of course, you have a lot of articles already fetched.

if you cancan ability is, for example:

  user ||= User.new
  can :manage, Article do |a|
      a.user_id== user.id
    end

then no queries are made, since you already have all the information about an article.

However, if you have to load extra information, something like

  can :manage, Article do |i|
      user.friends_articles.exists?(i.id)
    end

then a query is made (you had to see if the article belonged to the user's friend's collection).

No matter the scenario, there is no escape from asking each article for permissions, unless of course, you load only the articles an user can 'like', then, there is no need for asking ;).

EDIT:

Let's examine your ability.rb

if user.admin?
  can :manage, :all

User.admin?, assuming admin? is just an attribute, then it is already loaded, and no additional queries are made.

However, exists? consults the database, it searches for a like association user and articles.

  can :create, Like do |like|
    !Like.exists?(user: user, article: like.article)

As I've said before, there's no way to avoid this, unless you do some manipulations in the @article collection.

An advanced idea I can think of is to load @articles_liked and @articles_no_like, in one database transaction, and then mixing them for display, this requires a bit of work.


问:
Emacs: print with line numbers
Does anyone know how to print with the line numbers of the code in the margin? I can display the line number, cannot have that in the printout. Thanks!</p>

答:
Sorry for the solution on such an old post.  I used ps-print-buffer rather than print-buffer, since the results are much nicer looking. Anyway, for some reason it is not documented in the manual, but if you look at the source for ps-print.el, you find the ps-line-number variable that you can set to non-nil in order include line numbers.

```<code>M-x set-variable RET ps-line-number RET t
</code>```

That should set it temporarily so that you can print. You may want to set it permanently in your init.el.

You can also print using the M-x pr-interface command, which brings up a buffer of all sorts of printing options.

Title: Emacs: print with line numbers

Body:
Sorry for the solution on such an old post.  I used ps-print-buffer rather than print-buffer, since the results are much nicer looking. Anyway, for some reason it is not documented in the manual, but if you look at the source for ps-print.el, you find the ps-line-number variable that you can set to non-nil in order include line numbers.

M-x set-variable RET ps-line-number RET t

That should set it temporarily so that you can print. You may want to set it permanently in your init.el.

You can also print using the M-x pr-interface command, which brings up a buffer of all sorts of printing options.


问:
Show sharedpreference inside RecyclerView Adapter
I have problem to pass context from Activity to Adapter.

I am calling my sharedpreference like this:

```<code>    SharedPreferences pref = PreferenceManager
            .getDefaultSharedPreferences(ctx);
    String userObject = pref.getString(key, null);
</code>```

And this one need context, so i am using : getApplicationContext()

But this not work in the Adapter (RecyclerView), is there someone facing the same issue ?

Adding the adapter into the Manifest file will solve the problem ? (Just a suggestion)

答:
In your adapter create constructor with Context like this,

```<code>public AdapterList(Context ctx){
    SharedPreferences pref = PreferenceManager
            .getDefaultSharedPreferences(ctx);
    String userObject = pref.getString(key, null);
}
</code>```

and create it by passing

```<code>    adapter = new YourAdapter(getApplicationContext());
</code>```

Body:
I have problem to pass context from Activity to Adapter.

I am calling my sharedpreference like this:

    SharedPreferences pref = PreferenceManager
            .getDefaultSharedPreferences(ctx);
    String userObject = pref.getString(key, null);

And this one need context, so i am using : getApplicationContext()

But this not work in the Adapter (RecyclerView), is there someone facing the same issue ?

Adding the adapter into the Manifest file will solve the problem ? (Just a suggestion)

Body:
In your adapter create constructor with Context like this,

public AdapterList(Context ctx){
    SharedPreferences pref = PreferenceManager
            .getDefaultSharedPreferences(ctx);
    String userObject = pref.getString(key, null);
}

and create it by passing

    adapter = new YourAdapter(getApplicationContext());


答:
I am not sure what you are asking but here is a solution that I can think of.
Pass the context of the calling activity in your adapter through constructor and then use that context.

```<code>Context ctx;

public YourAdapter(Context ctx){
    this.ctx = ctx;
}
</code>```

now in your adapter you can do this

```<code>SharedPreferences pref = PreferenceManager
        .getDefaultSharedPreferences(ctx);
String userObject = pref.getString(key, null);
</code>```

Title: Show sharedpreference inside RecyclerView Adapter

Body:
I am not sure what you are asking but here is a solution that I can think of.
Pass the context of the calling activity in your adapter through constructor and then use that context.

Context ctx;

public YourAdapter(Context ctx){
    this.ctx = ctx;
}

now in your adapter you can do this

SharedPreferences pref = PreferenceManager
        .getDefaultSharedPreferences(ctx);
String userObject = pref.getString(key, null);


问:
editing file lines in place python 2.6
I have multiple files that I'm iterating through and for each file I check if a pattern exists there or not and the pattern can either exist once or multiple times or it doesn't exist at all. I want to edit the line that has the pattern once the pattern is found and rewrite the line with the pattern only. If the pattern is not there then I close the file without any modifications.
My code:

```<code>for root, dirs, files in os.walk('C:/Users/Documents/'):
    for fname in files:
            for line in fileinput.input(os.path.join(root, fname), inplace = 1):
                    if re.search(r"([\w-d])", line):
                        x=re.sub(r"([\w-d])", r"(\1).", line)
                        print line.replace(line,x)
</code>```

The problem is it changes the pattern fine when it finds it but for the files that doesn't have the pattern it deletes their contents completely. And if the pattern exists in multiple lines, it keeps one line only and deletes the rest. What am I missing?

EDIT

I'm flexible also to use "open" or any other method that can solve my problem. My main concern is I don't want to rewrite the lines in files that don't have the pattern. For tracking purposes I want to only modify the files that has the pattern. so far my research online [1] [2][3] shows that I can either write to a temp file and use it later as original file or read all the lines and then write all of them again regardless if the file has the pattern or not. is there a better way of solving this problem?

答:
but for the files that doesn't have the pattern it deletes their contents completely

Yes because that's how fileinput.input works. You need to print all lines, no matter whether you changed them or not.

```<code>for line in fileinput.input(os.path.join(root, fname), inplace=1):
    if re.search(r"([\w-d])", line):
        x=re.sub(r"([\w-d])", r"(\1).", line)
        print line.replace(line, x)
    else:
        print line
</code>```

Also consider using sys.stdout.write(line) as print adds a new line. Whereas line is the line read from the file including the new line at the end.

Thus if we have a file called test.txt with the following contents:

```<code>a1
b2
c3
</code>```

Then if we do this:

```<code>for line in fileinput.input("test.txt", inplace=1):
    if line.strip() == "b2":
        sys.stdout.write("-> ")
        sys.stdout.write(line)
    else:
        sys.stdout.write(line)
</code>```

Then after that the file will look like this:

```<code>a1
-> b2
c3
</code>```

So you do need to write unchanged lines as well.

Edit:

The most flexible is probably to do it like that. However you could read the file beforehand to check if the pattern exist and then do the same:

```<code>f = open(os.path.join(root, fname), "r")
found = False
for line in f:
    if re.search(r"([\w-d])", line):
        found = True
        break
f.close()

if found:
    for line in fileinput.input(os.path.join(root, fname), inplace=1):
        if re.search(r"([\w-d])", line):
            x=re.sub(r"([\w-d])", r"(\1).", line)
            print line.replace(line, x)
        else:
            print line
</code>```

Title: editing file lines in place python 2.6

Body:
I have multiple files that I'm iterating through and for each file I check if a pattern exists there or not and the pattern can either exist once or multiple times or it doesn't exist at all. I want to edit the line that has the pattern once the pattern is found and rewrite the line with the pattern only. If the pattern is not there then I close the file without any modifications.
My code:

for root, dirs, files in os.walk('C:/Users/Documents/'):
    for fname in files:
            for line in fileinput.input(os.path.join(root, fname), inplace = 1):
                    if re.search(r"([\w-d])", line):
                        x=re.sub(r"([\w-d])", r"(\1).", line)
                        print line.replace(line,x)

The problem is it changes the pattern fine when it finds it but for the files that doesn't have the pattern it deletes their contents completely. And if the pattern exists in multiple lines, it keeps one line only and deletes the rest. What am I missing?

EDIT

I'm flexible also to use "open" or any other method that can solve my problem. My main concern is I don't want to rewrite the lines in files that don't have the pattern. For tracking purposes I want to only modify the files that has the pattern. so far my research online [1] [2][3] shows that I can either write to a temp file and use it later as original file or read all the lines and then write all of them again regardless if the file has the pattern or not. is there a better way of solving this problem?

Body:
but for the files that doesn't have the pattern it deletes their contents completely

Yes because that's how fileinput.input works. You need to print all lines, no matter whether you changed them or not.

for line in fileinput.input(os.path.join(root, fname), inplace=1):
    if re.search(r"([\w-d])", line):
        x=re.sub(r"([\w-d])", r"(\1).", line)
        print line.replace(line, x)
    else:
        print line

Also consider using sys.stdout.write(line) as print adds a new line. Whereas line is the line read from the file including the new line at the end.

Thus if we have a file called test.txt with the following contents:

a1
b2
c3

Then if we do this:

for line in fileinput.input("test.txt", inplace=1):
    if line.strip() == "b2":
        sys.stdout.write("-> ")
        sys.stdout.write(line)
    else:
        sys.stdout.write(line)

Then after that the file will look like this:

a1
-> b2
c3

So you do need to write unchanged lines as well.

Edit:

The most flexible is probably to do it like that. However you could read the file beforehand to check if the pattern exist and then do the same:

f = open(os.path.join(root, fname), "r")
found = False
for line in f:
    if re.search(r"([\w-d])", line):
        found = True
        break
f.close()

if found:
    for line in fileinput.input(os.path.join(root, fname), inplace=1):
        if re.search(r"([\w-d])", line):
            x=re.sub(r"([\w-d])", r"(\1).", line)
            print line.replace(line, x)
        else:
            print line


问:
Overlap div over html5 video player issue in UC browser
Is that possible to overlap div element over HTML5 video player in UC browser.

```<code><div class="test">
  <div class="goover"></div>
  <video width="400" controls>
    <source src="http://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">`
    Your browser does not support HTML5 video.
  </video>
</div>
</code>```

fiddle

答:
How about this:

https://jsfiddle.net/zpjsz8g8/1/

```<code>.test { position: relative }
.goover {
    position: absolute;
    background: #ff0000;
    top: 0;
    bottom: 0;
    left: 0;
    /*right:0px*/
    width: 400 px;
    z - index: 1;
}
</code>```

or

```<code>var videoContainer = document.getElementsByTagName('video')[0];
var goover = document.getElementsByClassName('goover')[0];

goover.style.height = videoContainer.getBoundingClientRect().height + 'px';
goover.style.width = videoContainer.getBoundingClientRect().width + 'px'
</code>```

Body:
Is that possible to overlap div element over HTML5 video player in UC browser.

  <video width="400" controls>
    <source src="http://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">`
    Your browser does not support HTML5 video.
  </video>

fiddle

Body:
How about this:

https://jsfiddle.net/zpjsz8g8/1/

.test { position: relative }
.goover {
    position: absolute;
    background: #ff0000;
    top: 0;
    bottom: 0;
    left: 0;
    /*right:0px*/
    width: 400 px;
    z - index: 1;
}

or

var videoContainer = document.getElementsByTagName('video')[0];
var goover = document.getElementsByClassName('goover')[0];

goover.style.height = videoContainer.getBoundingClientRect().height + 'px';
goover.style.width = videoContainer.getBoundingClientRect().width + 'px'


问:
How to combine C# code with JavaScript code in onclick?
I want to use C# code and JavaScript in the same onclientclick event.

```<code><asp:LinkButton ID="lbTest" runat="server" Text='<%#Text%>'
    OnClientClick='<%#string.Format("passAccessory(\"{0}\");", Eval("Ref"))%>; window.close();' />
</code>```

But it doesn't work. How to do that?

Thanks.

答:
add an OnClientClick and OnClick events. The OnClientClick event will be executed first then the OnClick event.</p>

```<code><asp:LinkButton ID="lbTest" runat="server" OnClientClick="test()" OnClick="lbTest_Click" />
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I want to use C# code and JavaScript in the same onclientclick event.

<asp:LinkButton ID="lbTest" runat="server" Text='<%#Text%>'
    OnClientClick='<%#string.Format("passAccessory(\"{0}\");", Eval("Ref"))%>; window.close();' />

But it doesn't work. How to do that?

Thanks.

Body:
add an OnClientClick and OnClick events. The OnClientClick event will be executed first then the OnClick event.

<asp:LinkButton ID="lbTest" runat="server" OnClientClick="test()" OnClick="lbTest_Click" />


问:
Why can't I change the value of a variable captured by copy in a lambda function?
I'm reading the C++ Programming Language by B. Stroustrup in its section 11.4.3.4 "mutable Lambdas", which says the following:

Usually, we don’t want to modify the state of the function object (the
  closure), so by default we can’t. That is, the operator()() for the
  generated function object (§11.4.1) is a const member function. In the
  unlikely event that we want to modify the state (as opposed to
  modifying the state of some variable captured by reference; §11.4.3),
  we can declare the lambda mutable.

I don't understand why the default for the operator()() is const when the variable is captured by value. What's the rational for this? What could go wrong when I change the value of a variable, which is copied into the function object?

答:
One can think of lambdas as classes with operator()(), which by default is defined as const. That is, it cannot change the state of the object. Consequently, the lambda will behave as a regular function and produce the same result every time it is called. If instead, we declare the lambda as mutable, it is possible for the lambda to modify the internal state of the object, and provide a different result for different calls depending on that state. This is not very intuitive and therefore discouraged.

For example, with mutable lambda, this can happen:

```<code>#include <iostream>

int main()
{
  int n = 0;
  auto lam = [=]() mutable {
    n += 1;
    return n;
  };

  std::cout << lam() << "\n";  // Prints 1
  std::cout << n << "\n";      // Prints 0
  std::cout << lam() << "\n";  // Prints 2
  std::cout << n << "\n";      // Prints 0
}
</code>```

Body:
One can think of lambdas as classes with operator()(), which by default is defined as const. That is, it cannot change the state of the object. Consequently, the lambda will behave as a regular function and produce the same result every time it is called. If instead, we declare the lambda as mutable, it is possible for the lambda to modify the internal state of the object, and provide a different result for different calls depending on that state. This is not very intuitive and therefore discouraged.

For example, with mutable lambda, this can happen:

#include <iostream>

int main()
{
  int n = 0;
  auto lam = [=]() mutable {
    n += 1;
    return n;
  };

  std::cout << lam() << "\n";  // Prints 1
  std::cout << n << "\n";      // Prints 0
  std::cout << lam() << "\n";  // Prints 2
  std::cout << n << "\n";      // Prints 0
}


问:
How can I fix UI Control Map controls from losing their mappings?
I am creating a Coded UI Test on my machine (Windows 8.1) by creating all the mappings and manually writing the tests. (I do not use Action Recordings) When they run at night on my Nightly machine (Server 2012R2) the action to select my Group Lookup window actually selects my Customer Code lookup window during the test run.

Remapping the controls on my machine does not fix this, and it is not possible to remap them on the Server2012R2 machine as it is only meant to run the tests not to run Visual Studio.

The available search properties on the control are not helpful enough to differentiate the controls. Instead I tried modifying the Friendly Name property on the control and used the following code:

```<code>public void ClickControl(WinControl mycontrol, string resultId)
{
    UITestControlCollection controls = mycontrol.FindMatchingControls();
    foreach (UITestControl allControls in controls)
    {
        if (allControls.FriendlyName == resultId)
        {
            Mouse.Click(allControls);
        }
    }
}
</code>```

But when I run the code it seems to not use the modified value of the Friendly Name when the program is running.

Is there a way to ensure I am selecting the correct control before I send the Mouse.Click event?

答:
I found a work around by creating the following method. It's not as clean as I would like and I have to use the UIMap tool to find the ControlName, but the code is making my tests pass when I call it. </p>

```<code>public static UITestControl FindControl(WinControl myControl, string controlName)
        {
            try
            {
                UITestControlCollection controls = myControl.FindMatchingControls();
                foreach (UITestControl currentControl in controls)
                {
                    if (currentControl.ControlType == ControlType.Button)
                    {
                        WinButton mycont = (WinButton)currentControl;
                        if (mycont.ControlName == controlName)
                        {
                            return mycont;
                        }
                    }
                    if (currentControl.ControlType == ControlType.Edit)
                    {
                        WinEdit mycont = (WinEdit)currentControl;
                        if (mycont.ControlName == controlName)
                        {
                            return mycont;
                        }
                    }
                }
                return myControl;
            }
            catch
            {
                return myControl;
            }
        }
</code>```

Body:
I am creating a Coded UI Test on my machine (Windows 8.1) by creating all the mappings and manually writing the tests. (I do not use Action Recordings) When they run at night on my Nightly machine (Server 2012R2) the action to select my Group Lookup window actually selects my Customer Code lookup window during the test run.

Remapping the controls on my machine does not fix this, and it is not possible to remap them on the Server2012R2 machine as it is only meant to run the tests not to run Visual Studio.

The available search properties on the control are not helpful enough to differentiate the controls. Instead I tried modifying the Friendly Name property on the control and used the following code:

public void ClickControl(WinControl mycontrol, string resultId)
{
    UITestControlCollection controls = mycontrol.FindMatchingControls();
    foreach (UITestControl allControls in controls)
    {
        if (allControls.FriendlyName == resultId)
        {
            Mouse.Click(allControls);
        }
    }
}

But when I run the code it seems to not use the modified value of the Friendly Name when the program is running.

Is there a way to ensure I am selecting the correct control before I send the Mouse.Click event?

Body:
I found a work around by creating the following method. It's not as clean as I would like and I have to use the UIMap tool to find the ControlName, but the code is making my tests pass when I call it.

public static UITestControl FindControl(WinControl myControl, string controlName)
        {
            try
            {
                UITestControlCollection controls = myControl.FindMatchingControls();
                foreach (UITestControl currentControl in controls)
                {
                    if (currentControl.ControlType == ControlType.Button)
                    {
                        WinButton mycont = (WinButton)currentControl;
                        if (mycont.ControlName == controlName)
                        {
                            return mycont;
                        }
                    }
                    if (currentControl.ControlType == ControlType.Edit)
                    {
                        WinEdit mycont = (WinEdit)currentControl;
                        if (mycont.ControlName == controlName)
                        {
                            return mycont;
                        }
                    }
                }
                return myControl;
            }
            catch
            {
                return myControl;
            }
        }


问:
unexpected symbol 'end of file'
using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour {

```<code>public GameObject player;

private Vector3 offset;

void Start ()
{
    offset = transform.position - player.transform.position;
}
</code>```

答:
As Flaming Zombie stated, you are missing a curly brace. Below should work for you.</p>

```<code>using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour
{
    public GameObject player;

    private Vector3 offset;

    void Start ()
    {
        offset = transform.position - player.transform.position;
    }
}
</code>```

Title: unexpected symbol 'end of file'

Body:
As Flaming Zombie stated, you are missing a curly brace. Below should work for you.

using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour
{
    public GameObject player;

    private Vector3 offset;

    void Start ()
    {
        offset = transform.position - player.transform.position;
    }
}


问:
jQuery multiple target IDs for click function
This may be a little redundant but I was wondering if there's a way to improve the code by shortening it to avoid repetition.

```<code>$('a[href*="#about"]').click(function()
</code>```

I want to target #about #products #process #gallery #contact

I want to avoid:

```<code>$('a[href*="#about"]', 'a[href*="#process"]', a[href*="#etc"]' ).click(function()
</code>```

答:
Alternatively you can set up a single click handler on the page, and delegate based on which element was clicked.

```<code>var handledHrefs = ['#about', '#products', '#process', '#gallery', '#contact'];
$('body').on('click', 'a[href^=#]', function (e) {
  if (handledHrefs.includes(e.target.attr('href'))) {
    // ...
  }
});
</code>```

This actually has a better performance than attaching individual event handlers, surprisingly enough.

ContentLicense: CC BY-SA 4.0

Body:
This may be a little redundant but I was wondering if there's a way to improve the code by shortening it to avoid repetition.

$('a[href*="#about"]').click(function()

I want to target #about #products #process #gallery #contact

I want to avoid:

$('a[href*="#about"]', 'a[href*="#process"]', a[href*="#etc"]' ).click(function()

Body:
Alternatively you can set up a single click handler on the page, and delegate based on which element was clicked.

var handledHrefs = ['#about', '#products', '#process', '#gallery', '#contact'];
$('body').on('click', 'a[href^=#]', function (e) {
  if (handledHrefs.includes(e.target.attr('href'))) {
    // ...
  }
});

This actually has a better performance than attaching individual event handlers, surprisingly enough.


问:
Html / Php form not adding to SQL database
I've been working on this for hours now and including rebuilding my whole code I cannot figure out what is wrong. The HTML form is supposed to populate the patients SQL database but it is not working. I have a similar form that I am using on another part of the website that works flawlessly but this on doesn't seem to and a can't figure out why.

thanks for your help

Here is a picture of thedatabase fields :
Database fields

Heres the code:

<?php

//session_start();

//if( isset($_SESSION['user_id']) ){
//  header("Location: /");
//}

require 'connection.php';

$message = '';

if(!empty($_POST['name']) && !empty($_POST['dob']) && !empty($_POST['nok']) && !empty($_POST['nok_add']) && !empty($_POST['nok_phone'])&& !empty($_POST['doa'])&& !empty($_POST['allergies'])):

  // Enter the new user in the database
  $sql = "INSERT INTO patients (name, dob, nok, nok_add, nok_phone, doa, allergies) VALUES (:name, :dob, :nok, :nok_add, :nok_phone, :doa, :allergies)";
  $stmt = $conn->prepare($sql);

  $stmt->bindParam(':name', $_POST['name']);
  $stmt->bindParam(':dob', $_POST['dob']);
  $stmt->bindParam(':nok', $_POST['nok']);
  $stmt->bindParam(':nok_add', $_POST['nok_add']);
  $stmt->bindParam(':nok_phone', $_POST['nok_phone']);
  $stmt->bindParam(':doa', $_POST['doa']);
  $stmt->bindParam(':allergies', $_POST['allergies']);

  if( $stmt->execute() ):
    $message = 'Successfully created new user';
  else:
    $message = 'Sorry there must have been an issue creating your account';
  endif;

endif;

?>

    <title>Patient Add</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" type="text/css" href="assets/css/style.css">
      <link href="//fonts.googleapis.com/css?fami=Roboto:400,300,200,100&subset=latin,cyrillic" rel="stylesheet">

Patient Add

    <button onClick="window.location='manager_select.php';" class="_button">Back</button>
    <form method="POST" id="add">

Enter the Patient's Details

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

      Date of Birth:
      <input type="text" name="dob">

      Next of Kin:
      <input type="text" name="nok">

      Address:
      <input type="text" name="nok_add">

      Phone:
      <input type="text" name="nok_phone">

      Date of Admission:
      <input type="text" name="dob">

      Allergies:
      <input type="text" name="allergies">

      <?php if(!empty($message)): ?>

<?= $message ?>

      <?php endif; ?>
      <input type="submit">

    </form>

Copyright Ghyll Court Residental Home 2017

  </script>

```

答: I am not completely sure about this being the safest way but instead of using MSQLI PDO why don't you try simple mysqli_query($conn,$sql);


问:
Removing digits from list elements
I have a list of job titles (12,000 in total) formatted in this way:

Career_List = ['1) ABLE SEAMAN', '2) ABRASIVE GRADER', '3) ABRASIVE GRINDER']

How do I remove the numbers, parentheses, and spaces from the list elements so that I end up with this output:

    Career_List_Updated = ['ABLE SEAMAN', 'ABRASIVE GRADER', 'ABRASIVE GRINDER']

I know that I am unable to simply remove the first three characters because I have more than ten items in my list.

答:
We want to find the first index that STOPS being a bad character and return the rest of the string, as follows. </p>

```<code>def strip_bad_starting_characters_from_string(string):
    bad_chars = set(r"'0123456789 )") # set of characters we don't like
    for i, char in enumerate(string):
        if char not in bad_chars
            # we are at first index past "noise" digits
            return string[i:]

career_list_updated = [strip_bad_starting_characters_from_string(string) for string in career_list]
</code>```

Title: Removing digits from list elements

Body:
We want to find the first index that STOPS being a bad character and return the rest of the string, as follows.

def strip_bad_starting_characters_from_string(string):
    bad_chars = set(r"'0123456789 )") # set of characters we don't like
    for i, char in enumerate(string):
        if char not in bad_chars
            # we are at first index past "noise" digits
            return string[i:]

career_list_updated = [strip_bad_starting_characters_from_string(string) for string in career_list]


问:
Change Action Bar Overflow Icon in an app
I am trying to change the Action Bar Overflow Icon in an app.  I have seen some info on this site but it's not clear to me.  Does anyone know what code I should enter and in what files?  </p>

答:
You can change the Overflow Icon programmatically by using Toolbar.setOverflowIcon() method.

```<code>// ToolBar
Toobar toolbar = (Toolbar) findViewById(R.id.toolbar);

if (toolbar != null) {
    setSupportActionBar(toolbar);
    toolbar.setOverflowIcon(getResources().getDrawable(R.drawable.your_overflow_icon));
}
</code>```

Toolbar XML

```<code><android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorAccent"
    android:minHeight="?attr/actionBarSize"
    app:theme="@style/ThemeOverlay.AppCompat.Light"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

</android.support.v7.widget.Toolbar>
</code>```

or, you can also define a style for custom Overflow Icon in your main styles.xml like this:

```<code><style name="AppTheme.Base" parent="Theme.AppCompat.Light">
    <item name="actionOverflowButtonStyle">@style/OverFlow</item>
</style>

<style name="OverFlow" parent="Widget.AppCompat.ActionButton.Overflow">
    <item name="android:src">@drawable/your_overflow_icon</item>
</style>
</code>```

Body:
You can change the Overflow Icon programmatically by using Toolbar.setOverflowIcon() method.

// ToolBar
Toobar toolbar = (Toolbar) findViewById(R.id.toolbar);

if (toolbar != null) {
    setSupportActionBar(toolbar);
    toolbar.setOverflowIcon(getResources().getDrawable(R.drawable.your_overflow_icon));
}

Toolbar XML

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorAccent"
    android:minHeight="?attr/actionBarSize"
    app:theme="@style/ThemeOverlay.AppCompat.Light"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

</android.support.v7.widget.Toolbar>

or, you can also define a style for custom Overflow Icon in your main styles.xml like this:

<style name="AppTheme.Base" parent="Theme.AppCompat.Light">
    <item name="actionOverflowButtonStyle">@style/OverFlow</item>
</style>

<style name="OverFlow" parent="Widget.AppCompat.ActionButton.Overflow">
    <item name="android:src">@drawable/your_overflow_icon</item>
</style>


问:
Making DDE calls from Java
Wondering if anyone has experience and/or sample code for making DDE calls from Java.  I've done DDE using win32 calls from the stddde library (DdeInitialize, DdeClientTransaction), and could write a JNI wrapper for this, but I was thinking that it might be nice to do it from JNA

I also have some concerns about the fact that DDE calls need to occur from a thread with message pump, and I'm not entirely certain of how to force that in Java.

The calls we'll be doing are pretty simple (equivalent to VBA's DDInitiate, DDEExcecute and DDETerminate functions).

答:
JNA now has a DDE implementation in its contrib repository (the compiled classes are available in the jna-platform artifact):

https://github.com/java-native-access/jna/blob/master/contrib/platform/src/com/sun/jna/platform/win32/DdemlUtil.java

The unit tests contain many usage examples:

https://github.com/java-native-access/jna/blob/master/contrib/platform/test/com/sun/jna/platform/win32/DdemlUtilTest.java

Title: Making DDE calls from Java


问:
Get property value from C# dynamic object by string (reflection?)
Imagine that I have a dynamic variable:

```<code>dynamic d = *something*
</code>```

Now, I create properties for d which I have on the other hand from a string array:

```<code>string[] strarray = { 'property1','property2',..... }
</code>```

I don't know the property names in advance.

How in code, once d is created and strarray is pulled from DB, can I get the values?

I want to get d.property1 , d.property2.

I see that the object has a _dictionary internal dictionary that contains the keys and the values, how do I retrieve them?

答:
Thought this might help someone in the future.

If you know the property name already, you can do something like the following:

```<code>[HttpPost]
[Route("myRoute")]
public object SomeApiControllerMethod([FromBody] dynamic args){
   var stringValue = args.MyPropertyName.ToString();
   //do something with the string value.  If this is an int, we can int.Parse it, or if it's a string, we can just use it directly.
   //some more code here....
   return stringValue;
}
</code>```

Body:
Imagine that I have a dynamic variable:

dynamic d = *something*

Now, I create properties for d which I have on the other hand from a string array:

string[] strarray = { 'property1','property2',..... }

I don't know the property names in advance.

How in code, once d is created and strarray is pulled from DB, can I get the values?

I want to get d.property1 , d.property2.

I see that the object has a _dictionary internal dictionary that contains the keys and the values, how do I retrieve them?

Body:
Thought this might help someone in the future.

If you know the property name already, you can do something like the following:

[HttpPost]
[Route("myRoute")]
public object SomeApiControllerMethod([FromBody] dynamic args){
   var stringValue = args.MyPropertyName.ToString();
   //do something with the string value.  If this is an int, we can int.Parse it, or if it's a string, we can just use it directly.
   //some more code here....
   return stringValue;
}


问:
Why is this c code not changing the value of arr[3]?
I am creating an int array and then tricking c into believing that it's an array of short values. I know it's not good practice but I am just trying to understand why this isn't working. Shouldn't this change the value of arr[3] ?

```<code>#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    int arr[5];
    arr[0] = 0; arr[1] = 0; arr[2] = 0; arr[4] = 0;
    arr[3] = 128;
    ((short*)arr)[6] = 128; // Shouldn't this change arr[3] ? as 6,7 indices in the arr of short would compromise of arr[3] in arr of ints?
    int i = 0;
    for (i = 0; i < 5; i++){
        printf("%d\n", arr[i]);
    }
    return 0;
}
</code>```

PS: Here's a deeper clarification:
When I cast int array to a short array, it seemingly becomes an array of 10 short elements (not 5). So when I change arr[6], I am changing only the first 16 bits of the int arr[3]. So arr[3] should still change and it is NOT that I am changing it to 128 again and not seeing the change.

FOR CLARIFICATION: THIS CODE IS ONLY FOR EXPERIMENTAL REASONS! I AM JUST LEARNING HOW POINTERS WORK AND I GET THAT ITS NOT GOOD PRACTICE.

答:
It is changing arr[3], however you are setting it back to 128 so you arent noticing a change. Change the line to:

((short*)arr)[6] = 72;

and you should see the following output:

Also a couple of things to clean up if you are new to C. You can initialize an array to zero by doing the following.

...
int arr[5] = { 0 };
arr[3] = 128;
...

Hope this helps!

Body:
I am creating an int array and then tricking c into believing that it's an array of short values. I know it's not good practice but I am just trying to understand why this isn't working. Shouldn't this change the value of arr[3] ?

#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    int arr[5];
    arr[0] = 0; arr[1] = 0; arr[2] = 0; arr[4] = 0;
    arr[3] = 128;
    ((short*)arr)[6] = 128; // Shouldn't this change arr[3] ? as 6,7 indices in the arr of short would compromise of arr[3] in arr of ints?
    int i = 0;
    for (i = 0; i < 5; i++){
        printf("%d\n", arr[i]);
    }
    return 0;
}

PS: Here's a deeper clarification:
When I cast int array to a short array, it seemingly becomes an array of 10 short elements (not 5). So when I change arr[6], I am changing only the first 16 bits of the int arr[3]. So arr[3] should still change and it is NOT that I am changing it to 128 again and not seeing the change.

FOR CLARIFICATION: THIS CODE IS ONLY FOR EXPERIMENTAL REASONS! I AM JUST LEARNING HOW POINTERS WORK AND I GET THAT ITS NOT GOOD PRACTICE.


问:
SQL how to filter out a specific row with conflicting where clause
This should be a simple problem but for some reason I can't get it to work. I've got a table like the following:

```<code>|Name|Attribute|
----------------
|Foo |     1   |
|Foo |     2   |
|Foo |     3   |
|Bar |     1   |
|Bar |     2   |
|Bar |     3   |
|Yum |     1   |
|Yum |     2   |
|Yum |     3   |
</code>```

I want to filter it like the following

```<code>|Name|Attribute|
----------------
|Foo |     2   |
|Foo |     3   |
|Bar |     1   |
|Bar |     2   |
|Bar |     3   |
</code>```

Note that I've removed all the "Yum" and removed a "Foo" only when Attribute = 1

Problem is that when I do something like this

```<code>SELECT *
FROM table
WHERE name in ('Foo', 'Bar')
AND (name != 'Foo' AND attribute != 1)
</code>```

I get this result

```<code>|Name|Attribute|
----------------
|Bar |     2   |
|Bar |     3   |
</code>```

I would have thought that the brackets group things together?

答:
```<code>Select
   *
From
   table
Where
   (Name <> 'Yum') and
   not (Name = 'Foo' and attribute = 1)
</code>```

Body:
This should be a simple problem but for some reason I can't get it to work. I've got a table like the following:

|Name|Attribute|
----------------
|Foo |     1   |
|Foo |     2   |
|Foo |     3   |
|Bar |     1   |
|Bar |     2   |
|Bar |     3   |
|Yum |     1   |
|Yum |     2   |
|Yum |     3   |

I want to filter it like the following

|Name|Attribute|
----------------
|Foo |     2   |
|Foo |     3   |
|Bar |     1   |
|Bar |     2   |
|Bar |     3   |

Note that I've removed all the "Yum" and removed a "Foo" only when Attribute = 1

Problem is that when I do something like this

SELECT *
FROM table
WHERE name in ('Foo', 'Bar')
AND (name != 'Foo' AND attribute != 1)

I get this result

|Name|Attribute|
----------------
|Bar |     2   |
|Bar |     3   |

I would have thought that the brackets group things together?


问:
Insert list evenly in another list
I am wanting to merge 2 lists together with jQuery but I am not even sure where to start. Instead of prepending or appeding the list I need to place each item between the other list. Not quite sure the best way to word this but basically I have the following HTML

```<code><ul>
  <li>A<li>
  <li>B<li>
  <li>C<li>
  <li>D<li>
  <li>E<li>
</ul>

<ul>
  <li>1<li>
  <li>2<li>
  <li>3<li>
  <li>4<li>
  <li>5<li>
</ul>
</code>```

And I am wanting a way to get the following:

```<code><ul>
  <li>A<li>
  <li>1<li>
  <li>B<li>
  <li>2<li>
  <li>C<li>
  <li>3<li>
  <li>D<li>
  <li>4<li>
  <li>E<li>
  <li>5<li>
</ul>
</code>```

答:
Short answer

You can treat a selector from jQuery as any other array, so you can map the two selections into a new array containing the intertwined result (a1b2c3..) and move the elements into a new parent. Sometimes the hardest part of finding an answer is knowing how to word the problem.

Keep in mind you'll need to do some adjustments if your lists are not of the same length.

Working demo

//Intertwine them
var intertwined = $.map($("#first li"), function(v, i) {
  return [v, $("#second li")[i]];
});

//Remove them
$(intertwined).remove();

//Add them to a new parent
$.each(intertwined, function(i, e) {
  $("#intertwined").append($(e))
});

//Clean old parents
$("#first, #second").remove();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="first">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul>
<ul id="second">
  <li>a</li>
  <li>b</li>
  <li>c</li>
  <li>d</li>
  <li>e</li>
</ul>

<ul id="intertwined">
</ul></code>```

Title: Insert list evenly in another list

Body:
I am wanting to merge 2 lists together with jQuery but I am not even sure where to start. Instead of prepending or appeding the list I need to place each item between the other list. Not quite sure the best way to word this but basically I have the following HTML

A

B

C

D

E

1

2

3

4

5

And I am wanting a way to get the following:

A

1

B

2

C

3

D

4

E

5

Body:
Short answer

You can treat a selector from jQuery as any other array, so you can map the two selections into a new array containing the intertwined result (a1b2c3..) and move the elements into a new parent. Sometimes the hardest part of finding an answer is knowing how to word the problem.

Keep in mind you'll need to do some adjustments if your lists are not of the same length.

Working demo

//Intertwine them
var intertwined = $.map($("#first li"), function(v, i) {
  return [v, $("#second li")[i]];
});

//Remove them
$(intertwined).remove();

//Add them to a new parent
$.each(intertwined, function(i, e) {
  $("#intertwined").append($(e))
});

//Clean old parents
$("#first, #second").remove();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="first">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul>
<ul id="second">
  <li>a</li>
  <li>b</li>
  <li>c</li>
  <li>d</li>
  <li>e</li>
</ul>

<ul id="intertwined">
</ul>


问:
tracking submissions by registered and anonymous users in laravel
I am using Laravel's pre-build Auth code.  I have another table submissions which  looks like this

```<code>Schema::create( 'submissions', function( Blueprint $table ) {
    $table->increments( 'id' );
    $table->enum( 'complete', [ 'yes', 'no' ] );
    $table->string( 'formName' );
    $table->timestamps();

    // Reference to User ID but only when submitted by a registered user...
    //$table->integer( 'user_id' )->unsigned();
    //$table->foreign( 'user_id' )->references( 'id' )->on( 'users' );

    $table->integer( 'status_id' )->unsigned();
    $table->foreign( 'status_id' )->references( 'id' )->on( 'status' );
});
</code>```

When a submission is by a registered user I would like to reference that user id, But anonymous submissions are possible and I need some indicator that the submission is by an anonymous user.

should I?

creating an actual users records for an anon user

change my user_id foreign key to allow NULL values to indicate the anon user

or is there a better way?

EDIT: To expand on my use case

My application is basically a collection of forms( aren't they all ) for users to input and update information.  Most of the forms will be restricted to Authenticated users.  2-5 forms will be available to both authenticated and non-authenticated users.  IF the form submission is done by an Authenticated user I want to indicate to admins who that user is.  If the user was not authenticated then I simply want to indicate to the admin that it was an anonymous submission.  So Anon users wont require any logic, and this will simply be a flag to indicate the source of hte submission to Admins.  That said it sounds like nullable() key on user_id may be the way to go.

Going forward I'm looking at adding tracking so if a submission is made by a user that becomes an authenticated user I can back track and update their submissions to indicate the user.

Thanks

答:
This really depends on the rest of your system.

For instance, projects like phpBB and Shimmie use a real Anon user. But they flag that user as the guest account in some way. I think Shimmie uses a flag in the users table (ie. users.is_guest = 1) and just authenticates every guest as that user for permission masking. phpBB I believe looks for a user with a certain user_type and within a certain group (ie. users.user_type = 2 && users.groups.contains(1)). Again, phpBB authenticates guests as that Anon user.

One easy way to flag that user (assuming you just have the one non-user user) is to forcibly set its PK to 0 or -1. It'd save space in the database, inherently prevent duplicate "guest" users, and provide you an easy way to prevent routes from showing that user (->where('id', '[1-9][0-9]*')).

The alternative (not having a real user or group) means that your authorization logic will need to be able to handle an unauthenticated user. Without more information on your authorization logic, it's a bit difficult to advise.

I'd generally prefer using a real user or real group to pass to my authorization logic. It'd keep everything consistent in the code and provide a common interface in the UI for site admins to change guest permissions.

It'd just require a little work to prevent people from accessing that user via routes or from showing up in user listings and the like. It might be helpful to create a scope on your model to filter out non-user users (your guest account, any bot accounts, etc).

Body:
I am using Laravel's pre-build Auth code.  I have another table submissions which  looks like this

Schema::create( 'submissions', function( Blueprint $table ) {
    $table->increments( 'id' );
    $table->enum( 'complete', [ 'yes', 'no' ] );
    $table->string( 'formName' );
    $table->timestamps();

    // Reference to User ID but only when submitted by a registered user...
    //$table->integer( 'user_id' )->unsigned();
    //$table->foreign( 'user_id' )->references( 'id' )->on( 'users' );

    $table->integer( 'status_id' )->unsigned();
    $table->foreign( 'status_id' )->references( 'id' )->on( 'status' );
});

When a submission is by a registered user I would like to reference that user id, But anonymous submissions are possible and I need some indicator that the submission is by an anonymous user.

should I?

creating an actual users records for an anon user

change my user_id foreign key to allow NULL values to indicate the anon user

or is there a better way?

EDIT: To expand on my use case

My application is basically a collection of forms( aren't they all ) for users to input and update information.  Most of the forms will be restricted to Authenticated users.  2-5 forms will be available to both authenticated and non-authenticated users.  IF the form submission is done by an Authenticated user I want to indicate to admins who that user is.  If the user was not authenticated then I simply want to indicate to the admin that it was an anonymous submission.  So Anon users wont require any logic, and this will simply be a flag to indicate the source of hte submission to Admins.  That said it sounds like nullable() key on user_id may be the way to go.

Going forward I'm looking at adding tracking so if a submission is made by a user that becomes an authenticated user I can back track and update their submissions to indicate the user.

Thanks


问:
Vector drawable not drawn correctly in Android Studio
I'm in the middle of a redesign for an app, and I am having problems with getting some of the icons to draw correctly in Android Studio. I'm using Sketch for all of the design work.

I've looked around quite a bit online to try and figure out a solution but am having a very difficult explaining the problem with search terms, so I thought I would try posting screenshots and providing a Sketch file to see if the StackOverflow community can help.

I think the problem has to do with the construction of my vector paths in Sketch, in particular with how they overlap one another. Here is an example of an icon I'm working on:

Earth shape with longitude and latitude lines

As you can see, I have no problems creating the icon in Sketch. However, after I export the icon to an SVG file, and import it into Android Studio, here is how it is getting drawn:

Icon drawn in Android Studio

I only run into this problem when the shapes get more complex and start overlapping one another. Until now, I have been able to keep things simple for most icons, but it's getting to the point where I need to find a solution.

I was going to post a link to the Sketch file in Dropbox, but I need more reputation points to do that. If needed, hopefully I can provide that link to someone in a response.

Any help would be much appreciated. If this is a duplicate question, I apologize. In all of my searching, I may not have worded the issue in such a way to get good results.

@Paul LeBeau, thank you for the response. Here is the SVG code exported from Sketch:

```<code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg width="24px" height="24px" viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <!-- Generator: Sketch 3.8.3 (29802) - http://www.bohemiancoding.com/sketch -->
    <title>globe</title>
    <desc>Created with Sketch.</desc>
    <defs></defs>
    <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
        <g id="globe" fill="#368EFA">
            <g id="test" transform="translate(2.000000, 2.000000)">
                <path d="M1.76297407,13 L5.00480805,13 C4.73881764,12.1144772 4.55303608,11.1138143 4.50968627,10 L1.02773406,10 C1.01839018,9.83680058 1.01365419,9.67236691 1.01365419,9.5068271 C1.01365419,9.33666963 1.01865808,9.16768089 1.02852674,9 L4.50968627,9 C4.55303608,7.88618573 4.73881764,6.8855228 5.00480805,6 L1.76915759,6 C1.92639337,5.65361668 2.10620446,5.31965722 2.30671248,5 L5.35559719,5 C6.20744032,2.88601313 7.45296691,1.59423095 7.91693127,1.16221702 C8.43195688,1.06468547 8.96343249,1.01365419 9.5068271,1.01365419 C10.0442032,1.01365419 10.569923,1.06356132 11.0796041,1.15899346 C11.5408038,1.58777803 12.7904304,2.88072886 13.6444028,5 L16.7069417,5 C16.9074497,5.31965722 17.0872608,5.65361668 17.2444966,6 L13.9951919,6 C14.2611824,6.8855228 14.4469639,7.88618573 14.4903137,9 L17.9851275,9 C17.9949961,9.16768089 18,9.33666963 18,9.5068271 C18,9.67236691 17.995264,9.83680058 17.9859201,10 L14.4903137,10 C14.4469639,11.1138143 14.2611824,12.1144772 13.9951919,13 L17.2506801,13 C17.0942093,13.3463294 16.915188,13.6802868 16.7154884,14 L13.6444028,14 C12.7787643,16.1482222 11.506588,17.4473934 11.0611474,17.8580954 C10.5572344,17.95129 10.0377192,18 9.5068271,18 C8.96992723,18 8.44466314,17.9501813 7.93540532,17.8549144 C7.4868821,17.4407166 6.21901315,16.1427067 5.35559719,14 L2.29816579,14 C2.09846621,13.6802868 1.9194449,13.3463294 1.76297407,13 Z M6.02760136,13 L9,13 L9,10 L5.51031179,10 C5.55606369,11.1058076 5.7507371,12.108186 6.02760136,13 Z M6.38814497,14 L9,14 L9,17.9088258 C8.62776002,17.558389 7.2971495,16.2062617 6.38814497,14 Z M9,1.09117415 L9,5 L6.38814497,5 C7.2971495,2.79373835 8.62776002,1.44161098 9,1.09117415 Z M6.02760136,6 L9,6 L9,9 L5.51031179,9 C5.55606369,7.8941924 5.7507371,6.89181397 6.02760136,6 Z M10,13 L12.9723986,13 C13.2492629,12.108186 13.4439363,11.1058076 13.4896882,10 L10,10 L10,13 Z M10,14 L12.611855,14 C11.7028505,16.2062617 10.37224,17.558389 10,17.9088258 L10,14 Z M10,1.09117415 C10.37224,1.44161098 11.7028505,2.79373835 12.611855,5 L10,5 L10,1.09117415 Z M10,6 L12.9723986,6 C13.2492629,6.89181397 13.4439363,7.8941924 13.4896882,9 L10,9 L10,6 Z" id="earth"></path>
                <path d="M9.5,18 L9.5,18 C14.1944204,18 18,14.1944204 18,9.5 C18,4.80557963 14.1944204,1 9.5,1 C4.80557963,1 1,4.80557963 1,9.5 C1,14.1944204 4.80557963,18 9.5,18 L9.5,18 Z M9.5,19 L9.5,19 C4.25329488,19 0,14.7467051 0,9.5 C0,4.25329488 4.25329488,0 9.5,0 C14.7467051,0 19,4.25329488 19,9.5 C19,14.7467051 14.7467051,19 9.5,19 L9.5,19 Z" id="border"></path>
            </g>
        </g>
    </g>
</svg>
</code>```

Here is the code after importing the SVG file directly into Android Studio:

```<code><vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24.0"
    android:viewportHeight="24.0">
<path
    android:pathData="M3.763,15L7.005,15C6.739,14.114 6.553,13.114 6.51,12L3.028,12C3.018,11.837 3.014,11.672 3.014,11.507C3.014,11.337 3.019,11.168 3.029,11L6.51,11C6.553,9.886 6.739,8.886 7.005,8L3.769,8C3.926,7.654 4.106,7.32 4.307,7L7.356,7C8.207,4.886 9.453,3.594 9.917,3.162C10.432,3.065 10.963,3.014 11.507,3.014C12.044,3.014 12.57,3.064 13.08,3.159C13.541,3.588 14.79,4.881 15.644,7L18.707,7C18.907,7.32 19.087,7.654 19.244,8L15.995,8C16.261,8.886 16.447,9.886 16.49,11L19.985,11C19.995,11.168 20,11.337 20,11.507C20,11.672 19.995,11.837 19.986,12L16.49,12C16.447,13.114 16.261,14.114 15.995,15L19.251,15C19.094,15.346 18.915,15.68 18.715,16L15.644,16C14.779,18.148 13.507,19.447 13.061,19.858C12.557,19.951 12.038,20 11.507,20C10.97,20 10.445,19.95 9.935,19.855C9.487,19.441 8.219,18.143 7.356,16L4.298,16C4.098,15.68 3.919,15.346 3.763,15ZM8.028,15L11,15L11,12L7.51,12C7.556,13.106 7.751,14.108 8.028,15ZM8.388,16L11,16L11,19.909C10.628,19.558 9.297,18.206 8.388,16ZM11,3.091L11,7L8.388,7C9.297,4.794 10.628,3.442 11,3.091ZM8.028,8L11,8L11,11L7.51,11C7.556,9.894 7.751,8.892 8.028,8ZM12,15L14.972,15C15.249,14.108 15.444,13.106 15.49,12L12,12L12,15ZM12,16L14.612,16C13.703,18.206 12.372,19.558 12,19.909L12,16ZM12,3.091C12.372,3.442 13.703,4.794 14.612,7L12,7L12,3.091ZM12,8L14.972,8C15.249,8.892 15.444,9.894 15.49,11L12,11L12,8Z"
    android:strokeWidth="1"
    android:fillColor="#368EFA"
    android:strokeColor="#00000000"/>
<path
    android:pathData="M11.5,20L11.5,20C16.194,20 20,16.194 20,11.5C20,6.806 16.194,3 11.5,3C6.806,3 3,6.806 3,11.5C3,16.194 6.806,20 11.5,20L11.5,20ZM11.5,21L11.5,21C6.253,21 2,16.747 2,11.5C2,6.253 6.253,2 11.5,2C16.747,2 21,6.253 21,11.5C21,16.747 16.747,21 11.5,21L11.5,21Z"
    android:strokeWidth="1"
    android:fillColor="#368EFA"
    android:strokeColor="#00000000"/>
</code>```

答:
I've had the same problem too, three of my icons doesn't render properly in Android Studio.

While the root cause is VectorDrawable doesn't support even-odd fillType, to make it work you shouldn't edit it on the .svg files. You must edit it on Sketch itself. This article explain thoroughly about this topic. I'll try to recap some of the main point.

In Sketch. Find your missing shape. In my case, it was a circle shape.

On Fills configuration (Gear shaped icon), change it to Non-Zero.

You need to readjust your shape order, open Layer -> Paths -> Reverse Order.

Export your Grouped shape.

Convert it to VectorDrawable (via Android Studio or 3rd party tools).

Sometimes I need to repeat step 3. Nevertheless, it always works in my case. I hope this solves your problem.

Body:
I'm in the middle of a redesign for an app, and I am having problems with getting some of the icons to draw correctly in Android Studio. I'm using Sketch for all of the design work.

I've looked around quite a bit online to try and figure out a solution but am having a very difficult explaining the problem with search terms, so I thought I would try posting screenshots and providing a Sketch file to see if the StackOverflow community can help.

I think the problem has to do with the construction of my vector paths in Sketch, in particular with how they overlap one another. Here is an example of an icon I'm working on:

Earth shape with longitude and latitude lines

As you can see, I have no problems creating the icon in Sketch. However, after I export the icon to an SVG file, and import it into Android Studio, here is how it is getting drawn:

Icon drawn in Android Studio

I only run into this problem when the shapes get more complex and start overlapping one another. Until now, I have been able to keep things simple for most icons, but it's getting to the point where I need to find a solution.

I was going to post a link to the Sketch file in Dropbox, but I need more reputation points to do that. If needed, hopefully I can provide that link to someone in a response.

Any help would be much appreciated. If this is a duplicate question, I apologize. In all of my searching, I may not have worded the issue in such a way to get good results.

@Paul LeBeau, thank you for the response. Here is the SVG code exported from Sketch:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg width="24px" height="24px" viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">

    <title>globe</title>
    <desc>Created with Sketch.</desc>
    <defs></defs>
    <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
        <g id="globe" fill="#368EFA">
            <g id="test" transform="translate(2.000000, 2.000000)">
                <path d="M1.76297407,13 L5.00480805,13 C4.73881764,12.1144772 4.55303608,11.1138143 4.50968627,10 L1.02773406,10 C1.01839018,9.83680058 1.01365419,9.67236691 1.01365419,9.5068271 C1.01365419,9.33666963 1.01865808,9.16768089 1.02852674,9 L4.50968627,9 C4.55303608,7.88618573 4.73881764,6.8855228 5.00480805,6 L1.76915759,6 C1.92639337,5.65361668 2.10620446,5.31965722 2.30671248,5 L5.35559719,5 C6.20744032,2.88601313 7.45296691,1.59423095 7.91693127,1.16221702 C8.43195688,1.06468547 8.96343249,1.01365419 9.5068271,1.01365419 C10.0442032,1.01365419 10.569923,1.06356132 11.0796041,1.15899346 C11.5408038,1.58777803 12.7904304,2.88072886 13.6444028,5 L16.7069417,5 C16.9074497,5.31965722 17.0872608,5.65361668 17.2444966,6 L13.9951919,6 C14.2611824,6.8855228 14.4469639,7.88618573 14.4903137,9 L17.9851275,9 C17.9949961,9.16768089 18,9.33666963 18,9.5068271 C18,9.67236691 17.995264,9.83680058 17.9859201,10 L14.4903137,10 C14.4469639,11.1138143 14.2611824,12.1144772 13.9951919,13 L17.2506801,13 C17.0942093,13.3463294 16.915188,13.6802868 16.7154884,14 L13.6444028,14 C12.7787643,16.1482222 11.506588,17.4473934 11.0611474,17.8580954 C10.5572344,17.95129 10.0377192,18 9.5068271,18 C8.96992723,18 8.44466314,17.9501813 7.93540532,17.8549144 C7.4868821,17.4407166 6.21901315,16.1427067 5.35559719,14 L2.29816579,14 C2.09846621,13.6802868 1.9194449,13.3463294 1.76297407,13 Z M6.02760136,13 L9,13 L9,10 L5.51031179,10 C5.55606369,11.1058076 5.7507371,12.108186 6.02760136,13 Z M6.38814497,14 L9,14 L9,17.9088258 C8.62776002,17.558389 7.2971495,16.2062617 6.38814497,14 Z M9,1.09117415 L9,5 L6.38814497,5 C7.2971495,2.79373835 8.62776002,1.44161098 9,1.09117415 Z M6.02760136,6 L9,6 L9,9 L5.51031179,9 C5.55606369,7.8941924 5.7507371,6.89181397 6.02760136,6 Z M10,13 L12.9723986,13 C13.2492629,12.108186 13.4439363,11.1058076 13.4896882,10 L10,10 L10,13 Z M10,14 L12.611855,14 C11.7028505,16.2062617 10.37224,17.558389 10,17.9088258 L10,14 Z M10,1.09117415 C10.37224,1.44161098 11.7028505,2.79373835 12.611855,5 L10,5 L10,1.09117415 Z M10,6 L12.9723986,6 C13.2492629,6.89181397 13.4439363,7.8941924 13.4896882,9 L10,9 L10,6 Z" id="earth"></path>
                <path d="M9.5,18 L9.5,18 C14.1944204,18 18,14.1944204 18,9.5 C18,4.80557963 14.1944204,1 9.5,1 C4.80557963,1 1,4.80557963 1,9.5 C1,14.1944204 4.80557963,18 9.5,18 L9.5,18 Z M9.5,19 L9.5,19 C4.25329488,19 0,14.7467051 0,9.5 C0,4.25329488 4.25329488,0 9.5,0 C14.7467051,0 19,4.25329488 19,9.5 C19,14.7467051 14.7467051,19 9.5,19 L9.5,19 Z" id="border"></path>
            </g>
        </g>
    </g>
</svg>

Here is the code after importing the SVG file directly into Android Studio:

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24.0"
    android:viewportHeight="24.0">
<path
    android:pathData="M3.763,15L7.005,15C6.739,14.114 6.553,13.114 6.51,12L3.028,12C3.018,11.837 3.014,11.672 3.014,11.507C3.014,11.337 3.019,11.168 3.029,11L6.51,11C6.553,9.886 6.739,8.886 7.005,8L3.769,8C3.926,7.654 4.106,7.32 4.307,7L7.356,7C8.207,4.886 9.453,3.594 9.917,3.162C10.432,3.065 10.963,3.014 11.507,3.014C12.044,3.014 12.57,3.064 13.08,3.159C13.541,3.588 14.79,4.881 15.644,7L18.707,7C18.907,7.32 19.087,7.654 19.244,8L15.995,8C16.261,8.886 16.447,9.886 16.49,11L19.985,11C19.995,11.168 20,11.337 20,11.507C20,11.672 19.995,11.837 19.986,12L16.49,12C16.447,13.114 16.261,14.114 15.995,15L19.251,15C19.094,15.346 18.915,15.68 18.715,16L15.644,16C14.779,18.148 13.507,19.447 13.061,19.858C12.557,19.951 12.038,20 11.507,20C10.97,20 10.445,19.95 9.935,19.855C9.487,19.441 8.219,18.143 7.356,16L4.298,16C4.098,15.68 3.919,15.346 3.763,15ZM8.028,15L11,15L11,12L7.51,12C7.556,13.106 7.751,14.108 8.028,15ZM8.388,16L11,16L11,19.909C10.628,19.558 9.297,18.206 8.388,16ZM11,3.091L11,7L8.388,7C9.297,4.794 10.628,3.442 11,3.091ZM8.028,8L11,8L11,11L7.51,11C7.556,9.894 7.751,8.892 8.028,8ZM12,15L14.972,15C15.249,14.108 15.444,13.106 15.49,12L12,12L12,15ZM12,16L14.612,16C13.703,18.206 12.372,19.558 12,19.909L12,16ZM12,3.091C12.372,3.442 13.703,4.794 14.612,7L12,7L12,3.091ZM12,8L14.972,8C15.249,8.892 15.444,9.894 15.49,11L12,11L12,8Z"
    android:strokeWidth="1"
    android:fillColor="#368EFA"
    android:strokeColor="#00000000"/>
<path
    android:pathData="M11.5,20L11.5,20C16.194,20 20,16.194 20,11.5C20,6.806 16.194,3 11.5,3C6.806,3 3,6.806 3,11.5C3,16.194 6.806,20 11.5,20L11.5,20ZM11.5,21L11.5,21C6.253,21 2,16.747 2,11.5C2,6.253 6.253,2 11.5,2C16.747,2 21,6.253 21,11.5C21,16.747 16.747,21 11.5,21L11.5,21Z"
    android:strokeWidth="1"
    android:fillColor="#368EFA"
    android:strokeColor="#00000000"/>


问:
Will Google recognize/index Microdata or RDFa markup in template of Angular SPA?
Google has no problem fetching and rendering the dynamically loaded content of all of my Angular SPA pages. So that's good. But will the crawler recognize Microdata and/or RDFa markup in my templates? I want to create some rich snippets for my product pages by following Google's documentation.

Angular currently doesn't have the ability to create dynamic scripts (see this issue), so I was going to try implementing Microdata and/or RDFa markup instead.

Will this work? Do I have to have server-side rendering in-place for google to recognize the rich product snippets? Or is Google smart enough without server-side rendering?

答:
Microdata and RDFa in ng2 sounds like it would be much more difficult to implement than JSON-LD. Taking this path means that you are disseminating the SEO concern throughout all of your components views which is going to result in more complexity and lower your extensibility as far as SEO.

Google recommend JSON-LD over Microdata and RDFa as well, which means that in the long run, its likely the better choice as they'll most likely be focusing on building further SEO optimisations towards JSON-LD.

I haven't been working in ng2 for a while now, but this answer on the original question which relates to the github issue you've linked to suggests that inert script tags are no longer stripped?

I'd test to ensure that inert tags are still striped or whether it has been fixed in the framework before making the choice to move to MD or RDFa tags.

As to answering your original question as to whether google would index MD without SSR, I can't say from experience, but I'd say that there is a high probability of it working as they are rendering the JS version of the site so it would make sense for them to read it.


问:
how to make pdf from list of images using python
I have 190 images, each 1.5 to 3 MB in size and want to make a pdf out of all those images

I was following this
Create PDF from a list of images.

Problem is when I try to make pdf of small number of images like up to 20, it works perfect. Though pdf size becomes 35 to 40 MB and it takes considerable amount of time to execute but when I go with like 100 images, it never executes to output pdf file

```<code>from fpdf import FPDF
pdf = FPDF('P', 'mm', 'A4')

inp   = 'images'
sstr = open(inp).read()
imagelist = sstr.strip().split()
#print imagelist #list of 190 images
for image in imagelist:
    pdf.add_page()
    pdf.image(image,0,0,210,297)

pdf.output("yourfile.pdf", "F")
</code>```

答: Instead of fpdf, try img2pdf.py</p>

Body:
I have 190 images, each 1.5 to 3 MB in size and want to make a pdf out of all those images

I was following this
Create PDF from a list of images.

Problem is when I try to make pdf of small number of images like up to 20, it works perfect. Though pdf size becomes 35 to 40 MB and it takes considerable amount of time to execute but when I go with like 100 images, it never executes to output pdf file

from fpdf import FPDF
pdf = FPDF('P', 'mm', 'A4')

inp   = 'images'
sstr = open(inp).read()
imagelist = sstr.strip().split()
#print imagelist #list of 190 images
for image in imagelist:
    pdf.add_page()
    pdf.image(image,0,0,210,297)

pdf.output("yourfile.pdf", "F")

Body: Instead of fpdf, try img2pdf.py


问:
install python and make in cygwin
I have installed Cygwin Terminal in OS Windows. But I need to install also python and make in cygwin.All of these programs are needed to run petsc library.
Does Someone know how to install these components in cygwin?</p>

答:
Here is a command line version to install python in cygwin

wget rawgit.com/transcode-open/apt-cyg/master/apt-cyg

install apt-cyg /bin

apt-cyg install python

Title: install python and make in cygwin


问:
Adding fragments to a fragment
I am very new to Android (been at it for 1 week), and I can't seem to find the answer to what I am after.

I have in my main activity 3 tabs:

Home

Trending

Profile

When clicking each tab, I effectively load a fragment (corresponding to each one of my tabs) into my Main activity layout.

Additionally I have a fragment called articleEntryFragment.

For every one of my tab fragments I would like to load multiple article entries.

But as I understand it. Nested fragments don't work on APIs earlier than 17, and I want to have as much backward compatibility as possible.

Therefore, how is this very basic principal achieved?

For instance, when you go on the YouTube app, there are tabs, each tab has different videos.

It's my assumption that like in my app. Every tab is its own fragment, and every video listing uses a similar concept to my articleEntry fragment.

What's the proper way to achieve what I am after?

Thank you.

p.s. not looking for anyone to write code for me, but rather, direct me in the right path.

答: Use android.support.v4.app.Fragment and android.support.v13.app.FragmentCompat.

Title: Adding fragments to a fragment


问:
Setting default Index for a Drop Down List in flex 4
I have a drop down list that gets its data from a php web service method.This response is smthing like :

array('id'=>integer,'name'=>'lin')

When the page loads, I want to set the selected index to "lin" initially. How do I do this ?

答:
you just need to set selectedIndex property of dropdownlist control.

ex.

```<code>dwl.selectedIndex = 1; // "Index of "lin"
</code>```

you should do this.

```<code>var iIndex:int;

for(var i:int = 0; i < arrResponse.length; i++)
{

       // if(Array(arrResponse[i])[1] == "lin")

       if(Array(arrResponse[i]).name == "lin") {
            iIndex = i;

       }

}

dwl.selectedIndex = iIndex;
</code>```

Body:
you just need to set selectedIndex property of dropdownlist control.

ex.

dwl.selectedIndex = 1; // "Index of "lin"

you should do this.

var iIndex:int;

for(var i:int = 0; i < arrResponse.length; i++)
{

       // if(Array(arrResponse[i])[1] == "lin")

       if(Array(arrResponse[i]).name == "lin") {
            iIndex = i;

       }

}

dwl.selectedIndex = iIndex;


答: Nested fragments are supported in the Support Library Fragments and provide support back to API 7 (as of version 25.3.1)</p>

Title: Adding fragments to a fragment

Body:
I am very new to Android (been at it for 1 week), and I can't seem to find the answer to what I am after.

I have in my main activity 3 tabs:

Home

Trending

Profile

When clicking each tab, I effectively load a fragment (corresponding to each one of my tabs) into my Main activity layout.

Additionally I have a fragment called articleEntryFragment.

For every one of my tab fragments I would like to load multiple article entries.

But as I understand it. Nested fragments don't work on APIs earlier than 17, and I want to have as much backward compatibility as possible.

Therefore, how is this very basic principal achieved?

For instance, when you go on the YouTube app, there are tabs, each tab has different videos.

It's my assumption that like in my app. Every tab is its own fragment, and every video listing uses a similar concept to my articleEntry fragment.

What's the proper way to achieve what I am after?

Thank you.

p.s. not looking for anyone to write code for me, but rather, direct me in the right path.


问:
Laravel Middleware & Service Provider flow
I have a Laravel 5.4 app where I set the Locale of the app in a middleware, depending on the root domain, because I have a domain for each language. This is because of SEO & Adwords stuff, I can't change that.

Secondly I have a ViewComposerServiceProvider where I prepare Data for the Layout View. This data depends on the Language, but the language hasn't been set yet, because the ServiceProvider is executed first.

What should I do?

答:
If the current workflow is invalid, you should change it.

Probably you should move choosing language into provider (same or other) to have language already set in ViewComposerServiceProvider


问:
The Decorator Design Pattern: What is meant by adding functionality?
I have just gone into studying the Decorator Design Pattern using C#.

I have made an example which kinda functions as I think it is intended except for one thing.

I kinda understood that the whole point of the pattern is to add functionality to an object dynamically.

So when I create an object like this:

```<code>Inventory a = new Ashbringer(new TravelersBagpack());
a.Execute();
</code>```

Then I kinda expected that the point was that the a object would now be able to call the Execute() method which only exists in the Ashbringer class. Thus adding functionality to the a object.

Though this I can't do without adding the Execute() method to the Inventory interface which would ultimately mean I would have to implement the Execute() method to all the classes implementing Inventory Interface or the abstract Decorator.

Perhaps there is a thing or two I don't know about interfaces or perhaps I misunderstand the point of the Decorator Design Pattern?

答:
In the context of streams, let's say you wanted to write to a file. It would look like this:

```<code>using(var fileStream = new FileStream(...))
{ ... }
</code>```

Now let's say you wanted that file to be encrypted. You can do this with a second stream using the decorator pattern:

```<code>using(var fileStream = new FileStream(...))
using(var cryptoStream = new CryptoStream(fileStream))
{ ... }
</code>```

Now let's say you wanted that encrypted file to be compressed. Decorator to the rescue again!

```<code>using(var fileStream = new FileStream(...))
using(var cryptoStream = new CryptoStream(fileStream))
using(var zipStream = new ZipArchive(cryptoStream))
{ ... }
</code>```

...you get the picture.

Each stream adds functionality on the process of "writing" a stream.

Body:
I have just gone into studying the Decorator Design Pattern using C#.

I have made an example which kinda functions as I think it is intended except for one thing.

I kinda understood that the whole point of the pattern is to add functionality to an object dynamically.

So when I create an object like this:

Inventory a = new Ashbringer(new TravelersBagpack());
a.Execute();

Then I kinda expected that the point was that the a object would now be able to call the Execute() method which only exists in the Ashbringer class. Thus adding functionality to the a object.

Though this I can't do without adding the Execute() method to the Inventory interface which would ultimately mean I would have to implement the Execute() method to all the classes implementing Inventory Interface or the abstract Decorator.

Perhaps there is a thing or two I don't know about interfaces or perhaps I misunderstand the point of the Decorator Design Pattern?

Body:
In the context of streams, let's say you wanted to write to a file. It would look like this:

using(var fileStream = new FileStream(...))
{ ... }

Now let's say you wanted that file to be encrypted. You can do this with a second stream using the decorator pattern:

using(var fileStream = new FileStream(...))
using(var cryptoStream = new CryptoStream(fileStream))
{ ... }

Now let's say you wanted that encrypted file to be compressed. Decorator to the rescue again!

using(var fileStream = new FileStream(...))
using(var cryptoStream = new CryptoStream(fileStream))
using(var zipStream = new ZipArchive(cryptoStream))
{ ... }

...you get the picture.

Each stream adds functionality on the process of "writing" a stream.