问:
TLS support for GRPC in C#
I'm rather new to C#, and I need to use GRPC over TLS.

As a dry-run, I'm modifying the example provided in the main grpc repo to use TLS. To do this, I found another SO question with what seemed like a good answer: How to enable server side SSL for gRPC?. However, I get an error Unhandled Exception: Grpc.Core.RpcException: Status(StatusCode=Unavailable, Detail="Connect Failed") (full trace below).

I get the same error if I in the original, non-tls code, specify an incorrect port or just don't start the server. I'm using dotnet core on Ubuntu.

The important parts of the code are below, and also found in full on a fork on github.

Client:

```<code>  var cacert = File.ReadAllText(@"../ca.crt");
  var clientcert = File.ReadAllText(@"../client.crt");
  var clientkey = File.ReadAllText(@"../client.key");
  var ssl = new SslCredentials(cacert, new KeyCertificatePair(clientcert, clientkey));
  var channel = new Channel("localhost", 555, ssl);
  var client = new Greeter.GreeterClient(channel);

  String user = "you";

  var reply = client.SayHello(new HelloRequest {Name = user});
  Console.WriteLine("Greeting: " + reply.Message);

  channel.ShutdownAsync().Wait();
  Console.WriteLine("Press any key to exit...");
  Console.ReadKey();
</code>```

Server:

```<code>  var cacert = File.ReadAllText(@"../ca.crt");
  var servercert = File.ReadAllText(@"../server.crt");
  var serverkey = File.ReadAllText(@"../server.key");
  var keypair = new KeyCertificatePair(servercert, serverkey);
  var sslCredentials = new SslServerCredentials(new List<KeyCertificatePair>() {keypair}, cacert, false);

  var server = new Server
  {
    Services = {Greeter.BindService(new GreeterImpl())},
    Ports = {new ServerPort("0.0.0.0", 555, sslCredentials)}
  };
  server.Start();

  Console.WriteLine("Greeter server listening on port " + Port);
  Console.WriteLine("Press any key to stop the server...");
  Console.ReadKey();

  server.ShutdownAsync().Wait();
</code>```

Full output of the programs:

```<code>$ cd GreeterClient
$ dotnet run -f netcoreapp1.0

Unhandled Exception: Grpc.Core.RpcException: Status(StatusCode=Unavailable, Detail="Connect Failed")
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Grpc.Core.Internal.AsyncCall`2.UnaryCall(TRequest msg)
   at Grpc.Core.DefaultCallInvoker.BlockingUnaryCall[TRequest,TResponse](Method`2 method, String host, CallOptions options, TRequest request)
   at Grpc.Core.Internal.InterceptingCallInvoker.BlockingUnaryCall[TRequest,TResponse](Method`2 method, String host, CallOptions options, TRequest request)
   at Helloworld.Greeter.GreeterClient.SayHello(HelloRequest request, CallOptions options)
   at Helloworld.Greeter.GreeterClient.SayHello(HelloRequest request, Metadata headers, Nullable`1 deadline, CancellationToken cancellationToken)
   at GreeterClient.Program.Main(String[] args)
</code>```

And server:

```<code>$ cd GreeterServer/
$ dotnet run -f netcoreapp1.0
Greeter server listening on port 50051
Press any key to stop the server...
</code>```

Did I do some silly mistake, or does this not run on non-windows machines? Is there some way to debug the issue to figure out what is going on?

答:
Your code is implementing Mutual TLS with self signed certs correctly - I was able to run it on windows netcore without any changes.

I did have to tweak the certificate generation script a little:

Adding environment variable definition for CLIENT-COMPUTERNAME, used for the client /CN (Common Name)

Adding a -config option to get rid of unable to find 'distinguished_name' in config error (might be a openssl on Windows thing)

I was able to reproduce the same error message that you had by deliberately mismatching the host that the client connects to (127.0.0.1 instead of localhost). So maybe you just need to regenerate your keys with e.g. localhost as the client's common name.

Title: TLS support for GRPC in C#

Body:
I'm rather new to C#, and I need to use GRPC over TLS.

As a dry-run, I'm modifying the example provided in the main grpc repo to use TLS. To do this, I found another SO question with what seemed like a good answer: How to enable server side SSL for gRPC?. However, I get an error Unhandled Exception: Grpc.Core.RpcException: Status(StatusCode=Unavailable, Detail="Connect Failed") (full trace below).

I get the same error if I in the original, non-tls code, specify an incorrect port or just don't start the server. I'm using dotnet core on Ubuntu.

The important parts of the code are below, and also found in full on a fork on github.

Client:

  var cacert = File.ReadAllText(@"../ca.crt");
  var clientcert = File.ReadAllText(@"../client.crt");
  var clientkey = File.ReadAllText(@"../client.key");
  var ssl = new SslCredentials(cacert, new KeyCertificatePair(clientcert, clientkey));
  var channel = new Channel("localhost", 555, ssl);
  var client = new Greeter.GreeterClient(channel);

  String user = "you";

  var reply = client.SayHello(new HelloRequest {Name = user});
  Console.WriteLine("Greeting: " + reply.Message);

  channel.ShutdownAsync().Wait();
  Console.WriteLine("Press any key to exit...");
  Console.ReadKey();

Server:

  var cacert = File.ReadAllText(@"../ca.crt");
  var servercert = File.ReadAllText(@"../server.crt");
  var serverkey = File.ReadAllText(@"../server.key");
  var keypair = new KeyCertificatePair(servercert, serverkey);
  var sslCredentials = new SslServerCredentials(new List<KeyCertificatePair>() {keypair}, cacert, false);

  var server = new Server
  {
    Services = {Greeter.BindService(new GreeterImpl())},
    Ports = {new ServerPort("0.0.0.0", 555, sslCredentials)}
  };
  server.Start();

  Console.WriteLine("Greeter server listening on port " + Port);
  Console.WriteLine("Press any key to stop the server...");
  Console.ReadKey();

  server.ShutdownAsync().Wait();

Full output of the programs:

$ cd GreeterClient
$ dotnet run -f netcoreapp1.0

Unhandled Exception: Grpc.Core.RpcException: Status(StatusCode=Unavailable, Detail="Connect Failed")
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Grpc.Core.Internal.AsyncCall`2.UnaryCall(TRequest msg)
   at Grpc.Core.DefaultCallInvoker.BlockingUnaryCall[TRequest,TResponse](Method`2 method, String host, CallOptions options, TRequest request)
   at Grpc.Core.Internal.InterceptingCallInvoker.BlockingUnaryCall[TRequest,TResponse](Method`2 method, String host, CallOptions options, TRequest request)
   at Helloworld.Greeter.GreeterClient.SayHello(HelloRequest request, CallOptions options)
   at Helloworld.Greeter.GreeterClient.SayHello(HelloRequest request, Metadata headers, Nullable`1 deadline, CancellationToken cancellationToken)
   at GreeterClient.Program.Main(String[] args)

And server:

$ cd GreeterServer/
$ dotnet run -f netcoreapp1.0
Greeter server listening on port 50051
Press any key to stop the server...

Did I do some silly mistake, or does this not run on non-windows machines? Is there some way to debug the issue to figure out what is going on?


来源: stackexchange

问:
Login page with tkinter and python for API to AWS cloud
My code for login page not working , when i am calling the function 'HTTP_Connection' from button "open' on main page.

It will make connection to F5 device, syntax working fine, when i am giving
input for a,b,c directly, from Tkinter i am trying to achieve .

```<code>from tkinter import *
root=Tk()
root.title("Automated Configuration Manager")

def HTTP_Connection():
    a=et1.get()
    b=et2.get()
    c=et3.get()
    urllib3.disable_warnings()
    mgmt = ManagementRoot('a','b','c')
    ltm = mgmt.tm.ltm
    virtuals = mgmt.tm.ltm.virtuals
    virtual = mgmt.tm.ltm.virtuals.virtual

mainframe = Frame(root)
mainframe.grid(column=0,row=0, sticky=(N,W,E,S) )
mainframe.columnconfigure(0, weight = 1)
mainframe.rowconfigure(0, weight = 1)
mainframe.pack(pady = 100, padx = 100)

#choices = { 'F5','A5A','PA' }
var = StringVar()
popupMenu = OptionMenu(mainframe, var,'F5','A5A','PA')
Label(mainframe, text="Choose a Option").grid(row = 1, column = 1)
popupMenu.grid(row = 2, column =1)

l1 = Label(root, text = "Enter IP Address:")
l1.pack()
global et1
global et2
global et3
et1 = Entry(root, bd = 5)
et1.pack()
a=et1.get()

l2 = Label(root, text = "User Name:")
l2.pack()
et2 = Entry(root, bd=5)
et2.pack()
b=et2.get()

g=StringVar()
g="enter password:"
l3=Label(root, text = g)
l3.pack()
et3 = Entry(root, bd=5, show = "*")
et3.pack()

b = Button(root, text = "Open", bd =5,command=HTTP_Connection)
b.pack()

root.mainloop()
</code>```

答:
In this function:

```<code>def HTTP_Connection():
    a=et1.get()
    b=et2.get()
    c=et3.get()
    urllib3.disable_warnings()
    mgmt = ManagementRoot('a','b','c')
    ltm = mgmt.tm.ltm
    virtuals = mgmt.tm.ltm.virtuals
    virtual = mgmt.tm.ltm.virtuals.virtual
</code>```

You are declaring three variables a, b and c which you then don't use. Instead you are running ManagementRoot('a','b','c') which uses strings containing the values "a", "b" and "c" instead of the variables you declared earlier.

You should be able to fix this by changing the line to the below:

```<code>    mgmt = ManagementRoot(et1.get(),et2.get(),et3.get())
</code>```

ContentLicense: CC BY-SA 3.0

Body:
My code for login page not working , when i am calling the function 'HTTP_Connection' from button "open' on main page.

It will make connection to F5 device, syntax working fine, when i am giving
input for a,b,c directly, from Tkinter i am trying to achieve .

from tkinter import *
root=Tk()
root.title("Automated Configuration Manager")

def HTTP_Connection():
    a=et1.get()
    b=et2.get()
    c=et3.get()
    urllib3.disable_warnings()
    mgmt = ManagementRoot('a','b','c')
    ltm = mgmt.tm.ltm
    virtuals = mgmt.tm.ltm.virtuals
    virtual = mgmt.tm.ltm.virtuals.virtual

mainframe = Frame(root)
mainframe.grid(column=0,row=0, sticky=(N,W,E,S) )
mainframe.columnconfigure(0, weight = 1)
mainframe.rowconfigure(0, weight = 1)
mainframe.pack(pady = 100, padx = 100)

#choices = { 'F5','A5A','PA' }
var = StringVar()
popupMenu = OptionMenu(mainframe, var,'F5','A5A','PA')
Label(mainframe, text="Choose a Option").grid(row = 1, column = 1)
popupMenu.grid(row = 2, column =1)

l1 = Label(root, text = "Enter IP Address:")
l1.pack()
global et1
global et2
global et3
et1 = Entry(root, bd = 5)
et1.pack()
a=et1.get()

l2 = Label(root, text = "User Name:")
l2.pack()
et2 = Entry(root, bd=5)
et2.pack()
b=et2.get()

g=StringVar()
g="enter password:"
l3=Label(root, text = g)
l3.pack()
et3 = Entry(root, bd=5, show = "*")
et3.pack()

