问:
Unfinished verification, Missing method call for verify(mock) while writing a JUnit test case
I am facing

```<code>org.mockito.exceptions.misusing.UnfinishedVerificationException:
Missing method call for verify(mock) here:
-> at systemservice.test1.SysParamsBuilderTest.testBuildProcessingInfoIf3(SysParamsBuilderTest.java:241)
</code>```

I have checked for all the parameters and the object as well that is being passed to verify, But not able to figure out what is causing the above exception

The condition I am trying to test,

```<code>if( request.getProcessType() == IPRequest.IPREQUEST_TYPE_DE )
{

     LookInfoIf rdr = new MCLLookInfoReader();

    String origAnatomy = accessor.getValue(AttributeRepNames.ANATOMY_INFO.getTagName());
    String origView = accessor.getValue(AttributeRepNames.VIEW_INFO.getTagName());
    String origPatSize = accessor.getValue(AttributeRepNames.PATIENT_SIZE.getTagName());
    String mclPatSize = getMclPatientSize(origPatSize);
    String boneLook = rdr.getDefaultLook(origAnatomy,origView,core.MCLConstants.IMAGETYPEBONETAG,mclPatSize);
    String tissueLook = rdr.getDefaultLook(origAnatomy,origView,core.MCLConstants.IMAGETYPESOFTTISSUETAG,mclPatSize);

    params.setProcessingLookBone(boneLook);
    params.setProcessingLookTissue(tissueLook);
        params.setAnatomy(origAnatomy);
        params.setView(origView);
        params.setPatientSize(origPatSize);

}
</code>```

Test case

```<code>@Test
    public void testBuildProcessingInfoIf3() throws Exception
    {
        IPRequest req=new IPRequest(1);//value of IPRequest.IPREQUEST_TYPE_DE

        IPSysParams iPSysParams = Mockito.mock(IPSysParams.class);
        PowerMockito.whenNew(IPSysParams.class).withNoArguments().thenReturn(iPSysParams);

        TagAccessor accessor=Mockito.mock(TagAccessor.class);

        MCLLookInfoReader rdr=Mockito.mock(MCLLookInfoReader.class);
        PowerMockito.whenNew(MCLLookInfoReader.class).withNoArguments().thenReturn(rdr);

        Mockito.when(accessor.getValue(AttributeRepNames.ANATOMY_INFO.getTagName())).thenReturn("ANATOMY_INFO");
        Mockito.when(accessor.getValue(AttributeRepNames.VIEW_INFO.getTagName())).thenReturn("VIEW_INFO");
        Mockito.when(accessor.getValue(AttributeRepNames.PATIENT_SIZE.getTagName())).thenReturn("PATIENT_SIZE");
        Mockito.when(rdr.getDefaultLook("ANATOMY_INFO","VIEW_INFO",core.MCLConstants.IMAGETYPEBONETAG,"All")).thenReturn("boneLook");
        Mockito.when(rdr.getDefaultLook("ANATOMY_INFO","VIEW_INFO",core.MCLConstants.IMAGETYPESOFTTISSUETAG,"All")).thenReturn("tissueLook");

        sysParamsBuilder.buildProcessingInfo(req, info);

        String origAnatomy=accessor.getValue(AttributeRepNames.ANATOMY_INFO.getTagName());
        assertEquals("ANATOMY_INFO",origAnatomy);

        String origView=accessor.getValue(AttributeRepNames.VIEW_INFO.getTagName());
        assertEquals("VIEW_INFO",origView);

        String origPatSize=accessor.getValue(AttributeRepNames.PATIENT_SIZE.getTagName());
        assertEquals("PATIENT_SIZE",origPatSize);

        PowerMockito.verifyPrivate(sysParamsBuilder).invoke("getMclPatientSize",origPatSize);//line 241

        String boneLook=rdr.getDefaultLook("ANATOMY_INFO","VIEW_INFO",core.MCLConstants.IMAGETYPEBONETAG,"All");
        assertEquals("boneLook",boneLook);

        String tissueLook=rdr.getDefaultLook("ANATOMY_INFO","VIEW_INFO",core.MCLConstants.IMAGETYPESOFTTISSUETAG,"All");
        assertEquals("tissueLook",tissueLook);

        Mockito.verify(iPSysParams).setProcessingLookBone(boneLook);//line 244
        Mockito.verify(iPSysParams).setProcessingLookTissue(tissueLook);

        // fill the Anatomy View accrodingly
        Mockito.verify(iPSysParams,Mockito.times(1)).setAnatomy(origAnatomy);
        Mockito.verify(iPSysParams).setView(origView);
        Mockito.verify(iPSysParams).setPatientSize(origPatSize);

    }
</code>```

stack trace

```<code>org.mockito.exceptions.misusing.UnfinishedVerificationException:
Missing method call for verify(mock) here:
-> at systemservice.test1.SysParamsBuilderTest.testBuildProcessingInfoIf3(SysParamsBuilderTest.java:241)

Example of correct verification:
    verify(mock).doSomething()

Also, this error might show up because you verify either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.

    at systemservice.test1.SysParamsBuilderTest.testBuildProcessingInfoIf3(SysParamsBuilderTest.java:244)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:66)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:310)
    at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:86)
    at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:94)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
    at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:84)
    at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
    at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
    at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
    at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:104)
    at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
    at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:53)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
</code>```

I have done other test cases in the same way and it has worked but I don't know why its not working here, also all the methods are public. please help me figure It out, Thanks in advance

答:
From the exception message the problem is this line:

```<code>PowerMockito.verifyPrivate(sysParamsBuilder).invoke("getMclPatientSize",origPatSize);//line 241
</code>```

Using google to search for powermockito verifyprivate not working I found the following page: https://groups.google.com/forum/#!topic/powermock/CEdP24sb_HY

In short, if you want to use PowerMockito to spy on your objects you must not do

```<code>    SysParamsBuilder sysParamsBuilder = Mockito.spy(new SysParamsBuilder(...));
</code>```

Instead you need to do

```<code>    SysParamsBuilder sysParamsBuilder = PowerMockito.spy(new SysParamsBuilder(...));
</code>```

Otherwise if you try to verify private method invocations using PowerMockito you will get the exception you are seeing.

Body:
I am facing

org.mockito.exceptions.misusing.UnfinishedVerificationException:
Missing method call for verify(mock) here:
-> at systemservice.test1.SysParamsBuilderTest.testBuildProcessingInfoIf3(SysParamsBuilderTest.java:241)

I have checked for all the parameters and the object as well that is being passed to verify, But not able to figure out what is causing the above exception

The condition I am trying to test,

if( request.getProcessType() == IPRequest.IPREQUEST_TYPE_DE )
{

     LookInfoIf rdr = new MCLLookInfoReader();

    String origAnatomy = accessor.getValue(AttributeRepNames.ANATOMY_INFO.getTagName());
    String origView = accessor.getValue(AttributeRepNames.VIEW_INFO.getTagName());
    String origPatSize = accessor.getValue(AttributeRepNames.PATIENT_SIZE.getTagName());
    String mclPatSize = getMclPatientSize(origPatSize);
    String boneLook = rdr.getDefaultLook(origAnatomy,origView,core.MCLConstants.IMAGETYPEBONETAG,mclPatSize);
    String tissueLook = rdr.getDefaultLook(origAnatomy,origView,core.MCLConstants.IMAGETYPESOFTTISSUETAG,mclPatSize);

    params.setProcessingLookBone(boneLook);
    params.setProcessingLookTissue(tissueLook);
        params.setAnatomy(origAnatomy);
        params.setView(origView);
        params.setPatientSize(origPatSize);

}

Test case

@Test
    public void testBuildProcessingInfoIf3() throws Exception
    {
        IPRequest req=new IPRequest(1);//value of IPRequest.IPREQUEST_TYPE_DE

        IPSysParams iPSysParams = Mockito.mock(IPSysParams.class);
        PowerMockito.whenNew(IPSysParams.class).withNoArguments().thenReturn(iPSysParams);

        TagAccessor accessor=Mockito.mock(TagAccessor.class);

        MCLLookInfoReader rdr=Mockito.mock(MCLLookInfoReader.class);
        PowerMockito.whenNew(MCLLookInfoReader.class).withNoArguments().thenReturn(rdr);

        Mockito.when(accessor.getValue(AttributeRepNames.ANATOMY_INFO.getTagName())).thenReturn("ANATOMY_INFO");
        Mockito.when(accessor.getValue(AttributeRepNames.VIEW_INFO.getTagName())).thenReturn("VIEW_INFO");
        Mockito.when(accessor.getValue(AttributeRepNames.PATIENT_SIZE.getTagName())).thenReturn("PATIENT_SIZE");
        Mockito.when(rdr.getDefaultLook("ANATOMY_INFO","VIEW_INFO",core.MCLConstants.IMAGETYPEBONETAG,"All")).thenReturn("boneLook");
        Mockito.when(rdr.getDefaultLook("ANATOMY_INFO","VIEW_INFO",core.MCLConstants.IMAGETYPESOFTTISSUETAG,"All")).thenReturn("tissueLook");

        sysParamsBuilder.buildProcessingInfo(req, info);

        String origAnatomy=accessor.getValue(AttributeRepNames.ANATOMY_INFO.getTagName());
        assertEquals("ANATOMY_INFO",origAnatomy);

        String origView=accessor.getValue(AttributeRepNames.VIEW_INFO.getTagName());
        assertEquals("VIEW_INFO",origView);

        String origPatSize=accessor.getValue(AttributeRepNames.PATIENT_SIZE.getTagName());
        assertEquals("PATIENT_SIZE",origPatSize);

        PowerMockito.verifyPrivate(sysParamsBuilder).invoke("getMclPatientSize",origPatSize);//line 241

        String boneLook=rdr.getDefaultLook("ANATOMY_INFO","VIEW_INFO",core.MCLConstants.IMAGETYPEBONETAG,"All");
        assertEquals("boneLook",boneLook);

        String tissueLook=rdr.getDefaultLook("ANATOMY_INFO","VIEW_INFO",core.MCLConstants.IMAGETYPESOFTTISSUETAG,"All");
        assertEquals("tissueLook",tissueLook);

        Mockito.verify(iPSysParams).setProcessingLookBone(boneLook);//line 244
        Mockito.verify(iPSysParams).setProcessingLookTissue(tissueLook);

        // fill the Anatomy View accrodingly
        Mockito.verify(iPSysParams,Mockito.times(1)).setAnatomy(origAnatomy);
        Mockito.verify(iPSysParams).setView(origView);
        Mockito.verify(iPSysParams).setPatientSize(origPatSize);

    }

stack trace

