问:
How to make a variable inside a try/except block public?
How can I make a variable inside the try/except block public?

```<code>import urllib.request

try:
    url = "http://www.google.com"
    page = urllib.request.urlopen(url)
    text = page.read().decode('utf8')
except (ValueError, RuntimeError, TypeError, NameError):
    print("Unable to process your request dude!!")

print(text)
</code>```

This code returns an error

NameError: name 'text' is not defined
```

How can I make the variable text available outside of the try/except block?

答:
As answered before there is no new scope introduced by using try except clause, so if no exception occurs you should see your variable in locals list and it should be accessible in current (in your case global) scope.

```<code>print(locals())
</code>```

In module scope (your case) locals() == globals()

Body:
How can I make a variable inside the try/except block public?

import urllib.request

try:
    url = "http://www.google.com"
    page = urllib.request.urlopen(url)
    text = page.read().decode('utf8')
except (ValueError, RuntimeError, TypeError, NameError):
    print("Unable to process your request dude!!")

print(text)

This code returns an error

NameError: name 'text' is not defined

How can I make the variable text available outside of the try/except block?

Body:
As answered before there is no new scope introduced by using try except clause, so if no exception occurs you should see your variable in locals list and it should be accessible in current (in your case global) scope.

print(locals())

In module scope (your case) locals() == globals()


来源: stackexchange

问:
JSON print nested list from API request
I'm querying an API that interfaces to MariaDB and this is how I get the data back.

```<code>{'TestTable': {'columns': ['Name', 'Id'], 'records': [['Jack', 1], ['Jill', 2]]}}
</code>```

What I'm trying to achieve is to print the columns before the records like so:

Name: Jack
Id: 1
Name: Jill
Id: 2
```

<p>I tried to take the data and put the columns and records into different lists and then my idea was to use an if to match the indexes and if match to print the to the format above, but it was the wrong index.  Unfortuantely after trying to get it to work after about 5 different ways and 3 hours, I realized I had absolutely no idea what I was doing:</p>

```jsonData = json.loads(reqGet.text)
columns = jsonData['TestTable']['columns']
records = jsonData['TestTable']['records']

for idx, val in enumerate(records):
    print(idx, val)
```

<p>Output:</p>

<pre class="lang-none prettyprint-override"><code>0 ['Jack', 1]
1 ['Jill', 2]
</code>```

Any thoughts besides "Have you considered digging ditches?", would be great.

答:
Using your own code:

```<code>jsonData = json.loads(reqGet.text)
columns = jsonData['TestTable']['columns']
records = jsonData['TestTable']['records']
</code>```

And just changing a little bit your for loop to iterate through then using the same indexes:

```<code>for i in range(len(records)):
    data = records[i] # e.g. when i=0, data = ["Jack", 1]
    for j in range(len(columns)):
        print(col[j], data[j])
</code>```

ContentLicense: CC BY-SA 3.0

Title: JSON print nested list from API request

Body:
I'm querying an API that interfaces to MariaDB and this is how I get the data back.

{'TestTable': {'columns': ['Name', 'Id'], 'records': [['Jack', 1], ['Jill', 2]]}}

What I'm trying to achieve is to print the columns before the records like so:

Name: Jack
Id: 1
Name: Jill
Id: 2

I tried to take the data and put the columns and records into different lists and then my idea was to use an if to match the indexes and if match to print the to the format above, but it was the wrong index.  Unfortuantely after trying to get it to work after about 5 different ways and 3 hours, I realized I had absolutely no idea what I was doing:

jsonData = json.loads(reqGet.text)
columns = jsonData['TestTable']['columns']
records = jsonData['TestTable']['records']

for idx, val in enumerate(records):
    print(idx, val)

Output:

0 ['Jack', 1]
1 ['Jill', 2]

Any thoughts besides "Have you considered digging ditches?", would be great.

Body:
Using your own code:

jsonData = json.loads(reqGet.text)
columns = jsonData['TestTable']['columns']
records = jsonData['TestTable']['records']

And just changing a little bit your for loop to iterate through then using the same indexes:

for i in range(len(records)):
    data = records[i] # e.g. when i=0, data = ["Jack", 1]
    for j in range(len(columns)):
        print(col[j], data[j])


问:
Eclipse RCP - Content Assist trouble
I'm trying to add content assist to my editor. I've added

```<code>    public IContentAssistant getContentAssistant(ISourceViewer sv) {
    ContentAssistant ca = new ContentAssistant();
    IContentAssistProcessor pr = new TagCompletionProcessor();
    ca.setContentAssistProcessor(pr, XMLPartitionScanner.XML_TAG);
    ca.setContentAssistProcessor(pr, IDocument.DEFAULT_CONTENT_TYPE);
    return ca;
}
</code>```

to editor configuration, then made completion processor class:

```<code>public class TagCompletionProcessor implements IContentAssistProcessor {
private ITypedRegion wordRegion;
private String currentWord;
private SmartTreeSet tags;
public TagCompletionProcessor() {
    tags = new SmartTreeSet();
    //filling tags skipped
}
@Override
public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer,
        int offset) {
    System.out.println("compute");
    wordRegion = viewer.getDocument().getDocumentPartitioner().getPartition(offset);
    try {
        int offs = wordRegion.getOffset();
        int len = wordRegion.getLength();
        currentWord = viewer.getDocument().get(offs, len);
        return tags.getProposals(currentWord.toLowerCase(), offs, len);
    } catch (BadLocationException e) {
        return null;
    }
}
@Override
public IContextInformation[] computeContextInformation(ITextViewer viewer,
        int offset) {
    return null;
}
@Override
public char[] getCompletionProposalAutoActivationCharacters() {
    return new char[] {'<'};
}
@Override
public char[] getContextInformationAutoActivationCharacters() {
    return null;
}
@Override
public IContextInformationValidator getContextInformationValidator() {
    return null;
}
@Override
public String getErrorMessage() {
    return "No tags found";
}
</code>```

}

... but it's not working. Init goes normal, but auto-activation does not working and when I'm pressing ctrl-space (I've added org.eclipse.ui.edit.text.contentAssist.proposals command to Bindings ext point) empty list appearing (also it's not near cursor, but in some constant place). What am I doing wrong?

答: Sorry, there was some null output in the middle. What a fail =(</p>

OwnerDisplayName: Imaskar

ContentLicense: CC BY-SA 2.5

Title: Eclipse RCP - Content Assist trouble

Body:
I'm trying to add content assist to my editor. I've added

    public IContentAssistant getContentAssistant(ISourceViewer sv) {
    ContentAssistant ca = new ContentAssistant();
    IContentAssistProcessor pr = new TagCompletionProcessor();
    ca.setContentAssistProcessor(pr, XMLPartitionScanner.XML_TAG);
    ca.setContentAssistProcessor(pr, IDocument.DEFAULT_CONTENT_TYPE);
    return ca;
}

to editor configuration, then made completion processor class:

public class TagCompletionProcessor implements IContentAssistProcessor {
private ITypedRegion wordRegion;
private String currentWord;
private SmartTreeSet tags;
public TagCompletionProcessor() {
    tags = new SmartTreeSet();
    //filling tags skipped
}
@Override
public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer,
        int offset) {
    System.out.println("compute");
    wordRegion = viewer.getDocument().getDocumentPartitioner().getPartition(offset);
    try {
        int offs = wordRegion.getOffset();
        int len = wordRegion.getLength();
        currentWord = viewer.getDocument().get(offs, len);
        return tags.getProposals(currentWord.toLowerCase(), offs, len);
    } catch (BadLocationException e) {
        return null;
    }
}
@Override
public IContextInformation[] computeContextInformation(ITextViewer viewer,
        int offset) {
    return null;
}
@Override
public char[] getCompletionProposalAutoActivationCharacters() {
    return new char[] {'<'};
}
@Override
public char[] getContextInformationAutoActivationCharacters() {
    return null;
}
@Override
public IContextInformationValidator getContextInformationValidator() {
    return null;
}
@Override
public String getErrorMessage() {
    return "No tags found";
}

}

... but it's not working. Init goes normal, but auto-activation does not working and when I'm pressing ctrl-space (I've added org.eclipse.ui.edit.text.contentAssist.proposals command to Bindings ext point) empty list appearing (also it's not near cursor, but in some constant place). What am I doing wrong?

LastEditorDisplayName: Imaskar


问:
Python - Call numpy method on strings of dataframe column?
So I have a dataframe column that includes a numpy array, but its read in as a string. So, I end up with the following as a single element:

```<code>df['numpy_arr'].iloc[0] = ' 2 3 5 23 5  2 23 '
</code>```

I want to convert this to a numpy array, and have successfully done so for a single instance using numpy.fromstring:

```<code>first = df['numpy_arr'].iloc[0]
np.fromstring(first, sep=' ')
</code>```

However, when I try to generalize this using the apply:

```<code>df['numpy_arr'].apply(lambda x: np.fromstring(x, sep=' '))
</code>```

It returns an empty series. Why is this the case? Is it because the x in the lambda doesn't actually refer to the actual string? I also tried the following based off of this:

```<code>[np.fromstring(vector,sep=' ') for vector in df['numpy_arr']]
</code>```

Which again returns empty arrays. Why is this the case? How can I generalize this to work on the whole series and convert the elements to a numpy array?

[EDIT] As a last resort, I suppose I can iterate across .iloc[x] but that seems like a very inefficient way to do this, especially since I would have to transform it back into a series

Body:
So I have a dataframe column that includes a numpy array, but its read in as a string. So, I end up with the following as a single element:

df['numpy_arr'].iloc[0] = ' 2 3 5 23 5  2 23 '

I want to convert this to a numpy array, and have successfully done so for a single instance using numpy.fromstring:

first = df['numpy_arr'].iloc[0]
np.fromstring(first, sep=' ')

However, when I try to generalize this using the apply:

df['numpy_arr'].apply(lambda x: np.fromstring(x, sep=' '))

It returns an empty series. Why is this the case? Is it because the x in the lambda doesn't actually refer to the actual string? I also tried the following based off of this:

[np.fromstring(vector,sep=' ') for vector in df['numpy_arr']]

Which again returns empty arrays. Why is this the case? How can I generalize this to work on the whole series and convert the elements to a numpy array?

[EDIT] As a last resort, I suppose I can iterate across .iloc[x] but that seems like a very inefficient way to do this, especially since I would have to transform it back into a series

Body:
This works for me:

>>> df = pd.DataFrame({"A": [' 2 3 5 23 5 2 23 ', ' 3 4 5 ']})
>>> df
                   A
0   2 3 5 23 5 2 23
1             3 4 5
>>> df['A'].apply(lambda x: np.fromstring(x, sep = ' '))
0    [2.0, 3.0, 5.0, 23.0, 5.0, 2.0, 23.0]
1                          [3.0, 4.0, 5.0]
Name: A, dtype: object

Remember to assign the returned value to the dataframe column if you want the value to be saved:

>>> df['A'] = df['A'].apply(lambda x: np.fromstring(x, sep = ' '))
>>> df
                                       A
0  [2.0, 3.0, 5.0, 23.0, 5.0, 2.0, 23.0]
1                        [3.0, 4.0, 5.0]
>>>


问:
When we need to override Handler's handleMessage() method
I was learning about Looper and Handler and most time I read about it that it use to Communicate with UI thread. But then I saw the code which was child class of Handler with handleMessage(msg : Message) method then I got confused, because we can interact with GUI thread without extending Handler class.
As example in kotlin android.

```<code>val handler = Handler();
handler.post({
// update GUI here
});
</code>```

So I can easily interact with GUI thread without implementing child class or handleMessage().

Let me explain little more about my quesiton. Sometime I see this example.

```<code>class HandlerSub : Handler(){

    override fun handleMessage(msg : Message){
        // update GUI here.
    }
}
val handler = HandlerSub();
handler.send({
// send something..
});
</code>```

So in the above example both code are being used for updating/interacting with GUI thread. but the 1st code is more simple easy and less code to interact with GUI.

Then what is real purpose of handleMessage() method and when we should implement it?

答: The sendMessage(...) call is used when you want message.obj to be some custom class, to send it to potentially another thread for processing.  This is normally done by having message.what be an ID, and knowing the object type for that particular id's message.obj, then casting to that object type.  This is used in many places throughout the Android framework, for example check the BluetoothStateMachine and how they handle processMessage(Message msg) in each one of their state classes.  Each one of these states is delegated to by Handler.

Body:
I was learning about Looper and Handler and most time I read about it that it use to Communicate with UI thread. But then I saw the code which was child class of Handler with handleMessage(msg : Message) method then I got confused, because we can interact with GUI thread without extending Handler class.
As example in kotlin android.

val handler = Handler();
handler.post({
// update GUI here
});

So I can easily interact with GUI thread without implementing child class or handleMessage().

Let me explain little more about my quesiton. Sometime I see this example.

class HandlerSub : Handler(){

    override fun handleMessage(msg : Message){
        // update GUI here.
    }
}
val handler = HandlerSub();
handler.send({
// send something..
});

So in the above example both code are being used for updating/interacting with GUI thread. but the 1st code is more simple easy and less code to interact with GUI.

Then what is real purpose of handleMessage() method and when we should implement it?


问:
ASP.NET MVC - unit testing creation of action method URL's in a business assembly
I'm trying to write some unit tests for my ASP.NET MVC code, but I'm hitting a road block.

I have entity partial classes (in a business class library assembly) that need to determine a URL to call for an action method and controller. In order to do that, I found this snippet of code which works nicely - but alas, this uses the HttpContext.Current and thus prevents me from writing any unit tests:

```<code>public string NavigateUrl
{
    get
    {
            HttpContextWrapper httpContextWrapper = new HttpContextWrapper(HttpContext.Current);
            UrlHelper urlHelper = new UrlHelper(new RequestContext(httpContextWrapper, RouteTable.Routes.GetRouteData(httpContextWrapper)));

            string url = urlHelper.Action("SomeAction", "MyController");
    }
}
</code>```

I am reading about the HttpContextBase - but how does this come into play here?? Or is there another way to determine an action URL inside an entity class (that is in a business assembly - NOT the MVC project and not inside a controller or other MVC infrastructure class)?

Update: I need to return this URL from an entity class as a string, since I need to use it in a grid as the navigation URL of a hyperlink. And in reality, there are numerous conditions being checked and the URL string returned can be one of several possibilities - so I cannot just replace it by a single controller call...

答:
Create an abstraction to represent the desired functionality.

For example

```<code>public interface IUrlHelper {
    string Action(string actionName, string controllerName);
    //TODO: create other desired members to be exposed
}
</code>```

You then create a factory for that abstraction. Since you are not injecting it into the entities we are using a service locator ani-pattern.

```<code>public static class UrlHelperFactory {

    public static Func<IUrlHelper> Create = () => {
        throw new NotImplementedException();
    };

}
</code>```

The helper and factory are not coupled to anything and could live anywhere in the solution.

The following test mocks the service to allow the entity to be tested in isolation.

```<code>[TestClass]
public class UrlHelperFactory_Should {