b = Button(root, text = "Open", bd =5,command=HTTP_Connection)
b.pack()

root.mainloop()

Body:
In this function:

def HTTP_Connection():
    a=et1.get()
    b=et2.get()
    c=et3.get()
    urllib3.disable_warnings()
    mgmt = ManagementRoot('a','b','c')
    ltm = mgmt.tm.ltm
    virtuals = mgmt.tm.ltm.virtuals
    virtual = mgmt.tm.ltm.virtuals.virtual

You are declaring three variables a, b and c which you then don't use. Instead you are running ManagementRoot('a','b','c') which uses strings containing the values "a", "b" and "c" instead of the variables you declared earlier.

You should be able to fix this by changing the line to the below:

    mgmt = ManagementRoot(et1.get(),et2.get(),et3.get())


问:
Autowiring in Quartz multiple Jobs with Spring Boot not working
I'm try to use quartz scheduler in spring. I get below exception when configuring multiple jobs

Parameter 0 of method jobTrigger in Job2 required a bean of type 'org.quartz.JobDetail' that could not be found.

quartz - v2.3, Spring - v4.2.x

Config Class

```<code>@Configuration
 public class SchedulerConfig {

private static final Logger LOG = LoggerFactory.getLogger(SchedulerConfig.class);

@Autowired
List<Trigger> triggers;

@Bean
public JobFactory jobFactory(ApplicationContext applicationContext) {
    AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
    jobFactory.setApplicationContext(applicationContext);
    return jobFactory;
}

@Bean
public SchedulerFactoryBean schedulerFactoryBean(JobFactory jobFactory)  throws IOException {
    SchedulerFactoryBean factory = new SchedulerFactoryBean();
          factory.setAutoStartup(true);
    factory.setJobFactory(jobFactory);
         factory.setQuartzProperties(quartzProperties());
    if (triggers != null && !triggers.isEmpty()) {
         LOG.info("starting jobs... Total Triggers - " + triggers.size());
        factory.setTriggers(triggers.toArray(new Trigger[triggers.size()]));
    }

    return factory;
}

@Bean
public Properties quartzProperties() throws IOException {
    PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
    propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
    propertiesFactoryBean.afterPropertiesSet();
    return propertiesFactoryBean.getObject();
}

public static CronTriggerFactoryBean createCronTrigger(JobDetail jobDetail, String cronExpression) {
    CronTriggerFactoryBean factoryBean = new CronTriggerFactoryBean();
    factoryBean.setJobDetail(jobDetail);
    factoryBean.setCronExpression(cronExpression);
    factoryBean.setMisfireInstruction(SimpleTrigger.MISFIRE_INSTRUCTION_FIRE_NOW);
    return factoryBean;
}

public static JobDetailFactoryBean createJobDetail(Class jobClass) {
    JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();
    factoryBean.setJobClass(jobClass);
    factoryBean.setDurability(true);
    return factoryBean;
}
</code>```

SpringBeanJobFactory

```<code>public final class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements ApplicationContextAware {

private static final Logger LOG = LoggerFactory.getLogger(AutowiringSpringBeanJobFactory.class);

private transient AutowireCapableBeanFactory beanFactory;

@Override
public void setApplicationContext(final ApplicationContext context) {
    beanFactory = context.getAutowireCapableBeanFactory();
}

@Override
protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
    final Object job = super.createJobInstance(bundle);
    LOG.info("create job instance");
    beanFactory.autowireBean(job);
    return job;
}
</code>```

}

Job 1

```<code>@Component
@DisallowConcurrentExecution
public class Job1 implements Job {

private final Logger log = LoggerFactory.getLogger(this.getClass());

@Value("${schedule}")
private String frequency;

@Autowired
private Service service;

@Override
public void execute(JobExecutionContext jobExecutionContext) {
    log.info("execute");
}

@Bean(name = "jobBean1")
public JobDetailFactoryBean job() {
    return SchedulerConfig.createJobDetail(this.getClass());
}

@Bean(name = "jobBean1Trigger")
public CronTriggerFactoryBean jobTrigger(@Qualifier("jobBean1")JobDetail jobDetail) {
    return SchedulerConfig.createCronTrigger(jobDetail, frequency);
}
</code>```

Job 2

```<code>@Component
@DisallowConcurrentExecution
public class Job2 implements Job {

private final Logger log = LoggerFactory.getLogger(this.getClass());

@Value("${schedule}")
private String frequency;

@Autowired
private Service service;

@Override
public void execute(JobExecutionContext jobExecutionContext) {
    log.info("execute");
}

@Bean(name = "jobBean2")
public JobDetailFactoryBean job() {
    return SchedulerConfig.createJobDetail(this.getClass());
}

@Bean(name = "jobBean2Trigger")
public CronTriggerFactoryBean jobTrigger(@Qualifier("jobBean2")JobDetail jobDetail) {
    return SchedulerConfig.createCronTrigger(jobDetail, frequency);
}
</code>```

The Service class has Spring JPA repos.
The root cause of the problem is the below autowired service. If I remove the below autowired service from both the jobs, it works fine.

@Autowired
    private Service service;

If there is only one job with this autowired bean, then there is no exception.
How to configure multiple jobs using the same autowired dependency?
What is cause this issue?

答:
I faced the same issue and after a bit of struggling I was able to resolve it. It is probably realted to the annotation that is used in the job class. I see that you are using the @Component, as it was in my case. The quartz scheduler configuration instead, is annotated with @Configuration tag.

The solution is to annotate your jobs with @Configuration tag. My guess is that the @Bean's constructed in @Componentannotated classes are not completley constructed/mapped in the phase where @Configuration annotated ones are initialized.

Body:
I'm try to use quartz scheduler in spring. I get below exception when configuring multiple jobs

Parameter 0 of method jobTrigger in Job2 required a bean of type 'org.quartz.JobDetail' that could not be found.

quartz - v2.3, Spring - v4.2.x

Config Class

@Configuration
 public class SchedulerConfig {

private static final Logger LOG = LoggerFactory.getLogger(SchedulerConfig.class);

@Autowired
List<Trigger> triggers;

@Bean
public JobFactory jobFactory(ApplicationContext applicationContext) {
    AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
    jobFactory.setApplicationContext(applicationContext);
    return jobFactory;
}

@Bean
public SchedulerFactoryBean schedulerFactoryBean(JobFactory jobFactory)  throws IOException {
    SchedulerFactoryBean factory = new SchedulerFactoryBean();
          factory.setAutoStartup(true);
    factory.setJobFactory(jobFactory);
         factory.setQuartzProperties(quartzProperties());
    if (triggers != null && !triggers.isEmpty()) {
         LOG.info("starting jobs... Total Triggers - " + triggers.size());
        factory.setTriggers(triggers.toArray(new Trigger[triggers.size()]));
    }

    return factory;
}

@Bean
public Properties quartzProperties() throws IOException {
    PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
    propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
    propertiesFactoryBean.afterPropertiesSet();
    return propertiesFactoryBean.getObject();
}

public static CronTriggerFactoryBean createCronTrigger(JobDetail jobDetail, String cronExpression) {
    CronTriggerFactoryBean factoryBean = new CronTriggerFactoryBean();
    factoryBean.setJobDetail(jobDetail);
    factoryBean.setCronExpression(cronExpression);
    factoryBean.setMisfireInstruction(SimpleTrigger.MISFIRE_INSTRUCTION_FIRE_NOW);
    return factoryBean;
}

public static JobDetailFactoryBean createJobDetail(Class jobClass) {
    JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();
    factoryBean.setJobClass(jobClass);
    factoryBean.setDurability(true);
    return factoryBean;
}

SpringBeanJobFactory

public final class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements ApplicationContextAware {

private static final Logger LOG = LoggerFactory.getLogger(AutowiringSpringBeanJobFactory.class);

private transient AutowireCapableBeanFactory beanFactory;

@Override
public void setApplicationContext(final ApplicationContext context) {
    beanFactory = context.getAutowireCapableBeanFactory();
}

@Override
protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
    final Object job = super.createJobInstance(bundle);
    LOG.info("create job instance");
    beanFactory.autowireBean(job);
    return job;
}

}

Job 1