org.mockito.exceptions.misusing.UnfinishedVerificationException:
Missing method call for verify(mock) here:
-> at systemservice.test1.SysParamsBuilderTest.testBuildProcessingInfoIf3(SysParamsBuilderTest.java:241)

Example of correct verification:
    verify(mock).doSomething()

Also, this error might show up because you verify either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.

    at systemservice.test1.SysParamsBuilderTest.testBuildProcessingInfoIf3(SysParamsBuilderTest.java:244)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:66)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:310)
    at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:86)
    at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:94)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
    at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:84)
    at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
    at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
    at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
    at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:104)
    at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
    at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:53)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

I have done other test cases in the same way and it has worked but I don't know why its not working here, also all the methods are public. please help me figure It out, Thanks in advance

Body:
From the exception message the problem is this line:

PowerMockito.verifyPrivate(sysParamsBuilder).invoke("getMclPatientSize",origPatSize);//line 241

Using google to search for powermockito verifyprivate not working I found the following page: https://groups.google.com/forum/#!topic/powermock/CEdP24sb_HY

In short, if you want to use PowerMockito to spy on your objects you must not do

    SysParamsBuilder sysParamsBuilder = Mockito.spy(new SysParamsBuilder(...));

Instead you need to do

    SysParamsBuilder sysParamsBuilder = PowerMockito.spy(new SysParamsBuilder(...));

Otherwise if you try to verify private method invocations using PowerMockito you will get the exception you are seeing.


来源: stackexchange

问:
switch spring boot bean definitions by property and allow custom bean
Assume an interface Service {}. My platform provides two implementations of this interface:

FooService

BarService

What I want now is that the user can choose via yaml which service to use. In addition, if he'd rather use a CustomServicehe should be able to ignore both default implementations and provide his own bean.

Note: This is a starter project, so the user adds a dependency to my jar and should get either FooService, BarService or CustomService injected, depending on his yaml/configiguration.

Here's what I tried:

In @ConfigurationProperties I have a field String serviceType = "foo" (foo is the default)

In my AutoConfiguration, I provide both beans:

```<code> @EnableConfigurationProperties(MyProperties.class)
 public class MyAutoConfiguration  {
   @Bean
   @ConditionalOnMissingBean(Service.class) // only active if no custom present
   @ConditionalOnProperty(name="service-type", havingValue = "foo")
   public Service fooService() {
      return new FooService();
   }

   @Bean
   @ConditionalOnMissingBean(Service) // only active if no custom present
   @ConditionalOnProperty(name="service-type", havingValue = "bar")
   public Service barService() {
      return new BarService();
   }
}
</code>```

Creating a first simple test, I assumed to get FooService injected, but instead I got an ApplicationContext Exception because no bean is registered for the Service interface. In this test, I do not set any value for "service-type" in the yaml, I rely on the default "foo".

Where is my mistake? Can't I have ConditionalOnMissingBean on two beans? Is the default "foo" not considered when evaluating the  condition on property? Are there other ways to solve the general problem: Provide more than on default bean and still allow users to overwrite?

答:
The @ConditionalOnProperty is implemented by the OnPropertyCondition which looks in the Environment to check if a property exists. Adding property on in a @ConfigurationProperties annotated class isn't going to add that value to the properties. Hence the check still fails.

However the @ConditionalOnProperty als has a matchIfMissing attribute which you can set. The default value is false so if you set it to true for the value of foo it will match if the value hasn't been explicitly set.

