问:
(TypeConverterDelegate.java:529) - Cannot create copy of Collection type [java.util.ArrayList] - injecting original Collection as-is
I have the program:

```<code>public static void main(String[] args)
    {
        ApplicationContext ctx = ServiceLocator.getApplicationContext(); <-- error
.......}
</code>```

It has the error message below: I want to eliminate this error which seems coming from JAVA with [DEBUG]. But the program can continue to run. I searched in the google but no luck. I also does not know where is the code wrong. Is it possible to solve this?

```<code>14 Nov 2017 16:50:48,288 [DEBUG] (TypeConverterDelegate.java:529)  - Cannot create copy of Collection type [java.util.ArrayList] - injecting original Collection as-is
java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Collection
    at org.springframework.beans.TypeConverterDelegate.convertToTypedCollection(TypeConverterDelegate.java:524)
    at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:201)
    at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:104)
    at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:415)
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:657)
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:192)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:984)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:886)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:479)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:289)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:286)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:188)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:558)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:852)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:422)
    at org.springframework.context.access.ContextSingletonBeanFactoryLocator.initializeDefinition(ContextSingletonBeanFactoryLocator.java:143)
    at org.springframework.beans.factory.access.SingletonBeanFactoryLocator.useBeanFactory(SingletonBeanFactoryLocator.java:384)
    at com.xxxx.ServiceLocator.getApplicationContext(ServiceLocator.java:24)
    at com.xxxx.main(mcrpt.java:115)
    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.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)
</code>```

at com.xxxx.ServiceLocator.getApplicationContext(ServiceLocator.java:24)

```<code>  package com.xxxx;
        import org.springframework.beans.factory.BeanFactory;
        import org.springframework.beans.factory.access.BeanFactoryLocator;
        import org.springframework.beans.factory.access.BeanFactoryReference;
        import org.springframework.context.ApplicationContext;
        import org.springframework.context.access.ContextSingletonBeanFactoryLocator;
        public class ServiceLocator {
            private static ApplicationContext applicationContext;

            protected ServiceLocator() {
            }

            public static ApplicationContext getApplicationContext() {
                if (applicationContext == null) {

                    BeanFactoryLocator locator = ContextSingletonBeanFactoryLocator.getInstance("ApplicationContext.xml");
                    BeanFactoryReference bfr = locator.useBeanFactory("applicationContext");
                    BeanFactory factory = bfr.getFactory();
                    applicationContext = (ApplicationContext) factory;
                }
                return applicationContext;
            }

        }
</code>```

ApplicationContext.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

    <bean id="applicationContext"
        class="org.springframework.context.support.ClassPathXmlApplicationContext">
        <constructor-arg>
            <list>
                <value>ApplicationContext-properties.xml</value>
                <value>ApplicationContext-log4j.xml</value>
                <value>ApplicationContext-datasource.xml</value>
            </list>
        </constructor-arg>
    </bean>

</beans>
</code>```

答:
Your bean definition is incorrect.

replace:

```<code><bean id="applicationContext" class="org.springframework.context.support.ClassPathXmlApplicationContext">
    <constructor-arg>
        <list>
            <value>ApplicationContext-properties.xml</value>
            <value>ApplicationContext-log4j.xml</value>
            <value>ApplicationContext-datasource.xml</value>
        </list>
    </constructor-arg>
</bean>
</code>```

with

```<code><bean id="applicationContext" class="org.springframework.context.support.ClassPathXmlApplicationContext">
    <constructor-arg value="ApplicationContext-properties.xml" />
    <constructor-arg value="ApplicationContext-log4j.xml" />
    <constructor-arg value="ApplicationContext-datasource.xml" />
</bean>
</code>```

Body:
I have the program:

public static void main(String[] args)
    {
        ApplicationContext ctx = ServiceLocator.getApplicationContext(); <-- error
.......}

It has the error message below: I want to eliminate this error which seems coming from JAVA with [DEBUG]. But the program can continue to run. I searched in the google but no luck. I also does not know where is the code wrong. Is it possible to solve this?

14 Nov 2017 16:50:48,288 [DEBUG] (TypeConverterDelegate.java:529)  - Cannot create copy of Collection type [java.util.ArrayList] - injecting original Collection as-is
java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Collection
    at org.springframework.beans.TypeConverterDelegate.convertToTypedCollection(TypeConverterDelegate.java:524)
    at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:201)
    at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:104)
    at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:415)
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:657)
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:192)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:984)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:886)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:479)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:289)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:286)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:188)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:558)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:852)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:422)
    at org.springframework.context.access.ContextSingletonBeanFactoryLocator.initializeDefinition(ContextSingletonBeanFactoryLocator.java:143)
    at org.springframework.beans.factory.access.SingletonBeanFactoryLocator.useBeanFactory(SingletonBeanFactoryLocator.java:384)
    at com.xxxx.ServiceLocator.getApplicationContext(ServiceLocator.java:24)
    at com.xxxx.main(mcrpt.java:115)
    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.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)

at com.xxxx.ServiceLocator.getApplicationContext(ServiceLocator.java:24)

  package com.xxxx;
        import org.springframework.beans.factory.BeanFactory;
        import org.springframework.beans.factory.access.BeanFactoryLocator;
        import org.springframework.beans.factory.access.BeanFactoryReference;
        import org.springframework.context.ApplicationContext;
        import org.springframework.context.access.ContextSingletonBeanFactoryLocator;
        public class ServiceLocator {
            private static ApplicationContext applicationContext;

            protected ServiceLocator() {
            }

            public static ApplicationContext getApplicationContext() {
                if (applicationContext == null) {

                    BeanFactoryLocator locator = ContextSingletonBeanFactoryLocator.getInstance("ApplicationContext.xml");
                    BeanFactoryReference bfr = locator.useBeanFactory("applicationContext");
                    BeanFactory factory = bfr.getFactory();
                    applicationContext = (ApplicationContext) factory;
                }
                return applicationContext;
            }

        }

ApplicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

    <bean id="applicationContext"
        class="org.springframework.context.support.ClassPathXmlApplicationContext">
        <constructor-arg>
            <list>
                <value>ApplicationContext-properties.xml</value>
                <value>ApplicationContext-log4j.xml</value>
                <value>ApplicationContext-datasource.xml</value>
            </list>
        </constructor-arg>
    </bean>

</beans>

Body:
Your bean definition is incorrect.

replace:

<bean id="applicationContext" class="org.springframework.context.support.ClassPathXmlApplicationContext">
    <constructor-arg>
        <list>
            <value>ApplicationContext-properties.xml</value>
            <value>ApplicationContext-log4j.xml</value>
            <value>ApplicationContext-datasource.xml</value>
        </list>
    </constructor-arg>
</bean>

with

<bean id="applicationContext" class="org.springframework.context.support.ClassPathXmlApplicationContext">
    <constructor-arg value="ApplicationContext-properties.xml" />
    <constructor-arg value="ApplicationContext-log4j.xml" />
    <constructor-arg value="ApplicationContext-datasource.xml" />
</bean>


来源: stackexchange

问:
Regex to capture code comments not working when * followed by /
I've made a regex expression to capture code comments which seems to be working except in the case when the comments contains *  [anynumber of characters inbetween] /, e.g.:

/* these are some comments
=412414515/  * somecharacters /][;';'] */

Regex: (\/\*[^*]*[^/]*\*\/)

https://regex101.com/r/xmpTzw/2

答:
```<code>\/\*[\s\S]*?\*\/
</code>```

Just use a lazy operator instead of trying to not match *

ContentLicense: CC BY-SA 3.0

Body:
\/\*[\s\S]*?\*\/

Just use a lazy operator instead of trying to not match *


问:
PHP: Is timezone data somehow embeded into Timestamps?
```<code>date_default_timezone_set("Asia/Singapore"); // UTC +8
$dt = new DateTime();
$dt->setTimestamp(DateTime::createFromFormat('u', gmdate('u'))->getTimestamp());
echo $dt->getTimezone()->getName(); // Asia/Singapore
echo $dt->format('d M Y H:i:s'); // Correct local time

$dt->setTimezone(new DateTimeZone('UTC'));
echo $dt->format('d M Y H:i:s'); // Correct UTC Time
die;
</code>```

I am wondering if timestamps contain timezone data. On line 3 you see that I used gmdate() which should give me UTC/GMT time. But when I get the timezone & formatted datetime, they are in localtime. I didn't set timezones in my DateTime object yet, gave it a UTC timestamp. It somehow knew to convert to localtime. Which makes me wonder if Timezone data are included in timestamps

答:
setTimestamp accepts the timestamp in GMT 0 and you passed it in GMT, because of gmdate('u'). DateTime object takes your current timezone by default.

After that - you have properly set timestamp and current timezone, that is why DateTime object formats the date for Singapore.

Which makes me wonder if Timezone data are included in timestamps

No. Timestamp stores just amount of seconds since unix-epoch.

ContentLicense: CC BY-SA 2.5

Body:
date_default_timezone_set("Asia/Singapore"); // UTC +8
$dt = new DateTime();
$dt->setTimestamp(DateTime::createFromFormat('u', gmdate('u'))->getTimestamp());
echo $dt->getTimezone()->getName(); // Asia/Singapore
echo $dt->format('d M Y H:i:s'); // Correct local time

$dt->setTimezone(new DateTimeZone('UTC'));
echo $dt->format('d M Y H:i:s'); // Correct UTC Time
die;

I am wondering if timestamps contain timezone data. On line 3 you see that I used gmdate() which should give me UTC/GMT time. But when I get the timezone & formatted datetime, they are in localtime. I didn't set timezones in my DateTime object yet, gave it a UTC timestamp. It somehow knew to convert to localtime. Which makes me wonder if Timezone data are included in timestamps


问:
How do I retrieve the custom type of a typescript variable at runtime
I am defining a custom type "Identifier" and creating a variable of this type but I can't get the type of this variable at runtime

```<code>type Identifier = number;

let myNumber: number;
let myIdentifier: Identifier;

console.log(`myNumber is a ${typeof myNumber}`);
console.log(`myIdentifier is a ${typeof myIdentifier}`);

myNumber = 1234;
myIdentifier = 1234;