@Component
@DisallowConcurrentExecution
public class Job1 implements Job {

private final Logger log = LoggerFactory.getLogger(this.getClass());

@Value("${schedule}")
private String frequency;

@Autowired
private Service service;

@Override
public void execute(JobExecutionContext jobExecutionContext) {
    log.info("execute");
}

@Bean(name = "jobBean1")
public JobDetailFactoryBean job() {
    return SchedulerConfig.createJobDetail(this.getClass());
}

@Bean(name = "jobBean1Trigger")
public CronTriggerFactoryBean jobTrigger(@Qualifier("jobBean1")JobDetail jobDetail) {
    return SchedulerConfig.createCronTrigger(jobDetail, frequency);
}

Job 2

@Component
@DisallowConcurrentExecution
public class Job2 implements Job {

private final Logger log = LoggerFactory.getLogger(this.getClass());

@Value("${schedule}")
private String frequency;

@Autowired
private Service service;

@Override
public void execute(JobExecutionContext jobExecutionContext) {
    log.info("execute");
}

@Bean(name = "jobBean2")
public JobDetailFactoryBean job() {
    return SchedulerConfig.createJobDetail(this.getClass());
}

@Bean(name = "jobBean2Trigger")
public CronTriggerFactoryBean jobTrigger(@Qualifier("jobBean2")JobDetail jobDetail) {
    return SchedulerConfig.createCronTrigger(jobDetail, frequency);
}

The Service class has Spring JPA repos.
The root cause of the problem is the below autowired service. If I remove the below autowired service from both the jobs, it works fine.

@Autowired
    private Service service;

If there is only one job with this autowired bean, then there is no exception.
How to configure multiple jobs using the same autowired dependency?
What is cause this issue?


问:
python key in dict.keys() performance for large dictionaries
I was wondering if you guys might be able to give me some advice in regards to making the performance of my code much better.

I have a set of for loops which look to see if a key is in a dictionary of which its values are a list, if the key exists, it appends to the list and if it doesnt it adds a new list in for that key

```<code>dict={}
for value in value_list:
   if value.key in dict.keys():
      temp_list = dict[value.key]
      temp_list.append(value.val)
      dict[value.key] = temp_list
   else:
      dict[value.key] = [value.val]
</code>```

Now this code works fine, but evenrually as the dictionary starts to fill up the line value.key in dict.keys() becomes more and more cumbersome.

Is there a better way of doing this?

Thanks,

Mike

答:
Using collections.defaultdict, this can be simplified to

```<code>d = collections.defaultdict(list)
for value in value_list:
    d[value.key].append(value.val)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I was wondering if you guys might be able to give me some advice in regards to making the performance of my code much better.

I have a set of for loops which look to see if a key is in a dictionary of which its values are a list, if the key exists, it appends to the list and if it doesnt it adds a new list in for that key

dict={}
for value in value_list:
   if value.key in dict.keys():
      temp_list = dict[value.key]
      temp_list.append(value.val)
      dict[value.key] = temp_list
   else:
      dict[value.key] = [value.val]

Now this code works fine, but evenrually as the dictionary starts to fill up the line value.key in dict.keys() becomes more and more cumbersome.

Is there a better way of doing this?

Thanks,

Mike

Body:
Using collections.defaultdict, this can be simplified to

d = collections.defaultdict(list)
for value in value_list:
    d[value.key].append(value.val)


问:
Python: Manipulating list of Color objects?
I'm using the colour package to create a gradient of colors, like this:

```<code>from colour import Color
orange = Color("#e65318")
turquoise = Color("#3297A5")
palette_list = list(orange.range_to(turquoise,10))
</code>```

the output is a list, like this:

```<code>[<Color #e65318>, <Color #de911b>, <Color #d7c71f>, <Color #a7cf22>, <Color #6fc825>, <Color #3dc128>, <Color #2bb944>, <Color #2db36f>, <Color #30ac94>, <Color #3297a5>]
</code>```

and what I would really like, is this:

```<code>['#e65318', '#de911b', '#d7c71f', '#a7cf22', '#6fc825', '#3dc128', '#2bb944', '#2db36f', '#30ac94', '#3297a5']
</code>```

So far, I've tried ai_palette_list.remove('Color')

which returns ValueError: list.remove(x): x not in list.

I am thinking this is a pretty general problem, but can't seem to find any sane, systematic way of going about removing the word 'Color' and returning a string.

答:
This list comprehension should accomplish that:

```<code>[c.hex for c in palette_list]
</code>```

As @LeopoldVonBuschLight pointed out, what you have is a list of Color objects, this list comprehension gets the .hex value of each object and puts it into a list.

Body:
I'm using the colour package to create a gradient of colors, like this:

from colour import Color
orange = Color("#e65318")
turquoise = Color("#3297A5")
palette_list = list(orange.range_to(turquoise,10))

the output is a list, like this:

[<Color #e65318>, <Color #de911b>, <Color #d7c71f>, <Color #a7cf22>, <Color #6fc825>, <Color #3dc128>, <Color #2bb944>, <Color #2db36f>, <Color #30ac94>, <Color #3297a5>]

and what I would really like, is this:

['#e65318', '#de911b', '#d7c71f', '#a7cf22', '#6fc825', '#3dc128', '#2bb944', '#2db36f', '#30ac94', '#3297a5']

So far, I've tried ai_palette_list.remove('Color')

which returns ValueError: list.remove(x): x not in list.

I am thinking this is a pretty general problem, but can't seem to find any sane, systematic way of going about removing the word 'Color' and returning a string.

Body:
This list comprehension should accomplish that:

[c.hex for c in palette_list]

As @LeopoldVonBuschLight pointed out, what you have is a list of Color objects, this list comprehension gets the .hex value of each object and puts it into a list.


问:
Try-Catch-Finally Block
i already know that the traditional Try block in java must have at least catch block or finally block (both or either), and i already know that checked exceptions must be handled or declared.
but i am wondering why it won't compile although i have used correct try block syntax

i have this piece of code here , in the main method i used Try with finally block but i am wondering why it won't compile

Here is my code:

```<code>import java.io.IOException;
import java.net.Socket;

public class ExHandling {

public void connect() throws IOException
    {
        Socket s = new Socket();
        try
        {
            s.getInputStream();
        }
        catch(IOException e )
        {
            e.printStackTrace();
        }
        finally
        {
            s.close();
        }
    }
public static void main(String []args)
    {
        ExHandling ex = new ExHandling();

        try
        {
            ex.connect();

        }

        finally
        {
            System.out.println("Finally");
        }

    }
}
</code>```

Any Help Please

答: IOException checked exception so you need catch or add an exception to a signature method. final just guarantee whatever happens final block will be executed.

Title: Try-Catch-Finally Block

Body:
i already know that the traditional Try block in java must have at least catch block or finally block (both or either), and i already know that checked exceptions must be handled or declared.
but i am wondering why it won't compile although i have used correct try block syntax

i have this piece of code here , in the main method i used Try with finally block but i am wondering why it won't compile

Here is my code:

import java.io.IOException;
import java.net.Socket;

public class ExHandling {

public void connect() throws IOException
    {
        Socket s = new Socket();
        try
        {
            s.getInputStream();
        }
        catch(IOException e )
        {
            e.printStackTrace();
        }
        finally
        {
            s.close();
        }
    }
public static void main(String []args)
    {
        ExHandling ex = new ExHandling();

        try
        {
            ex.connect();

        }

        finally
        {
            System.out.println("Finally");
        }

    }
}

Any Help Please


问:
Save 1000s of data into mysql in most efficient way
I have almost 7000 data in mysql database. Some columns are empty and I want to fill them with related data. I am displaying the data from mysql and wrapped the empty fields with form and inserted inputs. The code is below;

```<code>while ($row = mysqli_fetch_array($results)) {
echo '
<form action="" method="post">
    <tr>
        <td>'._date($row["time"]).'</td>
        <td>$row["name"]</a>
        <br><input name="name" class="form-control input-sm" value="New name" >
        </td>
        <td>info@domain.com<br>
        <input name="email" class="form-control input-sm" value="newemail@domain.com" >
        </td>
        <td>0123456789<br>
        <input name="telephone" class="form-control input-sm" value="0987654321" >
        </td>
        <td>111 Some street name<br>
        <input name="address" class="form-control input-sm" value="New road name and address" >
        </td>
        <td>category</td>
        <td>
            <button type="submit" class="btn btn-success btn-flat"><i class="fa fa-save fa-fw"></i></button>
            <a href="index.php?p=subscribers&delete='.$row["id"].'" class="btn btn-danger btn-flat"><i class="fa fa-trash fa-fw"></i></a>
        </td>
    </tr>
</form>
';}
</code>```

As you can see i have the option of saving them individually but i also want to save all displayed data at once. displaying all the data can be very slow so i guess i need to display small part at a time.

Could anyone tell me have I can save all displayed form inputs at once?

答:
After doing more research, I finally managed to find a solution and i am posting here for anyone who needs it.</p>

```<code>if (isset($_POST['update'])){
    for($i=0; $i<count($_POST['id']); $i++){
       $sql = "
        UPDATE test
        SET
            name        = '".$_POST['name'][$i]."',
            email       = '".$_POST['email'][$i]."',
            telephone   = '".$_POST['telephone'][$i]."'
        WHERE id = '".$_POST['id'][$i]."'";

        if ($con->query($sql) === TRUE) {
            //echo "Record updated successfully";
        } else {
            echo "Error updating record: " . $con->error;
        }

    }
}

$sql = "SELECT * FROM test ORDER BY id ASC LIMIT 5";
$results = $con->query($sql);

if (mysqli_num_rows($results) > 0) {
     echo '<form action="" method="post">';
     echo '<input type="hidden" name="update"  >';
    // displaying records.
    while ($row = mysqli_fetch_array($results)) {
        echo '
            <input type="hidden" name="id[]" value="'.$row["id"].'" >
            <tr>
                <td><input type="text" name="name[]" class="form-control input-sm" value="'.$row["name"].'" ></td>
                <td><input type="text" name="email[]" class="form-control input-sm" value="'.$row["email"].'" ></td>
                <td><input type="text" name="telephone[]" class="form-control input-sm" value="'.$row["telephone"].'" ></td>
            </tr>
        ';
    }
    echo '<input type="submit" value="update">';
    echo '</form>';
}else {
    echo "No records are found.";
}
</code>```

Body:
I have almost 7000 data in mysql database. Some columns are empty and I want to fill them with related data. I am displaying the data from mysql and wrapped the empty fields with form and inserted inputs. The code is below;

while ($row = mysqli_fetch_array($results)) {
echo '
<form action="" method="post">

        '._date($row["time"]).'
        $row["name"]

<input name="name" class="form-control input-sm" value="New name" >

        info@domain.com

        <input name="email" class="form-control input-sm" value="newemail@domain.com" >

        0123456789

        <input name="telephone" class="form-control input-sm" value="0987654321" >

        111 Some street name

        <input name="address" class="form-control input-sm" value="New road name and address" >

        category

            <button type="submit" class="btn btn-success btn-flat"></button>

</form>
';}

As you can see i have the option of saving them individually but i also want to save all displayed data at once. displaying all the data can be very slow so i guess i need to display small part at a time.

Could anyone tell me have I can save all displayed form inputs at once?

Body:
After doing more research, I finally managed to find a solution and i am posting here for anyone who needs it.

if (isset($_POST['update'])){
    for($i=0; $i<count($_POST['id']); $i++){
       $sql = "
        UPDATE test
        SET
            name        = '".$_POST['name'][$i]."',
            email       = '".$_POST['email'][$i]."',
            telephone   = '".$_POST['telephone'][$i]."'
        WHERE id = '".$_POST['id'][$i]."'";

        if ($con->query($sql) === TRUE) {
            //echo "Record updated successfully";
        } else {
            echo "Error updating record: " . $con->error;
        }

    }
}

$sql = "SELECT * FROM test ORDER BY id ASC LIMIT 5";
$results = $con->query($sql);

if (mysqli_num_rows($results) > 0) {
     echo '<form action="" method="post">';
     echo '<input type="hidden" name="update"  >';
    // displaying records.
    while ($row = mysqli_fetch_array($results)) {
        echo '
            <input type="hidden" name="id[]" value="'.$row["id"].'" >
            <tr>
                <td><input type="text" name="name[]" class="form-control input-sm" value="'.$row["name"].'" ></td>
                <td><input type="text" name="email[]" class="form-control input-sm" value="'.$row["email"].'" ></td>
                <td><input type="text" name="telephone[]" class="form-control input-sm" value="'.$row["telephone"].'" ></td>
            </tr>
        ';
    }
    echo '<input type="submit" value="update">';
    echo '</form>';
}else {
    echo "No records are found.";
}


问:
windows store app receipt verification
I am working on a paid Universal Windows Platform app. where i need to confirm the payment receipt.i am not sure which of the receipt element is unique per user. so that if the user got the same app on another device he may be allowed to proceed. here's the app receipt.

```<code><Receipt Version="1.0" ReceiptDate="2012-08-30T23:10:05Z" CertificateId="b809e47cd0110a4db043b3f73e83acd917fe1336" ReceiptDeviceId="4e362949-acc3-fe3a-e71b-89893eb4f528">
<AppReceipt Id="8ffa256d-eca8-712a-7cf8-cbf5522df24b" AppId="55428GreenlakeApps.CurrentAppSimulatorEventTest_z7q3q7z11crfr" PurchaseDate="2012-06-04T23:07:24Z" LicenseType="Full" />
<ProductReceipt Id="6bbf4366-6fb2-8be8-7947-92fd5f683530" ProductId="Product1" PurchaseDate="2012-08-30T23:08:52Z" ExpirationDate="2012-09-02T23:08:49Z" ProductType="Durable" AppId="55428GreenlakeApps.CurrentAppSimulatorEventTest_z7q3q7z11crfr" />
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
    <SignedInfo>
        <CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
        <SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />
        <Reference URI="">
            <Transforms>
                <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
            </Transforms>
            <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />
            <DigestValue>cdiU06eD8X/w1aGCHeaGCG9w/kWZ8I099rw4mmPpvdU=</DigestValue>
        </Reference>
    </SignedInfo>
    <SignatureValue>SjRIxS/2r2P6ZdgaR9bwUSa6ZItYYFpKLJZrnAa3zkMylbiWjh9oZGGng2p6/gtBHC2dSTZlLbqnysJjl7mQp/A3wKaIkzjyRXv3kxoVaSV0pkqiPt04cIfFTP0JZkE5QD/vYxiWjeyGp1dThEM2RV811sRWvmEs/hHhVxb32e8xCLtpALYx3a9lW51zRJJN0eNdPAvNoiCJlnogAoTToUQLHs72I1dECnSbeNPXiG7klpy5boKKMCZfnVXXkneWvVFtAA1h2sB7ll40LEHO4oYN6VzD+uKd76QOgGmsu9iGVyRvvmMtahvtL1/pxoxsTRedhKq6zrzCfT8qfh3C1w==</SignatureValue>
</Signature>
</code>```

答:
Okay, this required a little digging on my behalf and unfortunately it will require a bit of setup on yours. You will need to set up a Web App in Azure AD to store customer ID's and link them to purchases. These keys expire every 90 days, so you will have to regenerate upon expiration. I'm linking the articles because I feel MSDN has elaborated well enough.

Setting Up Azure AD

Generating new keys upon expiration

FINALLY, you may use GetCustomerCollectionsIdAsync() or GetCustomerPurchaseIdAsync() (whichever one suits you best) to retrieve their purchase.

Getting the purchase ID

Title: windows store app receipt verification

Body:
I am working on a paid Universal Windows Platform app. where i need to confirm the payment receipt.i am not sure which of the receipt element is unique per user. so that if the user got the same app on another device he may be allowed to proceed. here's the app receipt.

<Receipt Version="1.0" ReceiptDate="2012-08-30T23:10:05Z" CertificateId="b809e47cd0110a4db043b3f73e83acd917fe1336" ReceiptDeviceId="4e362949-acc3-fe3a-e71b-89893eb4f528">
<AppReceipt Id="8ffa256d-eca8-712a-7cf8-cbf5522df24b" AppId="55428GreenlakeApps.CurrentAppSimulatorEventTest_z7q3q7z11crfr" PurchaseDate="2012-06-04T23:07:24Z" LicenseType="Full" />
<ProductReceipt Id="6bbf4366-6fb2-8be8-7947-92fd5f683530" ProductId="Product1" PurchaseDate="2012-08-30T23:08:52Z" ExpirationDate="2012-09-02T23:08:49Z" ProductType="Durable" AppId="55428GreenlakeApps.CurrentAppSimulatorEventTest_z7q3q7z11crfr" />
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
    <SignedInfo>
        <CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
        <SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />
        <Reference URI="">
            <Transforms>
                <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
            </Transforms>
            <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />
            <DigestValue>cdiU06eD8X/w1aGCHeaGCG9w/kWZ8I099rw4mmPpvdU=</DigestValue>
        </Reference>
    </SignedInfo>
    <SignatureValue>SjRIxS/2r2P6ZdgaR9bwUSa6ZItYYFpKLJZrnAa3zkMylbiWjh9oZGGng2p6/gtBHC2dSTZlLbqnysJjl7mQp/A3wKaIkzjyRXv3kxoVaSV0pkqiPt04cIfFTP0JZkE5QD/vYxiWjeyGp1dThEM2RV811sRWvmEs/hHhVxb32e8xCLtpALYx3a9lW51zRJJN0eNdPAvNoiCJlnogAoTToUQLHs72I1dECnSbeNPXiG7klpy5boKKMCZfnVXXkneWvVFtAA1h2sB7ll40LEHO4oYN6VzD+uKd76QOgGmsu9iGVyRvvmMtahvtL1/pxoxsTRedhKq6zrzCfT8qfh3C1w==</SignatureValue>
</Signature>


问:
Get line number from preg_match_all()
I'm using PHP's preg_match_all() to search a string imported using file_get_contents(). The regex returns matches but I would like to know at which line number those matches are found. What's the best technique to achieve this?

I could read the file as an array and perform the regex for each line, but the problem is that my regex matches results across carriage returns (new lines).

答:
You have got a couple options, but none are "simple":

a) exec() and use the system grep command, which can report line numbers:

```<code>exec("grep -n 'your pattern here' file.txt", $output);`
</code>```

b) Slurp in the file using file_get_contents(), split it into an array of lines, then use preg_grep() to find the matching lines.

```<code>$dat = file_get_contents('file.txt');
$lines = explode($dat, "\n");
$matches = preg_grep('/your pattern here/', $lines);
</code>```

c) Read the file in line-sized chunks, keep a running line count, and do your pattern match on each line.

```<code>$fh = fopen('file.txt', 'rb');
$line = 1;
while ($line = fgets($fh)) {
     if (preg_match('/your pattern here/', $line)) {
         ... whatever you need to do with matching lines ...
     }
     $line++;
}
</code>```

Each has its ups and downs

a) You're invoking an external program, and if your pattern contains any user-supplied data, you're potentially opening yourself up to the shell equivalent of an SQL injection attack. On the plus side, you don't have to slurp in the entire file and will save a bit on memory overhead.

b) You're safe from shell injection attacks, but you have to slurp in the entire file. If your file is large, you'll probably exhaust available memory.