    public class MyTestEntity {
        public string NavigateUrl {
            get {
                var urlHelper = UrlHelperFactory.Create();
                string url = urlHelper.Action("SomeAction", "MyController");
                return url;
            }
        }
    }

    [TestMethod]
    public void Generate_NavigationUrl() {
        //Arrange
        var mockHelper = Mock.Of<IUrlHelper>();
        UrlHelperFactory.Create = () => {
            return mockHelper;
        };
        var expected = "http://my_fake_url";
        Mock.Get(mockHelper)
            .Setup(_ => _.Action(It.IsAny<string>(), It.IsAny<string>()))
            .Returns(expected);

        var sut = new MyTestEntity();

        //Act
        var actual = sut.NavigateUrl;

        //Assert
        actual.Should().NotBeNullOrWhiteSpace()
            .And.Be(expected);
    }
}
</code>```

In production code at the composition root you make sure that the factory knows how to build the service

```<code>UrlHelperFactory.Create = () => {
    var httpContextWrapper = new HttpContextWrapper(HttpContext.Current);
    var urlHelper = new UrlHelper(new RequestContext(httpContextWrapper, RouteTable.Routes.GetRouteData(httpContextWrapper)));
    return new DefaultUrlHelperWrapper(urlHelper);
};
</code>```

Where a wrapper could look like this...

```<code>internal class DefaultUrlHelperWrapper : IUrlHelper {
    private UrlHelper urlHelper;

    public DefaultUrlHelperWrapper(UrlHelper urlHelper) {
        this.urlHelper = urlHelper;
    }

    public string Action(string actionName, string controllerName) {
        return urlHelper.Action(actionName, controllerName);
    }

    //TODO: Implement other members
}
</code>```

Body:
I'm trying to write some unit tests for my ASP.NET MVC code, but I'm hitting a road block.

I have entity partial classes (in a business class library assembly) that need to determine a URL to call for an action method and controller. In order to do that, I found this snippet of code which works nicely - but alas, this uses the HttpContext.Current and thus prevents me from writing any unit tests:

public string NavigateUrl
{
    get
    {
            HttpContextWrapper httpContextWrapper = new HttpContextWrapper(HttpContext.Current);
            UrlHelper urlHelper = new UrlHelper(new RequestContext(httpContextWrapper, RouteTable.Routes.GetRouteData(httpContextWrapper)));

            string url = urlHelper.Action("SomeAction", "MyController");
    }
}

I am reading about the HttpContextBase - but how does this come into play here?? Or is there another way to determine an action URL inside an entity class (that is in a business assembly - NOT the MVC project and not inside a controller or other MVC infrastructure class)?

Update: I need to return this URL from an entity class as a string, since I need to use it in a grid as the navigation URL of a hyperlink. And in reality, there are numerous conditions being checked and the URL string returned can be one of several possibilities - so I cannot just replace it by a single controller call...

Body:
Create an abstraction to represent the desired functionality.

For example

public interface IUrlHelper {
    string Action(string actionName, string controllerName);
    //TODO: create other desired members to be exposed
}

You then create a factory for that abstraction. Since you are not injecting it into the entities we are using a service locator ani-pattern.

public static class UrlHelperFactory {

    public static Func<IUrlHelper> Create = () => {
        throw new NotImplementedException();
    };

}

The helper and factory are not coupled to anything and could live anywhere in the solution.

The following test mocks the service to allow the entity to be tested in isolation.

[TestClass]
public class UrlHelperFactory_Should {

    public class MyTestEntity {
        public string NavigateUrl {
            get {
                var urlHelper = UrlHelperFactory.Create();
                string url = urlHelper.Action("SomeAction", "MyController");
                return url;
            }
        }
    }

    [TestMethod]
    public void Generate_NavigationUrl() {
        //Arrange
        var mockHelper = Mock.Of<IUrlHelper>();
        UrlHelperFactory.Create = () => {
            return mockHelper;
        };
        var expected = "http://my_fake_url";
        Mock.Get(mockHelper)
            .Setup(_ => _.Action(It.IsAny<string>(), It.IsAny<string>()))
            .Returns(expected);

        var sut = new MyTestEntity();

        //Act
        var actual = sut.NavigateUrl;

        //Assert
        actual.Should().NotBeNullOrWhiteSpace()
            .And.Be(expected);
    }
}

In production code at the composition root you make sure that the factory knows how to build the service

UrlHelperFactory.Create = () => {
    var httpContextWrapper = new HttpContextWrapper(HttpContext.Current);
    var urlHelper = new UrlHelper(new RequestContext(httpContextWrapper, RouteTable.Routes.GetRouteData(httpContextWrapper)));
    return new DefaultUrlHelperWrapper(urlHelper);
};

Where a wrapper could look like this...

internal class DefaultUrlHelperWrapper : IUrlHelper {
    private UrlHelper urlHelper;

    public DefaultUrlHelperWrapper(UrlHelper urlHelper) {
        this.urlHelper = urlHelper;
    }

    public string Action(string actionName, string controllerName) {
        return urlHelper.Action(actionName, controllerName);
    }

    //TODO: Implement other members
}


问:
Using Jenkins to deploy to staging and production based on condition
My project has a Jenkinsfile that runs smoothly. The problem is that I need to run some commands only on certain occasions. I'm using the Github plugin. I need to run the deploy only when it is in the master or a new tag, one will be for staging and the other will be production.

```<code>pipeline {
  agent any
  stages {
    stage('Test') {
      steps {
        sh 'node -v'
        sh 'yarn install'
        sh 'yarn test -- --coverage'
      }
    }
    stage('Build') {
      steps {
        sh 'yarn build'
      }
    }
    stage('Deploy') {
      steps {
        sh 'aws s3 sync ./build s3://my.bucket --only-show-errors'
      }
    }
  }
}
</code>```

I need the master to deploy to a bucket and when it is new tag to another. How can I create this conditional?

答:
How about the following working as two conditionals for two separate deployment scenarios? I think it's better to work with this using variables to indicate deployment scenarios instead of splitting this to two distinctly different steps though. You could for example write a shell script that would handle everything inside depending on tags/branches/whatever you need instead of forcing yourself to control this on pipeline level.

Each stage will have it's steps executed only when when part is satisfied. Stage Deploy will only work for master branch, while stage Deploy_NonMaster will only work any non master branch. Using the method written in when conditionals you can check for anything, including tags or whatnot.

```<code>stage ('Deploy') {

        when {
            expression {
                GIT_BRANCH = sh(returnStdout: true, script: 'git rev-parse --abbrev-ref HEAD').trim()
                return (GIT_BRANCH == 'master')
            }
        }
        steps {
            echo 'Do stuff/deploy.'
        }
    }