console.log(`myNumber is a ${typeof myNumber}`);
console.log(`myIdentifier is a ${typeof myIdentifier}`);
</code>```

When I run the code above I get the following results in the console

myNumber is a undefined

myIdentifier is a undefined

myNumber is a number

myIdentifier is a number

My first problem is that I get an undefined when the variable does not have a value.

My second problem is that when I assign a value to myIdentifier, the type is a number and not an Identifer.

The reason I'm doing this is to distinguish an Identifier as a special type for special processing later on.

答:
Because typescript is compiled into JavaScript and Javascript is not static typing, so at run time, you will not know the type of the variable, only know the type of the value that variable is holding. That is the reason you see 'undefined' instead of 'number'. Also, there is no concept of 'Identifier' in javascript (already stripped away when you compile to javascript), hence, you see 'number' not 'Identifier'.

Even on other programming language, when you define a type alias like you did, it only helps during the compile time, not run time. So you only see number, not Identifier.

Body:
I am defining a custom type "Identifier" and creating a variable of this type but I can't get the type of this variable at runtime

type Identifier = number;

let myNumber: number;
let myIdentifier: Identifier;

console.log(`myNumber is a ${typeof myNumber}`);
console.log(`myIdentifier is a ${typeof myIdentifier}`);

myNumber = 1234;
myIdentifier = 1234;

console.log(`myNumber is a ${typeof myNumber}`);
console.log(`myIdentifier is a ${typeof myIdentifier}`);

When I run the code above I get the following results in the console

myNumber is a undefined

myIdentifier is a undefined

myNumber is a number

myIdentifier is a number

My first problem is that I get an undefined when the variable does not have a value.

My second problem is that when I assign a value to myIdentifier, the type is a number and not an Identifer.

The reason I'm doing this is to distinguish an Identifier as a special type for special processing later on.


问:
GitLab on Azure, could not resolve host
I've installed GitLab on Azure according to this:
http://docs.gitlab.com/ce/install/azure/index.html

And now have a new VM running on mygit.northeurope.cloudapp.azure.com, with ports 22, 80 and 443 open. I can log in to my GitLab through the link above.

Locally I've set up the following:

```<code>git config --global user.name "Me My"
git config --global user.email "me.my@i.com"
</code>```

As well as ssh stuff according to https://help.github.com/articles/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent/

I've created a project (inside a group) in my GitLab repository, but then, whatever I try, cloning or pushing existing code, over SSH or HTTP, I get the following error messages:

ssh: Could not resolve hostname gitlab-ce.blablabla.cx.internal.cloudapp.net:MyGroup/MyProject.git: Name or service not known
  fatal: Could not read from remote repository.

Please make sure you have the correct access rights
  and the repository exists.

And

fatal: unable to access 'http://gitlab-ce.blablabla.cx.internal.cloudapp.net:MyGroup/MyProject.git/': Could not resolve host: gitlab-ce.blablabla.cx.internal.cloudapp.net

What could I be missing? Any help would be appreciated!

答:
What could I be missing? Any help would be appreciated!

In Azure, Gitlab is pre-configured, so that external_url is a example, not an existing address, we should change it to your domain name.

We find the external_url here: /etc/gitlab/gitlab.rb
Change it from http://gitlab-ce.hxakzvpf0otezeojz3wqhme5wg.cx.internal.cloudapp.net to your VM's domain name(we can find it via Azure portal), like this:

Then RUN sudo gitlab-ctl reconfigure for the change to take effect.

Now, we can refresh the browser to get new http address, like this:

Then we can use this new address to pull or clone.

Hope this helps.

Title: GitLab on Azure, could not resolve host

Body:
I've installed GitLab on Azure according to this:
http://docs.gitlab.com/ce/install/azure/index.html

And now have a new VM running on mygit.northeurope.cloudapp.azure.com, with ports 22, 80 and 443 open. I can log in to my GitLab through the link above.

Locally I've set up the following:

git config --global user.name "Me My"
git config --global user.email "me.my@i.com"

As well as ssh stuff according to https://help.github.com/articles/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent/

I've created a project (inside a group) in my GitLab repository, but then, whatever I try, cloning or pushing existing code, over SSH or HTTP, I get the following error messages:

ssh: Could not resolve hostname gitlab-ce.blablabla.cx.internal.cloudapp.net:MyGroup/MyProject.git: Name or service not known
  fatal: Could not read from remote repository.

Please make sure you have the correct access rights
  and the repository exists.

And

fatal: unable to access 'http://gitlab-ce.blablabla.cx.internal.cloudapp.net:MyGroup/MyProject.git/': Could not resolve host: gitlab-ce.blablabla.cx.internal.cloudapp.net

What could I be missing? Any help would be appreciated!


答:
For a start, I suggest this pattern:

```<code>(\/\*[\S\s]*?\*\/)
</code>```

Demo

const regex = /(\/\*[\S\s]*?\*\/)/g;
const str = `This is/ some code /* these are some comments
=412414515/  * somechars /  ][;';'] */*/
Some more code
/* and some more unreadable comments a[dpas[;[];135///]]
d0gewt0qkgekg;l''\\////
*/ god i hate regex  /* asda*asd
\\asd*sd */`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}```

Title: Regex to capture code comments not working when * followed by /

Body:
I've made a regex expression to capture code comments which seems to be working except in the case when the comments contains *  [anynumber of characters inbetween] /, e.g.:

/* these are some comments
=412414515/  * somecharacters /][;';'] */

Regex: (\/\*[^*]*[^/]*\*\/)

https://regex101.com/r/xmpTzw/2

Body:
For a start, I suggest this pattern:

(\/\*[\S\s]*?\*\/)

Demo

const regex = /(\/\*[\S\s]*?\*\/)/g;
const str = `This is/ some code /* these are some comments
=412414515/  * somechars /  ][;';'] */*/
Some more code
/* and some more unreadable comments a[dpas[;[];135///]]
d0gewt0qkgekg;l''\\////
*/ god i hate regex  /* asda*asd
\\asd*sd */`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}


问:
how to run query on dataset?
i have Dataset that contain any database.

how to run any query on this dataset ?

答:
You could use a DataView:

```<code>var view = new DataView(dataSet.Tables("TableName"));
view.RowFilter = "ColumnName LIKE '%something%'"

foreach (var row in view.Rows)
{
    // do something
}
</code>```

or LINQ:

```<code>var results = from row in dataSet.Tables("Table").AsEnumerable()
              where row.Field(Of String)("ColumnName").Contains("something")
              select row;

foreach (var row in results)
{
    // do something
}
</code>```

Google should suffice for a question like this...

Title: how to run query on dataset?

Body:
You could use a DataView:

var view = new DataView(dataSet.Tables("TableName"));
view.RowFilter = "ColumnName LIKE '%something%'"

foreach (var row in view.Rows)
{
    // do something
}

or LINQ:

var results = from row in dataSet.Tables("Table").AsEnumerable()
              where row.Field(Of String)("ColumnName").Contains("something")
              select row;

foreach (var row in results)
{
    // do something
}

Google should suffice for a question like this...


问:
Keyboard shortcuts in Metro apps
How do I capture a keyboard shortcut, no matter which control has focus? I don't want to go and write the same thing for each possible control that the user could give focus to. So how can I watch for a page-wide/control-independent shortcut?</p>

答:
The best solution was to use the root element as suggested previously, because global shortcuts use the functions of one class applied to every page, meaning that one must handle each shortcut separately on each page or risk errors.

My XAML was set up as follows:

```<code><Page
   Name="root"
    ...>

    ...

</Page>
</code>```

My C# to manipulate that page is like this:

```<code>...
namespace DenisQuiz.UWP
{
   public sealed partial class StudyADeck : Page
   {
      ...
      public StudyADeck()
      {
         ...
         // Keyboard shortcuts
         root.KeyDown += Root_KeyDown;
      }

      private void Root_KeyDown(object sender, KeyRoutedEventArgs e)
      {
         switch (e.Key)
         {
            case Windows.System.VirtualKey.F:
               FlipCard();
               break;
            case Windows.System.VirtualKey.Right:
               NextCard();
               break;
            case Windows.System.VirtualKey.Left:
               PreviousCard();
               break;
            case Windows.System.VirtualKey.S:
               Frame.GoBack(); // Stop Studying
               break;
            case Windows.System.VirtualKey.E:
               Frame.Navigate(typeof(EditANotecard)); // Edit this card
               break;
            case Windows.System.VirtualKey.D:
               DeleteNotecardAsync();
               break;
            default:
               break;
         }
      }
...
</code>```

The name root is accessed via any keypress made when that window is open, via the expression root.KeyDown += Root_KeyDown. That calls the Root_KeyDown() method, which then can implement any function based on the key send by the keypress argument KeyRoutedEventArgs e.

My code implements a switch statement to determine key functions.

Title: Keyboard shortcuts in Metro apps

Body:
The best solution was to use the root element as suggested previously, because global shortcuts use the functions of one class applied to every page, meaning that one must handle each shortcut separately on each page or risk errors.

My XAML was set up as follows:

<Page
   Name="root"
    ...>

    ...

</Page>

My C# to manipulate that page is like this:

...
namespace DenisQuiz.UWP
{
   public sealed partial class StudyADeck : Page
   {
      ...
      public StudyADeck()
      {
         ...
         // Keyboard shortcuts
         root.KeyDown += Root_KeyDown;
      }