```<code>@ConditionalOnProperty(name="service-type",
                       havingValue = "foo",
                       matchIfMissing=true)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Assume an interface Service {}. My platform provides two implementations of this interface:

FooService

BarService

What I want now is that the user can choose via yaml which service to use. In addition, if he'd rather use a CustomServicehe should be able to ignore both default implementations and provide his own bean.

Note: This is a starter project, so the user adds a dependency to my jar and should get either FooService, BarService or CustomService injected, depending on his yaml/configiguration.

Here's what I tried:

In @ConfigurationProperties I have a field String serviceType = "foo" (foo is the default)

In my AutoConfiguration, I provide both beans:

 @EnableConfigurationProperties(MyProperties.class)
 public class MyAutoConfiguration  {
   @Bean
   @ConditionalOnMissingBean(Service.class) // only active if no custom present
   @ConditionalOnProperty(name="service-type", havingValue = "foo")
   public Service fooService() {
      return new FooService();
   }

   @Bean
   @ConditionalOnMissingBean(Service) // only active if no custom present
   @ConditionalOnProperty(name="service-type", havingValue = "bar")
   public Service barService() {
      return new BarService();
   }
}

Creating a first simple test, I assumed to get FooService injected, but instead I got an ApplicationContext Exception because no bean is registered for the Service interface. In this test, I do not set any value for "service-type" in the yaml, I rely on the default "foo".

Where is my mistake? Can't I have ConditionalOnMissingBean on two beans? Is the default "foo" not considered when evaluating the  condition on property? Are there other ways to solve the general problem: Provide more than on default bean and still allow users to overwrite?

Body:
The @ConditionalOnProperty is implemented by the OnPropertyCondition which looks in the Environment to check if a property exists. Adding property on in a @ConfigurationProperties annotated class isn't going to add that value to the properties. Hence the check still fails.

However the @ConditionalOnProperty als has a matchIfMissing attribute which you can set. The default value is false so if you set it to true for the value of foo it will match if the value hasn't been explicitly set.

@ConditionalOnProperty(name="service-type",
                       havingValue = "foo",
                       matchIfMissing=true)


问:
use variables to define counters in nested for loop
I'm new to bash scripting.
I'm trying to use variables for counters in a nested for loop, like this:

```<code>dir_count=$(find dump_${d}/* -maxdepth 0 -type d | wc -l)
count_by=11

for ((i=0;i<=$dir_count;i+=$count_by))
do
    ((start=$i+1))
    ((end=$count_by+$i))
    echo  $start $end
    for dir in {$start..$end}
        echo $dir
    done
done
</code>```

Output is this (I'm getting errors):

```<code>1 11
./loopy.sh: line 23: [: {1..11}: integer expression expected
12 22
./loopy.sh: line 23: [: {12..22}: integer expression expected
23 33
./loopy.sh: line 23: [: {23..33}: integer expression expected
</code>```

1, 11, 12, 22, 23, 33 all look like integers to me! Is it possible to type variables? I thought it wasn't.

Thanks!

答:
In bash, brace-expansion will happen much before variable-expansion, so your code

```<code>for dir in {$start..$end}
</code>```

will never do what it is supposed to do; use a proper loop in bash with a C-style for-loop as

```<code>for ((dir=start; dir<=end; dir++)); do
    echo "$dir"
done
</code>```

Quoting from the man bash page,

[..] Brace expansion is performed before any other expansions, and any characters special to other expansions are preserved in the result.  It is strictly  textual [..]

Body:
I'm new to bash scripting.
I'm trying to use variables for counters in a nested for loop, like this:

dir_count=$(find dump_${d}/* -maxdepth 0 -type d | wc -l)
count_by=11

for ((i=0;i<=$dir_count;i+=$count_by))
do
    ((start=$i+1))
    ((end=$count_by+$i))
    echo  $start $end
    for dir in {$start..$end}
        echo $dir
    done
done

Output is this (I'm getting errors):

1 11
./loopy.sh: line 23: [: {1..11}: integer expression expected
12 22
./loopy.sh: line 23: [: {12..22}: integer expression expected
23 33
./loopy.sh: line 23: [: {23..33}: integer expression expected

1, 11, 12, 22, 23, 33 all look like integers to me! Is it possible to type variables? I thought it wasn't.

Thanks!

Body:
In bash, brace-expansion will happen much before variable-expansion, so your code

for dir in {$start..$end}

will never do what it is supposed to do; use a proper loop in bash with a C-style for-loop as

for ((dir=start; dir<=end; dir++)); do
    echo "$dir"
done

Quoting from the man bash page,

[..] Brace expansion is performed before any other expansions, and any characters special to other expansions are preserved in the result.  It is strictly  textual [..]


问:
C memory leak that i can't find at all
So everything is fine with the program but i get a very annoying memory leak. I am sitting in front of my computer for couple hours and can figure it out.

We have 2 struck very simple, one struct is a double linked list and one is a hash table that stores that double linked list.

Now i am inserting a key and a data into the double linked list here is the function.

```<code>void htable_insert(htable* ht, int key, int data) {
    // TODO: Insert a new entry with the given key and data
    // Overwrite the old data if the key already exists, duplicate keys are not allowed
    ht_entry *new_node;
    ht_entry *head;
    ht_entry *it;
    int sameKey;
    int bucketPosition;

    new_node = (ht_entry*)malloc(1*sizeof(ht_entry));
    bucketPosition = key % ht->size;
    sameKey = 0;

    for(it = ht->entries[bucketPosition]; it != NULL; it = it->next)
    {
      if(it->key == key) {
        it->data = data;
        sameKey = 1;
        free(new_node);
        new_node = NULL;
        break;

      }
    }

    if(!sameKey && new_node) {
      head = ht->entries[bucketPosition];
      if (head == NULL) {
        new_node->key = key;
        new_node->data = data;
        new_node->next = head;
        new_node->prev = NULL;
        ht->entries[bucketPosition] = new_node;
        new_node = NULL;

      } else {
        new_node->key = key;
        new_node->data = data;
        new_node->next = head;
        // new_node->prev = head;
        head->prev = new_node;
        head = new_node;
        ht->entries[bucketPosition] = head;

      }
    }
    // free(new_node);
    new_node = NULL;
    printf("%s\n %d", "INSERT:", key);
    for(it = ht->entries[bucketPosition]; it != NULL; it = it->next){
      printf("it->key: %d\nit->data: %d\n", it->key, it->data);
    }

    printf("%s\n", "-------------------------------");

}
</code>```

Here is my valgrind message:

```<code>==10692== Memcheck, a memory error detector
==10692== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==10692== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==10692== Command: ./chain_hash_table.out
==10692==
==10692==
==10692== HEAP SUMMARY:
==10692==     in use at exit: 72 bytes in 3 blocks
==10692==   total heap usage: 10 allocs, 7 frees, 376 bytes allocated
==10692==
==10692== 24 bytes in 1 blocks are definitely lost in loss record 2 of 3
==10692==    at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==10692==    by 0x4007EE: htable_insert (htable.c:53)
==10692==    by 0x400BD2: main (main.c:14)
==10692==
==10692== 48 (24 direct, 24 indirect) bytes in 1 blocks are definitely lost in loss record 3 of 3
==10692==    at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==10692==    by 0x4007EE: htable_insert (htable.c:53)
==10692==    by 0x400C25: main (main.c:18)
==10692==
==10692== LEAK SUMMARY:
==10692==    definitely lost: 48 bytes in 2 blocks
==10692==    indirectly lost: 24 bytes in 1 blocks
==10692==      possibly lost: 0 bytes in 0 blocks
==10692==    still reachable: 0 bytes in 0 blocks
==10692==         suppressed: 0 bytes in 0 blocks
==10692==
==10692== For counts of detected and suppressed errors, rerun with: -v
==10692== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
</code>```

And what i know it is always for first table insertion that is why it says at line main(18) for the rest after the first insertion there is no leaks.

Thank you guys for your time and help :)

答:
If you are mallocing space in a C program, unless you free everything at the end, you will end up with memory leaks.

For your current program, I'm assuming that you don't free correctly in the end. So the problem isn't within the htable_insert function, but rather within your freeing/cleanup functions.

If you free your linked list nodes in your htable_insert, you will not be able to access them in the rest of your program and you'll run into segfaults.

Title: C memory leak that i can't find at all

Body:
So everything is fine with the program but i get a very annoying memory leak. I am sitting in front of my computer for couple hours and can figure it out.

We have 2 struck very simple, one struct is a double linked list and one is a hash table that stores that double linked list.

Now i am inserting a key and a data into the double linked list here is the function.

void htable_insert(htable* ht, int key, int data) {
    // TODO: Insert a new entry with the given key and data
    // Overwrite the old data if the key already exists, duplicate keys are not allowed
    ht_entry *new_node;
    ht_entry *head;
    ht_entry *it;
    int sameKey;
    int bucketPosition;

    new_node = (ht_entry*)malloc(1*sizeof(ht_entry));
    bucketPosition = key % ht->size;
    sameKey = 0;

    for(it = ht->entries[bucketPosition]; it != NULL; it = it->next)
    {
      if(it->key == key) {
        it->data = data;
        sameKey = 1;
        free(new_node);
        new_node = NULL;
        break;

      }
    }

    if(!sameKey && new_node) {
      head = ht->entries[bucketPosition];
      if (head == NULL) {
        new_node->key = key;
        new_node->data = data;
        new_node->next = head;
        new_node->prev = NULL;
        ht->entries[bucketPosition] = new_node;
        new_node = NULL;

      } else {
        new_node->key = key;
        new_node->data = data;
        new_node->next = head;
        // new_node->prev = head;
        head->prev = new_node;
        head = new_node;
        ht->entries[bucketPosition] = head;

      }
    }
    // free(new_node);
    new_node = NULL;
    printf("%s\n %d", "INSERT:", key);
    for(it = ht->entries[bucketPosition]; it != NULL; it = it->next){
      printf("it->key: %d\nit->data: %d\n", it->key, it->data);
    }

    printf("%s\n", "-------------------------------");

}

Here is my valgrind message:

==10692== Memcheck, a memory error detector
==10692== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==10692== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==10692== Command: ./chain_hash_table.out
==10692==
==10692==
==10692== HEAP SUMMARY:
==10692==     in use at exit: 72 bytes in 3 blocks
==10692==   total heap usage: 10 allocs, 7 frees, 376 bytes allocated
==10692==
==10692== 24 bytes in 1 blocks are definitely lost in loss record 2 of 3
==10692==    at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==10692==    by 0x4007EE: htable_insert (htable.c:53)
==10692==    by 0x400BD2: main (main.c:14)
==10692==
==10692== 48 (24 direct, 24 indirect) bytes in 1 blocks are definitely lost in loss record 3 of 3
==10692==    at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==10692==    by 0x4007EE: htable_insert (htable.c:53)
==10692==    by 0x400C25: main (main.c:18)
==10692==
==10692== LEAK SUMMARY:
==10692==    definitely lost: 48 bytes in 2 blocks
==10692==    indirectly lost: 24 bytes in 1 blocks
==10692==      possibly lost: 0 bytes in 0 blocks
==10692==    still reachable: 0 bytes in 0 blocks
==10692==         suppressed: 0 bytes in 0 blocks
==10692==
==10692== For counts of detected and suppressed errors, rerun with: -v
==10692== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)

And what i know it is always for first table insertion that is why it says at line main(18) for the rest after the first insertion there is no leaks.

Thank you guys for your time and help :)


问:
Selenium: Parent window closes once child window is open
I have a scenario and facing problem switching to child window

Scenario:
1. Login Page: Enter user id and password
2. Click on submit button
3. System opens a new full size window (without toolbar or URL bar) and the entire application runs in it
4. As soon as the above child window is opened the parent window (Login Page) is closed

答:
You can use

```<code>for handle in driver.window_handles:
   driver.switch_to_window(handle)
</code>```

or you can use function

```<code>driver.switch_to_window("windowName")
</code>```

You can also check http://selenium-python.readthedocs.io/navigating.html for more information about navigating pages with python selenium webdriver.

Note that I have assumed you are using python, if you are using java reference here https://sqa.stackexchange.com/questions/3986/how-can-i-switch-to-new-window-using-webdriver

Body:
You can use

for handle in driver.window_handles:
   driver.switch_to_window(handle)

or you can use function

driver.switch_to_window("windowName")

You can also check http://selenium-python.readthedocs.io/navigating.html for more information about navigating pages with python selenium webdriver.

Note that I have assumed you are using python, if you are using java reference here https://sqa.stackexchange.com/questions/3986/how-can-i-switch-to-new-window-using-webdriver


问:
Kafka Streams: Handle Aging of events in a stream on window expiry
I'm currently using kafka streams to collate related events within a window. In case if all the related events don't arrive within a window, is there a way in Kafka streams where we get a handle to the events that are expired. This would assist in handling/ notifying the downstream application that all the related events didn't arrive for collation. Appreciate your response.

Below are the examples

Example-1:

 - GroupID: g1

 - Events arrival: E1,10am; E2 10:01am and E3 10:02am

 - Window: Session Window of inactivity duration of 5 mins.

 - Result: All the events are collated successfully.

Example-2:

 - Events arrival: E1,10am; E2 10:01am and E3 don't arrive

 - Window: Session Window of inactivity duration of 5 mins.

 - Result: Trigger an action OR get notified via a listener for partial
   collation upon window expiry for E1 and E2 at 10:06 am

答:
Windows in Kafka Streams "don't expire" but are kept open to allow the handling of late arriving data.

Compare How to send final kafka-streams aggregation result of a time windowed KTable?

It's not possible to register any call-back,

not for the case that "stream time" advances and passed "window end time"

not for the case that a window if finally dropped (ie, after retention period did pass)


问:
Kendo Grid Culture specific date format
I am creating a simple kendo grid something like this -

```<code> $("#grid").kendoGrid({
                    dataSource: {
                        type: "odata",
                        transport: {
                            read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Orders"
                        },
                        schema: {
                            model: {
                                fields: {
                                    OrderID: { type: "number" },
                                    Freight: { type: "number" },
                                    ShipName: { type: "string" },
                                    OrderDate: { type: "date" },
                                    ShipCity: { type: "string" }
                                }
                            }
                        },
                        pageSize: 20,
                        serverPaging: true,
                        serverFiltering: true,
                        serverSorting: true
                    },
                    height: 550,
                    filterable: true,
                    sortable: true,
                    pageable: true,
                    columns: [{
                            field:"OrderID",
                            filterable: false
                        },
                        "Freight",
                        {
                            field: "OrderDate",
                            title: "Order Date",
                            format: "{0:MM/dd/yyyy}"
                        }, {
                            field: "ShipName",
                            title: "Ship Name"
                        }, {
                            field: "ShipCity",
                            title: "Ship City"
                        }
                    ]
                });
</code>```

My problem is format: "{0:MM/dd/yyyy}".

I don't want to hardcode the format, I want it to be culture specific.
My web application => web.config has culture information set. I also tried kendo.culture("some culture code") but it didn't work.

If I remove format it shows me big date string like this, Please help?

screen shot

答:
You can try using the following libraries. They have both Jquery and non Jquery options
https://github.com/phstc/jquery-dateFormat

They have worked well with me for Kendo widgets, but I have not fully tested for culture specific context.

Title: Kendo Grid Culture specific date format

Body:
I am creating a simple kendo grid something like this -

 $("#grid").kendoGrid({
                    dataSource: {
                        type: "odata",
                        transport: {
                            read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Orders"
                        },
                        schema: {
                            model: {
                                fields: {
                                    OrderID: { type: "number" },
                                    Freight: { type: "number" },
                                    ShipName: { type: "string" },
                                    OrderDate: { type: "date" },
                                    ShipCity: { type: "string" }
                                }
                            }
                        },
                        pageSize: 20,
                        serverPaging: true,
                        serverFiltering: true,
                        serverSorting: true
                    },
                    height: 550,
                    filterable: true,
                    sortable: true,
                    pageable: true,
                    columns: [{
                            field:"OrderID",
                            filterable: false
                        },
                        "Freight",
                        {
                            field: "OrderDate",
                            title: "Order Date",
                            format: "{0:MM/dd/yyyy}"
                        }, {
                            field: "ShipName",
                            title: "Ship Name"
                        }, {
                            field: "ShipCity",
                            title: "Ship City"
                        }
                    ]
                });

My problem is format: "{0:MM/dd/yyyy}".

I don't want to hardcode the format, I want it to be culture specific.
My web application => web.config has culture information set. I also tried kendo.culture("some culture code") but it didn't work.

If I remove format it shows me big date string like this, Please help?

screen shot


问:
How to deploy a database file with a Xamarin.from app?
I created a sqlite file in my project with some data in it, but I don't know how to link it to my app. I expect the data could be loaded on a Android simulator.

I found a tutorial which was published in 2015, it works no longer, such as GetLocalFilePath function cannot be found after new a FileAccessHelper Class. And the tutorial project seemed using an olde version of SQLite.net-PCL package, because SQLite.Net.Platform.XamarinAndroid was used in the tutorial project, while this package is no longer exist. Any ideas?

http://arteksoftware.com/deploying-a-database-file-with-a-xamarin-forms-app/

This is the code from the tutorial:

```<code>[Activity (Label = "People", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);
        global::Xamarin.Forms.Forms.Init (this, bundle);

        string dbPath = FileAccessHelper.GetLocalFilePath ("people.db3");

        LoadApplication (new People.App (dbPath, new SQLitePlatformAndroid ()));
    }
}
</code>```

FileAccessHelper.cs

```<code>public class FileAccessHelper
{
    public static string GetLocalFilePath (string filename)
    {
        string path = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
        string dbPath = Path.Combine (path, filename);

        CopyDatabaseIfNotExists (dbPath);

        return dbPath;
    }

    private static void CopyDatabaseIfNotExists (string dbPath)
    {
        if (!File.Exists (dbPath)) {
            using (var br = new BinaryReader (Application.Context.Assets.Open ("people.db3"))) {
                using (var bw = new BinaryWriter (new FileStream (dbPath, FileMode.Create))) {
                    byte[] buffer = new byte[2048];
                    int length = 0;
                    while ((length = br.Read (buffer, 0, buffer.Length)) > 0) {
                        bw.Write (buffer, 0, length);
                    }
                }
            }
        }
    }
}
</code>```

答:
You will need to implement an Interface for each platform if you are wanting to call the method from Xamarin.Forms but I will not go into detail on how all that works in this example. Here are the Xamarin docs on the topic of the DependencyService used below.

For Android you will need to place the DB file in the Assets folder. This is the code you will need in your Android project for the interface that copies the DB and return its path:

```<code>[assembly: Xamarin.Forms.Dependency(typeof(FileAccessHelper))]
namespace MyNamespace.Droid
{
    class FileAccessHelper : MyXamarinFormsPage.IFileAccessHelper
    {
        public async Task<String> GetDBPathAndCreateIfNotExists()
        {
            String databaseName = "MyLite.db";
            var docFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            var dbFile = Path.Combine(docFolder, databaseName); // FILE NAME TO USE WHEN COPIED
            if (!File.Exists(dbFile))
            {
                FileStream writeStream = new FileStream(dbFile, FileMode.OpenOrCreate, FileAccess.Write);
                await Forms.Context.Assets.Open(databaseName).CopyToAsync(writeStream);
            }
            return dbFile;
        }
    }
}
</code>```

For UWP you will want to place the DB file in the root folder. The interface in your UWP project that copies the file and returns the path should look like this:

```<code>[assembly: Xamarin.Forms.Dependency(typeof(FileAccessHelper))]
namespace MyNamespace.UWP
{
    public class FileAccessHelper : MyXamarinFormsPage.IFileAccessHelper
    {
        public async Task<String> GetDBPathAndCreateIfNotExists()
        {
            String filename = "MyLite.db";
            bool isExisting = false;
            try
            {
                StorageFile storage = await ApplicationData.Current.LocalFolder.GetFileAsync(filename);
                isExisting = true;
            }
            catch (Exception)
            {
                isExisting = false;
            }
            if (!isExisting)
            {
                StorageFile databaseFile = await Package.Current.InstalledLocation.GetFileAsync(filename);
                await databaseFile.CopyAsync(ApplicationData.Current.LocalFolder, filename, NameCollisionOption.ReplaceExisting);
            }
            return Path.Combine(ApplicationData.Current.LocalFolder.Path, filename);
        }
    }
}
</code>```

For iOS you will want to place the DB file in your Resources folder. Then this is the code in your iOS project for the interface:

```<code>[assembly: Xamarin.Forms.Dependency(typeof(FileAccessHelper))]
namespace MyNamespace.iOS
{
    public class FileAccessHelper : MyXamarinFormsPage.IFileAccessHelper
    {
        public async Task<String> GetDBPathAndCreateIfNotExists()
        {
            String databaseName = "MyLite.db";
            var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            var path = Path.Combine(documentsPath, databaseName);
            if (!File.Exists(path))
            {
                var existingDb = NSBundle.MainBundle.PathForResource("MyLite", "db");
                File.Copy(existingDb, path);
            }
            return path;
        }
    }
}
</code>```

It can then be called from your Xamrin.Forms project by doing this:

```<code>public class MyXamarinFormsPage
{
    public MyXamarinFormsPage()
    {
        String DBPath = await DependencyService.Get<IFileAccessHelper>().GetDBPathAndCreateIfNotExists()
        //Store string for path
    }

    public interface IFileAccessHelper
    {
        Task<String> GetDBPathAndCreateIfNotExists();
    }
}
</code>```

Body:
I created a sqlite file in my project with some data in it, but I don't know how to link it to my app. I expect the data could be loaded on a Android simulator.

I found a tutorial which was published in 2015, it works no longer, such as GetLocalFilePath function cannot be found after new a FileAccessHelper Class. And the tutorial project seemed using an olde version of SQLite.net-PCL package, because SQLite.Net.Platform.XamarinAndroid was used in the tutorial project, while this package is no longer exist. Any ideas?

http://arteksoftware.com/deploying-a-database-file-with-a-xamarin-forms-app/

This is the code from the tutorial:

[Activity (Label = "People", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);
        global::Xamarin.Forms.Forms.Init (this, bundle);

        string dbPath = FileAccessHelper.GetLocalFilePath ("people.db3");

        LoadApplication (new People.App (dbPath, new SQLitePlatformAndroid ()));
    }
}

FileAccessHelper.cs

public class FileAccessHelper
{
    public static string GetLocalFilePath (string filename)
    {
        string path = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
        string dbPath = Path.Combine (path, filename);

        CopyDatabaseIfNotExists (dbPath);

        return dbPath;
    }

    private static void CopyDatabaseIfNotExists (string dbPath)
    {
        if (!File.Exists (dbPath)) {
            using (var br = new BinaryReader (Application.Context.Assets.Open ("people.db3"))) {
                using (var bw = new BinaryWriter (new FileStream (dbPath, FileMode.Create))) {
                    byte[] buffer = new byte[2048];
                    int length = 0;
                    while ((length = br.Read (buffer, 0, buffer.Length)) > 0) {
                        bw.Write (buffer, 0, length);
                    }
                }
            }
        }
    }
}

Body:
You will need to implement an Interface for each platform if you are wanting to call the method from Xamarin.Forms but I will not go into detail on how all that works in this example. Here are the Xamarin docs on the topic of the DependencyService used below.

For Android you will need to place the DB file in the Assets folder. This is the code you will need in your Android project for the interface that copies the DB and return its path:

[assembly: Xamarin.Forms.Dependency(typeof(FileAccessHelper))]
namespace MyNamespace.Droid
{
    class FileAccessHelper : MyXamarinFormsPage.IFileAccessHelper
    {
        public async Task<String> GetDBPathAndCreateIfNotExists()
        {
            String databaseName = "MyLite.db";
            var docFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            var dbFile = Path.Combine(docFolder, databaseName); // FILE NAME TO USE WHEN COPIED
            if (!File.Exists(dbFile))
            {
                FileStream writeStream = new FileStream(dbFile, FileMode.OpenOrCreate, FileAccess.Write);
                await Forms.Context.Assets.Open(databaseName).CopyToAsync(writeStream);
            }
            return dbFile;
        }
    }
}

For UWP you will want to place the DB file in the root folder. The interface in your UWP project that copies the file and returns the path should look like this:

[assembly: Xamarin.Forms.Dependency(typeof(FileAccessHelper))]
namespace MyNamespace.UWP
{
    public class FileAccessHelper : MyXamarinFormsPage.IFileAccessHelper
    {
        public async Task<String> GetDBPathAndCreateIfNotExists()
        {
            String filename = "MyLite.db";
            bool isExisting = false;
            try
            {
                StorageFile storage = await ApplicationData.Current.LocalFolder.GetFileAsync(filename);
                isExisting = true;
            }
            catch (Exception)
            {
                isExisting = false;
            }
            if (!isExisting)
            {
                StorageFile databaseFile = await Package.Current.InstalledLocation.GetFileAsync(filename);
                await databaseFile.CopyAsync(ApplicationData.Current.LocalFolder, filename, NameCollisionOption.ReplaceExisting);
            }
            return Path.Combine(ApplicationData.Current.LocalFolder.Path, filename);
        }
    }
}

For iOS you will want to place the DB file in your Resources folder. Then this is the code in your iOS project for the interface:

[assembly: Xamarin.Forms.Dependency(typeof(FileAccessHelper))]
namespace MyNamespace.iOS
{
    public class FileAccessHelper : MyXamarinFormsPage.IFileAccessHelper
    {
        public async Task<String> GetDBPathAndCreateIfNotExists()
        {
            String databaseName = "MyLite.db";
            var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            var path = Path.Combine(documentsPath, databaseName);
            if (!File.Exists(path))
            {
                var existingDb = NSBundle.MainBundle.PathForResource("MyLite", "db");
                File.Copy(existingDb, path);
            }
            return path;
        }
    }
}

It can then be called from your Xamrin.Forms project by doing this:

public class MyXamarinFormsPage
{
    public MyXamarinFormsPage()
    {
        String DBPath = await DependencyService.Get<IFileAccessHelper>().GetDBPathAndCreateIfNotExists()
        //Store string for path
    }

    public interface IFileAccessHelper
    {
        Task<String> GetDBPathAndCreateIfNotExists();
    }
}

ContentLicense: CC BY-SA 4.0


问:
Remove empty elements from list with character(0)
How can I remove empty elements from a list that contain zero length pairlist as
character(0), integer(0) etc...

```<code>list2
# $`hsa:7476`
# [1] "1","2","3"
#
# $`hsa:656`
# character(0)
#
# $`hsa:7475`
# character(0)
#
# $`hsa:7472`
# character(0)
</code>```

I don't know how to deal with them. I mean if NULL it is much simpler. How can I remove these elements such that just hsa:7476 remains in the list.

答:
For the sake of completeness, the purrr package from the popular tidyverse has some useful functions for working with lists - compact (introduction) does the trick, too, and works fine with magrittr's %>% pipes:

```<code>l <- list(1:3, "foo", character(0), integer(0))
library(purrr)
compact(l)
# [[1]]
# [1] 1 2 3
#
# [[2]]
# [1] "foo"
</code>```

or

```<code>list(1:3, "foo", character(0), integer(0)) %>% compact
</code>```

Body:
How can I remove empty elements from a list that contain zero length pairlist as
character(0), integer(0) etc...

list2
# $`hsa:7476`
# [1] "1","2","3"
#
# $`hsa:656`
# character(0)
#
# $`hsa:7475`
# character(0)
#
# $`hsa:7472`
# character(0)

I don't know how to deal with them. I mean if NULL it is much simpler. How can I remove these elements such that just hsa:7476 remains in the list.

Body:
For the sake of completeness, the purrr package from the popular tidyverse has some useful functions for working with lists - compact (introduction) does the trick, too, and works fine with magrittr's %>% pipes:

l <- list(1:3, "foo", character(0), integer(0))
library(purrr)
compact(l)
# [[1]]
# [1] 1 2 3
#
# [[2]]
# [1] "foo"

or

list(1:3, "foo", character(0), integer(0)) %>% compact


问:
Setting Corner Radius on UIImageView not working
I'm at a bit of a loss. I've used the layer property of UIView to round the corners of multiple elements in my app. However, this one UIImageView is simply not complying. Not sure what I am missing.

The UIImageView (called previewImage) is contained in a Table View Cell. I've tried setting the cornerRadius property multiple location (in the cell itself and in the controller that creates the cell) to no avail.

```<code>static NSString *CellIdentifier = @"MyTableViewCell";

MyTableViewCell *cell = (MyTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil];
    cell = [topLevelObjects objectAtIndex:0];
    cell.previewImage.layer.cornerRadius = 20; //Made it 20 to make sure it's obvious.
}
</code>```

Is there something about the way cells are loaded that I'm missing?

答:
You need to set the layer's masksToBounds property to YES:

cell.previewImage.layer.masksToBounds = YES;

This is because the UIImageView control creates a pseudo-subview to hold the UIImage object.

ContentLicense: CC BY-SA 2.5

Body:
I'm at a bit of a loss. I've used the layer property of UIView to round the corners of multiple elements in my app. However, this one UIImageView is simply not complying. Not sure what I am missing.

The UIImageView (called previewImage) is contained in a Table View Cell. I've tried setting the cornerRadius property multiple location (in the cell itself and in the controller that creates the cell) to no avail.

static NSString *CellIdentifier = @"MyTableViewCell";

MyTableViewCell *cell = (MyTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil];
    cell = [topLevelObjects objectAtIndex:0];
    cell.previewImage.layer.cornerRadius = 20; //Made it 20 to make sure it's obvious.
}

Is there something about the way cells are loaded that I'm missing?


问:
Why is this clone needed?
I'm learning Rust and creating a very simple application using Rust and Gtk:

```<code>extern crate gtk;

use gtk::prelude::*;
use gtk::{Window, WindowType, TextView, TextBuffer, timeout_add_seconds};

fn make_window() {
    let window = Window::new(WindowType::Toplevel);

    let textview = TextView::new();
    window.add(&textview);

    let buffer = match textview.get_buffer() {
        Some(x) => x,
        None => panic!("Textview did not contain a buffer."),
    };

    buffer.connect_changed(move |buffer: &TextBuffer| {
        let b = buffer.clone(); // Why is this clone needed?
        timeout_add_seconds(1, move || {
            let ref buffer = b;
            Continue(false)
        });
    });
    window.show_all();
}

fn main() {
    if gtk::init().is_err() {
        println!("Failed to initialize GTK.");
        return;
    }

    make_window();
    gtk::main();
}
</code>```

I am confused why that buffer.clone() is needed right before the inner closure.

If I leave it out, I get an error about lifetimes. But as far as I know, with or without clone, both have the same lifetime. So why does one work and one doesn't?

error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
  --> src/main.rs:18:17
   |
18 |         let b = buffer; // Why is this clone needed?
   |                 ^^^^^^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the body at 17:54...
  --> src/main.rs:17:55
   |
17 |       buffer.connect_changed(move |buffer: &TextBuffer| {
   |  _______________________________________________________^ starting here...
18 | |         let b = buffer; // Why is this clone needed?
19 | |         timeout_add_seconds(1, move || {
20 | |             let ref buffer = b;
21 | |             Continue(false)
22 | |         });
23 | |     });
   | |_____^ ...ending here
note: ...so that expression is assignable (expected &gtk::TextBuffer, found &gtk::TextBuffer)
  --> src/main.rs:18:17
   |
18 |         let b = buffer; // Why is this clone needed?
   |                 ^^^^^^
   = note: but, the lifetime must be valid for the static lifetime...
note: ...so that the type `[closure@src/main.rs:19:32: 22:10 b:&gtk::TextBuffer]` will meet its required lifetime bounds
  --> src/main.rs:19:9
   |
19 |         timeout_add_seconds(1, move || {
   |         ^^^^^^^^^^^^^^^^^^^
```

答:
But as far as I know, with or without clone, both have the same lifetime.

This is not quite true. If you clone a variable, you now have two versions of the variable. Each can be owned by a different owner and thus both can have a different lifetime. That's exactly what's happening in your case, it's just a bit hidden -- thanks to closure magic.

Let's look at your code again (I changed a few variable names to refer to them unambiguously later):

```<code>buffer_a.connect_changed(move |buffer_b: &TextBuffer| {
    let b = buffer_b.clone(); // Why is this clone needed?
    timeout_add_seconds(1, move || {
        let ref buffer_c = b;
        Continue(false)
    });
});
</code>```

Here, the variable b is created by cloning and first lives in the outer closure (it's a local variable there). But then it is used inside the inner closure which is a move closure. As such, b is moved into the inner closure which then owns the TextBuffer. Yes: the inner closure owns the buffer b. This means that b lives exactly as long as the closure does; independent from the original lifetime!

To make sure we understood everything, just check the types of various variables:

buffer_a: type TextBuffer

buffer_b: type &TextBuffer (probably borrowed from buffer_a)

b: type TextBuffer again (we cloned buffer_b, with the clone() signature of clone(&T) -> T)

buffer_c: &TextBuffer again (borrowed from b)

This is further mystified by the let ref buffer = b; line. It's more idiomatic to write let buffer = &b; (both versions do the same thing).

And why exactly does Rust complain if we don't clone? The inner closure is required (by timeout_add_seconds()) to be 'static (more formally: "to meet the 'static requirement). This means the closure can't reference anything that doesn't live forever ('static). If we don't clone, the inner closure would reference buffer_a which doesn't live forever.

Title: Why is this clone needed?

Body:
I'm learning Rust and creating a very simple application using Rust and Gtk:

extern crate gtk;

use gtk::prelude::*;
use gtk::{Window, WindowType, TextView, TextBuffer, timeout_add_seconds};

fn make_window() {
    let window = Window::new(WindowType::Toplevel);

    let textview = TextView::new();
    window.add(&textview);

    let buffer = match textview.get_buffer() {
        Some(x) => x,
        None => panic!("Textview did not contain a buffer."),
    };

    buffer.connect_changed(move |buffer: &TextBuffer| {
        let b = buffer.clone(); // Why is this clone needed?
        timeout_add_seconds(1, move || {
            let ref buffer = b;
            Continue(false)
        });
    });
    window.show_all();
}

fn main() {
    if gtk::init().is_err() {
        println!("Failed to initialize GTK.");
        return;
    }

    make_window();
    gtk::main();
}

I am confused why that buffer.clone() is needed right before the inner closure.

If I leave it out, I get an error about lifetimes. But as far as I know, with or without clone, both have the same lifetime. So why does one work and one doesn't?

error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
  --> src/main.rs:18:17
   |
18 |         let b = buffer; // Why is this clone needed?
   |                 ^^^^^^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the body at 17:54...
  --> src/main.rs:17:55
   |
17 |       buffer.connect_changed(move |buffer: &TextBuffer| {
   |  _______________________________________________________^ starting here...
18 | |         let b = buffer; // Why is this clone needed?
19 | |         timeout_add_seconds(1, move || {
20 | |             let ref buffer = b;
21 | |             Continue(false)
22 | |         });
23 | |     });
   | |_____^ ...ending here
note: ...so that expression is assignable (expected &gtk::TextBuffer, found &gtk::TextBuffer)
  --> src/main.rs:18:17
   |
18 |         let b = buffer; // Why is this clone needed?
   |                 ^^^^^^
   = note: but, the lifetime must be valid for the static lifetime...
note: ...so that the type `[closure@src/main.rs:19:32: 22:10 b:&gtk::TextBuffer]` will meet its required lifetime bounds
  --> src/main.rs:19:9
   |
19 |         timeout_add_seconds(1, move || {
   |         ^^^^^^^^^^^^^^^^^^^

Body:
But as far as I know, with or without clone, both have the same lifetime.

This is not quite true. If you clone a variable, you now have two versions of the variable. Each can be owned by a different owner and thus both can have a different lifetime. That's exactly what's happening in your case, it's just a bit hidden -- thanks to closure magic.

Let's look at your code again (I changed a few variable names to refer to them unambiguously later):

buffer_a.connect_changed(move |buffer_b: &TextBuffer| {
    let b = buffer_b.clone(); // Why is this clone needed?
    timeout_add_seconds(1, move || {
        let ref buffer_c = b;
        Continue(false)
    });
});

Here, the variable b is created by cloning and first lives in the outer closure (it's a local variable there). But then it is used inside the inner closure which is a move closure. As such, b is moved into the inner closure which then owns the TextBuffer. Yes: the inner closure owns the buffer b. This means that b lives exactly as long as the closure does; independent from the original lifetime!

To make sure we understood everything, just check the types of various variables:

buffer_a: type TextBuffer

buffer_b: type &TextBuffer (probably borrowed from buffer_a)

b: type TextBuffer again (we cloned buffer_b, with the clone() signature of clone(&T) -> T)

buffer_c: &TextBuffer again (borrowed from b)

This is further mystified by the let ref buffer = b; line. It's more idiomatic to write let buffer = &b; (both versions do the same thing).

And why exactly does Rust complain if we don't clone? The inner closure is required (by timeout_add_seconds()) to be 'static (more formally: "to meet the 'static requirement). This means the closure can't reference anything that doesn't live forever ('static). If we don't clone, the inner closure would reference buffer_a which doesn't live forever.


问:
Using an entity relationship diagram to document business processes
Past exam question: How can you use an entity relationship diagram to document business processes?

As far as I know, I would use an ERD to document the relationships between data entities when designing a database. I can't see how ERD's can be used for business processes as flow charts are more suited for this. I would really appreciate if someone could give an example of how this is done.

All the examples I've found online relating to ERD's are for databases and not business processes.

Thanks

答:
I wouldn't use a ER-Diagram to show the business processes. BPMN2.0 is a business process model notation with a wide variety of implementation on information technology. So process management can become a true beauty. If you want to take it further, it also allows Process Controlling in term of process roles, owners, editors, etc. There are a lot freeware designers available to fulfill your needs. I hope this answer helps you.

Regards


问:
Triggering and updating a docked window
I am trying to control some valves with a GUI and update the display when the button is pressed. The following code produces the correct initial display, but when I click one of the checkboxes I always get the value of i=2 and when unchecked I get i=0. I also have no idea how to update the docked window so that the message will toggle from close to open and vise versa. I do see the resultant value in self.states change in the array, but am always left with ['open', 'closed', 'open', 'closed', 'closed', 'closed'] Though this is changed the red closed on the right of the screen does not change to `open

```<code>class ApplicationWindow(gui.QMainWindow):
    def __init__(self):
        self.nCheckBoxes=6
        self.states = ['closed']*self.nCheckBoxes

        gui.QMainWindow.__init__(self)
        self.setAttribute(core.Qt.WA_DeleteOnClose)
        self.setWindowTitle("PiView")
        self.file_menu = gui.QMenu('&File', self)
        self.file_menu.addAction('&Quit', self.fileQuit, core.Qt.CTRL + core.Qt.Key_Q)
        self.menuBar().addMenu(self.file_menu)
        self.help_menu = gui.QMenu('&Help', self)
        self.menuBar().addSeparator()
        self.menuBar().addMenu(self.help_menu)
        self.help_menu.addAction('&About', self.about)
        self.help_menu.addAction('&Docs', self.doc)
        self.main_widget = gui.QWidget(self)

        l = gui.QVBoxLayout(self.main_widget)
        self.dc = MyMplCanvas(self.main_widget, width=5, height=4, dpi=100)
        l.addWidget(self.dc)

        self.main_widget.setFocus()
        self.setCentralWidget(self.main_widget)

        self.dw = self.createDockWindows(self.dc)
        self.statusBar().showMessage("Initialized", 2000)

    def createDockWindows(self, MyMplCanvas):
        """
        Create all the dock widgets
        """
        self.drawValves()
        self.drawGraphAdjustments()
        self.drawStartAndStop()

    def drawValves(self):
        cboxes = gui.QDockWidget("Controls", self)
        cboxes.setAllowedAreas(core.Qt.LeftDockWidgetArea)
        w = gui.QWidget()
        #layout = gui.QVBoxLayout()
        layout = gui.QGridLayout()
        w.setLayout(layout)

        self.c = [0]*self.nCheckBoxes
        # Create self.nCheckBoxes
        msgBox = gui.QLabel()
        msgBox.setText("States")
        font = gui.QFont()
        font.setBold(True)
        msgBox.setFont(font)
        msgBox.setStyleSheet("color: rgb(255,0,0)")
        layout.addWidget(msgBox,0,1)
        for i in range(self.nCheckBoxes):
            self.c[i] = gui.QCheckBox("Valve " + str(i))
            self.c[i].setChecked(False)
            #self.c[i].stateChanged.connect(lambda:self.btnstate(self.c[i]))
            #self.c[i].stateChanged.connect(self.checkedBox)
            self.c[i].stateChanged.connect(lambda i: self.checkedBox(i))
            layout.addWidget(self.c[i],i+1,0)
            # Messages
            msgBox = gui.QLabel()
            msgBox.setText(self.states[i])
            if self.states[i] == 'closed':
                msgBox.setStyleSheet("color: rgb(255,0,0)")
            else:
                msgBox.setStyleSheet("color: rgb(0,255,0)")
            layout.addWidget(msgBox,i+1,1)

        spacerItem = gui.QSpacerItem(20,40, gui.QSizePolicy.Minimum, gui.QSizePolicy.Expanding)
        layout.addItem(spacerItem)
        cboxes.setWidget(w)
        self.addDockWidget(core.Qt.LeftDockWidgetArea, cboxes)

    def checkedBox(self,i):
        sender = self.sender()
        self.states[i] = 'open' if 'close' else 'close'
        # For debugging
        print i
        print self.states
</code>```

If I understand correctly I can just actuate the valve like I would normally in the function checkedBox.

This is what is displayed

I want to be able to click a checkbox and the message just to the right to change from closed to open, and vise versa.

答:
The problem arises because the default value of i takes the value sent by the signal (ie state: Unchecked = 0, PartiallyChecked = 1, Checked = 2), to solve this we will add a further value to the function: Index of the checkbox. Also if you want to change the text of QLabel you must be able to access them so I have created a new list with labels. To make the change we will use the states list, for this implement the function updateLabels.

```<code>class ApplicationWindow(gui.QMainWindow):
    def __init__(self):
        self.nCheckBoxes=6
        self.states = ['closed']*self.nCheckBoxes

        gui.QMainWindow.__init__(self)
        self.setAttribute(core.Qt.WA_DeleteOnClose)
        self.setWindowTitle("PiView")
        self.file_menu = gui.QMenu('&File', self)
        #self.file_menu.addAction('&Quit', self.fileQuit, core.Qt.CTRL + core.Qt.Key_Q)
        self.menuBar().addMenu(self.file_menu)
        self.help_menu = gui.QMenu('&Help', self)
        self.menuBar().addSeparator()
        self.menuBar().addMenu(self.help_menu)
        #self.help_menu.addAction('&About', self.about)
        #self.help_menu.addAction('&Docs', self.doc)
        self.main_widget = gui.QWidget(self)

        l = gui.QVBoxLayout(self.main_widget)
        self.dc = MyMplCanvas(self.main_widget, width=5, height=4, dpi=100)
        l.addWidget(self.dc)

        self.main_widget.setFocus()
        self.setCentralWidget(self.main_widget)

        self.dw = self.createDockWindows(self.dc)
        self.statusBar().showMessage("Initialized", 2000)

    def createDockWindows(self, MyMplCanvas):
        """
        Create all the dock widgets
        """
        self.drawValves()
        #self.drawGraphAdjustments()
        #self.drawStartAndStop()

    def drawValves(self):
        cboxes = gui.QDockWidget("Controls", self)
        cboxes.setAllowedAreas(core.Qt.LeftDockWidgetArea)
        w = gui.QWidget()
        #layout = gui.QVBoxLayout()
        layout = gui.QGridLayout()
        w.setLayout(layout)

        self.c = []
        self.l = []
        # Create self.nCheckBoxes
        msgBox = gui.QLabel()
        msgBox.setText("States")
        font = gui.QFont()
        font.setBold(True)
        msgBox.setFont(font)
        msgBox.setStyleSheet("color: rgb(255,0,0)")
        layout.addWidget(msgBox,0,1)
        for i in range(self.nCheckBoxes):
            checkBox = gui.QCheckBox("Valve " + str(i))
            checkBox.setChecked(False)
            checkBox.stateChanged.connect(lambda state, p=i: self.checkedBox(state, p))
            self.c.append(checkBox)

            layout.addWidget(self.c[i],i+1,0)
            msgBox = gui.QLabel()
            msgBox.setText(self.states[i])
            self.l.append(msgBox)
            layout.addWidget(msgBox,i+1,1)

        self.update_labels()

        spacerItem = gui.QSpacerItem(20,40, gui.QSizePolicy.Minimum, gui.QSizePolicy.Expanding)
        layout.addItem(spacerItem)
        cboxes.setWidget(w)
        self.addDockWidget(core.Qt.LeftDockWidgetArea, cboxes)

    def checkedBox(self, state, p):
        if state == core.Qt.Unchecked:
            self.states[p] = 'closed'
        else:
            self.states[p] = 'open'

        self.update_labels()

    def update_labels(self):
        for i in range(self.nCheckBoxes):
            if self.states[i] == 'closed':
                text = "closed"
                styleSheet = "color: rgb(255,0,0)"
            else:
                text = "open"
                styleSheet = "color: rgb(0,255,0)"
            self.l[i].setText(text)
            self.l[i].setStyleSheet(styleSheet)
</code>```

Title: Triggering and updating a docked window

Body:
I am trying to control some valves with a GUI and update the display when the button is pressed. The following code produces the correct initial display, but when I click one of the checkboxes I always get the value of i=2 and when unchecked I get i=0. I also have no idea how to update the docked window so that the message will toggle from close to open and vise versa. I do see the resultant value in self.states change in the array, but am always left with ['open', 'closed', 'open', 'closed', 'closed', 'closed'] Though this is changed the red closed on the right of the screen does not change to `open

class ApplicationWindow(gui.QMainWindow):
    def __init__(self):
        self.nCheckBoxes=6
        self.states = ['closed']*self.nCheckBoxes

        gui.QMainWindow.__init__(self)
        self.setAttribute(core.Qt.WA_DeleteOnClose)
        self.setWindowTitle("PiView")
        self.file_menu = gui.QMenu('&File', self)
        self.file_menu.addAction('&Quit', self.fileQuit, core.Qt.CTRL + core.Qt.Key_Q)
        self.menuBar().addMenu(self.file_menu)
        self.help_menu = gui.QMenu('&Help', self)
        self.menuBar().addSeparator()
        self.menuBar().addMenu(self.help_menu)
        self.help_menu.addAction('&About', self.about)
        self.help_menu.addAction('&Docs', self.doc)
        self.main_widget = gui.QWidget(self)

        l = gui.QVBoxLayout(self.main_widget)
        self.dc = MyMplCanvas(self.main_widget, width=5, height=4, dpi=100)
        l.addWidget(self.dc)

        self.main_widget.setFocus()
        self.setCentralWidget(self.main_widget)

        self.dw = self.createDockWindows(self.dc)
        self.statusBar().showMessage("Initialized", 2000)

    def createDockWindows(self, MyMplCanvas):
        """
        Create all the dock widgets
        """
        self.drawValves()
        self.drawGraphAdjustments()
        self.drawStartAndStop()

    def drawValves(self):
        cboxes = gui.QDockWidget("Controls", self)
        cboxes.setAllowedAreas(core.Qt.LeftDockWidgetArea)
        w = gui.QWidget()
        #layout = gui.QVBoxLayout()
        layout = gui.QGridLayout()
        w.setLayout(layout)

        self.c = [0]*self.nCheckBoxes
        # Create self.nCheckBoxes
        msgBox = gui.QLabel()
        msgBox.setText("States")
        font = gui.QFont()
        font.setBold(True)
        msgBox.setFont(font)
        msgBox.setStyleSheet("color: rgb(255,0,0)")
        layout.addWidget(msgBox,0,1)
        for i in range(self.nCheckBoxes):
            self.c[i] = gui.QCheckBox("Valve " + str(i))
            self.c[i].setChecked(False)
            #self.c[i].stateChanged.connect(lambda:self.btnstate(self.c[i]))
            #self.c[i].stateChanged.connect(self.checkedBox)
            self.c[i].stateChanged.connect(lambda i: self.checkedBox(i))
            layout.addWidget(self.c[i],i+1,0)
            # Messages
            msgBox = gui.QLabel()
            msgBox.setText(self.states[i])
            if self.states[i] == 'closed':
                msgBox.setStyleSheet("color: rgb(255,0,0)")
            else:
                msgBox.setStyleSheet("color: rgb(0,255,0)")
            layout.addWidget(msgBox,i+1,1)

        spacerItem = gui.QSpacerItem(20,40, gui.QSizePolicy.Minimum, gui.QSizePolicy.Expanding)
        layout.addItem(spacerItem)
        cboxes.setWidget(w)
        self.addDockWidget(core.Qt.LeftDockWidgetArea, cboxes)

    def checkedBox(self,i):
        sender = self.sender()
        self.states[i] = 'open' if 'close' else 'close'
        # For debugging
        print i
        print self.states

If I understand correctly I can just actuate the valve like I would normally in the function checkedBox.

This is what is displayed

I want to be able to click a checkbox and the message just to the right to change from closed to open, and vise versa.

Body:
The problem arises because the default value of i takes the value sent by the signal (ie state: Unchecked = 0, PartiallyChecked = 1, Checked = 2), to solve this we will add a further value to the function: Index of the checkbox. Also if you want to change the text of QLabel you must be able to access them so I have created a new list with labels. To make the change we will use the states list, for this implement the function updateLabels.

class ApplicationWindow(gui.QMainWindow):
    def __init__(self):
        self.nCheckBoxes=6
        self.states = ['closed']*self.nCheckBoxes

        gui.QMainWindow.__init__(self)
        self.setAttribute(core.Qt.WA_DeleteOnClose)
        self.setWindowTitle("PiView")
        self.file_menu = gui.QMenu('&File', self)
        #self.file_menu.addAction('&Quit', self.fileQuit, core.Qt.CTRL + core.Qt.Key_Q)
        self.menuBar().addMenu(self.file_menu)
        self.help_menu = gui.QMenu('&Help', self)
        self.menuBar().addSeparator()
        self.menuBar().addMenu(self.help_menu)
        #self.help_menu.addAction('&About', self.about)
        #self.help_menu.addAction('&Docs', self.doc)
        self.main_widget = gui.QWidget(self)

        l = gui.QVBoxLayout(self.main_widget)
        self.dc = MyMplCanvas(self.main_widget, width=5, height=4, dpi=100)
        l.addWidget(self.dc)

        self.main_widget.setFocus()
        self.setCentralWidget(self.main_widget)

        self.dw = self.createDockWindows(self.dc)
        self.statusBar().showMessage("Initialized", 2000)

    def createDockWindows(self, MyMplCanvas):
        """
        Create all the dock widgets
        """
        self.drawValves()
        #self.drawGraphAdjustments()
        #self.drawStartAndStop()

    def drawValves(self):
        cboxes = gui.QDockWidget("Controls", self)
        cboxes.setAllowedAreas(core.Qt.LeftDockWidgetArea)
        w = gui.QWidget()
        #layout = gui.QVBoxLayout()
        layout = gui.QGridLayout()
        w.setLayout(layout)

        self.c = []
        self.l = []
        # Create self.nCheckBoxes
        msgBox = gui.QLabel()
        msgBox.setText("States")
        font = gui.QFont()
        font.setBold(True)
        msgBox.setFont(font)
        msgBox.setStyleSheet("color: rgb(255,0,0)")
        layout.addWidget(msgBox,0,1)
        for i in range(self.nCheckBoxes):
            checkBox = gui.QCheckBox("Valve " + str(i))
            checkBox.setChecked(False)
            checkBox.stateChanged.connect(lambda state, p=i: self.checkedBox(state, p))
            self.c.append(checkBox)

            layout.addWidget(self.c[i],i+1,0)
            msgBox = gui.QLabel()
            msgBox.setText(self.states[i])
            self.l.append(msgBox)
            layout.addWidget(msgBox,i+1,1)

        self.update_labels()

        spacerItem = gui.QSpacerItem(20,40, gui.QSizePolicy.Minimum, gui.QSizePolicy.Expanding)
        layout.addItem(spacerItem)
        cboxes.setWidget(w)
        self.addDockWidget(core.Qt.LeftDockWidgetArea, cboxes)

    def checkedBox(self, state, p):
        if state == core.Qt.Unchecked:
            self.states[p] = 'closed'
        else:
            self.states[p] = 'open'

        self.update_labels()

    def update_labels(self):
        for i in range(self.nCheckBoxes):
            if self.states[i] == 'closed':
                text = "closed"
                styleSheet = "color: rgb(255,0,0)"
            else:
                text = "open"
                styleSheet = "color: rgb(0,255,0)"
            self.l[i].setText(text)
            self.l[i].setStyleSheet(styleSheet)


问:
Responsive rollover image
I am trying to make a rollover image responsive to browser width and height. Here is the current code:

```<code>'<a href="google.com"><img src="http://i1146.photobucket.com/albums/o535/DanielleStateAuto/360_vid_033017_A_still_zpskfsuzshi.jpg" onmouseover="this.src='http://i1146.photobucket.com/albums/o535/DanielleStateAuto/360_vid_033017_A_zpsekucjvgf.gif'" onmouseout="this.src='http://i1146.photobucket.com/albums/o535/DanielleStateAuto/360_vid_033017_A_still_zpskfsuzshi.jpg'" /></a>'
</code>```

Any thoughts?

答:
Generally, you can do something like this:

```<code><a href="google.com"><img id="myImage" src="http://i1146.photobucket.com/albums/o535/DanielleStateAuto/360_vid_033017_A_still_zpskfsuzshi.jpg" onmouseover="this.src='http://i1146.photobucket.com/albums/o535/DanielleStateAuto/360_vid_033017_A_zpsekucjvgf.gif'" onmouseout="this.src='http://i1146.photobucket.com/albums/o535/DanielleStateAuto/360_vid_033017_A_still_zpskfsuzshi.jpg'" /></a>
<script>
  var w = window.innerWidth;
  document.getElementById("myImage").width = w;
</script>
</code>```

This would adjust the image width to the inner width of the browser window. If you want to adjust by height, use the window.innerHeight property instead. You can write some logic if you want to adjust your image by the smallest of the two in relation to your image.

Or, if you want to do it inline:

```<code><a href="google.com"><img src="http://i1146.photobucket.com/albums/o535/DanielleStateAuto/360_vid_033017_A_still_zpskfsuzshi.jpg" onmouseover="this.src='http://i1146.photobucket.com/albums/o535/DanielleStateAuto/360_vid_033017_A_zpsekucjvgf.gif'" onmouseout="this.src='http://i1146.photobucket.com/albums/o535/DanielleStateAuto/360_vid_033017_A_still_zpskfsuzshi.jpg'" width="window.innerWidth"/></a>
</code>```

would work also, but it would be hard to add additional logic to it.

Title: Responsive rollover image

Body:
I am trying to make a rollover image responsive to browser width and height. Here is the current code:

''

Any thoughts?

Body:
Generally, you can do something like this:

<a href="google.com"><img id="myImage" src="http://i1146.photobucket.com/albums/o535/DanielleStateAuto/360_vid_033017_A_still_zpskfsuzshi.jpg" onmouseover="this.src='http://i1146.photobucket.com/albums/o535/DanielleStateAuto/360_vid_033017_A_zpsekucjvgf.gif'" onmouseout="this.src='http://i1146.photobucket.com/albums/o535/DanielleStateAuto/360_vid_033017_A_still_zpskfsuzshi.jpg'" /></a>
<script>
  var w = window.innerWidth;
  document.getElementById("myImage").width = w;
</script>

This would adjust the image width to the inner width of the browser window. If you want to adjust by height, use the window.innerHeight property instead. You can write some logic if you want to adjust your image by the smallest of the two in relation to your image.

Or, if you want to do it inline:

<a href="google.com"><img src="http://i1146.photobucket.com/albums/o535/DanielleStateAuto/360_vid_033017_A_still_zpskfsuzshi.jpg" onmouseover="this.src='http://i1146.photobucket.com/albums/o535/DanielleStateAuto/360_vid_033017_A_zpsekucjvgf.gif'" onmouseout="this.src='http://i1146.photobucket.com/albums/o535/DanielleStateAuto/360_vid_033017_A_still_zpskfsuzshi.jpg'" width="window.innerWidth"/></a>

would work also, but it would be hard to add additional logic to it.


问:
WHere can I find the CSV file if I use write.csv in a R notebook on DSX
I have scored some data in a R notebook and used the write.csv method to create a CSV file of the scored data stored in a data frame. What is the best way to retrieve this file on DSX ?</p>

答:
The easiest way to get data out of Data Science Experience (DSX), is to write it to object storage.

For R specifically, there are a couple options for getting data into object storage:

objectStoreR - is a simple R package we wrote to make it easy to get or put data in your object storage container.  The readme should give enough code to get started. If you are missing any functionality leave us a Github issue.

ibmos2spark - is another option that is specifically designed to help with object storage i/o working with Spark objects

If you are using Python, I'd recommend checking out my blog on this topic.

Once you have the data in your object storage container, navigate to "Object Storage" under the main navigation on the left.  This will list all the containers in your object storage service, find the one associated with your project, then you can select the file and download it as one of the actions available.


问:
Javascript debugging with Symfony2 in PhpStorm
I'm developing a Symfony2 application using PHPStorm IDE.

I can't seem to make it work. I've tried Javascript Debug for both local and remote with multiple parameters. Messages varies from "Remote URL isn't specified for  so breakpoint..." etc.

Best case scenario is that I would be able to debug my Javascript codes inside PHPStorm. Is this possible?

I'm also using AsseticBundle for my assets.

答:
I was able to set this up

Install the JetBrains Chrome extension

In PHPStorm click the Run/Debug Configurations just to the left of the green bug near the top right

Add a Javascript Debug (using the plus sign)

In the URL box, just enter the URL of the page you're debugging (e.g. http://my.test/app_dev.php/route/here/not-there/3290), name the config, and apply

Add breakpoints in the js

Make sure dev tools is closed in the browser, then click the green bug (ensuring that the config named in 4 is chosen) and it will redirect to the page specified in 4.

The breakpoints will now be activated and are able to be stepped through (like xdebug). When it stops on a breakpoint it may be in a version of the original file with the file's name appended with a version number (this file is read-only). There is a button to the left hand side of the name where you can reload the read-only file being stopped at, after you have updated the actual (writable) file.


问:
How do vimeo / youtube etc. get referrer URL in their iframes?
Baffled by the huge quantity of answers and problems on this subject.

Now, I accept the security JS situation disallowing cross-domain access from iFrame to container window/pages but the ideal resolutions cited in numerous articles of Fragment Identifers or postMessage API is truly baffling.

What I want to do is replicate what vimeo seem to have pulled off; their new iframe embed code

```<code><iframe src="http://player.vimeo.com/video/17263117" width="400" height="225" frameborder="0"></iframe>
</code>```

Uses http://a.vimeocdn.com/js/player_combined.opt.js?8ba54 and seems to be able to fill out a referrer url in the iframe's source from the parent loading page. I.e. www.donkey.com/myvideo.html gets inserted in the http://player.vimeo.com/video/17263117 page. Normally, with security blocks on JS this is not possible with simple parent.location.href. So, I looked into it and have been going on a truly wild chase of the goose to find how this can be done.

I've tried to understand their JS and played with postMessage API but haven't got anything to show. Any guidance is very much welcome.

答:
It doesn't need to get it from the  source at all (security restrictions prevent this as you've already noted), it's passed to the server as a header, and it's rendered in the page by their server for the JavaScript to use, look at the options variable defined in the page.

Let's take an example here: http://www.jsfiddle.net/nick_craver/FfuPk/

If you look at the request to http://player.vimeo.com/video/17263117,

You'll see the referrer get's passed:

```<code>Referer: http://fiddle.jshell.net/nick_craver/FfuPk/show/light/
</code>```

In a script block in the page loaded by the iframe you'll see:

```<code>var options = {config: {
               //....
               "referrer":"http:\/\/fiddle.jshell.net\/nick_craver\/FfuPk\/show\/light\/"
               //....
              };
</code>```

So that's how it gets the referrer, ultimately from the header sent by your browser to the server.

Body:
Baffled by the huge quantity of answers and problems on this subject.

Now, I accept the security JS situation disallowing cross-domain access from iFrame to container window/pages but the ideal resolutions cited in numerous articles of Fragment Identifers or postMessage API is truly baffling.

What I want to do is replicate what vimeo seem to have pulled off; their new iframe embed code

Uses http://a.vimeocdn.com/js/player_combined.opt.js?8ba54 and seems to be able to fill out a referrer url in the iframe's source from the parent loading page. I.e. www.donkey.com/myvideo.html gets inserted in the http://player.vimeo.com/video/17263117 page. Normally, with security blocks on JS this is not possible with simple parent.location.href. So, I looked into it and have been going on a truly wild chase of the goose to find how this can be done.

I've tried to understand their JS and played with postMessage API but haven't got anything to show. Any guidance is very much welcome.

Body:
It doesn't need to get it from the <iframe> source at all (security restrictions prevent this as you've already noted), it's passed to the server as a header, and it's rendered in the page by their server for the JavaScript to use, look at the options variable defined in the page.

Let's take an example here: http://www.jsfiddle.net/nick_craver/FfuPk/

If you look at the request to http://player.vimeo.com/video/17263117,

You'll see the referrer get's passed:

Referer: http://fiddle.jshell.net/nick_craver/FfuPk/show/light/

In a script block in the page loaded by the iframe you'll see:

var options = {config: {
               //....
               "referrer":"http:\/\/fiddle.jshell.net\/nick_craver\/FfuPk\/show\/light\/"
               //....
              };

So that's how it gets the referrer, ultimately from the header sent by your browser to the server.


问:
Coinbase Historic Spot Price at Date-Time
The coinbase API allows you to specify a date when making a request to https://api.coinbase.com/v2/prices/BTC-USD/spot.  The API states the date should be formatted as YYYY-MM-DD.  Is it possible to receive the historic price up to a specific hour (Ex: price from 1 hour ago)?  I see this done on their ios app but it appears they may not be providing this data via the API.

Thanks for all the help!

答:
I did some research on this recently, and I think @gavinstevens answer is correct and the experiments described below confirm that.

Built up some dates to test with:

```<code>import dt as dt
import requests
today=dt.date.today()
today_dt=dt.datetime.now()
earlier_dt=today_dt-dt.timedelta(hours=6)

print(today)
'2017-03-31'
print(today_dt.strftime("%Y-%m-%d %H:%M:%S"))
'2017-03-31 11:57:58'
print(earlier_dt.strftime("%Y-%m-%d %H:%M:%S"))
'2017-03-31 05:57:58'

#build dicts to pass in the api requests
dict_today={'date':today.strftime("%Y-%m-%d")}
dict_dt_now={'date':today_dt.strftime("%Y-%m-%d %H:%M:%S")}
dict_dt_earler={'date': earlier_dt.strftime("%Y-%m-%d %H:%M:%S")}
</code>```

Now, for the Spot Price case:

```<code>r=requests.get('https://api.coinbase.com/v2/prices/BTC-USD/spot/',params=dict_today)
print(r.text)

{"data":{"amount":"1082.42","currency":"USD"},...}

r=requests.get('https://api.coinbase.com/v2/prices/BTC-USD/spot/',params=dict_dt_now)
print(r.text)

{"data":{"amount":"1078.45","currency":"USD"},...}

r=requests.get('https://api.coinbase.com/v2/prices/BTC-USD/spot/',params=dict_dt_earler)
print(r.text)

{"data":{"amount":"1078.03","currency":"USD"},...}
</code>```

as you can see from the code snips above the api returned a different price for each datetime passed.  Next to go back many days just to make sure that this model holds up for all historical data...

```<code>way_earlier_dt=today_dt-dt.timedelta(days=365)
dict_way_earlier={'date': way_earlier_dt.strftime("%Y-%m-%d %H:%M:%S")}

r=requests.get('https://api.coinbase.com/v2/prices/BTC-USD/spot/',params=dict_way_earlier)
print(r.text)

{"data":{"amount":"415.23","currency":"USD"},...}
</code>```

Indeed this returns a reasonable price for that datetime.  Subtracting six hours as a final check...

```<code>way_earlier_dt=way_earlier_dt-dt.timedelta(hours=6)
dict_way_earlier={'date': way_earlier_dt.strftime("%Y-%m-%d %H:%M:%S")}

r=requests.get('https://api.coinbase.com/v2/prices/BTC-USD/spot/',params=dict_way_earlier)
print(r.text)

{"data":{"amount":"415.23","currency":"USD"},...}
</code>```

Uh-oh! Price is identical as the previous request. Looks like we may have a breakdown.

Let's do a "walk across midnight" test to see if the datetime history request is only valid for the current day. We can start back with our "today_dt" value and subtract 12, then 16 hours...

```<code>yesterday_dt_12=today_dt-dt.timedelta(hours=12)
yesterday_dt_16=today_dt-dt.timedelta(hours=16)

print(yesterday_dt_12.strftime("%Y-%m-%d %H:%M:%S"))
'2017-03-30 23:57:58'
print(yesterday_dt_16.strftime("%Y-%m-%d %H:%M:%S"))
'2017-03-30 19:57:58'

dict_yest_12={'date':yesterday_dt_12.strftime("%Y-%m-%d %H:%M:%S")}
dict_yest_16={'date':yesterday_dt_16.strftime("%Y-%m-%d %H:%M:%S")}

r=requests.get('https://api.coinbase.com/v2/prices/BTC-USD/spot/',params=dict_yest_12)
print(r.text)

{"data":{"amount":"1039.37","currency":"USD"},..}

r=requests.get('https://api.coinbase.com/v2/prices/BTC-USD/spot/',params=dict_yest_16)
print(r.text)

{"data":{"amount":"1039.37","currency":"USD"},...}
</code>```

Alas, we have our answer.  We cannot get historical BTC Spot prices using the coinbase api spot request.  I did some more fiddling, and  confirmed the price differences in the initial experiment are fluctuations in the current BTC Spot price today that the api is returning.

Sad!

Body:
I did some research on this recently, and I think @gavinstevens answer is correct and the experiments described below confirm that.

Built up some dates to test with:

import dt as dt
import requests
today=dt.date.today()
today_dt=dt.datetime.now()
earlier_dt=today_dt-dt.timedelta(hours=6)

print(today)
'2017-03-31'
print(today_dt.strftime("%Y-%m-%d %H:%M:%S"))
'2017-03-31 11:57:58'
print(earlier_dt.strftime("%Y-%m-%d %H:%M:%S"))
'2017-03-31 05:57:58'

#build dicts to pass in the api requests
dict_today={'date':today.strftime("%Y-%m-%d")}
dict_dt_now={'date':today_dt.strftime("%Y-%m-%d %H:%M:%S")}
dict_dt_earler={'date': earlier_dt.strftime("%Y-%m-%d %H:%M:%S")}

Now, for the Spot Price case:

r=requests.get('https://api.coinbase.com/v2/prices/BTC-USD/spot/',params=dict_today)
print(r.text)

{"data":{"amount":"1082.42","currency":"USD"},...}

r=requests.get('https://api.coinbase.com/v2/prices/BTC-USD/spot/',params=dict_dt_now)
print(r.text)

{"data":{"amount":"1078.45","currency":"USD"},...}

r=requests.get('https://api.coinbase.com/v2/prices/BTC-USD/spot/',params=dict_dt_earler)
print(r.text)

{"data":{"amount":"1078.03","currency":"USD"},...}

as you can see from the code snips above the api returned a different price for each datetime passed.  Next to go back many days just to make sure that this model holds up for all historical data...

way_earlier_dt=today_dt-dt.timedelta(days=365)
dict_way_earlier={'date': way_earlier_dt.strftime("%Y-%m-%d %H:%M:%S")}

r=requests.get('https://api.coinbase.com/v2/prices/BTC-USD/spot/',params=dict_way_earlier)
print(r.text)

{"data":{"amount":"415.23","currency":"USD"},...}

Indeed this returns a reasonable price for that datetime.  Subtracting six hours as a final check...

way_earlier_dt=way_earlier_dt-dt.timedelta(hours=6)
dict_way_earlier={'date': way_earlier_dt.strftime("%Y-%m-%d %H:%M:%S")}

r=requests.get('https://api.coinbase.com/v2/prices/BTC-USD/spot/',params=dict_way_earlier)
print(r.text)

{"data":{"amount":"415.23","currency":"USD"},...}

Uh-oh! Price is identical as the previous request. Looks like we may have a breakdown.

Let's do a "walk across midnight" test to see if the datetime history request is only valid for the current day. We can start back with our "today_dt" value and subtract 12, then 16 hours...

yesterday_dt_12=today_dt-dt.timedelta(hours=12)
yesterday_dt_16=today_dt-dt.timedelta(hours=16)

print(yesterday_dt_12.strftime("%Y-%m-%d %H:%M:%S"))
'2017-03-30 23:57:58'
print(yesterday_dt_16.strftime("%Y-%m-%d %H:%M:%S"))
'2017-03-30 19:57:58'

dict_yest_12={'date':yesterday_dt_12.strftime("%Y-%m-%d %H:%M:%S")}
dict_yest_16={'date':yesterday_dt_16.strftime("%Y-%m-%d %H:%M:%S")}

r=requests.get('https://api.coinbase.com/v2/prices/BTC-USD/spot/',params=dict_yest_12)
print(r.text)

{"data":{"amount":"1039.37","currency":"USD"},..}

r=requests.get('https://api.coinbase.com/v2/prices/BTC-USD/spot/',params=dict_yest_16)
print(r.text)

{"data":{"amount":"1039.37","currency":"USD"},...}

Alas, we have our answer.  We cannot get historical BTC Spot prices using the coinbase api spot request.  I did some more fiddling, and  confirmed the price differences in the initial experiment are fluctuations in the current BTC Spot price today that the api is returning.

Sad!