stage ('Deploy_NonMaster') {

        when {
            expression {
                GIT_BRANCH = sh(returnStdout: true, script: 'git rev-parse --abbrev-ref HEAD').trim()
                return !(GIT_BRANCH == 'master')
            }
        }
        steps {
            echo 'Do stuff/deploy.'
        }
    }
</code>```

Body:
My project has a Jenkinsfile that runs smoothly. The problem is that I need to run some commands only on certain occasions. I'm using the Github plugin. I need to run the deploy only when it is in the master or a new tag, one will be for staging and the other will be production.

pipeline {
  agent any
  stages {
    stage('Test') {
      steps {
        sh 'node -v'
        sh 'yarn install'
        sh 'yarn test -- --coverage'
      }
    }
    stage('Build') {
      steps {
        sh 'yarn build'
      }
    }
    stage('Deploy') {
      steps {
        sh 'aws s3 sync ./build s3://my.bucket --only-show-errors'
      }
    }
  }
}

I need the master to deploy to a bucket and when it is new tag to another. How can I create this conditional?

Body:
How about the following working as two conditionals for two separate deployment scenarios? I think it's better to work with this using variables to indicate deployment scenarios instead of splitting this to two distinctly different steps though. You could for example write a shell script that would handle everything inside depending on tags/branches/whatever you need instead of forcing yourself to control this on pipeline level.

Each stage will have it's steps executed only when when part is satisfied. Stage Deploy will only work for master branch, while stage Deploy_NonMaster will only work any non master branch. Using the method written in when conditionals you can check for anything, including tags or whatnot.

stage ('Deploy') {

        when {
            expression {
                GIT_BRANCH = sh(returnStdout: true, script: 'git rev-parse --abbrev-ref HEAD').trim()
                return (GIT_BRANCH == 'master')
            }
        }
        steps {
            echo 'Do stuff/deploy.'
        }
    }
stage ('Deploy_NonMaster') {

        when {
            expression {
                GIT_BRANCH = sh(returnStdout: true, script: 'git rev-parse --abbrev-ref HEAD').trim()
                return !(GIT_BRANCH == 'master')
            }
        }
        steps {
            echo 'Do stuff/deploy.'
        }
    }


问:
Unable to Switch to New Window Running Test with C# and Selenium
I'm using C# and Selenium to try to automate testing of our web site. I have a link that when clicked opens up a new window. I'm trying to figure out how to switch to this new window to continue the testing.

I've tried the following line which I've found on many blogs, but Last is not showing up in Intellisense and has the red squiggly under it.

```<code>driverIE.SwitchTo().Window(driverIE.WindowHandles.Last());
</code>```

I'm new to working with C# in Visual Studio, so I'm not sure if I'm not including something I should be. Here is the start of the test I'm trying to run.

```<code>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.ObjectModel;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;

namespace SeleniumTest
{
    [TestClass]
    public class UnitTest1
    {
        static IWebDriver driverIE;

        [AssemblyInitialize]
        public static void SetUp(TestContext context)
        {
            driverIE = new InternetExplorerDriver(@"C:\Selenium");
        }

        [TestMethod]
        public void TestIEDriver()
        {
            driverIE.Navigate().GoToUrl("http://localhost/site/");
            driverIE.FindElement(By.Id("txtUserId")).SendKeys("username");
            driverIE.FindElement(By.Id("txtPassword")).SendKeys("password");
            driverIE.FindElement(By.Id("txtPassword")).SendKeys(Keys.Enter);

            //Open Quote
            driverIE.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
            driverIE.FindElement(By.LinkText("Personal Auto")).Click();

            //Switch to Quote Window
            driverIE.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
            ReadOnlyCollection<string> WindowList = driverIE.WindowHandles;
            driverIE.SwitchTo().Window(driverIE.WindowHandles.Last());
            driverIE.FindElement(By.Id("txtAgencyCd")).SendKeys("Code");
        }
    }
}
</code>```

答:
You can use this once you switch to your url</p>

```<code>        WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); //you can change 10 seconds to whatever it suits you the best.
        wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.Id("login")));
</code>```

Body:
I'm using C# and Selenium to try to automate testing of our web site. I have a link that when clicked opens up a new window. I'm trying to figure out how to switch to this new window to continue the testing.

I've tried the following line which I've found on many blogs, but Last is not showing up in Intellisense and has the red squiggly under it.

driverIE.SwitchTo().Window(driverIE.WindowHandles.Last());

I'm new to working with C# in Visual Studio, so I'm not sure if I'm not including something I should be. Here is the start of the test I'm trying to run.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.ObjectModel;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;

namespace SeleniumTest
{
    [TestClass]
    public class UnitTest1
    {
        static IWebDriver driverIE;

        [AssemblyInitialize]
        public static void SetUp(TestContext context)
        {
            driverIE = new InternetExplorerDriver(@"C:\Selenium");
        }

        [TestMethod]
        public void TestIEDriver()
        {
            driverIE.Navigate().GoToUrl("http://localhost/site/");
            driverIE.FindElement(By.Id("txtUserId")).SendKeys("username");
            driverIE.FindElement(By.Id("txtPassword")).SendKeys("password");
            driverIE.FindElement(By.Id("txtPassword")).SendKeys(Keys.Enter);

            //Open Quote
            driverIE.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
            driverIE.FindElement(By.LinkText("Personal Auto")).Click();

            //Switch to Quote Window
            driverIE.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
            ReadOnlyCollection<string> WindowList = driverIE.WindowHandles;
            driverIE.SwitchTo().Window(driverIE.WindowHandles.Last());
            driverIE.FindElement(By.Id("txtAgencyCd")).SendKeys("Code");
        }
    }
}

Body:
You can use this once you switch to your url

        WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); //you can change 10 seconds to whatever it suits you the best.
        wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.Id("login")));


问:
Resizing N # of squares to be as big as possible while still fitting into box of X by Y dimensions. (Thumbnails!)
I have N squares.
I have a Rectangular box.
I want all the squares to fit in the box.
I want the squares to be as large as possible.

How do I calculate the largest size for the squares such that they all fit in the box?

This is for thumbnails in a thumbnail gallery.

```<code>int function thumbnailSize(
    iItems, // The number of items to fit.
    iWidth, // The width of the container.
    iHeight, // The height of the container.
    iMin // The smallest an item can be.
)
{
    // if there are no items we don't care how big they are!
    if (iItems = 0) return 0;

    // Max size is whichever dimension is smaller, height or width.
    iDimension = (iWidth min iHeight);

    // Add .49 so that we always round up, even if the square root
    // is something like 1.2.  If the square root is whole (1, 4, etc..)
    // then it won't round up.
    iSquare = (round(sqrt(iItems) + 0.49));

    // If we arrange our items in a square pattern we have the same
    // number of rows and columns, so we can just divide by the number
    // iSquare, because iSquare = iRows = iColumns.
    iSize = (iDimension / iSquare);

    // Don't use a size smaller than the minimum.
    iSize = (iSize max iMin);

    return iSize;
 }
</code>```

This code currently works OK.  The idea behind it is to take the smallest dimension of the rectangular container, pretend the container is a square of that dimension, and then assume we have an equal number of rows and columns, just enough to fit iItems squares inside.

This function works great if the container is mostly squarish.  If you have a long rectangle, though, the thumbnails come out smaller than they could be.  For instance, if my rectangle is 100 x 300, and I have three thumbnails, it should return 100, but instead returns 33.

答:
The solution on https://math.stackexchange.com/a/466248 works perfectly.

An unoptimized javascript implementation:

```<code>var getMaxSizeOfSquaresInRect = function(n,w,h)
{
    var sw, sh;
    var pw = Math.ceil(Math.sqrt(n*w/h));
    if (Math.floor(pw*h/w)*pw < n) sw = h/Math.ceil(pw*h/w);
    else sw = w/pw;
    var ph = Math.ceil(Math.sqrt(n*h/w));
    if (Math.floor(ph*w/h)*ph < n) sh = w/Math.ceil(w*ph/h);
    else sh = h/ph;
    return Math.max(sw,sh);
}
</code>```

Body:
I have N squares.
I have a Rectangular box.
I want all the squares to fit in the box.
I want the squares to be as large as possible.

How do I calculate the largest size for the squares such that they all fit in the box?

This is for thumbnails in a thumbnail gallery.

int function thumbnailSize(
    iItems, // The number of items to fit.
    iWidth, // The width of the container.
    iHeight, // The height of the container.
    iMin // The smallest an item can be.
)
{
    // if there are no items we don't care how big they are!
    if (iItems = 0) return 0;

    // Max size is whichever dimension is smaller, height or width.
    iDimension = (iWidth min iHeight);

    // Add .49 so that we always round up, even if the square root
    // is something like 1.2.  If the square root is whole (1, 4, etc..)
    // then it won't round up.
    iSquare = (round(sqrt(iItems) + 0.49));

    // If we arrange our items in a square pattern we have the same
    // number of rows and columns, so we can just divide by the number
    // iSquare, because iSquare = iRows = iColumns.
    iSize = (iDimension / iSquare);

    // Don't use a size smaller than the minimum.
    iSize = (iSize max iMin);

    return iSize;
 }

This code currently works OK.  The idea behind it is to take the smallest dimension of the rectangular container, pretend the container is a square of that dimension, and then assume we have an equal number of rows and columns, just enough to fit iItems squares inside.

This function works great if the container is mostly squarish.  If you have a long rectangle, though, the thumbnails come out smaller than they could be.  For instance, if my rectangle is 100 x 300, and I have three thumbnails, it should return 100, but instead returns 33.

Body:
The solution on https://math.stackexchange.com/a/466248 works perfectly.

An unoptimized javascript implementation:

var getMaxSizeOfSquaresInRect = function(n,w,h)
{
    var sw, sh;
    var pw = Math.ceil(Math.sqrt(n*w/h));
    if (Math.floor(pw*h/w)*pw < n) sw = h/Math.ceil(pw*h/w);
    else sw = w/pw;
    var ph = Math.ceil(Math.sqrt(n*h/w));
    if (Math.floor(ph*w/h)*ph < n) sh = w/Math.ceil(w*ph/h);
    else sh = h/ph;
    return Math.max(sw,sh);
}


问:
Write reliably to same file from different processes
I did create a small C++ Tracing solution which works very well. Within one process all is well but when I open the output file from diferent processes the data gets not correctly written. I did open the file with FILE_SHARE_WRITE to be able to write to the file when it is already open. Then I did create a named mutex to ensure proper synchronisation between processes. But it appears that this is not enough. According to the MSDN this does work within one process but not between different processes.
Next I tried to call FlushFileBuffers after every write while the mutex was still held but data was still distorted like this

The format is time process id/Thread id method enter/leave/severity namespace+method and then the message text.

```<code>10:29:42.994 7448/2236       }} Dll2.Test.fndll2 L1 -> Duration: 0.094s
10:29:43.040 7448/2236 {{       Dll2.DllMain L1
10:29:43.134 7448/2236 Info     Dll2.DllMain L1 Process detach
10:29:43.181 7448/2236       }} Dll2.DllMain L1 -> Duration: 0.141s
     }} Dll2.DllMain L1 -10:29:42.681 7448/2236 Info     Dll1.DllMain L1 Process attach