      private void Root_KeyDown(object sender, KeyRoutedEventArgs e)
      {
         switch (e.Key)
         {
            case Windows.System.VirtualKey.F:
               FlipCard();
               break;
            case Windows.System.VirtualKey.Right:
               NextCard();
               break;
            case Windows.System.VirtualKey.Left:
               PreviousCard();
               break;
            case Windows.System.VirtualKey.S:
               Frame.GoBack(); // Stop Studying
               break;
            case Windows.System.VirtualKey.E:
               Frame.Navigate(typeof(EditANotecard)); // Edit this card
               break;
            case Windows.System.VirtualKey.D:
               DeleteNotecardAsync();
               break;
            default:
               break;
         }
      }
...

The name root is accessed via any keypress made when that window is open, via the expression root.KeyDown += Root_KeyDown. That calls the Root_KeyDown() method, which then can implement any function based on the key send by the keypress argument KeyRoutedEventArgs e.

My code implements a switch statement to determine key functions.


问:
Processing after the request was completed
I have one API endpoint that needs to return to the caller as soon as possible. It currently returns under 1ms. If, however, I log some stuff to the database it now takes closer to 10ms.

How would you approach completing the request and then doing some kind of processing after the request was completed? I tried with Response.Body.Flush(), but that doesn't complete the request and it still takes the full 10ms. It looks like it's sending/flushing the payload, but the request still doesn't complete until the action method is completed.

Would it work to do the logging in a middleware?

EDIT:

One workaround that I found was to use FluentScheduler like this:

```<code>JobManager.Initialize(new Registry());
JobManager.Start();
</code>```

in Program.cs before host.Run() and then schedule an immediate task from an action like this:

```<code>JobManager.AddJob(() =>
{
    // do something...
}, (s) => s.ToRunOnceIn(1).Seconds());
</code>```

答:
Could you use HttpResponse.RegisterForDispose()?  For example:

```<code>public class JobToRunAfterRequestIsComplete : IDisposable {
    public void Dispose()
    {
        // Do your post-processing here.
    }
}

public class YourController {
    public void YourAction() {
        // Do your normal processing here
        ...
        // Register your post processing here
        this.Response.RegisterForDispose(new JobToRunAfterRequestIsComplete ());
    }
}
</code>```

Body:
I have one API endpoint that needs to return to the caller as soon as possible. It currently returns under 1ms. If, however, I log some stuff to the database it now takes closer to 10ms.

How would you approach completing the request and then doing some kind of processing after the request was completed? I tried with Response.Body.Flush(), but that doesn't complete the request and it still takes the full 10ms. It looks like it's sending/flushing the payload, but the request still doesn't complete until the action method is completed.

Would it work to do the logging in a middleware?

EDIT:

One workaround that I found was to use FluentScheduler like this:

JobManager.Initialize(new Registry());
JobManager.Start();

in Program.cs before host.Run() and then schedule an immediate task from an action like this:

JobManager.AddJob(() =>
{
    // do something...
}, (s) => s.ToRunOnceIn(1).Seconds());

Body:
Could you use HttpResponse.RegisterForDispose()?  For example:

public class JobToRunAfterRequestIsComplete : IDisposable {
    public void Dispose()
    {
        // Do your post-processing here.
    }
}

public class YourController {
    public void YourAction() {
        // Do your normal processing here
        ...
        // Register your post processing here
        this.Response.RegisterForDispose(new JobToRunAfterRequestIsComplete ());
    }
}

ContentLicense: CC BY-SA 4.0


问:
Can't take a screenshot of entire div element (scroll chat div)
There is a div. In this div has a chat. This div has scroll bar. I want to take a screenshot of all this div content at once. I almost did it by changing the div height to 500% and overflow: visible, but I got a problem. In fact I got about a large part of the chat in the screenshot, but at some point the chat just disappeared with a long white space till the end of the image as shown below.

I took this screenshot using the Firefox's "Screenshot node" feature. And I tried all possible extensions you can imagine before it and none worked (they don't detect the div scroll, just the main page scroll). Anyways, I want a HTML/CSS solution if possible. I want to understand why it is not working.

As you can see, there a lot of white space, but there is a lot of more chat that was ignored by the print.

What could have happened?

答: You can use FastStone Capture if you want to get a screenshot of a scrolling window or anything with scroll bars. Use the Capture Scrolling Window <Ctrl + Alt + PrtSc> in manual mode.


问:
Extract only number between commas
I have a returned string like this from my code:  (<C1>, 4.297, %)
And I am trying to extract only the value 4.297 from this string using gsub command:

```<code>Fat<-gsub("\\D", "", stringV)
</code>```

However, this extracts not only 4.297 but also the number '1' in C1.
Is there a way to extract only 4.297 from this string, please can you help.

Thanks

Title: Extract only number between commas

Body:
I have a returned string like this from my code:  (<C1>, 4.297, %)
And I am trying to extract only the value 4.297 from this string using gsub command:

Fat<-gsub("\\D", "", stringV)

However, this extracts not only 4.297 but also the number '1' in C1.
Is there a way to extract only 4.297 from this string, please can you help.

Thanks

Body:
How about this?

# Your sample character string
ss <- "(<C1>, 4.297, %)";

gsub(".+,\\s*(\\d+\\.\\d+),.+", "\\1", ss)
#[1] "4.297"

or

gsub(".+,\\s*([0-9\\.]+),.+", "\\1", ss)

Convert to numeric with as.numeric if necessary.


问:
How can I get input validation with Java using Scanner with regex.Pattern and arrays
I want to apply some input validation to a simple Java application using java.util.regex.Pattern. Before adding the pattern matching I was able to get user input into my arrays as expected, but I can't figure out how to do this with the pattern matching included.

This lines seems to be problematic: in.nextLine(); Is it in the wrong place now that I have added the while statement with the pattern matching?

Here is the relevant chunk of code from my little app.

```<code>//These variables used during input validation
        String tempName;
        int tempGrade;

        //These regex patterns are for input validation
        //Names can be 1-15 letters and grades are 2 digits
        Pattern namePattern = Pattern.compile("[A-Za-z]{1,15}");
        Pattern gradePattern = Pattern.compile("[0-9]{2,2}");

        //Parallel arrays to hold last names and grades
        String[] names = new String[5];
        int[] grades = new int[5];

        Scanner in = new Scanner(System.in);
        try {

            for(int i = 0; i<5; i++) {
                System.out.println("Enter a name:");
                tempName = in.nextLine();
                System.out.println("Enter a grade:");
                tempGrade = in.nextInt();
                in.nextLine();
                while(!namePattern.matcher(tempName).matches()) {
                    System.out.println("Bad input. Try again");
                }
                names[i] = tempName;
                grades[i] = tempGrade;
                }
</code>```

答:
No. in.nextLine() is correct (and consumes the trailing newline from calling nextInt()). The problem is your loop.

```<code>while(!namePattern.matcher(tempName).matches()) {
    System.out.println("Bad input. Try again");
    tempName = in.nextLine();  //<-- add this.
}
</code>```

Without updating tempName, if you enter the loop body you never leave because the condition is always true after printing your message.

Body:
I want to apply some input validation to a simple Java application using java.util.regex.Pattern. Before adding the pattern matching I was able to get user input into my arrays as expected, but I can't figure out how to do this with the pattern matching included.

This lines seems to be problematic: in.nextLine(); Is it in the wrong place now that I have added the while statement with the pattern matching?

Here is the relevant chunk of code from my little app.

//These variables used during input validation
        String tempName;
        int tempGrade;

        //These regex patterns are for input validation
        //Names can be 1-15 letters and grades are 2 digits
        Pattern namePattern = Pattern.compile("[A-Za-z]{1,15}");
        Pattern gradePattern = Pattern.compile("[0-9]{2,2}");

        //Parallel arrays to hold last names and grades
        String[] names = new String[5];
        int[] grades = new int[5];

        Scanner in = new Scanner(System.in);
        try {

            for(int i = 0; i<5; i++) {
                System.out.println("Enter a name:");
                tempName = in.nextLine();
                System.out.println("Enter a grade:");
                tempGrade = in.nextInt();
                in.nextLine();
                while(!namePattern.matcher(tempName).matches()) {
                    System.out.println("Bad input. Try again");
                }
                names[i] = tempName;
                grades[i] = tempGrade;
                }

Body:
No. in.nextLine() is correct (and consumes the trailing newline from calling nextInt()). The problem is your loop.

while(!namePattern.matcher(tempName).matches()) {
    System.out.println("Bad input. Try again");
    tempName = in.nextLine();  //<-- add this.
}

Without updating tempName, if you enter the loop body you never leave because the condition is always true after printing your message.


问:
allen-sdk get_flourescence_timeStamps
I believe I am downloading the NWB files properly as I am able to get the df/F traces and stimuli information without trouble. However, I am receiving an error when I try to call "get_running_speed":

AttributeError: 'BrainObservatoryNwbDataSet' object has no attribute 'get_flourescence_timeStamps'

I receive the same error when I call the "get_fourescence_timeStamps" function as well. I have updated the allen sdk packages, so I should be working with the most current version of the software.

Is this a problem anyone else can replicate?

答:
Is the spelling in your question correct?  get_flourescence_timeStamps with the capital 'S' is not a function.  Neither is get_fourescence_timeStamps with a missing l.

Here's where that function is called inside of get_running_speed:

https://github.com/AllenInstitute/AllenSDK/blob/master/allensdk/core/brain_observatory_nwb_data_set.py#L807

It looks like it's spelled correctly.  Here's the definition of get_fluorescence_timestamps:

https://github.com/AllenInstitute/AllenSDK/blob/master/allensdk/core/brain_observatory_nwb_data_set.py#L256

Could you post a small code snippet that reproduces your error?

Title: allen-sdk get_flourescence_timeStamps


问:
I want to get and show images with Drag&Drop methods of pyqt5

I want to get and show  images with Drag&Drop methods of pyqt5. For example,like this image,

I want to make Drag&Drop space and Image-show space.

```<code>import sys
from PyQt5.QtWidgets import (QPushButton, QWidget,
    QLineEdit, QApplication)
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class Button(QPushButton):

    def __init__(self, title, parent):
        super().__init__(title, parent)

        self.setAcceptDrops(True)

    def dragEnterEvent(self, e):

        if e.mimeData().hasFormat('image/*'):
            e.accept()
        else:
            e.ignore()

    def dropEvent(self, e):
        self.label.setPixmap(QPixmap(event.mimeData().imageData()))

class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):

        button = Button("",self)
        button.resize(100,100)
        button.setIcon(QIcon("gazo1.jpg"))
        button.setIconSize(QSize(100,100))
        button.move(0, 0)

        self.label = QLabel(self)
        self.label.setPixmap(QPixmap('gazo2.jpg'))
        self.label.move(150,150)

        self.setWindowTitle('Simple drag & drop')
        self.setGeometry(300, 300, 300, 300)

if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    ex.show()
    app.exec_()
</code>```

I expect that if I drag&drop jpg-image in upper left space, the image is showed in the middle space.

But when I drag jpg image to the upper left space, "drop enabled mark" isn't displayed. So when I drag&drop a image, there is no reaction.

答:
As you want to drag an image from the desktop, the path of this image provides it through a local url, to verify it uses the mimeData(). hasUrls(), and urls() to get the url, then we get the local path with the method toLocalFile(), all the above is implemented in the following code:

```<code>class Button(QPushButton):
    def __init__(self, title, parent):
        super().__init__(title, parent)
        self.setAcceptDrops(True)

    def dragEnterEvent(self, e):
        m = e.mimeData()
        if m.hasUrls():
            e.accept()
        else:
            e.ignore()

    def dropEvent(self, e):
        m = e.mimeData()
        if m.hasUrls():
            self.parent().label.setPixmap(QPixmap(m.urls()[0].toLocalFile()))

class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        button = Button("",self)
        button.resize(100,100)
        button.setIcon(QIcon("gazo1.jpg"))
        button.setIconSize(QSize(100,100))
        button.move(0, 0)

        self.label = QLabel(self)
        self.label.setPixmap(QPixmap('gazo2.png'))
        self.label.move(150,150)

        self.setWindowTitle('Simple drag & drop')
        self.setGeometry(300, 300, 300, 300)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    ex.show()
    app.exec_()
</code>```

Body:
I want to get and show  images with Drag&Drop methods of pyqt5. For example,like this image,

I want to make Drag&Drop space and Image-show space.

import sys
from PyQt5.QtWidgets import (QPushButton, QWidget,
    QLineEdit, QApplication)
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class Button(QPushButton):

    def __init__(self, title, parent):
        super().__init__(title, parent)

        self.setAcceptDrops(True)

    def dragEnterEvent(self, e):

        if e.mimeData().hasFormat('image/*'):
            e.accept()
        else:
            e.ignore()

    def dropEvent(self, e):
        self.label.setPixmap(QPixmap(event.mimeData().imageData()))

class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):