c) You're invoking a regex every line, which would have significant overhead if you're dealing with a large number of lines.

Title: Get line number from preg_match_all()

Body:
You have got a couple options, but none are "simple":

a) exec() and use the system grep command, which can report line numbers:

exec("grep -n 'your pattern here' file.txt", $output);`

b) Slurp in the file using file_get_contents(), split it into an array of lines, then use preg_grep() to find the matching lines.

$dat = file_get_contents('file.txt');
$lines = explode($dat, "\n");
$matches = preg_grep('/your pattern here/', $lines);

c) Read the file in line-sized chunks, keep a running line count, and do your pattern match on each line.

$fh = fopen('file.txt', 'rb');
$line = 1;
while ($line = fgets($fh)) {
     if (preg_match('/your pattern here/', $line)) {
         ... whatever you need to do with matching lines ...
     }
     $line++;
}

Each has its ups and downs

a) You're invoking an external program, and if your pattern contains any user-supplied data, you're potentially opening yourself up to the shell equivalent of an SQL injection attack. On the plus side, you don't have to slurp in the entire file and will save a bit on memory overhead.

b) You're safe from shell injection attacks, but you have to slurp in the entire file. If your file is large, you'll probably exhaust available memory.

c) You're invoking a regex every line, which would have significant overhead if you're dealing with a large number of lines.


问:
How can I replace the text of this button only
How can I replace the text of this button only. I do not understand the behavior of this button. And this is all the code I came up with to solve this issue

$('.for_whom .close').click(function(z) {

  if ($(this).hasClass('active')) {
    $('body .for .close').removeClass('active');
    $('body .for .close').text('No');

  } else {
    $(this).addClass('active');
    $('body .for .close').not(this).removeClass('active');
    $(this).text('Yes').css('margin-top', '30px');
  }

});```
<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>
<body>
  <div class="for">
    <button class="close">No</button>
  </div>
  <div class="for">
    <button class="close">No</button>
  </div>
  <div class="for">
    <button class="close">No</button>
  </div>
  <div class="for">
    <button class="close">No</button>
  </div>