10:29:42.728 7448/2236       }} Dll1.DllMain L1 -10:29:42.744 2216/5510:29:42.775 7448/2236 {{       Dll1.Test.fndll1 10:210:29:42.822 7448/2236 Info     Dll1.Test.fndll1 10:29:42.837 2216/557610:29:42.853 7448/2236       }} Dll1.Test.fndll1 L110:29:42.884 2216/557610:29:43.306 7448/2236 {{       Dll1.DllMain L1
10:29:43.353 7448/2236 Info     Dll1.DllMain L1 Process detach
10:29:43.400 7448/2236       }} Dll1.DllMain L1 -> Duration: 0.094s
</code>```

I have looked at FILE_FLAG_NO_BUFFERING but it has severe limitations and it seems not easy to use.

Does anybody know the right way to write synchronized to the same file without distoriting the output?

Yours,

Alois Kraus

答: You have to protect or synchronize concurrent calls to the function that writes into the file with a named mutex. See CreateMutex</p>

Body:
I did create a small C++ Tracing solution which works very well. Within one process all is well but when I open the output file from diferent processes the data gets not correctly written. I did open the file with FILE_SHARE_WRITE to be able to write to the file when it is already open. Then I did create a named mutex to ensure proper synchronisation between processes. But it appears that this is not enough. According to the MSDN this does work within one process but not between different processes.
Next I tried to call FlushFileBuffers after every write while the mutex was still held but data was still distorted like this

The format is time process id/Thread id method enter/leave/severity namespace+method and then the message text.

10:29:42.994 7448/2236       }} Dll2.Test.fndll2 L1 -> Duration: 0.094s
10:29:43.040 7448/2236 {{       Dll2.DllMain L1
10:29:43.134 7448/2236 Info     Dll2.DllMain L1 Process detach
10:29:43.181 7448/2236       }} Dll2.DllMain L1 -> Duration: 0.141s
     }} Dll2.DllMain L1 -10:29:42.681 7448/2236 Info     Dll1.DllMain L1 Process attach
10:29:42.728 7448/2236       }} Dll1.DllMain L1 -10:29:42.744 2216/5510:29:42.775 7448/2236 {{       Dll1.Test.fndll1 10:210:29:42.822 7448/2236 Info     Dll1.Test.fndll1 10:29:42.837 2216/557610:29:42.853 7448/2236       }} Dll1.Test.fndll1 L110:29:42.884 2216/557610:29:43.306 7448/2236 {{       Dll1.DllMain L1
10:29:43.353 7448/2236 Info     Dll1.DllMain L1 Process detach
10:29:43.400 7448/2236       }} Dll1.DllMain L1 -> Duration: 0.094s

I have looked at FILE_FLAG_NO_BUFFERING but it has severe limitations and it seems not easy to use.

Does anybody know the right way to write synchronized to the same file without distoriting the output?

Yours,

Alois Kraus


问:
How to Dialogfragment disable click outside on android?
I use extends DialogFragment

I want except dialog, disable click on android.

I try setCanceledOnTouchOutside(true) but it doesn't not work.

and please check my source.

```<code>public class QuestDialog extends DialogFragment {
   private String mainMessage = "";
   private View.OnClickListener positiveListener = null;
   private View.OnClickListener negativeListener = null;

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

   View view = inflater.inflate(R.layout.main_dialog, container, false);

   TextView textView = (TextView) view.findViewById(R.id.main_msg);
   textView.setText(mainMessage);

   Button positiveBtn = (Button) view.findViewById(R.id.dialog_positive_btn);
   Button negativeBtn = (Button) view.findViewById(R.id.dialog_negative_btn);

   positiveBtn.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
          dismiss();
          if (positiveListener != null) {
              positiveListener.onClick(view);
          }
       }
   });
   negativeBtn.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
          dismiss();

          if (negativeListener != null) [
              negativeListener.onClick(view);
          }
       }
    });
    return view;
  }

  @Override
  public Dialog onCreateDialog(Bundle savedInstanceState) {

    Dialog dialog = super.onCreateDialog(savedInstanceState);
    dialog.setCanceledOnTouchOutside(true);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

    dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
    dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM |
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    dialog.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_FULLSCREEN
            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
    return dialog;
 }
 public void setMessage(final String msg) {
     mainMessage = new String(msg);
 }

 public void setPositiveButton(View.OnClickListener listener) {
     positiveListener = listener;
 }
</code>```

this one.

How to disable click of dialogfragment outside on android?

thanks.

答: Plain setCancelable(false) (without Dialog.) in onCreateView worked for me</p>

Body:
I use extends DialogFragment

I want except dialog, disable click on android.

I try setCanceledOnTouchOutside(true) but it doesn't not work.

and please check my source.

public class QuestDialog extends DialogFragment {
   private String mainMessage = "";
   private View.OnClickListener positiveListener = null;
   private View.OnClickListener negativeListener = null;

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

   View view = inflater.inflate(R.layout.main_dialog, container, false);

   TextView textView = (TextView) view.findViewById(R.id.main_msg);
   textView.setText(mainMessage);

   Button positiveBtn = (Button) view.findViewById(R.id.dialog_positive_btn);
   Button negativeBtn = (Button) view.findViewById(R.id.dialog_negative_btn);

   positiveBtn.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
          dismiss();
          if (positiveListener != null) {
              positiveListener.onClick(view);
          }
       }
   });
   negativeBtn.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
          dismiss();

          if (negativeListener != null) [
              negativeListener.onClick(view);
          }
       }
    });
    return view;
  }

  @Override
  public Dialog onCreateDialog(Bundle savedInstanceState) {

    Dialog dialog = super.onCreateDialog(savedInstanceState);
    dialog.setCanceledOnTouchOutside(true);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

    dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
    dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM |
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    dialog.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_FULLSCREEN
            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
    return dialog;
 }
 public void setMessage(final String msg) {
     mainMessage = new String(msg);
 }

 public void setPositiveButton(View.OnClickListener listener) {
     positiveListener = listener;
 }

this one.

How to disable click of dialogfragment outside on android?

thanks.


问:
Webpack: Cannot destructure property `curry` of 'undefined' or 'null'
After compiling my application using webpack & babel-loader for the browser, the following error appears right off the bat before the main function starts:

```<code>Uncaught TypeError: Cannot destructure property `curry` of 'undefined' or 'null'.
    at Object../node_modules/@qzdio/f/lib/combinators/sync.js (index-c1596672f4.js:formatted:268)
    at n (runtime-74c3f0da77.js:formatted:10)
    at Object../node_modules/@qzdio/f/lib/combinators/index.js (index-c1596672f4.js:formatted:251)
    at n (runtime-74c3f0da77.js:formatted:10)
    at Object../node_modules/@qzdio/f/lib/index.js (index-c1596672f4.js:formatted:723)
    at n (runtime-74c3f0da77.js:formatted:10)
    at Object../dist/graph/visualizer/src/index.js (index-c1596672f4.js:formatted:9)
    at n (runtime-74c3f0da77.js:formatted:10)
    at window.webpackJsonp (runtime-74c3f0da77.js:formatted:26)
    at index-c1596672f4.js:formatted:1
</code>```

The faulty code is the ES5 transpilation of the following:

```<code>import R from 'ramda';
const { curry } = R;

// I :: a -> a
const I = (x) => x;
...
</code>```

Where the said code is from a private functional library that relies on ramda and bluebird. The library is used and working under Node.js 8.9.1.

The webpack config used is straight up from philipwalton's webpack-esnext-boilerplate (great to start with :D)

Versions:

babel-cli: ^6.26.0,

babel-loader: ^7.1.2,

webpack: ^3.8.1,

Browser: Google Chrome Version 62.0.3202.89 (Official Build) (64-bit),

Node.js: 8.9.1,

npm: 5.5.1

What is the source of the error and how can it be resolved?

Cheers ✨

答:
You have to use import { curry } from 'ramda'.  You can see here how rambda is exporting it's modules.  It doesn't export the ramda module itself, but rather the individual functions.

If you want to access additional methods, you can use this for example:

import { curry, addIndex, clone } from 'ramda'

Body:
After compiling my application using webpack & babel-loader for the browser, the following error appears right off the bat before the main function starts:

Uncaught TypeError: Cannot destructure property `curry` of 'undefined' or 'null'.
    at Object../node_modules/@qzdio/f/lib/combinators/sync.js (index-c1596672f4.js:formatted:268)
    at n (runtime-74c3f0da77.js:formatted:10)
    at Object../node_modules/@qzdio/f/lib/combinators/index.js (index-c1596672f4.js:formatted:251)
    at n (runtime-74c3f0da77.js:formatted:10)
    at Object../node_modules/@qzdio/f/lib/index.js (index-c1596672f4.js:formatted:723)
    at n (runtime-74c3f0da77.js:formatted:10)
    at Object../dist/graph/visualizer/src/index.js (index-c1596672f4.js:formatted:9)
    at n (runtime-74c3f0da77.js:formatted:10)
    at window.webpackJsonp (runtime-74c3f0da77.js:formatted:26)
    at index-c1596672f4.js:formatted:1

The faulty code is the ES5 transpilation of the following:

import R from 'ramda';
const { curry } = R;

// I :: a -> a
const I = (x) => x;
...

Where the said code is from a private functional library that relies on ramda and bluebird. The library is used and working under Node.js 8.9.1.

The webpack config used is straight up from philipwalton's webpack-esnext-boilerplate (great to start with :D)

Versions:

babel-cli: ^6.26.0,

babel-loader: ^7.1.2,

webpack: ^3.8.1,

Browser: Google Chrome Version 62.0.3202.89 (Official Build) (64-bit),

Node.js: 8.9.1,

npm: 5.5.1

What is the source of the error and how can it be resolved?

Cheers ✨


问:
Creating variables using existing variables in the dataset
I was dealing with creating a variable for a mean score difference between male and female students for each classroom. Class id stands for each classroom. Gender is for each student and the last column is their scores.

I want to have a mean difference value (female(1)-male(0)) for each classroom;

My data looks like this:

```<code>data <- matrix(c(1,1,1,1,2,2,2,2,3,3,3,3,
                 0,1,1,0,1,0,0,1,0,1,1,0,
                 20,25,22,21,30,35,32,31,40,45,42,44),
                 nrow=12,
                 ncol=3)
colnames(data) <- c("class id","gender","score")