        button = Button("",self)
        button.resize(100,100)
        button.setIcon(QIcon("gazo1.jpg"))
        button.setIconSize(QSize(100,100))
        button.move(0, 0)

        self.label = QLabel(self)
        self.label.setPixmap(QPixmap('gazo2.jpg'))
        self.label.move(150,150)

        self.setWindowTitle('Simple drag & drop')
        self.setGeometry(300, 300, 300, 300)

if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    ex.show()
    app.exec_()

I expect that if I drag&drop jpg-image in upper left space, the image is showed in the middle space.

But when I drag jpg image to the upper left space, "drop enabled mark" isn't displayed. So when I drag&drop a image, there is no reaction.

Body:
As you want to drag an image from the desktop, the path of this image provides it through a local url, to verify it uses the mimeData(). hasUrls(), and urls() to get the url, then we get the local path with the method toLocalFile(), all the above is implemented in the following code:

class Button(QPushButton):
    def __init__(self, title, parent):
        super().__init__(title, parent)
        self.setAcceptDrops(True)

    def dragEnterEvent(self, e):
        m = e.mimeData()
        if m.hasUrls():
            e.accept()
        else:
            e.ignore()

    def dropEvent(self, e):
        m = e.mimeData()
        if m.hasUrls():
            self.parent().label.setPixmap(QPixmap(m.urls()[0].toLocalFile()))

class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        button = Button("",self)
        button.resize(100,100)
        button.setIcon(QIcon("gazo1.jpg"))
        button.setIconSize(QSize(100,100))
        button.move(0, 0)

        self.label = QLabel(self)
        self.label.setPixmap(QPixmap('gazo2.png'))
        self.label.move(150,150)

        self.setWindowTitle('Simple drag & drop')
        self.setGeometry(300, 300, 300, 300)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    ex.show()
    app.exec_()


问:
How to retrieve the id using the label as reference?
I have the following HTML, how can I retrieve the ID of the input from the tag's name in JavaScript?

```<code><div class="named-tags">
     <label for="radio_01" class="radio" >
         <input type="radio" name="Name[labeled_tags][]" value="01" id="radio_button_01">
        Fblabel
         <span class="control-indicator">  </span>
         </label>
        </div>
</code>```

答:
Using document.getElementsByName('Name[labeled_tags][]') will return an array of elements with the specified tag.

You're most likely wanting to select the very first element with the tag name, in this case you would use document.getElementsByName('Name[labeled_tags][]')[0]

let inputElem = document.getElementsByName('Name[labeled_tags][]')[0];
console.log(inputElem.outerHTML);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="named-tags">
 <label for="radio_01" class="radio">
  <input type="radio" name="Name[labeled_tags][]" value="01" id="radio_button_01"> Fblabel
  <span class="control-indicator"> </span>
 </label>
</div></code>```

Body:
I have the following HTML, how can I retrieve the ID of the input from the tag's name in JavaScript?

         <input type="radio" name="Name[labeled_tags][]" value="01" id="radio_button_01">
        Fblabel

Body:
Using document.getElementsByName('Name[labeled_tags][]') will return an array of elements with the specified tag.

You're most likely wanting to select the very first element with the tag name, in this case you would use document.getElementsByName('Name[labeled_tags][]')[0]

let inputElem = document.getElementsByName('Name[labeled_tags][]')[0];
console.log(inputElem.outerHTML);

<div class="named-tags">
 <label for="radio_01" class="radio">
  <input type="radio" name="Name[labeled_tags][]" value="01" id="radio_button_01"> Fblabel
  <span class="control-indicator"> </span>
 </label>
</div>


问:
Syntax error when I add an additional field to select statement
SQL novice hoping to get some help with a select statement

I can run this successfully:

```<code>select distinct t.QUALIFIEDORGUNITCODE as DEALERNUMBER,
       count(distinct(t.TRANSACTIONID)) as TRANSACTION_VOLUME
  from adtdealers.transaction t
  where t.DATECREATED between '01-oct-17' and '01-nov-17'
  group by t.QUALIFIEDORGUNITCODE;
</code>```

but if I attempt to add another field to the select I receive the following error:

ORA-00936: missing expression 00936. 00000 - "missing expression" *Cause: *Action: Error at Line: 17 Column: 105

```<code>select to_char(t.DATECREATED, 'MON-DD') as DAY,
       count(distinct(t.TRANSACTIONID)) as TRANSACTION_VOLUME,
       distinct t.QUALIFIEDORGUNITCODE as DEALERNUMBER
  from adtdealers.transaction t
  where t.DATECREATED between '01-oct-17' and '01-nov-17'
  group by to_char(t.DATECREATED, 'MON-DD'), t.QUALIFIEDORGUNITCODE;
</code>```

I can also run this succesfully:

```<code>select distinct t.QUALIFIEDORGUNITCODE as DEALERNUMBER,
       to_char(t.DATECREATED, 'MON-DD') as DAY
  from adtdealers.transaction t
  where t.DATECREATED between '01-oct-17' and '01-nov-17'
  group by t.QUALIFIEDORGUNITCODE, t.DATECREATED;
</code>```

答: In select statement only one time you can use distinct.</p>

Body:
SQL novice hoping to get some help with a select statement

I can run this successfully:

select distinct t.QUALIFIEDORGUNITCODE as DEALERNUMBER,
       count(distinct(t.TRANSACTIONID)) as TRANSACTION_VOLUME
  from adtdealers.transaction t
  where t.DATECREATED between '01-oct-17' and '01-nov-17'
  group by t.QUALIFIEDORGUNITCODE;

but if I attempt to add another field to the select I receive the following error:

ORA-00936: missing expression 00936. 00000 - "missing expression" *Cause: *Action: Error at Line: 17 Column: 105

select to_char(t.DATECREATED, 'MON-DD') as DAY,
       count(distinct(t.TRANSACTIONID)) as TRANSACTION_VOLUME,
       distinct t.QUALIFIEDORGUNITCODE as DEALERNUMBER
  from adtdealers.transaction t
  where t.DATECREATED between '01-oct-17' and '01-nov-17'
  group by to_char(t.DATECREATED, 'MON-DD'), t.QUALIFIEDORGUNITCODE;

I can also run this succesfully:

select distinct t.QUALIFIEDORGUNITCODE as DEALERNUMBER,
       to_char(t.DATECREATED, 'MON-DD') as DAY
  from adtdealers.transaction t
  where t.DATECREATED between '01-oct-17' and '01-nov-17'
  group by t.QUALIFIEDORGUNITCODE, t.DATECREATED;


问:
List index out of range error on simple python for loop
Can someone explain to me why this for loop doesn't work. I'm trying to use something like this in another program to loop through a list using this N as a parameter.

```<code>    N = [20,40,60,80]

    for j in N:
        print(j)
        for i in range(0,N[j]):
            print(i)
</code>```

Thanks in advance!

答:
you could use enumerate</p>

```<code>N = [20,40,60,80]
for index, j in enumerate(N):
    print(j)
    for i in range(0,N[index]):
        print(i)
</code>```

Body:
Can someone explain to me why this for loop doesn't work. I'm trying to use something like this in another program to loop through a list using this N as a parameter.

    N = [20,40,60,80]

    for j in N:
        print(j)
        for i in range(0,N[j]):
            print(i)

Thanks in advance!

Body:
you could use enumerate

N = [20,40,60,80]
for index, j in enumerate(N):
    print(j)
    for i in range(0,N[index]):
        print(i)


问:
How to mock.patch a dependancy in Python?
Mocking a method that is a dependancy is not working for me. When the method I need to test is calling its dependancy method, the real method is called instead of the mock version of it.

I do have the following files:

myLibrary.py

```<code>from src.myOtherLibrary import myOtherLibrary
class myLibrary():
    def __init__():
        self.myVar = myOtherLibrary() #dependancy

    def my_method():
        method1 = self.method1()

        externalMethod2 self.myVar.method2() #method2 called from the external class myOtherLibrary

        return method1 + externalMethod2

    def method1():
        return "method1 from myLibrary..."
</code>```

src/myOtherLibrary.py

```<code>class myOtherLibrary():
    def method2():
        return "method2 from myOtherLibrary..."
</code>```

Finally the Unit Test:

TestMyLibrary.py

```<code>import unittest
import mock
from myLibrary import myLibrary
from src.myOtherLibrary import myOtherLibrary
class TestMyLibrary(unittest.TestCase):
    @mock.patch('myLibrary.myLibrary.method1') #mocking this works because it's a sibling method from my_method() to test
    @mock.patch('src.myOtherLibrary.myOtherLibrary.method2') #this does not work because it's an external class from myLibrary
    def test_my_method(my_method1_to_mock, my_method2_to_mock):
        my_method1_to_mock.return_value = "something_to_return.."
        my_method2_to_mock.return_value = "something_else_to_return.."