</body></code>```

答:
Here you go:
https://jsfiddle.net/sudakatux/dwqg4v00/

```<code>$(document).ready(function(){
    $('.close').click(function(z) {

            if ($(this).hasClass('active')) {
                $(this).removeClass('active');
                $(this).text('No');

            } else {
                $(this).addClass('active');
                 $(this).text('Yes').css('margin-top', '30px');
            }

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

If i understood the question correctly you want to toggle between yes and no,

I change your selectros a bit since you are only interested in the buttons. but you are on the right track so you'll get the idea. note that the this keyword is for the handler you previously put to that button. meaning the this is for the clicked button.

Hope it helps

Body:
How can I replace the text of this button only. I do not understand the behavior of this button. And this is all the code I came up with to solve this issue

$('.for_whom .close').click(function(z) {

  if ($(this).hasClass('active')) {
    $('body .for .close').removeClass('active');
    $('body .for .close').text('No');

  } else {
    $(this).addClass('active');
    $('body .for .close').not(this).removeClass('active');
    $(this).text('Yes').css('margin-top', '30px');
  }

});

    <button class="close">No</button>

    <button class="close">No</button>

    <button class="close">No</button>

    <button class="close">No</button>

Body:
Here you go:
https://jsfiddle.net/sudakatux/dwqg4v00/

$(document).ready(function(){
    $('.close').click(function(z) {

            if ($(this).hasClass('active')) {
                $(this).removeClass('active');
                $(this).text('No');

            } else {
                $(this).addClass('active');
                 $(this).text('Yes').css('margin-top', '30px');
            }

        });
  })

If i understood the question correctly you want to toggle between yes and no,

I change your selectros a bit since you are only interested in the buttons. but you are on the right track so you'll get the idea. note that the this keyword is for the handler you previously put to that button. meaning the this is for the clicked button.

Hope it helps


问:
Live stdout output from Python subprocess in Jupyter notebook
I'm using subprocess to run a command line program from a Python (3.5.2) script, which I am running in a Jupyter notebook. The subprocess takes a long time to run and so I would like its stdout to be printed live to the screen in the Jupyter notebook.

I can do this no problem in a normal Python script run from the terminal. I do this using:

```<code>def run_command(cmd):
from subprocess import Popen, PIPE
import shlex

with Popen(shlex.split(cmd), stdout=PIPE, bufsize=1, universal_newlines=True) as p:
    for line in p.stdout:
        print(line, end='')
    exit_code = p.poll()
return exit_code
</code>```

However, when I run the script in a Jupyter notebook, it does not print the stdout live to the screen. Instead, it prints everything after the subprocess has finished running.

Does anyone have any ideas on how to remedy this?

Many thanks,
Johnny

答:
The ipython notebook has it's own support for running shell commands. If you don't need to capture with subprocess stuff you can just do

```<code>cmd = 'ls -l'
!{cmd}
</code>```

Output from commands executed with ! is automatically piped through the notebook.

Body:
I'm using subprocess to run a command line program from a Python (3.5.2) script, which I am running in a Jupyter notebook. The subprocess takes a long time to run and so I would like its stdout to be printed live to the screen in the Jupyter notebook.

I can do this no problem in a normal Python script run from the terminal. I do this using:

def run_command(cmd):
from subprocess import Popen, PIPE
import shlex

with Popen(shlex.split(cmd), stdout=PIPE, bufsize=1, universal_newlines=True) as p:
    for line in p.stdout:
        print(line, end='')
    exit_code = p.poll()
return exit_code

However, when I run the script in a Jupyter notebook, it does not print the stdout live to the screen. Instead, it prints everything after the subprocess has finished running.

Does anyone have any ideas on how to remedy this?

Many thanks,
Johnny

Body:
The ipython notebook has it's own support for running shell commands. If you don't need to capture with subprocess stuff you can just do

cmd = 'ls -l'
!{cmd}

Output from commands executed with ! is automatically piped through the notebook.


问:
Spring Boot - Font Awesome OTS parsing error: Failed to convert
Problem with Fonts not working correctly within a Spring Boot / Spring MVC Application.

The problem is that all of the font files show various errors such as below

```<code>Failed to decode downloaded font: http://localhost:8080/fonts/fontawesome-webfont.woff2?v=4.4.0
OTS parsing error: Failed to convert WOFF 2.0 font to SFNT

Failed to decode downloaded font: http://localhost:8080/fonts/fontawesome-webfont.woff?v=4.4.0
OTS parsing error: incorrect file size in WOFF header

Failed to decode downloaded font: http://localhost:8080/fonts/fontawesome-webfont.ttf?v=4.4.0
OTS parsing error: incorrect entrySelector for table directory
</code>```

答:
Another way to do it is update the configuration of the maven-resources-plugin as follows:</p>

```<code><plugin>
     <groupId>org.apache.maven.plugins</groupId>
     <artifactId>maven-resources-plugin</artifactId>
     <configuration>
          <nonFilteredFileExtensions>
               <nonFilteredFileExtension>ttf</nonFilteredFileExtension>
               <nonFilteredFileExtension>woff</nonFilteredFileExtension>
               <nonFilteredFileExtension>woff2</nonFilteredFileExtension>
          </nonFilteredFileExtensions>
     </configuration>
</plugin>
</code>```

Body:
Problem with Fonts not working correctly within a Spring Boot / Spring MVC Application.

The problem is that all of the font files show various errors such as below

Failed to decode downloaded font: http://localhost:8080/fonts/fontawesome-webfont.woff2?v=4.4.0
OTS parsing error: Failed to convert WOFF 2.0 font to SFNT

Failed to decode downloaded font: http://localhost:8080/fonts/fontawesome-webfont.woff?v=4.4.0
OTS parsing error: incorrect file size in WOFF header

Failed to decode downloaded font: http://localhost:8080/fonts/fontawesome-webfont.ttf?v=4.4.0
OTS parsing error: incorrect entrySelector for table directory

Body:
Another way to do it is update the configuration of the maven-resources-plugin as follows:

<plugin>
     <groupId>org.apache.maven.plugins</groupId>
     <artifactId>maven-resources-plugin</artifactId>
     <configuration>
          <nonFilteredFileExtensions>
               <nonFilteredFileExtension>ttf</nonFilteredFileExtension>
               <nonFilteredFileExtension>woff</nonFilteredFileExtension>
               <nonFilteredFileExtension>woff2</nonFilteredFileExtension>
          </nonFilteredFileExtensions>
     </configuration>
</plugin>


问:
.CSV to DataGridView Rows coming up blank in VB.NET
Here is the CSV data I am trying to import into my VB.NET app:

Raw Data

But when I run it through the app it only populates the last row:

Output

Here's the code for the import:

```<code>Private Sub btnBrowse_Click(sender As Object, e As EventArgs) Handles btnBrowse.Click
    DataGridView1.ClearSelection()
    ofd.Filter = "(*csv)|*.csv"
    If ComboBox1.Text = "zVBImportTEST" Then
        If (ofd.ShowDialog() = DialogResult.OK) Then
            txtbxFilePath.Text = ofd.FileName
        End If
        Dim colsexpected As Integer = 6
        Dim thereader As New StreamReader(txtbxFilePath.Text, Encoding.ASCII)
        Dim sline As String = ""
        thereader.ReadLine()
        Do
            sline = thereader.ReadLine
            If sline Is Nothing Then Exit Do
            Dim words() As String = sline.Split(",")
            DataGridView1.Rows.Add("")
            For ix As Integer = 0 To 5
                DataGridView1.Rows(DataGridView1.Rows.Count - 1).Cells(ix).Value = words(ix)
            Next

        Loop
        thereader.Close()
    Else
        MessageBox.Show("Please select a project.", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
    End If
End Sub
</code>```

I can't seem to figure out why the other rows are coming up blank.
If anyone could help me it would be greatly appreciated.

答:
This is C# but the snippet shows what you are currently doing, and how to do it so that it works.

```<code>using System.Collections.Generic;
using System.Windows.Forms;

namespace DataGridNoBinding_47308996
{
    public partial class Form1 : Form
    {

        DataGridView dgv = new DataGridView();
        public Form1()
        {
            InitializeComponent();
            dgv.Dock = DockStyle.Fill;
            dgv.AutoGenerateColumns = false;
            dgv.Columns.Add("Key","Key");
            dgv.Columns.Add("Value", "Value");
            this.Controls.Add(dgv);

            Dictionary<string, string> dgvdata = new Dictionary<string, string>();
            for (int i = 0; i < 10; i++)
            {
                dgvdata.Add($"key{i}", $"value{i}");
            }

            //AddToGridNoWork(dgvdata);
            AddToGridDoesWork(dgvdata);

        }

        /// <summary>
        /// This method does not work. This emulates what you are currently doing.
        /// </summary>
        /// <param name="dgvdata"></param>
        private void AddToGridNoWork(Dictionary<string, string> dgvdata)
        {
            foreach (KeyValuePair<string, string> item in dgvdata)
            {
                dgv.Rows.Add();
                dgv.Rows[dgv.Rows.Count - 1].Cells[0].Value = item.Key;
                dgv.Rows[dgv.Rows.Count - 1].Cells[1].Value = item.Value;
                dgv.Refresh();
            }
        }

        /// <summary>
        /// This method does work.
        /// Add a new row to the Grid and store the new row index in rowindex
        /// Then use the variable rowindex to update the correct row
        /// </summary>
        /// <param name="dgvdata"></param>
        private void AddToGridDoesWork(Dictionary<string, string> dgvdata)
        {
            foreach (KeyValuePair<string, string> item in dgvdata)
            {
                int rowindex = dgv.Rows.Add();
                dgv.Rows[rowindex].Cells[0].Value = item.Key;
                dgv.Rows[rowindex].Cells[1].Value = item.Value;
            }
        }
    }
}
</code>```

In your VB.net application, it's probably just a matter of doing somehting like this

```<code>dim newRowIndex as Integer
newRowIndex = DataGridView1.Rows.Add("")
For ix As Integer = 0 To 5
    DataGridView1.Rows(newRowIndex).Cells(ix).Value = words(ix)
Next
</code>```

With DataDriver instead
Here's my code, re spun using a data driver instead of the StreamReader

```<code>using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data;

namespace DataGridNoBinding_47308996
{
    public partial class Form1 : Form
    {

        DataGridView dgv = new DataGridView();
        public Form1()
        {
            InitializeComponent();
            dgv.Dock = DockStyle.Fill;
            this.Controls.Add(dgv);

            Dictionary<string, string> dgvdata = new Dictionary<string, string>();
            for (int i = 0; i < 10; i++)
            {
                dgvdata.Add($"key{i}", $"value{i}");
            }

            //AddToGridNoWork(dgvdata);
            //AddToGridDoesWork(dgvdata);
            //AddToGridUsingDataDriver(@"M:\StackOverflowQuestionsAndAnswers\DataGridNoBinding_47308996\SampleData.csv");
            AddToGridByBindingTheWholeTable(@"M:\StackOverflowQuestionsAndAnswers\DataGridNoBinding_47308996\SampleData.csv");

        }

        /// <summary>
        /// This method will do what you want using a Data Driver instead of a StreamReader
        /// Though, this method binds the whole DataTable to the DataGridView instead of manually creating 1 row per data row
        /// </summary>
        /// <param name="dataFilePath"></param>
        private void AddToGridByBindingTheWholeTable(string dataFilePath)
        {
            dgv.AutoGenerateColumns = true;

            string connstring = $"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={System.IO.Path.GetDirectoryName(dataFilePath)};Extended Properties=\"Text;HDR=NO;FMT=Delimited\"";
            OleDbConnection conn = new OleDbConnection(connstring);
            OleDbCommand command = new OleDbCommand($"select * from {System.IO.Path.GetFileName(dataFilePath)}", conn);
            OleDbDataAdapter dataAdapter = new OleDbDataAdapter(command);
            DataTable dt = new DataTable();
            conn.Open();
            dataAdapter.Fill(dt);
            conn.Close();

            dgv.DataSource = dt;
        }

        /// <summary>
        /// This method will do what you want using a Data Driver instead of a StreamReader
        /// In this method, we are actively creating 1 DataGridRow for each DataRow in the DataTable
        /// </summary>
        /// <param name="dataFilePath"></param>
        private void AddToGridUsingDataDriver(string dataFilePath)
        {
            dgv.AutoGenerateColumns = false;
            dgv.Columns.Add("Key", "Key");
            dgv.Columns.Add("Value", "Value");

            string connstring = $"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={System.IO.Path.GetDirectoryName(dataFilePath)};Extended Properties=\"Text;HDR=NO;FMT=Delimited\"";
            OleDbConnection conn = new OleDbConnection(connstring);
            OleDbCommand command = new OleDbCommand($"select * from {System.IO.Path.GetFileName(dataFilePath)}", conn);
            OleDbDataAdapter dataAdapter = new OleDbDataAdapter(command);
            DataTable dt = new DataTable();
            conn.Open();
            dataAdapter.Fill(dt);
            conn.Close();

            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow item in dt.Rows)
                {
                    int newrowid = dgv.Rows.Add();
                    dgv.Rows[newrowid].Cells[0].Value = item.Field<string>(0);
                    dgv.Rows[newrowid].Cells[1].Value = item.Field<string>(1);
                }
            }
            dgv.Refresh();
        }

        /// <summary>
        /// This method does not work. This emulates what you are currently doing.
        /// </summary>
        /// <param name="dgvdata"></param>
        private void AddToGridNoWork(Dictionary<string, string> dgvdata)
        {
            dgv.AutoGenerateColumns = false;
            dgv.Columns.Add("Key","Key");
            dgv.Columns.Add("Value", "Value");

            foreach (KeyValuePair<string, string> item in dgvdata)
            {
                dgv.Rows.Add();
                dgv.Rows[dgv.Rows.Count - 1].Cells[0].Value = item.Key;
                dgv.Rows[dgv.Rows.Count - 1].Cells[1].Value = item.Value;
                dgv.Refresh();
            }
        }

        /// <summary>
        /// This method does work.
        /// Add a new row to the Grid and store the new row index in rowindex
        /// Then use the variable rowindex to update the correct row
        /// </summary>
        /// <param name="dgvdata"></param>
        private void AddToGridDoesWork(Dictionary<string, string> dgvdata)
        {
            dgv.AutoGenerateColumns = false;
            dgv.Columns.Add("Key", "Key");
            dgv.Columns.Add("Value", "Value");

            foreach (KeyValuePair<string, string> item in dgvdata)
            {
                int rowindex = dgv.Rows.Add();
                dgv.Rows[rowindex].Cells[0].Value = item.Key;
                dgv.Rows[rowindex].Cells[1].Value = item.Value;
            }
        }
    }
}
</code>```

Body:
Here is the CSV data I am trying to import into my VB.NET app:

Raw Data

But when I run it through the app it only populates the last row:

Output

Here's the code for the import:

Private Sub btnBrowse_Click(sender As Object, e As EventArgs) Handles btnBrowse.Click
    DataGridView1.ClearSelection()
    ofd.Filter = "(*csv)|*.csv"
    If ComboBox1.Text = "zVBImportTEST" Then
        If (ofd.ShowDialog() = DialogResult.OK) Then
            txtbxFilePath.Text = ofd.FileName
        End If
        Dim colsexpected As Integer = 6
        Dim thereader As New StreamReader(txtbxFilePath.Text, Encoding.ASCII)
        Dim sline As String = ""
        thereader.ReadLine()
        Do
            sline = thereader.ReadLine
            If sline Is Nothing Then Exit Do
            Dim words() As String = sline.Split(",")
            DataGridView1.Rows.Add("")
            For ix As Integer = 0 To 5
                DataGridView1.Rows(DataGridView1.Rows.Count - 1).Cells(ix).Value = words(ix)
            Next

        Loop
        thereader.Close()
    Else
        MessageBox.Show("Please select a project.", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
    End If
End Sub

I can't seem to figure out why the other rows are coming up blank.
If anyone could help me it would be greatly appreciated.

Body:
This is C# but the snippet shows what you are currently doing, and how to do it so that it works.

using System.Collections.Generic;
using System.Windows.Forms;

namespace DataGridNoBinding_47308996
{
    public partial class Form1 : Form
    {

        DataGridView dgv = new DataGridView();
        public Form1()
        {
            InitializeComponent();
            dgv.Dock = DockStyle.Fill;
            dgv.AutoGenerateColumns = false;
            dgv.Columns.Add("Key","Key");
            dgv.Columns.Add("Value", "Value");
            this.Controls.Add(dgv);

            Dictionary<string, string> dgvdata = new Dictionary<string, string>();
            for (int i = 0; i < 10; i++)
            {
                dgvdata.Add($"key{i}", $"value{i}");
            }

            //AddToGridNoWork(dgvdata);
            AddToGridDoesWork(dgvdata);

        }

        /// <summary>
        /// This method does not work. This emulates what you are currently doing.
        /// </summary>
        /// <param name="dgvdata"></param>
        private void AddToGridNoWork(Dictionary<string, string> dgvdata)
        {
            foreach (KeyValuePair<string, string> item in dgvdata)
            {
                dgv.Rows.Add();
                dgv.Rows[dgv.Rows.Count - 1].Cells[0].Value = item.Key;
                dgv.Rows[dgv.Rows.Count - 1].Cells[1].Value = item.Value;
                dgv.Refresh();
            }
        }

        /// <summary>
        /// This method does work.
        /// Add a new row to the Grid and store the new row index in rowindex
        /// Then use the variable rowindex to update the correct row
        /// </summary>
        /// <param name="dgvdata"></param>
        private void AddToGridDoesWork(Dictionary<string, string> dgvdata)
        {
            foreach (KeyValuePair<string, string> item in dgvdata)
            {
                int rowindex = dgv.Rows.Add();
                dgv.Rows[rowindex].Cells[0].Value = item.Key;
                dgv.Rows[rowindex].Cells[1].Value = item.Value;
            }
        }
    }
}

In your VB.net application, it's probably just a matter of doing somehting like this

dim newRowIndex as Integer
newRowIndex = DataGridView1.Rows.Add("")
For ix As Integer = 0 To 5
    DataGridView1.Rows(newRowIndex).Cells(ix).Value = words(ix)
Next

With DataDriver instead
Here's my code, re spun using a data driver instead of the StreamReader

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data;

namespace DataGridNoBinding_47308996
{
    public partial class Form1 : Form
    {

        DataGridView dgv = new DataGridView();
        public Form1()
        {
            InitializeComponent();
            dgv.Dock = DockStyle.Fill;
            this.Controls.Add(dgv);

            Dictionary<string, string> dgvdata = new Dictionary<string, string>();
            for (int i = 0; i < 10; i++)
            {
                dgvdata.Add($"key{i}", $"value{i}");
            }

            //AddToGridNoWork(dgvdata);
            //AddToGridDoesWork(dgvdata);
            //AddToGridUsingDataDriver(@"M:\StackOverflowQuestionsAndAnswers\DataGridNoBinding_47308996\SampleData.csv");
            AddToGridByBindingTheWholeTable(@"M:\StackOverflowQuestionsAndAnswers\DataGridNoBinding_47308996\SampleData.csv");

        }

        /// <summary>
        /// This method will do what you want using a Data Driver instead of a StreamReader
        /// Though, this method binds the whole DataTable to the DataGridView instead of manually creating 1 row per data row
        /// </summary>
        /// <param name="dataFilePath"></param>
        private void AddToGridByBindingTheWholeTable(string dataFilePath)
        {
            dgv.AutoGenerateColumns = true;

            string connstring = $"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={System.IO.Path.GetDirectoryName(dataFilePath)};Extended Properties=\"Text;HDR=NO;FMT=Delimited\"";
            OleDbConnection conn = new OleDbConnection(connstring);
            OleDbCommand command = new OleDbCommand($"select * from {System.IO.Path.GetFileName(dataFilePath)}", conn);
            OleDbDataAdapter dataAdapter = new OleDbDataAdapter(command);
            DataTable dt = new DataTable();
            conn.Open();
            dataAdapter.Fill(dt);
            conn.Close();

            dgv.DataSource = dt;
        }

        /// <summary>
        /// This method will do what you want using a Data Driver instead of a StreamReader
        /// In this method, we are actively creating 1 DataGridRow for each DataRow in the DataTable
        /// </summary>
        /// <param name="dataFilePath"></param>
        private void AddToGridUsingDataDriver(string dataFilePath)
        {
            dgv.AutoGenerateColumns = false;
            dgv.Columns.Add("Key", "Key");
            dgv.Columns.Add("Value", "Value");

            string connstring = $"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={System.IO.Path.GetDirectoryName(dataFilePath)};Extended Properties=\"Text;HDR=NO;FMT=Delimited\"";
            OleDbConnection conn = new OleDbConnection(connstring);
            OleDbCommand command = new OleDbCommand($"select * from {System.IO.Path.GetFileName(dataFilePath)}", conn);
            OleDbDataAdapter dataAdapter = new OleDbDataAdapter(command);
            DataTable dt = new DataTable();
            conn.Open();
            dataAdapter.Fill(dt);
            conn.Close();

            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow item in dt.Rows)
                {
                    int newrowid = dgv.Rows.Add();
                    dgv.Rows[newrowid].Cells[0].Value = item.Field<string>(0);
                    dgv.Rows[newrowid].Cells[1].Value = item.Field<string>(1);
                }
            }
            dgv.Refresh();
        }

        /// <summary>
        /// This method does not work. This emulates what you are currently doing.
        /// </summary>
        /// <param name="dgvdata"></param>
        private void AddToGridNoWork(Dictionary<string, string> dgvdata)
        {
            dgv.AutoGenerateColumns = false;
            dgv.Columns.Add("Key","Key");
            dgv.Columns.Add("Value", "Value");

            foreach (KeyValuePair<string, string> item in dgvdata)
            {
                dgv.Rows.Add();
                dgv.Rows[dgv.Rows.Count - 1].Cells[0].Value = item.Key;
                dgv.Rows[dgv.Rows.Count - 1].Cells[1].Value = item.Value;
                dgv.Refresh();
            }
        }

        /// <summary>
        /// This method does work.
        /// Add a new row to the Grid and store the new row index in rowindex
        /// Then use the variable rowindex to update the correct row
        /// </summary>
        /// <param name="dgvdata"></param>
        private void AddToGridDoesWork(Dictionary<string, string> dgvdata)
        {
            dgv.AutoGenerateColumns = false;
            dgv.Columns.Add("Key", "Key");
            dgv.Columns.Add("Value", "Value");

            foreach (KeyValuePair<string, string> item in dgvdata)
            {
                int rowindex = dgv.Rows.Add();
                dgv.Rows[rowindex].Cells[0].Value = item.Key;
                dgv.Rows[rowindex].Cells[1].Value = item.Value;
            }
        }
    }
}


问:
Spark context 'sc' not defined
I am new to Spark and I am trying to install the PySpark by referring to the below site.

http://ramhiser.com/2015/02/01/configuring-ipython-notebook-support-for-pyspark/

I tried to install both prebuilt package and also by building the Spark package thru SBT.

When I try to run a python code in IPython Notebook I get the below error.

```<code>    NameError                                 Traceback (most recent call last)
   <ipython-input-1-f7aa330f6984> in <module>()
      1 # Check that Spark is working
----> 2 largeRange = sc.parallelize(xrange(100000))
      3 reduceTest = largeRange.reduce(lambda a, b: a + b)
      4 filterReduceTest = largeRange.filter(lambda x: x % 7 == 0).sum()
      5

      NameError: name 'sc' is not defined
</code>```

In the command window I can see the below error.

```<code><strong>Failed to find Spark assembly JAR.</strong>
<strong>You need to build Spark before running this program.</strong>
</code>```

Note that I got a scala prompt when I executed spark-shell command

Update:

With help of a friend I am able to fix the issue related to Spark assembly JAR by correcting the contents of .ipython/profile_pyspark/startup/00-pyspark-setup.py file

I have now only the problem of Spark Context variable. Changing the title to be appropriately reflect my current issue.

答:
You have to creat instance of SparkContext like following:

import:

```<code>from pyspark import SparkContext
</code>```

and then:

```<code>sc =SparkContext.getOrCreate()
</code>```

NB:sc =SparkContext.getOrCreate() works well than sc =SparkContext().

Title: Spark context 'sc' not defined

Body:
I am new to Spark and I am trying to install the PySpark by referring to the below site.

http://ramhiser.com/2015/02/01/configuring-ipython-notebook-support-for-pyspark/

I tried to install both prebuilt package and also by building the Spark package thru SBT.

When I try to run a python code in IPython Notebook I get the below error.

    NameError                                 Traceback (most recent call last)
   <ipython-input-1-f7aa330f6984> in <module>()
      1 # Check that Spark is working
----> 2 largeRange = sc.parallelize(xrange(100000))
      3 reduceTest = largeRange.reduce(lambda a, b: a + b)
      4 filterReduceTest = largeRange.filter(lambda x: x % 7 == 0).sum()
      5

      NameError: name 'sc' is not defined

In the command window I can see the below error.

Failed to find Spark assembly JAR.
You need to build Spark before running this program.

Note that I got a scala prompt when I executed spark-shell command

Update:

With help of a friend I am able to fix the issue related to Spark assembly JAR by correcting the contents of .ipython/profile_pyspark/startup/00-pyspark-setup.py file

I have now only the problem of Spark Context variable. Changing the title to be appropriately reflect my current issue.

Body:
You have to creat instance of SparkContext like following:

import:

from pyspark import SparkContext

and then:

sc =SparkContext.getOrCreate()

NB:sc =SparkContext.getOrCreate() works well than sc =SparkContext().


问:
ASP.Net Membership.DeleteUser
In testing, the user on a db i've used was a big jefe.  In production, he only has Execute.

When I called,

```<code>Membership.DeleteUser(user)
</code>```

In testing, it worked.
I try the same in production, and I get this:

The DELETE statement conflicted with the REFERENCE constraint
  "FK__aspnet_Us__UserI__37703C52". The conflict occurred in database
  "Testing", table "dbo.aspnet_UsersInRoles", column 'UserId'.

In my seargles (searches on Google), I came across this link
where the dude was saying,

Error: The DELETE statement conflicted
  with the REFERENCE constraint
  "FK__aspnet_Me__UserI__15502E78". The
  conflict occurred in database
  "YourDBName", table
  "dbo.aspnet_Membership", column
  'UserId'.

Took me a while to find a solution to
  this across multiple sites and options
  as the error and possible solutions
  were rather misleading.  Turns out, at
  least in my case, it was a problem
  with permissions on the membership
  database.  The user I'm using to
  connect had access to view the
  membership details within the database
  itself, but as part of the
  aspnet_Users_DeleteUser stored
  procedure it selects from the
  sysobjects table.  The membership
  connection user apparently did not
  have sufficient rights to do that
  select so the overall delete failed.

The fix for me was to add the user to
  the aspnet_Membership_FullAccess role
  for the membership database.

But when I did that it didn't work. Anyone have any ideas on how to deal with this?

答:
I believe your 'REFERENCE' constraint is actually a Foreign key in the database that exists between the aspnet_Users table and the aspnet_UsersInRoles table.  I would figure that the user you are trying, has it's UserId in both tables, and before you can remove it from the Users table, it has to be removed from the UsersInRoles table also.

Have you tried http://msdn.microsoft.com/en-us/library/system.web.security.roleprovider.removeusersfromroles.aspx to ensure that all the roles are removed from this user?  You could verify too by inspecting the rows of these two tables in the database.

Title: ASP.Net Membership.DeleteUser

Body:
In testing, the user on a db i've used was a big jefe.  In production, he only has Execute.

When I called,

Membership.DeleteUser(user)

In testing, it worked.
I try the same in production, and I get this:

The DELETE statement conflicted with the REFERENCE constraint
  "FK__aspnet_Us__UserI__37703C52". The conflict occurred in database
  "Testing", table "dbo.aspnet_UsersInRoles", column 'UserId'.

In my seargles (searches on Google), I came across this link
where the dude was saying,

Error: The DELETE statement conflicted
  with the REFERENCE constraint
  "FK__aspnet_Me__UserI__15502E78". The
  conflict occurred in database
  "YourDBName", table
  "dbo.aspnet_Membership", column
  'UserId'.

Took me a while to find a solution to
  this across multiple sites and options
  as the error and possible solutions
  were rather misleading.  Turns out, at
  least in my case, it was a problem
  with permissions on the membership
  database.  The user I'm using to
  connect had access to view the
  membership details within the database
  itself, but as part of the
  aspnet_Users_DeleteUser stored
  procedure it selects from the
  sysobjects table.  The membership
  connection user apparently did not
  have sufficient rights to do that
  select so the overall delete failed.

The fix for me was to add the user to
  the aspnet_Membership_FullAccess role
  for the membership database.

But when I did that it didn't work. Anyone have any ideas on how to deal with this?

OwnerDisplayName: Kyle B.


问:
Check if image view not null
On my app, I insert an image by camera or gallery, then convert it to byte[] to save on sqlite database.
When insert, I check if image view not null and this is the error

java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap android.graphics.drawable.BitmapDrawable.getBitmap()' on a null object reference

This is my code (insert to sqlite)

```<code>private void xuLyLuuTatCa() {

    String rangbuoc = etxtname.getText().toString();

    Bitmap bitmap = ((BitmapDrawable)imghinh3.getDrawable()).getBitmap();
    if(rangbuoc != null && rangbuoc.length() > 0
            || etxtadd.getText().toString() != null && etxtadd.getText().toString().length() > 0
            || etxtprice.getText().toString() != null && etxtprice.getText().toString().length() > 0
            || etxtopen.getText().toString() != null && etxtopen.getText().toString().length() > 0
            || etxtrate.getText().toString() != null && etxtrate.getText().toString().length() > 0
            || etxtdanhgia.getText().toString() != null && etxtdanhgia.getText().toString().length() > 0
            || imghinh1.getDrawable() != null || imghinh2.getDrawable() != null || bitmap != null) {

        db = database.initDatabase(this,DATABASE_NAME);
        String name = etxtname.getText().toString();
        String add = etxtadd.getText().toString();
        String price = etxtprice.getText().toString();
        String gio = etxtopen.getText().toString();
        double danhgia = Double.parseDouble(etxtrate.getText().toString());
        String binhluan = etxtdanhgia.getText().toString();
        byte[] anh = ConverttoArrayByte(imghinh1);
        byte[] anh2 = ConverttoArrayByte(imghinh2);
        byte[] anh3 = ConverttoArrayByte(imghinh3);
        boolean thich = false;
        ContentValues values = new ContentValues();
        //values.put("IDQuan", id);
        values.put("TenQuan", name);
        values.put("DiaChi", add);
        values.put("Gia", price);
        values.put("GioMoCua", gio);
        values.put("DanhGia", danhgia);
        values.put("Review", binhluan);
        values.put("YeuThich", thich);
        values.put("HinhAnh", anh);
        values.put("Hinh1", anh2);
        values.put("Hinh2", anh3);
        values.put("ViDo", 0);
        values.put("KinhDo", 0);
        String mess = "";
        if(db.insert("Quan",null,values) == -1)
        {
            mess = "Lỗi";
        }
        else
            mess = "Thành công";
        Toast.makeText(this, mess, Toast.LENGTH_SHORT).show();
        db.close();
        finish();
    }
    else
    {
        Toast.makeText(this, "Mời bạn nhập vào mục còn trống", Toast.LENGTH_LONG).show();
    }
}

public byte[] ConverttoArrayByte(ImageView img)
{
    BitmapDrawable bitmapDrawable = (BitmapDrawable) img.getDrawable();
    Bitmap bitmap=bitmapDrawable.getBitmap();

    ByteArrayOutputStream stream=new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
    return stream.toByteArray();
}
</code>```

So how to check imageview not null??? Thanks in advance

答:
You could use a try catch inside you method like this</p>

```<code>public byte[] ConverttoArrayByte(ImageView img) {
    try {
        BitmapDrawable bitmapDrawable = (BitmapDrawable) img.getDrawable();
        Bitmap bitmap = bitmapDrawable.getBitmap();

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        return stream.toByteArray();

    } catch (NullPointerException e) {
        // do something
    }

    return null;
}
</code>```

Title: Check if image view not null

Body:
On my app, I insert an image by camera or gallery, then convert it to byte[] to save on sqlite database.
When insert, I check if image view not null and this is the error

java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap android.graphics.drawable.BitmapDrawable.getBitmap()' on a null object reference

This is my code (insert to sqlite)

private void xuLyLuuTatCa() {

    String rangbuoc = etxtname.getText().toString();

    Bitmap bitmap = ((BitmapDrawable)imghinh3.getDrawable()).getBitmap();
    if(rangbuoc != null && rangbuoc.length() > 0
            || etxtadd.getText().toString() != null && etxtadd.getText().toString().length() > 0
            || etxtprice.getText().toString() != null && etxtprice.getText().toString().length() > 0
            || etxtopen.getText().toString() != null && etxtopen.getText().toString().length() > 0
            || etxtrate.getText().toString() != null && etxtrate.getText().toString().length() > 0
            || etxtdanhgia.getText().toString() != null && etxtdanhgia.getText().toString().length() > 0
            || imghinh1.getDrawable() != null || imghinh2.getDrawable() != null || bitmap != null) {

        db = database.initDatabase(this,DATABASE_NAME);
        String name = etxtname.getText().toString();
        String add = etxtadd.getText().toString();
        String price = etxtprice.getText().toString();
        String gio = etxtopen.getText().toString();
        double danhgia = Double.parseDouble(etxtrate.getText().toString());
        String binhluan = etxtdanhgia.getText().toString();
        byte[] anh = ConverttoArrayByte(imghinh1);
        byte[] anh2 = ConverttoArrayByte(imghinh2);
        byte[] anh3 = ConverttoArrayByte(imghinh3);
        boolean thich = false;
        ContentValues values = new ContentValues();
        //values.put("IDQuan", id);
        values.put("TenQuan", name);
        values.put("DiaChi", add);
        values.put("Gia", price);
        values.put("GioMoCua", gio);
        values.put("DanhGia", danhgia);
        values.put("Review", binhluan);
        values.put("YeuThich", thich);
        values.put("HinhAnh", anh);
        values.put("Hinh1", anh2);
        values.put("Hinh2", anh3);
        values.put("ViDo", 0);
        values.put("KinhDo", 0);
        String mess = "";
        if(db.insert("Quan",null,values) == -1)
        {
            mess = "Lỗi";
        }
        else
            mess = "Thành công";
        Toast.makeText(this, mess, Toast.LENGTH_SHORT).show();
        db.close();
        finish();
    }
    else
    {
        Toast.makeText(this, "Mời bạn nhập vào mục còn trống", Toast.LENGTH_LONG).show();
    }
}

public byte[] ConverttoArrayByte(ImageView img)
{
    BitmapDrawable bitmapDrawable = (BitmapDrawable) img.getDrawable();
    Bitmap bitmap=bitmapDrawable.getBitmap();

    ByteArrayOutputStream stream=new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
    return stream.toByteArray();
}

So how to check imageview not null??? Thanks in advance

Body:
You could use a try catch inside you method like this

public byte[] ConverttoArrayByte(ImageView img) {
    try {
        BitmapDrawable bitmapDrawable = (BitmapDrawable) img.getDrawable();
        Bitmap bitmap = bitmapDrawable.getBitmap();

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        return stream.toByteArray();

    } catch (NullPointerException e) {
        // do something
    }

    return null;
}


问:
What are the review requirements regarding QUERY intents?
Due to hardware restrictions, we are unable to retrieve the current status of many of our lights (their color/brightness/etc.).

In the QA test cases spreadsheet found here, at the bottom under Deploying, a number of QUERY intents are listed to be tested. Does this mean our Smart Home application will not be able to pass certification?

Thank you for reading.

答:
If anything, just try to be honest with the review team and they will keep certain limitations in mind.

When submitting for review make sure you provide them with a perfectly working test environment. So if some of your lights don't function like you want them to and you can't get their info, don't provide them for testing.

I'm not familiar with the review process of Smart Home applications but if you provide the review team with the right information of which hardware is and isn't supported I'm sure they won't straight up reject your application for it.


问:
How to place multiple objects using ARCore
I want to make an ARCore app where you can select what you want to place. Does anyone know how to do this</p>

答:
If you are using the default example, you can change the line:

```<code>public GameObject m_andyAndroidPrefab;
</code>```

to the line:

```<code>public List<GameObject> m_Prefabs;
</code>```

In your Update() method, change the existing Instantiate invocation with this:

```<code>var object = Instantiate(m_Prefabs[m_currentObjectIndex],
                    hit.Point, Quaternion.identity, anchor.transform);
</code>```

m_currentObjectIndex is an integer that holds the current index of the desired prefab to create. You will need to update this field when the user selects an object in your menu, for example.

Body:
If you are using the default example, you can change the line:

public GameObject m_andyAndroidPrefab;

to the line:

public List<GameObject> m_Prefabs;

In your Update() method, change the existing Instantiate invocation with this:

var object = Instantiate(m_Prefabs[m_currentObjectIndex],
                    hit.Point, Quaternion.identity, anchor.transform);

m_currentObjectIndex is an integer that holds the current index of the desired prefab to create. You will need to update this field when the user selects an object in your menu, for example.


问:
Modifying object for each web service call
In our web application we have a lot of REST services. Suddenly it found out that we need to modify one object inside of each request before we go on.
So let's say we have n different controllers with REST services. In each controller, before we call the service from next layer, we need to modify an object inside the request.

The question is how to achieve this without providing hundreds of changes inside the controllers... Is there any simple way to do this?

UPDATE:

```<code>@RestController
public class OrderController {

    @Autowired
    private OrderService orderService;

    @RequestMapping(path = "/order", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public OrderResponse getOrderData(@RequestHeader HttpHeaders httpHeaders,
            @RequestBody OrderDataRequest orderDataRequest) {

        // Use here interceptor to modify the object Details
        // (inside OrderDataRequest) before below call:
        OrderResponse resp = orderService.getOrderData(orderDataRequest);

        return resp;
    }

    @RequestMapping(path = "/cancel/{orderId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public boolean cancelOrder(@RequestHeader HttpHeaders httpHeaders,
            @RequestBody Details details, @PathVariable Integer orderId) {

        // Use here interceptor to modify object Details before below call:
        return orderService.cancelOrder(details, orderId);
    }
}
</code>```

In each controller I need to modift the object Details, which as you can see could be inside another object like in the first example or exist alone like in the second option.

答: You can use Spring AOP to achieve this. Another option using traditional Filters.</p>

Body:
In our web application we have a lot of REST services. Suddenly it found out that we need to modify one object inside of each request before we go on.
So let's say we have n different controllers with REST services. In each controller, before we call the service from next layer, we need to modify an object inside the request.

The question is how to achieve this without providing hundreds of changes inside the controllers... Is there any simple way to do this?

UPDATE:

@RestController
public class OrderController {

    @Autowired
    private OrderService orderService;

    @RequestMapping(path = "/order", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public OrderResponse getOrderData(@RequestHeader HttpHeaders httpHeaders,
            @RequestBody OrderDataRequest orderDataRequest) {

        // Use here interceptor to modify the object Details
        // (inside OrderDataRequest) before below call:
        OrderResponse resp = orderService.getOrderData(orderDataRequest);

        return resp;
    }

    @RequestMapping(path = "/cancel/{orderId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public boolean cancelOrder(@RequestHeader HttpHeaders httpHeaders,
            @RequestBody Details details, @PathVariable Integer orderId) {

        // Use here interceptor to modify object Details before below call:
        return orderService.cancelOrder(details, orderId);
    }
}

In each controller I need to modift the object Details, which as you can see could be inside another object like in the first example or exist alone like in the second option.


问:
.NET MEF Load unreferenced .dll's
I've made a 3 layer web application (web api -> logic-> DAL). A Shared project contains all the interfaces used for injection the dependencies between the layers. I load my layers as components with MEF (reflection) Thus, the web api project does not have any build time dependency to the other layers! This means that the DLL's (logic.dll + DAL.dll) will not be present in the web api's /bin folder - and thus the MEF will not find and load my dll's.

Everything works if i just add an (unused) reference between the projects in the solution - but it makes no sense for me having this dependency... The whole purpose of using MEF components was to decouple everything and communicate through interfaces. :-)

答:
You can use DirectoryCatalog for such a task. Here is an example:

```<code> var dirPath = @"Z:\MyAssemblies";
 var registration = new RegistrationBuilder();
 registration.ForTypesMatching(t => typeof(IFoo).IsAssignableFrom(t))
      .Export<IFoo>();
 var dirCatalog = new DirectoryCatalog(dirPath,registration);
 var container = new CompositionContainer(dirCatalog);
</code>```

As you can see it recieves as a parameter the full path to the directory where youre dlls are. It then scan it and does known MEF stuff..

This way you achieve to decouple everything as you said.

Title: .NET MEF Load unreferenced .dll's

Body:
You can use DirectoryCatalog for such a task. Here is an example:

 var dirPath = @"Z:\MyAssemblies";
 var registration = new RegistrationBuilder();
 registration.ForTypesMatching(t => typeof(IFoo).IsAssignableFrom(t))
      .Export<IFoo>();
 var dirCatalog = new DirectoryCatalog(dirPath,registration);
 var container = new CompositionContainer(dirCatalog);

As you can see it recieves as a parameter the full path to the directory where youre dlls are. It then scan it and does known MEF stuff..

This way you achieve to decouple everything as you said.


答: The list you are printing out is a list of objects, not strings; <Color #e65318>is a Color object. From the docs it looks like you can get the hex representation using hex or hex_l: https://pypi.python.org/pypi/colour

Title: Python: Manipulating list of Color objects?

Body:
I'm using the colour package to create a gradient of colors, like this:

from colour import Color
orange = Color("#e65318")
turquoise = Color("#3297A5")
palette_list = list(orange.range_to(turquoise,10))

the output is a list, like this:

[<Color #e65318>, <Color #de911b>, <Color #d7c71f>, <Color #a7cf22>, <Color #6fc825>, <Color #3dc128>, <Color #2bb944>, <Color #2db36f>, <Color #30ac94>, <Color #3297a5>]

and what I would really like, is this:

['#e65318', '#de911b', '#d7c71f', '#a7cf22', '#6fc825', '#3dc128', '#2bb944', '#2db36f', '#30ac94', '#3297a5']

So far, I've tried ai_palette_list.remove('Color')

which returns ValueError: list.remove(x): x not in list.

I am thinking this is a pretty general problem, but can't seem to find any sane, systematic way of going about removing the word 'Color' and returning a string.


答: Declare your main method to catch the IOException. If you do so, when the exception is thrown in your connect() method, it will be propagated to the main method and your finally block will be executed. If that is what you wanted.

Title: Try-Catch-Finally Block

Body:
i already know that the traditional Try block in java must have at least catch block or finally block (both or either), and i already know that checked exceptions must be handled or declared.
but i am wondering why it won't compile although i have used correct try block syntax

i have this piece of code here , in the main method i used Try with finally block but i am wondering why it won't compile

Here is my code:

import java.io.IOException;
import java.net.Socket;

public class ExHandling {

public void connect() throws IOException
    {
        Socket s = new Socket();
        try
        {
            s.getInputStream();
        }
        catch(IOException e )
        {
            e.printStackTrace();
        }
        finally
        {
            s.close();
        }
    }
public static void main(String []args)
    {
        ExHandling ex = new ExHandling();

        try
        {
            ex.connect();

        }

        finally
        {
            System.out.println("Finally");
        }

    }
}

Any Help Please


问:
AWS Cloudformation dynamodb tablename has characters at the end
I'm creating a Dynamodb table though serverless SAM and this is what I have

```<code>  MyTable:
    Type: AWS::DynamoDB::Table
    Properties:
      AttributeDefinitions:
        - AttributeName: Id
          AttributeType: S
      KeySchema:
        - AttributeName: Id
          KeyType: HASH
      ProvisionedThroughput:
        ReadCapacityUnits: 5
        WriteCapacityUnits: 5
      StreamSpecification:
        StreamViewType: KEYS_ONLY
</code>```

The problem is that when the table is created it has a random set of characters at the end, so for example my table after being created in DynamoDB will look like this

stackname-Stores-10H9IHDFESTE0

Why are these random characters added at the end and how do I get rid of them?  Plus my code needs to read from this table and everytime I deploy something if these characters are added to the end, how do I solve this?  The same is true for the lambda function being deployed as well, it adds this weird characters at the end for eample my Lambda function once deployed looks like this

stakcname-StoresFunction-1D1J4W48RVDUR

答:
I think you're missing the name of the table and the name of the Lambda function in your SAM - under the Properties key in the respective resources:

TableName: String

FunctionName : String

Body:
I'm creating a Dynamodb table though serverless SAM and this is what I have

  MyTable:
    Type: AWS::DynamoDB::Table
    Properties:
      AttributeDefinitions:
        - AttributeName: Id
          AttributeType: S
      KeySchema:
        - AttributeName: Id
          KeyType: HASH
      ProvisionedThroughput:
        ReadCapacityUnits: 5
        WriteCapacityUnits: 5
      StreamSpecification:
        StreamViewType: KEYS_ONLY

The problem is that when the table is created it has a random set of characters at the end, so for example my table after being created in DynamoDB will look like this

stackname-Stores-10H9IHDFESTE0

Why are these random characters added at the end and how do I get rid of them?  Plus my code needs to read from this table and everytime I deploy something if these characters are added to the end, how do I solve this?  The same is true for the lambda function being deployed as well, it adds this weird characters at the end for eample my Lambda function once deployed looks like this

stakcname-StoresFunction-1D1J4W48RVDUR


问:
Generic type bounded by another generic
Suppose I have this:

```<code>interface Shape {}
interface Square extends Shape {}
interface Circle extends Shape {}

interface ShapeBuilder<S extends Shape> {}
</code>```

I want something like this:

```<code>class ShapeBuilderFactory<SB extends ShapeBuilder> {
    SB<Square> getSquareBuilder(){...}
    SB<Circle> getCircleBuilder(){...}
}
</code>```

This code doesn't compile (because ShapeBuilder is a raw type), but I hope you understand the idea.
Is it possible to do something like this in java? How?

(the real problem isn't with shapes builders and factories, I used this example for simplicity)

Edit (more context)

I have different kind of builders:

```<code>interface RegularShapeBuilder<S extends Shape> extends ShapeBuilder<S> {}
interface FunnyShapeBuilder<S extends Shape> extends ShapeBuilder<S> {}

class RegularSquareBuilder extends RegularShapeBuilder<Square> {}
class FunnySquareBuilder extends FunnyShapeBuilder<Square> {}
class RegularCircleBuilder extends RegularShapeBuilder<Circle> {}
class FunnyCircleBuilder extends FunnyShapeBuilder<Circle> {}
</code>```

And I want the factory to do things like this:

```<code>ShapeBuilderFactory<FunnyShapeBuilder> funnyShapeBuilderFactory = ...;
FunnyShapeBuilder<Square> funnySquareBuilder = funnyShapeBuilderFactory.getSquareBuilder();
</code>```

答:
```<code>class ShapeBuilderFactory<S extends Shape, SB extends ShapeBuilder<S>> {
</code>```

Although you might consider whether you need it to be generic at all.

Title: Generic type bounded by another generic

Body:
Suppose I have this:

interface Shape {}
interface Square extends Shape {}
interface Circle extends Shape {}

interface ShapeBuilder<S extends Shape> {}

I want something like this:

class ShapeBuilderFactory<SB extends ShapeBuilder> {
    SB<Square> getSquareBuilder(){...}
    SB<Circle> getCircleBuilder(){...}
}

This code doesn't compile (because ShapeBuilder is a raw type), but I hope you understand the idea.
Is it possible to do something like this in java? How?

(the real problem isn't with shapes builders and factories, I used this example for simplicity)

Edit (more context)

I have different kind of builders:

interface RegularShapeBuilder<S extends Shape> extends ShapeBuilder<S> {}
interface FunnyShapeBuilder<S extends Shape> extends ShapeBuilder<S> {}

class RegularSquareBuilder extends RegularShapeBuilder<Square> {}
class FunnySquareBuilder extends FunnyShapeBuilder<Square> {}
class RegularCircleBuilder extends RegularShapeBuilder<Circle> {}
class FunnyCircleBuilder extends FunnyShapeBuilder<Circle> {}

And I want the factory to do things like this:

ShapeBuilderFactory<FunnyShapeBuilder> funnyShapeBuilderFactory = ...;
FunnyShapeBuilder<Square> funnySquareBuilder = funnyShapeBuilderFactory.getSquareBuilder();

Body:
class ShapeBuilderFactory<S extends Shape, SB extends ShapeBuilder<S>> {

Although you might consider whether you need it to be generic at all.