> data
         class id    gender score
 [1,]        1         0    20
 [2,]        1         1    25
 [3,]        1         1    22
 [4,]        1         0    21
 [5,]        2         1    30
 [6,]        2         0    35
 [7,]        2         0    32
 [8,]        2         1    31
 [9,]        3         0    40
 [10,]        3        1    45
 [11,]        3        1    42
 [12,]        3        0    44
</code>```

I need it to be something like:

```<code>> data
            class id  mean score
 [1,]        1             3
 [2,]        2            -3
 [3,]        3            1.5
</code>```

Any thoughts?

Thanks!

答:
Here's a solution that uses the tidyverse functions

```<code>library(tidyverse)
data %>% as_tibble %>%
  group_by(`class id`, gender) %>%
  summarize(mean=mean(score)) %>%
  spread(gender, mean) %>%
  mutate(mean_score=`1`-`0`) %>%
  select(`class id`, mean_score)
</code>```

Working with a tibble or data.frame is much easier than a matrix, so you start by converting your input data. Then we calculate a mean per gender. Then we spread it out to have a value for each gender in the same record for each class. Then we just take the difference. Note the backticks because of the odd column names in this example.

Alternatively you could do something like this

```<code>data %>% as_tibble %>%
  group_by(`class id`) %>%
  summarize(mean_score=mean(score[gender==1]) - mean(score[gender==0]))
</code>```

which avoids the reshaping.

Body:
I was dealing with creating a variable for a mean score difference between male and female students for each classroom. Class id stands for each classroom. Gender is for each student and the last column is their scores.

I want to have a mean difference value (female(1)-male(0)) for each classroom;

My data looks like this:

data <- matrix(c(1,1,1,1,2,2,2,2,3,3,3,3,
                 0,1,1,0,1,0,0,1,0,1,1,0,
                 20,25,22,21,30,35,32,31,40,45,42,44),
                 nrow=12,
                 ncol=3)
colnames(data) <- c("class id","gender","score")

> data
         class id    gender score
 [1,]        1         0    20
 [2,]        1         1    25
 [3,]        1         1    22
 [4,]        1         0    21
 [5,]        2         1    30
 [6,]        2         0    35
 [7,]        2         0    32
 [8,]        2         1    31
 [9,]        3         0    40
 [10,]        3        1    45
 [11,]        3        1    42
 [12,]        3        0    44

I need it to be something like:

> data
            class id  mean score
 [1,]        1             3
 [2,]        2            -3
 [3,]        3            1.5

Any thoughts?

Thanks!

Body:
Here's a solution that uses the tidyverse functions

library(tidyverse)
data %>% as_tibble %>%
  group_by(`class id`, gender) %>%
  summarize(mean=mean(score)) %>%
  spread(gender, mean) %>%
  mutate(mean_score=`1`-`0`) %>%
  select(`class id`, mean_score)

Working with a tibble or data.frame is much easier than a matrix, so you start by converting your input data. Then we calculate a mean per gender. Then we spread it out to have a value for each gender in the same record for each class. Then we just take the difference. Note the backticks because of the odd column names in this example.

Alternatively you could do something like this

data %>% as_tibble %>%
  group_by(`class id`) %>%
  summarize(mean_score=mean(score[gender==1]) - mean(score[gender==0]))

which avoids the reshaping.


问:
AngularJS $http.get passing variable as param key
I am new to AngularJS and trying to see if this is possible.  I have looked at a lot of $http.get questions online but can't find an answer to this.

I have an api call that has three different parameter key possibilities.

```<code>$http.get(url, {params : {$scope.searchBy : $scope.value}})
</code>```

$scope.searchBy is marked as a syntax error. It has 3 possible values from a dropdown list.

I tried var search = $scope.searchBy; but when I use {params : {search : $scope.value}} the value is "search" and not $scope.searchBy.

Any suggestions how this can be done without if statements and separate api calls?

Thank you.

答:
You will have to do something like this as this is valid javascript syntax.

```<code>var paramValues = {};
paramValues[$scope.searchBy] = $scope.value;
return $http.get(url, {params: paramValues});
</code>```

When you define an object using the syntax you have in your question the property/field name must be a known constant. If it is variable, which you want in this case, then you can create the object first and then set the value using the obj[propertyName] = someValue; notation.

Body:
I am new to AngularJS and trying to see if this is possible.  I have looked at a lot of $http.get questions online but can't find an answer to this.

I have an api call that has three different parameter key possibilities.

$http.get(url, {params : {$scope.searchBy : $scope.value}})

$scope.searchBy is marked as a syntax error. It has 3 possible values from a dropdown list.

I tried var search = $scope.searchBy; but when I use {params : {search : $scope.value}} the value is "search" and not $scope.searchBy.

Any suggestions how this can be done without if statements and separate api calls?

Thank you.

Body:
You will have to do something like this as this is valid javascript syntax.

var paramValues = {};
paramValues[$scope.searchBy] = $scope.value;
return $http.get(url, {params: paramValues});

When you define an object using the syntax you have in your question the property/field name must be a known constant. If it is variable, which you want in this case, then you can create the object first and then set the value using the obj[propertyName] = someValue; notation.


问:
How to flatten / merge overlapping time periods
I have a large data set of time periods, defined by a 'start' and and an 'end' column. Some of the periods overlap.

I would like to combine (flatten / merge / collapse) all overlapping time periods to have one 'start' value and one 'end' value.

Some example data:

```<code>  ID      start        end
1  A 2013-01-01 2013-01-05
2  A 2013-01-01 2013-01-05
3  A 2013-01-02 2013-01-03
4  A 2013-01-04 2013-01-06
5  A 2013-01-07 2013-01-09
6  A 2013-01-08 2013-01-11
7  A 2013-01-12 2013-01-15
</code>```

Desired result:

```<code>  ID      start        end
1  A 2013-01-01 2013-01-06
2  A 2013-01-07 2013-01-11
3  A 2013-01-12 2013-01-15
</code>```

What I have tried:

```<code>  require(dplyr)
  data <- structure(list(ID = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L), class = "factor", .Label = "A"),
    start = structure(c(1356998400, 1356998400, 1357084800, 1357257600,
    1357516800, 1357603200, 1357948800), tzone = "UTC", class = c("POSIXct",
    "POSIXt")), end = structure(c(1357344000, 1357344000, 1357171200,
    1357430400, 1357689600, 1357862400, 1358208000), tzone = "UTC", class = c("POSIXct",
    "POSIXt"))), .Names = c("ID", "start", "end"), row.names = c(NA,
-7L), class = "data.frame")

remove.overlaps <- function(data){
data2 <- data
for ( i in 1:length(unique(data$start))) {
x3 <- filter(data2, start>=data$start[i] & start<=data$end[i])
x4 <- x3[1,]
x4$end <- max(x3$end)
data2 <- filter(data2, start<data$start[i] | start>data$end[i])
data2 <- rbind(data2,x4)
}
data2 <- na.omit(data2)}

data <- remove.overlaps(data)
</code>```

答:
@David Arenburg's answer is great - but I ran into an issue where an earlier interval ended after a later interval - but using last in the summarise call resulted in the wrong end date. I'd suggest changing first(start) and last(end) to min(start) and max(end)

```<code>data %>%
  group_by(ID) %>%
  mutate(indx = c(0, cumsum(as.numeric(lead(start)) >
                     cummax(as.numeric(end)))[-n()])) %>%
  group_by(ID, indx) %>%
  summarise(start = min(start), end = max(end))
</code>```

Also, as @Jonno Bourne mentioned, sorting by start and any grouping variables is important before applying the method.

ContentLicense: CC BY-SA 4.0

Body:
I have a large data set of time periods, defined by a 'start' and and an 'end' column. Some of the periods overlap.

I would like to combine (flatten / merge / collapse) all overlapping time periods to have one 'start' value and one 'end' value.

Some example data:

  ID      start        end
1  A 2013-01-01 2013-01-05
2  A 2013-01-01 2013-01-05
3  A 2013-01-02 2013-01-03
4  A 2013-01-04 2013-01-06
5  A 2013-01-07 2013-01-09
6  A 2013-01-08 2013-01-11
7  A 2013-01-12 2013-01-15

Desired result:

  ID      start        end
1  A 2013-01-01 2013-01-06
2  A 2013-01-07 2013-01-11
3  A 2013-01-12 2013-01-15

What I have tried:

  require(dplyr)
  data <- structure(list(ID = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L), class = "factor", .Label = "A"),
    start = structure(c(1356998400, 1356998400, 1357084800, 1357257600,
    1357516800, 1357603200, 1357948800), tzone = "UTC", class = c("POSIXct",
    "POSIXt")), end = structure(c(1357344000, 1357344000, 1357171200,
    1357430400, 1357689600, 1357862400, 1358208000), tzone = "UTC", class = c("POSIXct",
    "POSIXt"))), .Names = c("ID", "start", "end"), row.names = c(NA,
-7L), class = "data.frame")

remove.overlaps <- function(data){
data2 <- data
for ( i in 1:length(unique(data$start))) {
x3 <- filter(data2, start>=data$start[i] & start<=data$end[i])
x4 <- x3[1,]
x4$end <- max(x3$end)
data2 <- filter(data2, start<data$start[i] | start>data$end[i])
data2 <- rbind(data2,x4)
}
data2 <- na.omit(data2)}

data <- remove.overlaps(data)

Body:
@David Arenburg's answer is great - but I ran into an issue where an earlier interval ended after a later interval - but using last in the summarise call resulted in the wrong end date. I'd suggest changing first(start) and last(end) to min(start) and max(end)

data %>%
  group_by(ID) %>%
  mutate(indx = c(0, cumsum(as.numeric(lead(start)) >
                     cummax(as.numeric(end)))[-n()])) %>%
  group_by(ID, indx) %>%
  summarise(start = min(start), end = max(end))

Also, as @Jonno Bourne mentioned, sorting by start and any grouping variables is important before applying the method.


问:
Minor Upgrade in Wix (Not a Patch)
I am trying to implement a Minor Upgrade (not a patch) using WiX. I am not sure if there are many tutorials or samples for this, including the steps to uninstall it. Can anyone please help?</p>

答:
First of all there is very little benefit in using a minor upgrade because basically you make another MSI file that is the same as the existing one except for the updated files you want to update. The ProductCode is the same. It is applied with a command line such as:

msiexec /I [path to msi] REINSTALLMODE=vomus REINSTALL=ALL

There's really no advantage to this because you might as well make a major upgrade MSI which is a fresh install for new clients and it happens to upgrade any older existing installed products, using the same command line.

The basic documentation is here:

https://msdn.microsoft.com/en-us/library/windows/desktop/aa370037(v=vs.85).aspx

explaining the ProductCode, ProductVersion rules. You also need to follow component rules in a minor upgrade, as with a patch.

Title: Minor Upgrade in Wix (Not a Patch)


问:
Status bar color isn't changing on iPhone X to the left and right of notch
Hello I updated to new Xcode 9 and started using safeAreaLayout guide to support iphone X. From xib, I just used safeAreaLayout guide and adjusted by top and bottom constraints to safeArea.

Here is what I got

iphone X (iOS 11)

iphone 6 (iOS 11)

As you can see my custom navigation bar is down 20pxls

iphone 6 (iOS 9 and 10)

Here you can see how the navigation bar starts from 0 and status bar is merged.

Actually,

1) I want the green color to filled by notch.
2) Status Bar should not show in white color but green color as in 3 image.

I have searched many solutions. But none is working. So I need help.

Regards
Ranjit

答:
The status bar's background is showing the color of the view below it. To change the "color of the status bar", you need to place a view behind it and give that view a background color.

To solve your problem, the easiest solution is to create a separate view that is always the height of the status bar and has the same background color as your custom navigation view.

To do this, pin the new view's top to the top of the superview, and pin its bottom to the top of your custom navigation view.

This solution is simpler than adding the height of the top safe area inset to your custom navigation view because it avoids adjusting the custom view's layout to account for this extra variable height.


问:
Android Studio AVD Manager button is disabled
I'm very new to Android development and have never used Android Studio before. I set it up, got my app working on my phone and left it alone for a few weeks. Upon returning, I could not find the Android Studio executable on my computer, so I reinstalled it and restarted on the same project.

Not sure if this has to do with the AVD Manager button being grayed out. Things I have tried:

Making sure my SDK path is correct

Running Android Studio as administrator

Launching the AVD Manager executable from windows. I can create a virtual device but doesn't affect disabled AVD Manager button when restarting Android Studio.

Installing Intel X86 Atom System Image and Google APIs in SDK Manager, under API 24.Everything under API 25 is installed.

Any help is appreciated. Thank you!

答:
For anyone seeing this problem following the React Native tutorial make sure to click the "Configure" button in the Event Log next to the log text that reads "Frameworks detected: Android framework is detected in the project"

This action seems to be what configures the project to be an Android project.


问:
When is a value type / reference type constraint useful in C#?
I'm looking for simple examples that demonstrate when the value type / reference type constraints are useful.

```<code>... where T : struct  // when is this useful?
... where T : class   // and what about this?
</code>```

I remember seeing some very nice examples in the past but I just can't find them.

答:
It allows you to use as operator on T if it is T:class.

It forbids you to compare T with null if T is T:struct.

Note that if you omit T:class then you can compare T to null even when T is a value type.

[Note: I needed to edit this post a few times before it got correct. At least I hope it is now correct.]

Body:
I'm looking for simple examples that demonstrate when the value type / reference type constraints are useful.

... where T : struct  // when is this useful?
... where T : class   // and what about this?

I remember seeing some very nice examples in the past but I just can't find them.


问:
Benefit of using forEachOrdered with Parallel streams
The official Oracle documentation says:

Note that you may lose the benefits of parallelism if you use
  operations like forEachOrdered with parallel streams.
  Oracle - Parallelism

Why would anyone use forEachOrdered with parallel stream if we are losing parallelism?

答:
depending on the situation, one does not lose all the benefits of parallelism by using ForEachOrdered.

Assume that we have something as such:

```<code>stringList.parallelStream().map(String::toUpperCase)
                           .forEachOrdered(System.out::println);