        myLibraryVar = myLibrary()
        result = myLibraryVar.my_method()
        print result #I would expect to see this: "something_to_return..something_else_to_return.."
                     #But it actually prints this: "something_to_return..method2 from myOtherLibrary..."
                     #So mocking is not working for method2

        self.assertEqual('something_to_return..something_else_to_return..', result)

if __name__ == '__main__':
    unittest.main()
</code>```

Perhaps it's important to mention that myLibrary.py and TestMyLibrary.py are in the same folder, but myOtherLibrary.py is under different folder level.

I hope you can help me find what I'm missing here.

Any suggestion will be very well appreciated.
Thanks.

答:
You can't patch like that because the methods you are trying to mock are class methods not functions. So you need to use patch.object.

```<code>@mock.patch.object(myLibrary, 'method1')
@mock.patch.object(myOtherLibrary, 'method2')
...
</code>```

Body:
Mocking a method that is a dependancy is not working for me. When the method I need to test is calling its dependancy method, the real method is called instead of the mock version of it.

I do have the following files:

myLibrary.py

from src.myOtherLibrary import myOtherLibrary
class myLibrary():
    def __init__():
        self.myVar = myOtherLibrary() #dependancy

    def my_method():
        method1 = self.method1()

        externalMethod2 self.myVar.method2() #method2 called from the external class myOtherLibrary

        return method1 + externalMethod2

    def method1():
        return "method1 from myLibrary..."

src/myOtherLibrary.py

class myOtherLibrary():
    def method2():
        return "method2 from myOtherLibrary..."

Finally the Unit Test:

TestMyLibrary.py

import unittest
import mock
from myLibrary import myLibrary
from src.myOtherLibrary import myOtherLibrary
class TestMyLibrary(unittest.TestCase):
    @mock.patch('myLibrary.myLibrary.method1') #mocking this works because it's a sibling method from my_method() to test
    @mock.patch('src.myOtherLibrary.myOtherLibrary.method2') #this does not work because it's an external class from myLibrary
    def test_my_method(my_method1_to_mock, my_method2_to_mock):
        my_method1_to_mock.return_value = "something_to_return.."
        my_method2_to_mock.return_value = "something_else_to_return.."

        myLibraryVar = myLibrary()
        result = myLibraryVar.my_method()
        print result #I would expect to see this: "something_to_return..something_else_to_return.."
                     #But it actually prints this: "something_to_return..method2 from myOtherLibrary..."
                     #So mocking is not working for method2

        self.assertEqual('something_to_return..something_else_to_return..', result)

if __name__ == '__main__':
    unittest.main()

Perhaps it's important to mention that myLibrary.py and TestMyLibrary.py are in the same folder, but myOtherLibrary.py is under different folder level.

I hope you can help me find what I'm missing here.

Any suggestion will be very well appreciated.
Thanks.

Body:
You can't patch like that because the methods you are trying to mock are class methods not functions. So you need to use patch.object.

@mock.patch.object(myLibrary, 'method1')
@mock.patch.object(myOtherLibrary, 'method2')
...


问:
Sync two sheets regarding row insertion/deletion
Is there a way to link two sheets in Excel in a way that I can have the first three columns synced between them (one way is sufficient) and at the same time have row insertion and deletion synced (one way is also sufficient here)?

For instance, I want the contents of columns A,B,C from Sheet1 copied to columns A,B,C of Sheet2 and when I delete a row in Sheet1 I want the whole row deleted in Sheet2 as well. Same thing for a row insertion.

答:
I'm assuming you want to get past the reference error. You will need to have at least one reference cell locked. I'm assuming that the column headers do not change

Here's how I would do it if it was Sheet1 and Sheet2 and row 1 is fixed

```<code>=OFFSET(Sheet1!$A$1,ROW()-1,)
</code>```

the offset function can be used as an array or individual cell function.
I'm only using the first three arguments.

This is the syntax

```<code>OFFSET(reference, rows, cols, [height], [width])
</code>```

I'm using the row function ROW() to return the row number and offset from the reference by ROW()-1

This should solve your issue as long as the reference is not deleted

Body:
I'm assuming you want to get past the reference error. You will need to have at least one reference cell locked. I'm assuming that the column headers do not change

Here's how I would do it if it was Sheet1 and Sheet2 and row 1 is fixed

=OFFSET(Sheet1!$A$1,ROW()-1,)

the offset function can be used as an array or individual cell function.
I'm only using the first three arguments.

This is the syntax

OFFSET(reference, rows, cols, [height], [width])

I'm using the row function ROW() to return the row number and offset from the reference by ROW()-1

This should solve your issue as long as the reference is not deleted


答:
Another option is str_extract to match one or more numeric elements with . and is preceded by a word boundary and succeeded by word boundary(\\b)

```<code>library(stringr)
as.numeric(str_extract(stringV, "\\b[0-9.]+\\b"))
#[1] 4.297
</code>```

If there are multiple numbers, use str_extract_all

data

```<code>stringV <- "(<C1>, 4.297, %)"
</code>```

Title: Extract only number between commas

Body:
Another option is str_extract to match one or more numeric elements with . and is preceded by a word boundary and succeeded by word boundary(\\b)

library(stringr)
as.numeric(str_extract(stringV, "\\b[0-9.]+\\b"))
#[1] 4.297

If there are multiple numbers, use str_extract_all

data

stringV <- "(<C1>, 4.297, %)"


问:
Sorting integers in an array from largest to smallest. Negative ints not working
Recently I created a program that takes the ints inside of an array and puts them in another array from largest to smallest, but it doesn't work when you insert negatives. It prints a 0 rather than the negative integer.

```<code>import java.util.Arrays;

public class g2lArrays2 {