</code>```

In this case, we can guarantee that the ForEachOrdered terminal operation will print out the strings in uppercase in the encounter order but we should not assume that the elements will be passed to the map intermediate operation in the same order they were picked for processing. The map operation will be executed by multiple threads concurrently. So one may still benefit from parallelism but it's just that we’re not leveraging the full potential of parallelism. To conclude, we should use ForEachOrdered when it matters to perform an action in the encounter order of the stream.

edit following your comment:

What happens when you skip map operation? I am more interested in
  forEachOrdered right after parallelStream()

if you're referring to something as in:

```<code> stringList.parallelStream().forEachOrdered(action);
</code>```

there is no benefit in doing such thing and I doubt that's what the designers had in mind when they decided to create the method. in such case, it would make more sense to do:

```<code>stringList.stream().forEach(action);
</code>```

to extend on your question "Why would anyone use forEachOrdered with parallel stream if we are losing parallelism", say you wanted to perform an action on each element with respect to the streams encounter order; in such case you will need to use forEachOrdered as the forEach terminal operation is non deterministic when used in parallel hence there is one version for sequential streams and one specifically for parallel streams.

Body:
depending on the situation, one does not lose all the benefits of parallelism by using ForEachOrdered.

Assume that we have something as such:

stringList.parallelStream().map(String::toUpperCase)
                           .forEachOrdered(System.out::println);

In this case, we can guarantee that the ForEachOrdered terminal operation will print out the strings in uppercase in the encounter order but we should not assume that the elements will be passed to the map intermediate operation in the same order they were picked for processing. The map operation will be executed by multiple threads concurrently. So one may still benefit from parallelism but it's just that we’re not leveraging the full potential of parallelism. To conclude, we should use ForEachOrdered when it matters to perform an action in the encounter order of the stream.

edit following your comment:

What happens when you skip map operation? I am more interested in
  forEachOrdered right after parallelStream()

if you're referring to something as in:

 stringList.parallelStream().forEachOrdered(action);

there is no benefit in doing such thing and I doubt that's what the designers had in mind when they decided to create the method. in such case, it would make more sense to do:

stringList.stream().forEach(action);

to extend on your question "Why would anyone use forEachOrdered with parallel stream if we are losing parallelism", say you wanted to perform an action on each element with respect to the streams encounter order; in such case you will need to use forEachOrdered as the forEach terminal operation is non deterministic when used in parallel hence there is one version for sequential streams and one specifically for parallel streams.


问:
Git checkout branch doesn't change working directory
I am not exactly sure how to phrase this question, as I am new to git.  One of my coworkers was working on a feature in a branch called "rotation."  I wanted to make use of the code he wrote, so I ran git checkout rotation.  The main difference between master and rotation branches is that the rotation branch has an extra subdirectory titled rotation/.  However, after running git checkout, this subdirectory did not show up in my working directory.  How do I get this subdirectory to show up?  I did some googling and found that git doesn't make changes to your working directory when you git checkout a branch if those changes would conflict with tracked changes in your working directory.  However, this is not the case here, at least for the rotation/ subdirectory, as it does not even exist in master.  So why doesn't this subdirectory show up?  How do I get it to?

答:
In the following comments, I assume that there are three repositories, your own local repo, your coworker's repo, and a central repo. It sounds like you already have a local branch named rotation. If your coworker pushed her rotation branch to the central repo, you need to update that branch with your coworker's changes:

```<code>$ git checkout rotation
$ git pull origin rotation
</code>```

Note, that if your coworker only created a directory without adding any files, then she cannot commit it. Git does not track directories themselves. Instead, it tracks files and stores extra information about the directory where the file belongs.

Body:
In the following comments, I assume that there are three repositories, your own local repo, your coworker's repo, and a central repo. It sounds like you already have a local branch named rotation. If your coworker pushed her rotation branch to the central repo, you need to update that branch with your coworker's changes:

$ git checkout rotation
$ git pull origin rotation

Note, that if your coworker only created a directory without adding any files, then she cannot commit it. Git does not track directories themselves. Instead, it tracks files and stores extra information about the directory where the file belongs.


问:
create durations for different items in a single dataframe
How can I create durations for different items in a single dataframe

Example dataset

```<code>Item       Date           OnSale
apple      2017-01-01     Yes
orange     2017-01-01     Yes
orange     2017-01-02     Yes
orange     2017-01-03     No
apple      2017-01-02     No
apple      2017-01-03     No
apple      2017-01-04     No
apple      2017-01-05     Yes
</code>```

How do I calculate the number of days since an item has been on sale?

Desired output

```<code>Item       Date           OnSale      DaySinceSale
apple      2017-01-01     Yes         0
orange     2017-01-01     Yes         0
orange     2017-01-02     Yes         0
orange     2017-01-03     No          1
apple      2017-01-02     No          1
apple      2017-01-03     No          2
apple      2017-01-04     No          3
apple      2017-01-05     Yes         0
</code>```

答:
Try

```<code>df['DaySinceSale'] = df.groupby('Item')['OnSale'].apply(lambda x: (x == 'No') * (x == 'No').cumsum())

    Item    Date    OnSale  DaySinceSale
0   apple   2017-01-01  Yes 0
1   orange  2017-01-01  Yes 0
2   orange  2017-01-02  Yes 0
3   orange  2017-01-03  No  1
4   apple   2017-01-02  No  1
5   apple   2017-01-03  No  2
6   apple   2017-01-04  No  3
7   apple   2017-01-05  Yes 0
</code>```

You can also use series.multiply()

```<code>df.groupby('Item')['OnSale'].apply(lambda x: (x == 'No').multiply((x == 'No').cumsum()))
</code>```

Body:
How can I create durations for different items in a single dataframe

Example dataset

Item       Date           OnSale
apple      2017-01-01     Yes
orange     2017-01-01     Yes
orange     2017-01-02     Yes
orange     2017-01-03     No
apple      2017-01-02     No
apple      2017-01-03     No
apple      2017-01-04     No
apple      2017-01-05     Yes

How do I calculate the number of days since an item has been on sale?

Desired output

Item       Date           OnSale      DaySinceSale
apple      2017-01-01     Yes         0
orange     2017-01-01     Yes         0
orange     2017-01-02     Yes         0
orange     2017-01-03     No          1
apple      2017-01-02     No          1
apple      2017-01-03     No          2
apple      2017-01-04     No          3
apple      2017-01-05     Yes         0

Body:
Try

df['DaySinceSale'] = df.groupby('Item')['OnSale'].apply(lambda x: (x == 'No') * (x == 'No').cumsum())

    Item    Date    OnSale  DaySinceSale
0   apple   2017-01-01  Yes 0
1   orange  2017-01-01  Yes 0
2   orange  2017-01-02  Yes 0
3   orange  2017-01-03  No  1
4   apple   2017-01-02  No  1
5   apple   2017-01-03  No  2
6   apple   2017-01-04  No  3
7   apple   2017-01-05  Yes 0

You can also use series.multiply()

df.groupby('Item')['OnSale'].apply(lambda x: (x == 'No').multiply((x == 'No').cumsum()))


问:
Allocating unmanaged memory in managed .NET code
Hi I have a unmanaged function that takes a chunk of memory allocated by malloc and deallocates it later on in async manner. I want to wrap it into managed wrapper. Is following code OK?</p>

```<code>void managed_fx (byte data __gc[], size_t size)
{
    //  Pin the data
    byte __pin *pinned_data = &data [0];

    //  Copy data to the unmanaged buffer.
    void *unmanaged_data = malloc (size);
    memcpy (unmanaged_data, (byte*) pinned_data, size);

    //  Forward the call
    fx (unmanaged_data, size);
}
</code>```

答:
My MC++ is a little rusty, but I think __pin pins the source variable until "pinned_data" goes out of scope (at least, that's what the equivalent pin_ptr in C++/CLI does). You should generally un-pin it as soon as possible, i.e. you shouldn't call fx in the same scope for performance reasons.

Is pinning necessary at all in this case?

Yes. You want to access managed memory from unmanaged code.

Can gc deallocate it before memcpy

No. There is a strong reference to data, so the gc won't collect it. It might however collect some other object, and move data in memory in the compacting step. Then malloc would access the wrong memory area. Pinning prevents this, at the cost of additional bookkeeping for the GC (which is why you should un-pin objects as soon as possible).

Does malloc allocate an unmanaged memory even though it's used in managed code?

Yes.

OwnerDisplayName: martin

LastEditorDisplayName: MSalters

Body:
Hi I have a unmanaged function that takes a chunk of memory allocated by malloc and deallocates it later on in async manner. I want to wrap it into managed wrapper. Is following code OK?

void managed_fx (byte data __gc[], size_t size)
{
    //  Pin the data
    byte __pin *pinned_data = &data [0];

    //  Copy data to the unmanaged buffer.
    void *unmanaged_data = malloc (size);
    memcpy (unmanaged_data, (byte*) pinned_data, size);

    //  Forward the call
    fx (unmanaged_data, size);
}

OwnerDisplayName: Niki


问:
Prevent dialog on mobile screen from scrolling the body
I'm displaying a dialog on a mobile screen that's longer than the size of the screen (so it scrolls).

Here's the problem: When you scroll past the bottom of the dialog (I happen to be using Bootstrap 3), I expect it to just stop. Instead, it starts scrolling the underlying body. I've tried everything that's been suggested in this recommended solution, and it still doesn't freaking work!

Here's a live demo of the issue on JSbin, for your viewing pleasure

http://jsbin.com/EdAhAsU/1/

Note: To reproduce the issue, access it using a mobile - any mobile - and attempt to scroll past the end of the dialog. Tried it on Android, and iPhone - doesn't work for either.

Thanks!

答:
The easiest option is to use the overscroll-behavior CSS property on the popup.

```<code>.modal {
overscroll-behavior: contain;
}
</code>```

This property was added to CSS specifically for this use case.

Body:
The easiest option is to use the overscroll-behavior CSS property on the popup.

.modal {
overscroll-behavior: contain;
}

This property was added to CSS specifically for this use case.


问:
JSON print nested list from API request
I'm querying an API that interfaces to MariaDB and this is how I get the data back.

```<code>{'TestTable': {'columns': ['Name', 'Id'], 'records': [['Jack', 1], ['Jill', 2]]}}
</code>```

What I'm trying to achieve is to print the columns before the records like so:

Name: Jack
Id: 1
Name: Jill
Id: 2
```

<p>I tried to take the data and put the columns and records into different lists and then my idea was to use an if to match the indexes and if match to print the to the format above, but it was the wrong index.  Unfortuantely after trying to get it to work after about 5 different ways and 3 hours, I realized I had absolutely no idea what I was doing:</p>

```jsonData = json.loads(reqGet.text)
columns = jsonData['TestTable']['columns']
records = jsonData['TestTable']['records']

for idx, val in enumerate(records):
    print(idx, val)
```

<p>Output:</p>

<pre class="lang-none prettyprint-override"><code>0 ['Jack', 1]
1 ['Jill', 2]
</code>```

Any thoughts besides "Have you considered digging ditches?", would be great.

答:
```<code>d={'TestTable': {'columns': ['Name', 'Id'], 'records': [['Jack', 1], ['Jill', 2]]}}

for record in d['TestTable']['records']:
    for col_name, value in zip(d['TestTable']['columns'], record):
        print('{}: {}'.format(col_name, value))
</code>```

will print out

```<code>Name: Jack
Id: 1
Name: Jill
Id: 2
</code>```

Title: JSON print nested list from API request

Body:
I'm querying an API that interfaces to MariaDB and this is how I get the data back.

{'TestTable': {'columns': ['Name', 'Id'], 'records': [['Jack', 1], ['Jill', 2]]}}

What I'm trying to achieve is to print the columns before the records like so:

Name: Jack
Id: 1
Name: Jill
Id: 2

I tried to take the data and put the columns and records into different lists and then my idea was to use an if to match the indexes and if match to print the to the format above, but it was the wrong index.  Unfortuantely after trying to get it to work after about 5 different ways and 3 hours, I realized I had absolutely no idea what I was doing:

jsonData = json.loads(reqGet.text)
columns = jsonData['TestTable']['columns']
records = jsonData['TestTable']['records']

for idx, val in enumerate(records):
    print(idx, val)

Output:

0 ['Jack', 1]
1 ['Jill', 2]

Any thoughts besides "Have you considered digging ditches?", would be great.

Body:
d={'TestTable': {'columns': ['Name', 'Id'], 'records': [['Jack', 1], ['Jill', 2]]}}

for record in d['TestTable']['records']:
    for col_name, value in zip(d['TestTable']['columns'], record):
        print('{}: {}'.format(col_name, value))

will print out

Name: Jack
Id: 1
Name: Jill
Id: 2


问:
Selenium WebDriver click child element
I'm using selenium and I want to click a child element with 2 as value.

This is the full code:

```<code><div class="dialer-keypad">
    <div class="dialpad-row">
        <div class="key">
            <div class="value">1</div>
            <div class="letters"></div>
        </div>
        <div class="key">
            <div class="value">2</div>
            <div class="letters">ABC</div>
        </div>
        <div class="key">
            <div class="value">3</div>
            <div class="letters">DEF</div>
        </div>
    </div>
    <div class="dialpad-row">
        <div class="key">
            <div class="value">4</div>
            <div class="letters">GHI</div>
        </div>
        <div class="key">
            <div class="value">5</div>
            <div class="letters">JKL</div>
        </div>
        <div class="key">
            <div class="value">6</div>
            <div class="letters">MNO</div>
        </div>
    </div>
</div>
</code>```

So my question is How can I click this element?

```<code><div class="value">2</div>
</code>```

答:
Simply use xpath</p>

```<code>//div[contains (@class,'value') and contains (text(),'2')]
</code>```

Title: Selenium WebDriver click child element

Body:
I'm using selenium and I want to click a child element with 2 as value.

This is the full code:

1

2

ABC

3

DEF

4

GHI

5

JKL

6

MNO

So my question is How can I click this element?

2

Body:
Simply use xpath

//div[contains (@class,'value') and contains (text(),'2')]


问:
Python - How to filter list of dics based on another list of dics
can you please give me advice, how to speed up things in Python

My current issue - code works - but eat all the memory - as I have 2 included for loop (

So - I have 2 lists of dicts and need filter it based on logic below.

```<code>  count = 0
  size = 0
  latest = dateutil.parser.parse('1900-01-01T00:00:00.000')

  for obj_seg in objects_segments[1]:
    exclude = False
    for obj in objects[1]:
      if obj['name'] in obj_seg['name']:
        exclude = True
        break

    if not exclude:
      d = dateutil.parser.parse(obj_seg['last_modified'])
      if d > latest:
        latest = d
      size+=obj_seg['bytes']
      count+=1
</code>```

Problem that "objects_segments[1]" can include up to 30M elements, and "objects[1]" - up to 100K...

What the better way to operate with such data without this ugly included for_loop (

UPD1: Change boolean logic and add break to second cycle. Tnx @nthall

答:
Well, one easy improvement would be to stop the inner loop after setting exclude = False -- right now you will continue through the loop unnecessarily.

```<code>for obj in objects[1]:
  if obj['name'] not in obj_seg['name']:
    exclude = False
    break