    public static void main(String[] args) {
        int[] nums = {15,31,7,2,7};
        int[] place = new int [nums.length];
        int[] definer = new int [nums.length];
        int a = 0,b = 0,c;
        place[0] = a;
        place[1] = 1;
        for (int i1 = 0; i1<place.length; i1++) {
        for (int i = 0; i<nums.length; i++) {
            if (nums[i] > a) {
                place[i1]=nums[i];
                a=place[i1];
                definer[i]=1;
            }
        }
        a = 0;
        for (c = definer.length-1; b==0 && c>-1; c--) {
            if (definer[c]==1) {
                b=c;
            }
        }
        nums[b]=0;
        b=0;
        for (int i2 = 0; i2<definer.length; i2++) {
            definer[i2]=0;
        }
        }
        System.out.println(Arrays.toString(place));
    }
}
</code>```

It works otherwise, but like I've stated, just not with negative integers. So I'm curious about what I'm doing wrong and if there's a more efficient way to sort this program. All feedback is appreciated.

答:
Okay i think FairPlay answer is totally the best way to sort a array. That said you asked why your code was having problems and that is what i will try to explain here.

First you are printing the array named place and so i will only comment about the places where the code involves that specific array.

this is the parts in your code that affect the place array:

```<code>public static void main(String[] args) {
    int[] nums = {15,31,7,2,7};
    int[] place = new int [nums.length];
    int[] definer = new int [nums.length];
    int a = 0,b = 0,c;
    place[0] = a;
    place[1] = 1;
    for (int i1 = 0; i1<place.length; i1++) {
    for (int i = 0; i<nums.length; i++) {
        if (nums[i] > a) {
            place[i1]=nums[i];
            a=place[i1];
            definer[i]=1;
</code>```

Okay first lets clear this. First things to pay attention is correct identation and create lines breaks whenever you think it is good. Second, when creating a variable that will only be used in a loop or inside a for name them i, j or k and repeat them if possible (this is something i do so it is more of a tip than a rule).

Here is the clean code:

```<code>public static void main(String[] args) {

    int[] nums = {15,31,7,2,7};
    int[] place = new int [nums.length];
    int[] definer = new int [nums.length];

    int a = 0,
    int b = 0;

    place[0] = a;
    place[1] = 1;

    for (int i = 0; i < place.length; i++) {

        for (int j = 0; j < nums.length; j++) {

            if (nums[j] > a) {

                //first a = 0 just so i remember
                //int[] nums = {15,31,7,2,7};

                place[i] = nums[j];
                a = place[i];
                definer[j] = 1;
</code>```

Got it! The problem is exactly in the if above. the problem is in the nums[j] > a. Clearly a negative number wont pass the check ever and that is the problem.

EDIT: Okay i just realized i misread where the first for ends (bad identation) but the problem is the same. You will have problems with negative numbers because your a and b are set to 0 every loop. The 0 that appear in the place of negative numbers are because you added b = 0 in the nums array.

To solve that you should just use array.sort() as FairPlay said in his answer. it is not worth the trouble trying to fix this.

Body:
Recently I created a program that takes the ints inside of an array and puts them in another array from largest to smallest, but it doesn't work when you insert negatives. It prints a 0 rather than the negative integer.

import java.util.Arrays;

public class g2lArrays2 {

    public static void main(String[] args) {
        int[] nums = {15,31,7,2,7};
        int[] place = new int [nums.length];
        int[] definer = new int [nums.length];
        int a = 0,b = 0,c;
        place[0] = a;
        place[1] = 1;
        for (int i1 = 0; i1<place.length; i1++) {
        for (int i = 0; i<nums.length; i++) {
            if (nums[i] > a) {
                place[i1]=nums[i];
                a=place[i1];
                definer[i]=1;
            }
        }
        a = 0;
        for (c = definer.length-1; b==0 && c>-1; c--) {
            if (definer[c]==1) {
                b=c;
            }
        }
        nums[b]=0;
        b=0;
        for (int i2 = 0; i2<definer.length; i2++) {
            definer[i2]=0;
        }
        }
        System.out.println(Arrays.toString(place));
    }
}

It works otherwise, but like I've stated, just not with negative integers. So I'm curious about what I'm doing wrong and if there's a more efficient way to sort this program. All feedback is appreciated.

Body:
Okay i think FairPlay answer is totally the best way to sort a array. That said you asked why your code was having problems and that is what i will try to explain here.

First you are printing the array named place and so i will only comment about the places where the code involves that specific array.

this is the parts in your code that affect the place array:

public static void main(String[] args) {
    int[] nums = {15,31,7,2,7};
    int[] place = new int [nums.length];
    int[] definer = new int [nums.length];
    int a = 0,b = 0,c;
    place[0] = a;
    place[1] = 1;
    for (int i1 = 0; i1<place.length; i1++) {
    for (int i = 0; i<nums.length; i++) {
        if (nums[i] > a) {
            place[i1]=nums[i];
            a=place[i1];
            definer[i]=1;

Okay first lets clear this. First things to pay attention is correct identation and create lines breaks whenever you think it is good. Second, when creating a variable that will only be used in a loop or inside a for name them i, j or k and repeat them if possible (this is something i do so it is more of a tip than a rule).

Here is the clean code:

public static void main(String[] args) {

    int[] nums = {15,31,7,2,7};
    int[] place = new int [nums.length];
    int[] definer = new int [nums.length];

    int a = 0,
    int b = 0;

    place[0] = a;
    place[1] = 1;

    for (int i = 0; i < place.length; i++) {

        for (int j = 0; j < nums.length; j++) {

            if (nums[j] > a) {

                //first a = 0 just so i remember
                //int[] nums = {15,31,7,2,7};

                place[i] = nums[j];
                a = place[i];
                definer[j] = 1;

Got it! The problem is exactly in the if above. the problem is in the nums[j] > a. Clearly a negative number wont pass the check ever and that is the problem.

EDIT: Okay i just realized i misread where the first for ends (bad identation) but the problem is the same. You will have problems with negative numbers because your a and b are set to 0 every loop. The 0 that appear in the place of negative numbers are because you added b = 0 in the nums array.

To solve that you should just use array.sort() as FairPlay said in his answer. it is not worth the trouble trying to fix this.


问:
I see 'The background is pink!' in the console but it stubbornly remains white
Using the example in their docs, I created the following:

entry.js:

```<code>require('./style.scss');
console.log('The background is pink!')
</code>```

style.scss:

```<code>body {
  background: pink;
}
</code>```

I then run this through browserify: browserify -t sassify entry.js > bundle.js and get this:

```<code>(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
require('./style.scss');

console.log('The background is pink!')

},{"./style.scss":2}],2:[function(require,module,exports){
module.exports = "body {\n  background: pink; }\n";
},{}]},{},[1]);
</code>```

I can see my css in there! But when I create a minimal html that loads the bundle, I see 'The background is pink!' in the console - but it stubbornly remains white. Am I forgetting anything? What does it take for the styles to actually show up?

index.html:

```<code><html>
  <body>
    <h1>Pink!</h1>
  </body>
  <script src='bundle.js'></script>
</html>
</code>```

答:
In the sassify github page it says Currently breaks in some cases on node 0.11.x with latest version (2.0.1) of node-sass as documented in node-sass issue #550. This is also the reason why node 0.11 is currently not supported. Use at your own risk (though no actual risk is involved, it might just not work).

I too couldn't get it to work. As he says, it doesn't break anything. It just doesn't do anything at all.

You might want to try cody-greene's scssify. All you need is: npm i scssify -D

And in place of browserify -t sassify entry.js > bundle.js you need browserify -t scssify entry.js > bundle.js

You just need to make sure you use sassify@4.0.0

Body:
Using the example in their docs, I created the following:

entry.js:

require('./style.scss');
console.log('The background is pink!')

style.scss:

body {
  background: pink;
}

I then run this through browserify: browserify -t sassify entry.js > bundle.js and get this:

(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
require('./style.scss');

console.log('The background is pink!')

},{"./style.scss":2}],2:[function(require,module,exports){
module.exports = "body {\n  background: pink; }\n";
},{}]},{},[1]);

I can see my css in there! But when I create a minimal html that loads the bundle, I see 'The background is pink!' in the console - but it stubbornly remains white. Am I forgetting anything? What does it take for the styles to actually show up?

index.html:

Pink!


问:
Why do two identical MySQL questions have different execution plans and take vastly different amounts of time?
I have a two statements that are basically identical. Yet, one takes 55 seconds, the other 2 seconds. WHY?

Here's the query that works fine:

```<code>SELECT
    employees.EmployeeID
FROM
    employees
LEFT JOIN req_budget_centers ON employees.BudgetCenter =    req_budget_centers.BudgetCenter
INNER JOIN req_bcjc ON employees.BudgetCenter = req_bcjc.BudgetCenter AND   employees.JobCode = req_bcjc.JobCode AND employees.EmpContr = req_bcjc.EmpContr
INNER JOIN j_bcjc_req ON req_bcjc.bcjcID = j_bcjc_req.bcjcID
INNER JOIN req_requirements ON j_bcjc_req.requirementID =   req_requirements.id
WHERE
    req_requirements.BoardCategoryID = 4 /*PROBLEM VALUE*/
    AND req_requirements.isActive = 1
    AND employees.`Status` = 'A'
</code>```

Here's the code for the query that takes 50+ seconds:

```<code>SELECT
    employees.EmployeeID
FROM
    employees
LEFT JOIN req_budget_centers ON employees.BudgetCenter =    req_budget_centers.BudgetCenter
INNER JOIN req_bcjc ON employees.BudgetCenter = req_bcjc.BudgetCenter AND   employees.JobCode = req_bcjc.JobCode AND employees.EmpContr = req_bcjc.EmpContr
INNER JOIN j_bcjc_req ON req_bcjc.bcjcID = j_bcjc_req.bcjcID
INNER JOIN req_requirements ON j_bcjc_req.requirementID =   req_requirements.id
WHERE
    req_requirements.BoardCategoryID = 8 /* WORKS FINE */
    AND req_requirements.isActive = 1
    AND employees.`Status` = 'A'
</code>```

Here are the execution plans for those two queries:

There's nothing in the database or in the tables that's different for the value 8 vs 4... the number of overall records involved is the same... How do I hunt down the bottleneck here?

I would also add that leaving the condition ( = 8 or =4) out completely, but leaving all the joins in, speeds up the query considerably as well...

答:
I would suggest to pass the parameter and check the timing for value 4 and 8.

Example : how to pass the parameter. set @type = 'foo';

select * from Stuff where type=@type;

Body:
I have a two statements that are basically identical. Yet, one takes 55 seconds, the other 2 seconds. WHY?

Here's the query that works fine:

SELECT
    employees.EmployeeID
FROM
    employees
LEFT JOIN req_budget_centers ON employees.BudgetCenter =    req_budget_centers.BudgetCenter
INNER JOIN req_bcjc ON employees.BudgetCenter = req_bcjc.BudgetCenter AND   employees.JobCode = req_bcjc.JobCode AND employees.EmpContr = req_bcjc.EmpContr
INNER JOIN j_bcjc_req ON req_bcjc.bcjcID = j_bcjc_req.bcjcID
INNER JOIN req_requirements ON j_bcjc_req.requirementID =   req_requirements.id
WHERE
    req_requirements.BoardCategoryID = 4 /*PROBLEM VALUE*/
    AND req_requirements.isActive = 1
    AND employees.`Status` = 'A'

Here's the code for the query that takes 50+ seconds:

SELECT
    employees.EmployeeID
FROM
    employees
LEFT JOIN req_budget_centers ON employees.BudgetCenter =    req_budget_centers.BudgetCenter
INNER JOIN req_bcjc ON employees.BudgetCenter = req_bcjc.BudgetCenter AND   employees.JobCode = req_bcjc.JobCode AND employees.EmpContr = req_bcjc.EmpContr
INNER JOIN j_bcjc_req ON req_bcjc.bcjcID = j_bcjc_req.bcjcID
INNER JOIN req_requirements ON j_bcjc_req.requirementID =   req_requirements.id
WHERE
    req_requirements.BoardCategoryID = 8 /* WORKS FINE */
    AND req_requirements.isActive = 1
    AND employees.`Status` = 'A'

Here are the execution plans for those two queries:

There's nothing in the database or in the tables that's different for the value 8 vs 4... the number of overall records involved is the same... How do I hunt down the bottleneck here?

I would also add that leaving the condition ( = 8 or =4) out completely, but leaving all the joins in, speeds up the query considerably as well...


问:
.htaccess - DirectoryIndex appears to have no effect
I'm trying to adapt the .htaccess file in the root of my CodeIgniter installation so I don't have to include index.php in all the URLs leading to my controllers.

This is the content of my .htaccess file:

```<code><IfModule authz_core_module>
    Require all granted
</IfModule>
<IfModule !authz_core_module>
    Deny from all
</IfModule>

DirectoryIndex login.php

RewriteEngine On
RewriteCond $1 !^(index\.php)
RewriteCond $(REQUEST_FILENAME) !-f
RewriteCond $(REQUEST_FILENAME) !-d
RewriteRule ^(.*)$ ./index.php/$1
</code>```

As you can see, it's the default .htaccess file with some rewrite rules for mod_rewrite and a DirectoryIndex directive appended to it. Mod_rewrite is enabled (I've checked this using apachectl -M).

Now, I'm running Apache 2.4.18 on Ubuntu 16.04 LTS and I am using CodeIgniter 3.1.6. The problem is that when I type in no URL I get redirected to CodeIgniters index.php instead of my wanted login.php. I'd rather get the DirectoryIndex directive working instead of transferring the contents of login.php into index.php for obvious reasons. My mod_rewrite rules are meant to route URLs to existing files "through" index.php without having to include index.php in their URL. This way, my URLs are cleaner but I can still use CodeIgniter's facilities.

My master Apache configuration obviously allows me to use .htaccess files (since CodeIgniter needs this too) and the URL rewrite directives work just fine. Why does the DirectoryIndex not seem to do anything no matter where I place it inside the file?

答:
I fixed the problem but not in an elegant way.

It appears to me that mod_rewrite just doesn't work (correctly) when you use it in a .htaccess file of a subdirectory of your DocumentRoot.

My CodeIgniter installation was in a subdirectory called "CodeIgniter" inside the DocumentRoot. I made two .htaccess files:

DocumentRoot/.htaccess:

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %1 !^index.php
RewriteRule ^(.*)$ /CodeIgniter/index.php [L]
</code>```

DocumentRoot/CodeIgniter/.htaccess:

```<code><IfModule authz_core_module>
    Require all granted
</IfModule>
<IfModule !authz_core_module>
    Deny from all
</IfModule>
Options FollowSymLinks
DirectoryIndex login.php
</code>```

This seems to be doing the trick for me

Moral of the story: do all of your URL rewriting using mod_rewrite in the .htaccess located directly in your DocumentRoot

Body:
I'm trying to adapt the .htaccess file in the root of my CodeIgniter installation so I don't have to include index.php in all the URLs leading to my controllers.

This is the content of my .htaccess file:

<IfModule authz_core_module>
    Require all granted
</IfModule>
<IfModule !authz_core_module>
    Deny from all
</IfModule>

DirectoryIndex login.php

RewriteEngine On
RewriteCond $1 !^(index\.php)
RewriteCond $(REQUEST_FILENAME) !-f
RewriteCond $(REQUEST_FILENAME) !-d
RewriteRule ^(.*)$ ./index.php/$1

As you can see, it's the default .htaccess file with some rewrite rules for mod_rewrite and a DirectoryIndex directive appended to it. Mod_rewrite is enabled (I've checked this using apachectl -M).

Now, I'm running Apache 2.4.18 on Ubuntu 16.04 LTS and I am using CodeIgniter 3.1.6. The problem is that when I type in no URL I get redirected to CodeIgniters index.php instead of my wanted login.php. I'd rather get the DirectoryIndex directive working instead of transferring the contents of login.php into index.php for obvious reasons. My mod_rewrite rules are meant to route URLs to existing files "through" index.php without having to include index.php in their URL. This way, my URLs are cleaner but I can still use CodeIgniter's facilities.

My master Apache configuration obviously allows me to use .htaccess files (since CodeIgniter needs this too) and the URL rewrite directives work just fine. Why does the DirectoryIndex not seem to do anything no matter where I place it inside the file?

Body:
I fixed the problem but not in an elegant way.

It appears to me that mod_rewrite just doesn't work (correctly) when you use it in a .htaccess file of a subdirectory of your DocumentRoot.

My CodeIgniter installation was in a subdirectory called "CodeIgniter" inside the DocumentRoot. I made two .htaccess files:

DocumentRoot/.htaccess:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %1 !^index.php
RewriteRule ^(.*)$ /CodeIgniter/index.php [L]

DocumentRoot/CodeIgniter/.htaccess:

<IfModule authz_core_module>
    Require all granted
</IfModule>
<IfModule !authz_core_module>
    Deny from all
</IfModule>
Options FollowSymLinks
DirectoryIndex login.php

This seems to be doing the trick for me

Moral of the story: do all of your URL rewriting using mod_rewrite in the .htaccess located directly in your DocumentRoot


问:
Storing data from the keyboard to an array while ignoring duplicates
So I have a program that I'm working on as an assignment, and part of the requirement is asking me to call a method that retrieve numbers from the user, and storing them into an array of size 20. I have to do this while not including any duplicate values in the array, and I will continue storing the users numbers until the array is full, or the user has entered a negative value. I'm running into a couple of issues.

The user has to be able to enter data through multiple lines of text (using the 'enter' key) without interruption, for example:

Enter the integers for the array:
1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
17 18 18 18 18 18 19
20

That should store: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 into the array without duplicate values. The program didn't accept any other values because 20 unique digits had been entered, which filled the array.
I've tried to use different options such as nextInt(), nextLine(), and even storing the numbers as a List and then converting but I'm having so many issues.

So my question is, how do I allow the user to enter values across multiple lines of input as well as checking if the current value in the keyboard buffer is duplicate/negative, so I can know to skip that value in the buffer or end the program?

I'll include my code, but honestly I've tried reworking this so many times that it's an absolute mess. Any help will be more than welcomed.

```<code>    public static int getData(int [] set){
    Scanner keyboard = new Scanner(System.in);

    System.out.println("Enter the integers for the array.");
    System.out.println("The program will stop accepting values when you enter a negative number or reach the 20 unique limit.");

    int usrInput=keyboard.nextInt(), arraySizeUsed = 0;

    for(int position = 0; position < 20; ) {

        if(!Arrays.asList(set).contains(usrInput)) {
            if(usrInput > -1) {

                set[position] = usrInput;
                position++;
                arraySizeUsed++;
            }

            else {
                return arraySizeUsed;
            }
        }
        else {
            continue;
        }
    }

    return arraySizeUsed;
}
</code>```

I don't think I should use 'continue' in the loop as I just want to keep the position from incrementing in the case that the current number in the keyboard buffer is already in the array. What am I missing?

答:
Try something like this;</p>

```<code>int position = 0;
while (position < 20) {
   int next = keyboard.nextInt();
   if (next < 0) {
      break; // Negative so exit loop and return
   }

   if (!ArrayUtils.contains(set, next)) {
      set[position] = next;
      position++;
   }

return set;
</code>```

Body:
So I have a program that I'm working on as an assignment, and part of the requirement is asking me to call a method that retrieve numbers from the user, and storing them into an array of size 20. I have to do this while not including any duplicate values in the array, and I will continue storing the users numbers until the array is full, or the user has entered a negative value. I'm running into a couple of issues.

The user has to be able to enter data through multiple lines of text (using the 'enter' key) without interruption, for example:

Enter the integers for the array:
1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
17 18 18 18 18 18 19
20

That should store: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 into the array without duplicate values. The program didn't accept any other values because 20 unique digits had been entered, which filled the array.
I've tried to use different options such as nextInt(), nextLine(), and even storing the numbers as a List and then converting but I'm having so many issues.

So my question is, how do I allow the user to enter values across multiple lines of input as well as checking if the current value in the keyboard buffer is duplicate/negative, so I can know to skip that value in the buffer or end the program?

I'll include my code, but honestly I've tried reworking this so many times that it's an absolute mess. Any help will be more than welcomed.

    public static int getData(int [] set){
    Scanner keyboard = new Scanner(System.in);

    System.out.println("Enter the integers for the array.");
    System.out.println("The program will stop accepting values when you enter a negative number or reach the 20 unique limit.");

    int usrInput=keyboard.nextInt(), arraySizeUsed = 0;

    for(int position = 0; position < 20; ) {

        if(!Arrays.asList(set).contains(usrInput)) {
            if(usrInput > -1) {

                set[position] = usrInput;
                position++;
                arraySizeUsed++;
            }

            else {
                return arraySizeUsed;
            }
        }
        else {
            continue;
        }
    }

    return arraySizeUsed;
}

I don't think I should use 'continue' in the loop as I just want to keep the position from incrementing in the case that the current number in the keyboard buffer is already in the array. What am I missing?

Body:
Try something like this;

int position = 0;
while (position < 20) {
   int next = keyboard.nextInt();
   if (next < 0) {
      break; // Negative so exit loop and return
   }

   if (!ArrayUtils.contains(set, next)) {
      set[position] = next;
      position++;
   }

return set;


答:
An alternative is to treat your vector as a comma-separated-variable, and use read.csv

```<code>df <- read.csv(text = stringV, colClasses = c("character", "numeric", "character"), header = F)
    V1    V2  V3
1 (<C1> 4.297  %)
</code>```

This method is relying on the 'numeric' being in the 'second' position in the vector.

Title: Extract only number between commas

Body:
I have a returned string like this from my code:  (<C1>, 4.297, %)
And I am trying to extract only the value 4.297 from this string using gsub command:

Fat<-gsub("\\D", "", stringV)

However, this extracts not only 4.297 but also the number '1' in C1.
Is there a way to extract only 4.297 from this string, please can you help.

Thanks

Body:
An alternative is to treat your vector as a comma-separated-variable, and use read.csv

df <- read.csv(text = stringV, colClasses = c("character", "numeric", "character"), header = F)
    V1    V2  V3
1 (<C1> 4.297  %)

This method is relying on the 'numeric' being in the 'second' position in the vector.


问:
Firebase Cloud Messaging With AWS SNS
I am trying to integrate FCM with SNS. I read in this answer that the setup should be identical with GCM. I managed to create an FCM app and can send messages to an android device. The device receives a notif in tray when app is in background, or print received message when app is in foreground. I am trying to integrate it now to SNS but I can't seem to make it work, no error message whatsoever.

In create platform, which key should I use? I used the one form firebase console-> project settings-> cloud messaging -> Server key
Is this wrong?

For the platform endpoint, I used FCM token for Device Token, which is also used when sending notif in firebase console.
Also what should I put in User Data, will any arbitrary string do?

For the message, I used the Json Generated in SNS console. Does FCM accept different format from GCM?

Am I missing something?

答:
Did you ever find out what your issue was? This is probably too late to help you, but might help any others that stumble across this question.

In create platform, which key should I use? I used the one form firebase console-> project settings-> cloud messaging -> Server key Is this wrong?

Yep, that key should work. I have managed to get both the "Server key" and the "Legacy server key" to work fine with SNS. I'd say you should use the newer server key just to ensure things don't break in future if the legacy key is retired by Google.

For the platform endpoint, I used FCM token for Device Token, which is also used when sending notif in firebase console.

Yes, that should work. To be clear you want to use the token that's retrieved by your FCM ID listener service.

Also what should I put in User Data, will any arbitrary string do?

Anything here is fine. It's just a note for yourself.

For the message, I used the Json Generated in SNS console. Does FCM accept different format from GCM?

The message format is slightly different - the answer you linked describes the differences. Even with these differences though I think you should be able to receive something just using the SNS JSON message generator.

Title: Firebase Cloud Messaging With AWS SNS


问:
Making large text box for ajax search
I am making an AJAX application where the user can input the name of a movie and the results from the database will be loaded through jquery from a PHP API, However I am unsure how to implement a text box that will:

(a) Be the focus of attention on the page (i.e. quite large with a glow around it)

(b) automatically execute a function that uses jquery to make an ajax request on every time a letter is entered (kind of like google instant)

Any suggestions would be very greatly appreciated,
thanks, RayQuang

答:
a) For the glow, will an outline or a border do?

b) Use an <textarea> tag and trap its onchange event to send the AJAX request each time. You can make the textarea as large as you want by defining rows and cols

Title: Making large text box for ajax search


问:
Chef is incapable of installing scipy = MemoryError
I am now getting rather concerned about using chef in low ram env's.

The fact that I cant install scipy for python is quite unreal.  I have to wait for an error..ssh into the server, manually run pip install scipy and rerun chef solo and then sever works.  RAM is 1 gig for the server.

Chef..whats the deal?

```<code>python_package 'scipy' do
  version '0.18.1'
end

--- 67.205.184.137 [2017-02-21T03:20:22+00:00] ERROR: bash[install_scipy] (forex::worker line 34) had an error: Mixlib::ShellOut::ShellCommandFailed: Expected process to exit with [0], but received '2'
---- Begin output of "bash"  "/tmp/chef-script20170221-3127-cmg0gp" ----
STDOUT: Collecting scipy==0.18.1
  Downloading scipy-0.18.1-cp27-cp27mu-manylinux1_x86_64.whl (40.3MB)
STDERR: /usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:318: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html#snimissingwarning.
  SNIMissingWarning
/usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:122: InsecurePlatformWarning: A true SSLContext
--- 67.205.184.137  object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html#insecureplatformwarning.
  InsecurePlatformWarning
Exception:
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/usr/local/lib/python2.7/dist-packages/pip/commands/install.py", line 335, in run
    wb.build(autobuilding=True)
  File "/usr/local/lib/python2.7/dist-packages/pip/wheel.py", line 749, in build
    self.requirement_set.prepare_files(self.finder)
  File "/usr/local/lib/python2.7/dist-packages/pip/req/req_set.py", line 380, in prepare_files
    ignore_dependencies=self.ignore_dependencies))
  File "/usr/local/lib/python2.7/dist-packages/pip/req/req_set.py", line 620, in _prepare_file
    session=self.session, hashes=hash
--- 67.205.184.137 es)
  File "/usr/local/lib/python2.7/dist-packages/pip/download.py", line 821, in unpack_url
    hashes=hashes
  File "/usr/local/lib/python2.7/dist-packages/pip/download.py", line 659, in unpack_http_url
    hashes)
  File "/usr/local/lib/python2.7/dist-packages/pip/download.py", line 882, in _download_http_url
    _download_url(resp, link, content_file, hashes)
  File "/usr/local/lib/python2.7/dist-packages/pip/download.py", line 603, in _download_url
    hashes.check_against_chunks(downloaded_chunks)
  File "/usr/local/lib/python2.7/dist-packages/pip/utils/hashes.py", line 46, in check_against_chunks
    for chunk in chunks:
  File "/usr/local/lib/python2.7/dist-packages/pip/download.py", line 571, in written_chunks
    for chunk in chunks:
  File "/usr/local/lib/python2.7/dist-packages/pip/utils/ui.py", line 139, in iter
    for x in it:
  File "/usr/local/lib/python2.7/dist-packages/pip/download.py", line 560, in resp_read
    decode_content=False):
  File "/usr/local/lib/python2.7/dist-packages/pip/_ven
--- 67.205.184.137 dor/requests/packages/urllib3/response.py", line 357, in stream
    data = self.read(amt=amt, decode_content=decode_content)
  File "/usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/packages/urllib3/response.py", line 314, in read
    data = self._fp.read(amt)
  File "/usr/local/lib/python2.7/dist-packages/pip/_vendor/cachecontrol/filewrapper.py", line 63, in read
    self._close()
  File "/usr/local/lib/python2.7/dist-packages/pip/_vendor/cachecontrol/filewrapper.py", line 50, in _close
    self.__callback(self.__buf.getvalue())
  File "/usr/local/lib/python2.7/dist-packages/pip/_vendor/cachecontrol/controller.py", line 275, in cache_response
    self.serializer.dumps(request, response, body=body),
  File "/usr/local/lib/python2.7/dist-packages/pip/_vendor/cachecontrol/serialize.py", line 87, in dumps
    ).encode("utf8"),
MemoryError
---- End output of "bash"  "/tmp/chef-script20170221-3127-cmg0gp" ----
Ran "bash"  "/tmp/chef-script20170221-3127-cmg0gp" returned 2

--- 67.205.184.137 [2017-02-21T03:20:22+00:00] FATAL: Chef::Exceptions::ChildConvergeError: Chef run process exited unsuccessfully (exit code 1)
</code>```

答:
Try pip install --no-cache-dir <pkgname>.

For more information, see Excessive memory use when caching large packages.

Body:
I am now getting rather concerned about using chef in low ram env's.

The fact that I cant install scipy for python is quite unreal.  I have to wait for an error..ssh into the server, manually run pip install scipy and rerun chef solo and then sever works.  RAM is 1 gig for the server.

Chef..whats the deal?

python_package 'scipy' do
  version '0.18.1'
end

--- 67.205.184.137 [2017-02-21T03:20:22+00:00] ERROR: bash[install_scipy] (forex::worker line 34) had an error: Mixlib::ShellOut::ShellCommandFailed: Expected process to exit with [0], but received '2'
---- Begin output of "bash"  "/tmp/chef-script20170221-3127-cmg0gp" ----
STDOUT: Collecting scipy==0.18.1
  Downloading scipy-0.18.1-cp27-cp27mu-manylinux1_x86_64.whl (40.3MB)
STDERR: /usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:318: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html#snimissingwarning.
  SNIMissingWarning
/usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:122: InsecurePlatformWarning: A true SSLContext
--- 67.205.184.137  object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html#insecureplatformwarning.
  InsecurePlatformWarning
Exception:
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/usr/local/lib/python2.7/dist-packages/pip/commands/install.py", line 335, in run
    wb.build(autobuilding=True)
  File "/usr/local/lib/python2.7/dist-packages/pip/wheel.py", line 749, in build
    self.requirement_set.prepare_files(self.finder)
  File "/usr/local/lib/python2.7/dist-packages/pip/req/req_set.py", line 380, in prepare_files
    ignore_dependencies=self.ignore_dependencies))
  File "/usr/local/lib/python2.7/dist-packages/pip/req/req_set.py", line 620, in _prepare_file
    session=self.session, hashes=hash
--- 67.205.184.137 es)
  File "/usr/local/lib/python2.7/dist-packages/pip/download.py", line 821, in unpack_url
    hashes=hashes
  File "/usr/local/lib/python2.7/dist-packages/pip/download.py", line 659, in unpack_http_url
    hashes)
  File "/usr/local/lib/python2.7/dist-packages/pip/download.py", line 882, in _download_http_url
    _download_url(resp, link, content_file, hashes)
  File "/usr/local/lib/python2.7/dist-packages/pip/download.py", line 603, in _download_url
    hashes.check_against_chunks(downloaded_chunks)
  File "/usr/local/lib/python2.7/dist-packages/pip/utils/hashes.py", line 46, in check_against_chunks
    for chunk in chunks:
  File "/usr/local/lib/python2.7/dist-packages/pip/download.py", line 571, in written_chunks
    for chunk in chunks:
  File "/usr/local/lib/python2.7/dist-packages/pip/utils/ui.py", line 139, in iter
    for x in it:
  File "/usr/local/lib/python2.7/dist-packages/pip/download.py", line 560, in resp_read
    decode_content=False):
  File "/usr/local/lib/python2.7/dist-packages/pip/_ven