</code>```

Body:
can you please give me advice, how to speed up things in Python

My current issue - code works - but eat all the memory - as I have 2 included for loop (

So - I have 2 lists of dicts and need filter it based on logic below.

  count = 0
  size = 0
  latest = dateutil.parser.parse('1900-01-01T00:00:00.000')

  for obj_seg in objects_segments[1]:
    exclude = False
    for obj in objects[1]:
      if obj['name'] in obj_seg['name']:
        exclude = True
        break

    if not exclude:
      d = dateutil.parser.parse(obj_seg['last_modified'])
      if d > latest:
        latest = d
      size+=obj_seg['bytes']
      count+=1

Problem that "objects_segments[1]" can include up to 30M elements, and "objects[1]" - up to 100K...

What the better way to operate with such data without this ugly included for_loop (

UPD1: Change boolean logic and add break to second cycle. Tnx @nthall

Body:
Well, one easy improvement would be to stop the inner loop after setting exclude = False -- right now you will continue through the loop unnecessarily.

for obj in objects[1]:
  if obj['name'] not in obj_seg['name']:
    exclude = False
    break


问:
Filter Firestore with multiple where not working
I have this docs

```<code>let wall = firebase.wallCollection;
</code>```

then I want to filter it with multiple where:

location (location == filterLocation)

price (price < filterMaximumPrice)

This is my filter methods on Vue

```<code>filterResult(){
    let self = this;
    if(self.filterLocation!=""){
        wall.where('location','==', self.filterLocation);
        console.log("Location flag");
    }
    if(parseInt(self.filterMaximumPrice)!=0){
        dinding.where('price','<', parseInt(self.filterMaximumPrice));
        console.log("Price flag");
    }

    wall.get()
    .then(snapshots => {
        snapshots.forEach(doc => {
        self.listFilteredWall.push(doc.data());
        }, this);
    })
}
</code>```

The problem is that 2 where function not working and still give all wall output without filter.

How to fix this?

答:
CollectionReference extends Query.  The result of where() is a new Query:

Creates a new query that returns only documents that include the
  specified fields and where the values satisfy the constraints
  provided.

You need to retain the result Query if each where() and use it for the get().  Something like this:

```<code>filterResult(){
    let self = this;
    let query = wall;

    if(self.filterLocation!=""){
        query = query.where('location','==', self.filterLocation);
        console.log("Location flag");
    }
    if(parseInt(self.filterMaximumPrice)!=0){
        query = query.where('price','<', parseInt(self.filterMaximumPrice));
        console.log("Price flag");
    }

    query.get()
    .then(snapshots => {
        snapshots.forEach(doc => {
        self.listFilteredWall.push(doc.data());
        }, this);
    })
}
</code>```

Body:
I have this docs

let wall = firebase.wallCollection;

then I want to filter it with multiple where:

location (location == filterLocation)

price (price < filterMaximumPrice)

This is my filter methods on Vue

filterResult(){
    let self = this;
    if(self.filterLocation!=""){
        wall.where('location','==', self.filterLocation);
        console.log("Location flag");
    }
    if(parseInt(self.filterMaximumPrice)!=0){
        dinding.where('price','<', parseInt(self.filterMaximumPrice));
        console.log("Price flag");
    }

    wall.get()
    .then(snapshots => {
        snapshots.forEach(doc => {
        self.listFilteredWall.push(doc.data());
        }, this);
    })
}

The problem is that 2 where function not working and still give all wall output without filter.

How to fix this?

Body:
CollectionReference extends Query.  The result of where() is a new Query:

Creates a new query that returns only documents that include the
  specified fields and where the values satisfy the constraints
  provided.

You need to retain the result Query if each where() and use it for the get().  Something like this:

filterResult(){
    let self = this;
    let query = wall;

    if(self.filterLocation!=""){
        query = query.where('location','==', self.filterLocation);
        console.log("Location flag");
    }
    if(parseInt(self.filterMaximumPrice)!=0){
        query = query.where('price','<', parseInt(self.filterMaximumPrice));
        console.log("Price flag");
    }

    query.get()
    .then(snapshots => {
        snapshots.forEach(doc => {
        self.listFilteredWall.push(doc.data());
        }, this);
    })
}


问:
Check if an element has event listener on it. No jQuery
How to check if an element has event listener on it, if I use an inline function on it like the code below? Because I have a function that recalls the function and add the event listener, but it cause to have duplication event listener causing it to trigger a function twice. How can I check it so I can prevent it to add an event listener if is it already exist?  </p>

```<code>for (var a = 0;a<formFieldInput.length;a++) {
    if(formFieldInput[a].hasAttribute("name") && formFieldInput[a].attributes.title.value !== "Valid Until") {
        formFieldInput[a].addEventListener("click",function(event) {
            toggleFieldList(event,"show");
        });
    }
</code>```

答:
You don't need to. Just slap it on there as many times as you want and as often as you want. MDN explains identical event listeners:

If multiple identical EventListeners are registered on the same
EventTarget with the same parameters, the duplicate instances are
discarded. They do not cause the EventListener to be called twice, and
they do not need to be removed manually with the removeEventListener
method.

Note, however that when using an anonymous function as the handler, such listeners will NOT be identical, because anonymous functions are not identical even if defined using the SAME unchanging source-code called repeatedly, even if in a loop.

Body:
How to check if an element has event listener on it, if I use an inline function on it like the code below? Because I have a function that recalls the function and add the event listener, but it cause to have duplication event listener causing it to trigger a function twice. How can I check it so I can prevent it to add an event listener if is it already exist?

for (var a = 0;a<formFieldInput.length;a++) {
    if(formFieldInput[a].hasAttribute("name") && formFieldInput[a].attributes.title.value !== "Valid Until") {
        formFieldInput[a].addEventListener("click",function(event) {
            toggleFieldList(event,"show");
        });
    }


答:
Use property accessor bracket notation
 to construct the desired params object:     </p>

```<code>var config = { params: {} };
config.params[$scope.searchBy] = $scope.value;

$http.get(url, config);
</code>```

Title: AngularJS $http.get passing variable as param key

Body:
I am new to AngularJS and trying to see if this is possible.  I have looked at a lot of $http.get questions online but can't find an answer to this.

I have an api call that has three different parameter key possibilities.

$http.get(url, {params : {$scope.searchBy : $scope.value}})

$scope.searchBy is marked as a syntax error. It has 3 possible values from a dropdown list.

I tried var search = $scope.searchBy; but when I use {params : {search : $scope.value}} the value is "search" and not $scope.searchBy.

Any suggestions how this can be done without if statements and separate api calls?

Thank you.

Body:
Use property accessor bracket notation
 to construct the desired params object:

var config = { params: {} };
config.params[$scope.searchBy] = $scope.value;

$http.get(url, config);


问:
R - Understanding pipes and the magrittr syntax
I am trying out pipes and the magrittr package.
Although it seems somewhat easy to understand, I have a hard time understanding how to write conditional subsetting with pipes.

For a dataset, you can use 'filter' function and others but it gets  unclear for a vector (at least to me).

For example, if I want to subset values greater than 2, how am I supposed to do that?
I know there is the aliases available but they did something funky yesterday.

I'd like to understand how to write my pipes using [and <for example but also using the aliases.
Can you provide me with some examples and compare the two syntax?
Like

1) subsetting of a vector and retrieving values greater/lower than 2

2) how to combine two logical expressions (that I would normally do with & or |...)

```<code>Num1 <-
DataSet$myvariable %>%
strsplit(split = " ") %>%
lengths() %>% is_less_than(2) %>% #subset?
</code>```

How to extract the values when I have my TRUE and FALSE?

Thanks a lot

答:
To subset a vector with a condition, you can do the following:

```<code>library(magrittr)

1:10 %>%  `<`(5) %>%  `[`(1:10,.)
</code>```

or:

```<code>1:10 %>% `<`(5) %>% (1:10)[.]
# [1] 1 2 3 4
</code>```

These are equivalent to:

```<code>(1:10)[1:10 < 5]
</code>```

The reason I am placing the . after 1:10 in `[`(1:10,.), but placing it (implicitly) before 5 in `<`(5) is because for the latter, I am feeding in the vector 1:10, whereas for the former, I am feeding in the condition from 1:10 < 5.

To subset a dataset with a condition from a vector:

```<code>mtcars$cyl %>% `<`(5) %>% `[`(mtcars, ., )
</code>```

or:

```<code>mtcars$cyl %>% `<`(5) %>% mtcars[.,]
</code>```

These are equivalent to:

```<code>mtcars[mtcars$cyl < 5,]
</code>```

The extra comma in `[`(mtcars, ., ) is needed because you are subsetting dataframes intead of vectors, just like the difference between (1:10)[1:10 < 5] and mtcars[mtcars$cyl < 5,]

Result:

```<code>                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Datsun 710     22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Merc 240D      24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230       22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Toyota Corona  21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2
Volvo 142E     21.4   4 121.0 109 4.11 2.780 18.60  1  1    4    2
</code>```

Body:
I am trying out pipes and the magrittr package.
Although it seems somewhat easy to understand, I have a hard time understanding how to write conditional subsetting with pipes.

For a dataset, you can use 'filter' function and others but it gets  unclear for a vector (at least to me).

For example, if I want to subset values greater than 2, how am I supposed to do that?
I know there is the aliases available but they did something funky yesterday.

I'd like to understand how to write my pipes using [and <for example but also using the aliases.
Can you provide me with some examples and compare the two syntax?
Like

1) subsetting of a vector and retrieving values greater/lower than 2

2) how to combine two logical expressions (that I would normally do with & or |...)

Num1 <-
DataSet$myvariable %>%
strsplit(split = " ") %>%
lengths() %>% is_less_than(2) %>% #subset?

How to extract the values when I have my TRUE and FALSE?

Thanks a lot

Body:
To subset a vector with a condition, you can do the following:

library(magrittr)

1:10 %>%  `<`(5) %>%  `[`(1:10,.)

or:

1:10 %>% `<`(5) %>% (1:10)[.]
# [1] 1 2 3 4

These are equivalent to:

(1:10)[1:10 < 5]

The reason I am placing the . after 1:10 in `[`(1:10,.), but placing it (implicitly) before 5 in `<`(5) is because for the latter, I am feeding in the vector 1:10, whereas for the former, I am feeding in the condition from 1:10 < 5.

To subset a dataset with a condition from a vector:

mtcars$cyl %>% `<`(5) %>% `[`(mtcars, ., )

or:

mtcars$cyl %>% `<`(5) %>% mtcars[.,]

These are equivalent to:

mtcars[mtcars$cyl < 5,]

The extra comma in `[`(mtcars, ., ) is needed because you are subsetting dataframes intead of vectors, just like the difference between (1:10)[1:10 < 5] and mtcars[mtcars$cyl < 5,]

Result:

                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Datsun 710     22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Merc 240D      24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230       22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Toyota Corona  21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2
Volvo 142E     21.4   4 121.0 109 4.11 2.780 18.60  1  1    4    2


问:
Group item from an array based on the date
I have the following array:

```<code>Array
(
    [0] => Array
        (
            [Date] => 2017-11-01 09:15:02
            [Country] => France
        )
    [1] => Array
        (
            [Date] => 2017-11-01 04:45:01
            [Country] => Spain
        )
    [1] => Array
        (
            [Date] => 2017-11-03 04:45:01
            [Country] => Italy
        )
    [1] => Array
        (
            [Date] => 2017-11-04 04:45:01
            [Country] => Canada
        )
)
</code>```

I need to group this array based on the date.

For example, countries with the same day (not hour) should be grouped together.

What I tried:

```<code>$array = array();
foreach ($array as $data) {
  $id = $data['Date'];
  if (isset($array[$Date])) {
     $array[$Date][] = $data;
  } else {
     $array[$Date] = array($data);
  }
}
</code>```

Could you please help me finding what I missed ?

Thanks.

答:
Set the key to the date in only Y-m-d format or something that doesn't include the time.  Also, create a new array and don't add to the existing one:

```<code>foreach($array as $data) {
    $id = date('Y-m-d', strtotime($data['Date']));
    $result[$id][] = $data;
}
</code>```

Body:
I have the following array:

Array
(
    [0] => Array
        (
            [Date] => 2017-11-01 09:15:02
            [Country] => France
        )
    [1] => Array
        (
            [Date] => 2017-11-01 04:45:01
            [Country] => Spain
        )
    [1] => Array
        (
            [Date] => 2017-11-03 04:45:01
            [Country] => Italy
        )
    [1] => Array
        (
            [Date] => 2017-11-04 04:45:01
            [Country] => Canada
        )
)

I need to group this array based on the date.

For example, countries with the same day (not hour) should be grouped together.

What I tried:

$array = array();
foreach ($array as $data) {
  $id = $data['Date'];
  if (isset($array[$Date])) {
     $array[$Date][] = $data;
  } else {
     $array[$Date] = array($data);
  }
}

Could you please help me finding what I missed ?

Thanks.

Body:
Set the key to the date in only Y-m-d format or something that doesn't include the time.  Also, create a new array and don't add to the existing one:

foreach($array as $data) {
    $id = date('Y-m-d', strtotime($data['Date']));
    $result[$id][] = $data;
}


问:
Sensing acceleration w.r.t. absolute orientation
I am trying to make a circuit which can sense acceleration in the X, Y, Z axis. (e.g. movement straight down should be in, say, Z axis - not X and Y)

However, the circuit may not always be mounted straight - so if I want the data to be in line with the axis (i.e. compensate for being wonky), what do I need - can it be done easily? Does it need a magnetometer/gyroscope?

I have also just found inertial measurement units - are these just a combination of gyroscope + accelerometer? Would this do the job?

答:
This would need

A Controller calibration Environment, where you can calibrate output of your circut in known environment.

And Error Corrector which can apply the error estimation or offset estimation from the calibration data to your actual output.

Would recommend to use Gyroscope along with accelerometer if you want to measure tilts. This is because Accelerometer data is typically noisy, and too smoothen it you need low pas filter but that takes away accuracy. Here combining with gyroscope data can help.

This link give more insight on how to use more then one sensor to get usable data