--- 67.205.184.137 dor/requests/packages/urllib3/response.py", line 357, in stream
    data = self.read(amt=amt, decode_content=decode_content)
  File "/usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/packages/urllib3/response.py", line 314, in read
    data = self._fp.read(amt)
  File "/usr/local/lib/python2.7/dist-packages/pip/_vendor/cachecontrol/filewrapper.py", line 63, in read
    self._close()
  File "/usr/local/lib/python2.7/dist-packages/pip/_vendor/cachecontrol/filewrapper.py", line 50, in _close
    self.__callback(self.__buf.getvalue())
  File "/usr/local/lib/python2.7/dist-packages/pip/_vendor/cachecontrol/controller.py", line 275, in cache_response
    self.serializer.dumps(request, response, body=body),
  File "/usr/local/lib/python2.7/dist-packages/pip/_vendor/cachecontrol/serialize.py", line 87, in dumps
    ).encode("utf8"),
MemoryError
---- End output of "bash"  "/tmp/chef-script20170221-3127-cmg0gp" ----
Ran "bash"  "/tmp/chef-script20170221-3127-cmg0gp" returned 2

--- 67.205.184.137 [2017-02-21T03:20:22+00:00] FATAL: Chef::Exceptions::ChildConvergeError: Chef run process exited unsuccessfully (exit code 1)


问:
Value of type 'AVCaptureDevice' has no member 'supporteddepthdataformats'
supporteddepthdataformats is listed in Apple documentation
https://developer.apple.com/documentation/avfoundation/avcapturedevice.format/2865753-supporteddepthdataformats
but can't be seen from code by:

```<code>let device = AVCaptureDevice.default(.builtInWideAngleCamera, for: AVMediaType.video, position: .back)
print("depth data formats: \(device.supportedDepthDataFormats)")
</code>```

Error message said:

```<code>Value of type 'AVCaptureDevice' has no member 'supporteddepthdataformats'
</code>```

I am using Xcode Version 9.2 beta (9C34b) since the current official Xcode 9.1 does not work with iOS 11.2.

答:
```<code>let device = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back )
print("depth data formats: \(device?.activeFormat.supportedDepthDataFormats)")
</code>```

Hope this helps

Body:
supporteddepthdataformats is listed in Apple documentation
https://developer.apple.com/documentation/avfoundation/avcapturedevice.format/2865753-supporteddepthdataformats
but can't be seen from code by:

let device = AVCaptureDevice.default(.builtInWideAngleCamera, for: AVMediaType.video, position: .back)
print("depth data formats: \(device.supportedDepthDataFormats)")

Error message said:

Value of type 'AVCaptureDevice' has no member 'supporteddepthdataformats'

I am using Xcode Version 9.2 beta (9C34b) since the current official Xcode 9.1 does not work with iOS 11.2.

Body:
let device = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back )
print("depth data formats: \(device?.activeFormat.supportedDepthDataFormats)")

Hope this helps