问:
MSI installer removes target folder AFTER install
I've been using a custom MSI deployment process for years without a hitch. Recently, I upgraded from VS2005 to VS2017 and tried to deploy a new version of a program using VS2017. Then the weirdness started.

The first odd thing I noticed was that after installing the new version of my program, it wouldn't run. After some investigation, it turns out that the target install folder (in Program Files) was simply gone. The program was still listed in Programs and Features and still "acted" as if it was installed (all menus/shortcuts built by the installer were still there, attempts to rerun the same installer asked me if I wanted to repair or remove, etc), but the install folder itself was gone. After rerunning the same installer to repair it, the target folder was back and the program worked just fine. I tried putting out another new version (with an incremented version number) from VS2017 and that installer worked just fine without a problem.

So, subsequent installs built in VS2017 work just fine, just like subsequent installs built in VS2005 worked just fine. The issue is moving from the last version I built in VS2005 to the first version built in VS2017. I tested this by removing the app, installing the last VS2005 version, and doing an upgrade to a version built in VS2017. The same problem occurs on three different machines.

I think the problem might have something to do with the GUID of the main executable changing in the MSI file (which it did once I built the installer in VS2017), but I'm not sure.

I turned on verbose MSI logging and did a test upgrade (from the last VS2005 version to a VS2017 version) and instead of creating just one log file, it created two. The first said the install was successful, the second said it failed. They were created just a few seconds apart from each other. Here is the end of each log:

```<code>=== Logging stopped: 7/6/2017  9:23:12 ===
MSI (c) (7C:EC) [09:23:12:733]: Note: 1: 1707
MSI (c) (7C:EC) [09:23:12:733]: Note: 1: 2262 2: Error 3: -2147287038
MSI (c) (7C:EC) [09:23:12:733]: Note: 1: 2262 2: Error 3: -2147287038
MSI (c) (7C:EC) [09:23:12:733]: Product: TaskRunner -- Installation completed successfully.

MSI (c) (7C:EC) [09:23:12:734]: Windows Installer installed the product. Product Name: TaskRunner. Product Version: 3.3.1059. Product Language: 1033. Manufacturer: WATYF. Installation success or error status: 0.

MSI (c) (7C:EC) [09:23:12:736]: Grabbed execution mutex.
MSI (c) (7C:EC) [09:23:12:736]: Cleaning up uninstalled install packages, if any exist
MSI (c) (7C:EC) [09:23:12:744]: MainEngineThread is returning 0
=== Verbose logging stopped: 7/6/2017  9:23:12 ===

=== Logging stopped: 7/6/2017  9:23:39 ===
MSI (c) (B8:90) [09:23:39:075]: Note: 1: 1729
MSI (c) (B8:90) [09:23:39:075]: Note: 1: 2262 2: Error 3: -2147287038
MSI (c) (B8:90) [09:23:39:075]: Note: 1: 2262 2: Error 3: -2147287038
MSI (c) (B8:90) [09:23:39:075]: Product: TaskRunner -- Configuration failed.

MSI (c) (B8:90) [09:23:39:075]: Windows Installer reconfigured the product. Product Name: TaskRunner. Product Version: 3.3.1059. Product Language: 1033. Manufacturer: WATYF. Reconfiguration success or error status: 1602.

MSI (c) (B8:90) [09:23:39:075]: Grabbed execution mutex.
MSI (c) (B8:90) [09:23:39:075]: Cleaning up uninstalled install packages, if any exist
MSI (c) (B8:90) [09:23:39:075]: MainEngineThread is returning 1602
=== Verbose logging stopped: 7/6/2017  9:23:39 ===
</code>```

No errors or messages or oddities of any kind appear during the install. It appears to complete as expected. I don't even know for certain that the second installer log is the cause of the problem. It just seems odd that it would be there and say it failed.

The other odd thing that happened was that after doing this, ALL of the .NET programs that I've built and installed on my machines suddenly started acting as if they weren't properly installed any more. I have two other apps (built in VS2005) that are on this machine and after trying to install the new version of the app I built in VS2017, the two other apps try to run an installer whenever I start them (instead of just launching the program). Those two apps haven't been changed in any way. I'm also not entirely sure that this is related, but it seems odd that it would happen at the exact same time as the other issue.

Does anyone know an explanation for any or all of this?

答:
The most likely explanation is a combination of a couple of things:

Starting with VS 2008 the RemovePreviousVersions upgrades no longer uninstall all of the older product (files, registry entries etc) before installing the new product. The install is now an overwrite where all of the incoming upgrade files are installed on top of the new files, so overwrite rules apply. That also means that uninstall custom actions in the old setup actually run towards the end of the upgrade and shouldn't remove any files because they will now remove files that were just installed.

As a consequence of MSI installer removes target folder AFTER install you might need to set the BackwardCompatibleIDGeneration  property in the setup project, otherwise the internal component Guids may not be compatible with those generated by VS 2005 and the issues you got are the likely result of an upgrade.

Body:
I've been using a custom MSI deployment process for years without a hitch. Recently, I upgraded from VS2005 to VS2017 and tried to deploy a new version of a program using VS2017. Then the weirdness started.

The first odd thing I noticed was that after installing the new version of my program, it wouldn't run. After some investigation, it turns out that the target install folder (in Program Files) was simply gone. The program was still listed in Programs and Features and still "acted" as if it was installed (all menus/shortcuts built by the installer were still there, attempts to rerun the same installer asked me if I wanted to repair or remove, etc), but the install folder itself was gone. After rerunning the same installer to repair it, the target folder was back and the program worked just fine. I tried putting out another new version (with an incremented version number) from VS2017 and that installer worked just fine without a problem.

So, subsequent installs built in VS2017 work just fine, just like subsequent installs built in VS2005 worked just fine. The issue is moving from the last version I built in VS2005 to the first version built in VS2017. I tested this by removing the app, installing the last VS2005 version, and doing an upgrade to a version built in VS2017. The same problem occurs on three different machines.

I think the problem might have something to do with the GUID of the main executable changing in the MSI file (which it did once I built the installer in VS2017), but I'm not sure.

I turned on verbose MSI logging and did a test upgrade (from the last VS2005 version to a VS2017 version) and instead of creating just one log file, it created two. The first said the install was successful, the second said it failed. They were created just a few seconds apart from each other. Here is the end of each log:

=== Logging stopped: 7/6/2017  9:23:12 ===
MSI (c) (7C:EC) [09:23:12:733]: Note: 1: 1707
MSI (c) (7C:EC) [09:23:12:733]: Note: 1: 2262 2: Error 3: -2147287038
MSI (c) (7C:EC) [09:23:12:733]: Note: 1: 2262 2: Error 3: -2147287038
MSI (c) (7C:EC) [09:23:12:733]: Product: TaskRunner -- Installation completed successfully.

MSI (c) (7C:EC) [09:23:12:734]: Windows Installer installed the product. Product Name: TaskRunner. Product Version: 3.3.1059. Product Language: 1033. Manufacturer: WATYF. Installation success or error status: 0.

MSI (c) (7C:EC) [09:23:12:736]: Grabbed execution mutex.
MSI (c) (7C:EC) [09:23:12:736]: Cleaning up uninstalled install packages, if any exist
MSI (c) (7C:EC) [09:23:12:744]: MainEngineThread is returning 0
=== Verbose logging stopped: 7/6/2017  9:23:12 ===

=== Logging stopped: 7/6/2017  9:23:39 ===
MSI (c) (B8:90) [09:23:39:075]: Note: 1: 1729
MSI (c) (B8:90) [09:23:39:075]: Note: 1: 2262 2: Error 3: -2147287038
MSI (c) (B8:90) [09:23:39:075]: Note: 1: 2262 2: Error 3: -2147287038
MSI (c) (B8:90) [09:23:39:075]: Product: TaskRunner -- Configuration failed.

MSI (c) (B8:90) [09:23:39:075]: Windows Installer reconfigured the product. Product Name: TaskRunner. Product Version: 3.3.1059. Product Language: 1033. Manufacturer: WATYF. Reconfiguration success or error status: 1602.

MSI (c) (B8:90) [09:23:39:075]: Grabbed execution mutex.
MSI (c) (B8:90) [09:23:39:075]: Cleaning up uninstalled install packages, if any exist
MSI (c) (B8:90) [09:23:39:075]: MainEngineThread is returning 1602
=== Verbose logging stopped: 7/6/2017  9:23:39 ===

No errors or messages or oddities of any kind appear during the install. It appears to complete as expected. I don't even know for certain that the second installer log is the cause of the problem. It just seems odd that it would be there and say it failed.

The other odd thing that happened was that after doing this, ALL of the .NET programs that I've built and installed on my machines suddenly started acting as if they weren't properly installed any more. I have two other apps (built in VS2005) that are on this machine and after trying to install the new version of the app I built in VS2017, the two other apps try to run an installer whenever I start them (instead of just launching the program). Those two apps haven't been changed in any way. I'm also not entirely sure that this is related, but it seems odd that it would happen at the exact same time as the other issue.

Does anyone know an explanation for any or all of this?


来源: stackexchange

问:
Numpy array remove duplicates non-order specific with additional element priority
I have a numpy array which looks like this:

```<code>[['Apple' 'Banana' 'A']
 ['Banana' 'Apple' 'A']
 ['Banana' 'Apple' 'B']
 ['Banana' 'Apple' 'Z']
 ['Pear' 'Apple' 'Z']
 ['Apple' 'Pear' 'A']
 ['Apple' 'Orange' 'Z']]
</code>```

I would like to first remove dups regardless of the order of elements. To appear as:

```<code>[['Apple' 'Banana' 'A']
 ['Banana' 'Apple' 'B']
 ['Banana' 'Apple' 'Z']
 ['Pear' 'Apple' 'Z']
 ['Apple' 'Pear' 'A']
 ['Apple' 'Orange' 'Z']]
</code>```

Removed:  ['Banana' 'Apple' 'A']

Then remove all 'Z' elements when 'A' or 'B' element are present:

```<code>[['Apple' 'Banana' 'A']
 ['Banana' 'Apple' 'B']
 ['Apple' 'Pear' 'A']
 ['Apple' 'Orange' 'Z']]
</code>```

Not necessary to maintain row order. If it can be done in 1 step that is even better. Thanks!

答:
Below, a is your data array:

```<code>[list(k) + v for k, v in {tuple(sorted(set(x[:2]))) : [x[2]] for x in a}.items()]
</code>```

However, from your question it is not clear in which order items should be removed. For example you say: "Removed: ['Banana' 'Apple' 'A']. Then remove all 'Z' elements when 'A' or 'B' element are present..." There appears no logic in which order items are removed: A, Z, B, ... So, my code removes items in an arbitrary order.

ContentLicense: CC BY-SA 3.0

Body:
I have a numpy array which looks like this:

[['Apple' 'Banana' 'A']
 ['Banana' 'Apple' 'A']
 ['Banana' 'Apple' 'B']
 ['Banana' 'Apple' 'Z']
 ['Pear' 'Apple' 'Z']
 ['Apple' 'Pear' 'A']
 ['Apple' 'Orange' 'Z']]

I would like to first remove dups regardless of the order of elements. To appear as:

[['Apple' 'Banana' 'A']
 ['Banana' 'Apple' 'B']
 ['Banana' 'Apple' 'Z']
 ['Pear' 'Apple' 'Z']
 ['Apple' 'Pear' 'A']
 ['Apple' 'Orange' 'Z']]

Removed:  ['Banana' 'Apple' 'A']

Then remove all 'Z' elements when 'A' or 'B' element are present:

[['Apple' 'Banana' 'A']
 ['Banana' 'Apple' 'B']
 ['Apple' 'Pear' 'A']
 ['Apple' 'Orange' 'Z']]

Not necessary to maintain row order. If it can be done in 1 step that is even better. Thanks!

Body:
Below, a is your data array:

[list(k) + v for k, v in {tuple(sorted(set(x[:2]))) : [x[2]] for x in a}.items()]

However, from your question it is not clear in which order items should be removed. For example you say: "Removed: ['Banana' 'Apple' 'A']. Then remove all 'Z' elements when 'A' or 'B' element are present..." There appears no logic in which order items are removed: A, Z, B, ... So, my code removes items in an arbitrary order.


问:
Explicit explanation as to what a return type is, why void is necessary
I'm sorry to ask a question that is conceptual but I am having a very hard time visualizing the idea of 'returning a value' from a method. I am still a beginner, sorry about this.

Take this code snippet for example:

```<code>public static NameGenerator(string x)
{
    Random r = new Random();
    string[] randomNamePossibilities = new string[15]
    {
        "John", "Billy", "Tommy", "Kyle", "Jackson", "George", "Paco",
        "Sruy", "Mateus", "Matt",
        "Jared", "Sage", "Kai", "Trent", "Dillon"
    };
    int randomNumberPicker = r.Next(15);
    return randomNamePossibilities[randomNumberPicker];
}
</code>```

notice how it returns the one-dimensional string array, randomNamePossibilities[15].  The intention is for this method to generate a randomized number with Random r (that has a maximum value of 15), and then for the method to return one of these randomized names from the array as a string.

The error I'm getting is with NameGenerator() & return randomNamePossibilities[randomnumberPicker]; Giving me the errors 'Method must have a return type', and 'Since Person.NameGenerator(string) returns void, a return keyword must not be followed by an object expression.'

So my question is this: In explicitly simple terms, what does return do inside of a method like this? In what case is it used properly? Why is it that this code snippet gives me an error if I use void? How can I rewrite this to function well?

答:
Ignoring the code in your example, a return type is explicitly defined in the methods declaration. Example:

```<code>public int MethodName()
{
    int i = 1;
    return i;
}
</code>```

Why is the return value important?

When you call your method (and sometimes you don't) the return value can be assigned or compared. Example:

```<code>if(MethodName() == 1)
{
    MessageBox.Show("The returned value from MethodName is 1");
}
</code>```

Another example:

```<code>int i2 = MethodName(); //i2 is now equal to 1, since MethodName returns a value of 1
</code>```

More examples with a different return value:

```<code>public string StringMethod()
{
    string s = "this is a string";
    return s;
}

public void MainMethod()
{
    string newString = StringMethod(); //newString is now equal to "this is a string"
    if(StringMethod().Equals(newString))
    {
        //this code block will run, since both string are "this is a string"
    }
}
</code>```

Body:
I'm sorry to ask a question that is conceptual but I am having a very hard time visualizing the idea of 'returning a value' from a method. I am still a beginner, sorry about this.

Take this code snippet for example:

public static NameGenerator(string x)
{
    Random r = new Random();
    string[] randomNamePossibilities = new string[15]
    {
        "John", "Billy", "Tommy", "Kyle", "Jackson", "George", "Paco",
        "Sruy", "Mateus", "Matt",
        "Jared", "Sage", "Kai", "Trent", "Dillon"
    };
    int randomNumberPicker = r.Next(15);
    return randomNamePossibilities[randomNumberPicker];
}

notice how it returns the one-dimensional string array, randomNamePossibilities[15].  The intention is for this method to generate a randomized number with Random r (that has a maximum value of 15), and then for the method to return one of these randomized names from the array as a string.

The error I'm getting is with NameGenerator() & return randomNamePossibilities[randomnumberPicker]; Giving me the errors 'Method must have a return type', and 'Since Person.NameGenerator(string) returns void, a return keyword must not be followed by an object expression.'

So my question is this: In explicitly simple terms, what does return do inside of a method like this? In what case is it used properly? Why is it that this code snippet gives me an error if I use void? How can I rewrite this to function well?

Body:
Ignoring the code in your example, a return type is explicitly defined in the methods declaration. Example:

public int MethodName()
{
    int i = 1;
    return i;
}

Why is the return value important?

When you call your method (and sometimes you don't) the return value can be assigned or compared. Example:

if(MethodName() == 1)
{
    MessageBox.Show("The returned value from MethodName is 1");
}

Another example:

int i2 = MethodName(); //i2 is now equal to 1, since MethodName returns a value of 1

More examples with a different return value:

public string StringMethod()
{
    string s = "this is a string";
    return s;
}

public void MainMethod()
{
    string newString = StringMethod(); //newString is now equal to "this is a string"
    if(StringMethod().Equals(newString))
    {
        //this code block will run, since both string are "this is a string"
    }
}


问:
Creating an instance variable that represents other variables with same names but unique values in different classes (Java)
I am currently attempting to integrate automated tests with our test management tool with the use of APIs. Each test(which is contained in a single class) has a unique id which needs to be referenced in the API call. I can either declare the Test IDs in the tests themselves (preferred) or create a separate class that contains all of the IDs for reference. The issue I am having is coming up with a good way to represent these IDs as a variable when the particular test is run, so I do not a have to repeat the API framework for each unique ID.

Here is the general set up of the API class/listener class.

```<code>  package testPackage;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;

import org.json.simple.JSONObject;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;

import com.gurock.testrail.APIClient;
import com.gurock.testrail.APIException;

public class MyTestResultsListener extends TestListenerAdapter {

    public final APIClient client = new APIClient("https://api.url/");
    public final Map data = new HashMap();

    public final void APISendCredentials() {
        client.setUser("username");
        client.setPassword("password");

    }

    @Override
    public void onTestFailure(ITestResult result) {
        APISendCredentials();
        data.put("status_id", new Integer(5));
        data.put("comment", "This test failed");
        try {
            JSONObject r = (JSONObject) client.sendPost("add_result_for_case/" + "Unique ID", data);
        } catch (MalformedURLException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        } catch (APIException e) {

            e.printStackTrace();
        }
    }

    @Override
    public void onTestSuccess(ITestResult result) {
        APISendCredentials();
        data.put("status_id", new Integer(1));
        data.put("comment", "This test passed");
        try {
            JSONObject r = (JSONObject) client.sendPost("add_result_for_case/" + TestClass.AutomationID, data);
        } catch (MalformedURLException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        } catch (APIException e) {

            e.printStackTrace();
        }

    }

    @Override
    public void onTestSkipped(ITestResult result) {
        APISendCredentials();
        data.put("status_id", new Integer(2));
        data.put("comment", "This test was blocked or skipped");
        try {
            JSONObject r = (JSONObject) client.sendPost("add_result_for_case/" + TestClass.AutomationID, data);
        } catch (MalformedURLException e) {

            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (APIException e) {
            e.printStackTrace();
        }

    }
}
</code>```

Test class

```<code>package testPackage;

import java.io.IOException;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import com.gurock.testrail.APIException;

@Listeners(MyTestResultsListener.class)

public class TestClass {

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface TestData {
    String testId() default "0";

}

public static String AutomationID = "236/50819";

@Test
@TestData(testId = "236/50819")
public void test1() {
    //sometest

}

@AfterTest
public void aftertest() {
    //This was my initial blind attempt at reflection. I am getting
    //an error below stating "test1" cannot be resolved to a variable
    //also unclear on how to feed this to the APIclass
    Method testMethod = getClass().getMethod(test1);
    if (testMethod.isAnnotationPresent(TestData.class)) {
        TestData testData = testMethod.getAnnotation(TestData.class);
        //stuck at this point
    }
}
</code>```

}

As you can see on the lines that start with JSONobject r I have a place holder for the uniqueID variable. What would be the best way/most efficient way to create a variable that could take these unqiue IDs from the different test classes ?

Thx, let me know if there is any additional information needed that would be helpful !

答: If the id for each test does not change, you can create an annotation e.g. @TestId holding the test id. Each test class (or method depending on the granularity level desired) can be annotated with its own test id. Then in the API code you can simply get it via reflection.

Body:
I am currently attempting to integrate automated tests with our test management tool with the use of APIs. Each test(which is contained in a single class) has a unique id which needs to be referenced in the API call. I can either declare the Test IDs in the tests themselves (preferred) or create a separate class that contains all of the IDs for reference. The issue I am having is coming up with a good way to represent these IDs as a variable when the particular test is run, so I do not a have to repeat the API framework for each unique ID.

Here is the general set up of the API class/listener class.

  package testPackage;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;

import org.json.simple.JSONObject;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;

import com.gurock.testrail.APIClient;
import com.gurock.testrail.APIException;

public class MyTestResultsListener extends TestListenerAdapter {

    public final APIClient client = new APIClient("https://api.url/");
    public final Map data = new HashMap();

    public final void APISendCredentials() {
        client.setUser("username");
        client.setPassword("password");

    }

    @Override
    public void onTestFailure(ITestResult result) {
        APISendCredentials();
        data.put("status_id", new Integer(5));
        data.put("comment", "This test failed");
        try {
            JSONObject r = (JSONObject) client.sendPost("add_result_for_case/" + "Unique ID", data);
        } catch (MalformedURLException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        } catch (APIException e) {

            e.printStackTrace();
        }
    }

    @Override
    public void onTestSuccess(ITestResult result) {
        APISendCredentials();
        data.put("status_id", new Integer(1));
        data.put("comment", "This test passed");
        try {
            JSONObject r = (JSONObject) client.sendPost("add_result_for_case/" + TestClass.AutomationID, data);
        } catch (MalformedURLException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        } catch (APIException e) {

            e.printStackTrace();
        }

    }

    @Override
    public void onTestSkipped(ITestResult result) {
        APISendCredentials();
        data.put("status_id", new Integer(2));
        data.put("comment", "This test was blocked or skipped");
        try {
            JSONObject r = (JSONObject) client.sendPost("add_result_for_case/" + TestClass.AutomationID, data);
        } catch (MalformedURLException e) {

            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (APIException e) {
            e.printStackTrace();
        }

    }
}

Test class

package testPackage;

import java.io.IOException;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import com.gurock.testrail.APIException;

@Listeners(MyTestResultsListener.class)

public class TestClass {

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface TestData {
    String testId() default "0";

}

public static String AutomationID = "236/50819";

@Test
@TestData(testId = "236/50819")
public void test1() {
    //sometest

}

@AfterTest
public void aftertest() {
    //This was my initial blind attempt at reflection. I am getting
    //an error below stating "test1" cannot be resolved to a variable
    //also unclear on how to feed this to the APIclass
    Method testMethod = getClass().getMethod(test1);
    if (testMethod.isAnnotationPresent(TestData.class)) {
        TestData testData = testMethod.getAnnotation(TestData.class);
        //stuck at this point
    }
}

}

As you can see on the lines that start with JSONobject r I have a place holder for the uniqueID variable. What would be the best way/most efficient way to create a variable that could take these unqiue IDs from the different test classes ?

Thx, let me know if there is any additional information needed that would be helpful !


问:
Angular Resource Save Promise
I am trying to resolve a promise from angular $resource save.

The docs specify that I can access the raw $http promise via the $promise property on the object returned as follows:

```<code>var User = $resource('/user/:userId', {userId:'@id'});
User.get({userId:123})
    .$promise.then(function(user) {
      $scope.user = user;
    });
</code>```

This works for the get, however, when I attempt to access the promise on the save, I get an error. What am I doing wrong and why would resolving the save work differently than resolving the get?

Note: The POST request is working and I can see the correct response being returned from the server in the browser's Network tool. I just can't access the results in the promise.

In My Service

```<code>var itemResource = $resource('/api/myUrl/:id/:action', { id: '@id', action: '@action' });

function getItem(id) {
    return itemResource.get({ id: id });
}

function saveItem(item) {
    return itemResource.save(item);
}
</code>```

In My Controller

```<code>var getResult = itemService.getItem({ id: 1560 });
getResult.$promise.then(function (itemDef) { // THIS WORKS!!!
    console.log(itemDef);
});

var saveResult = itemService.saveItem(item);
saveResult.$promise.then(function (itemDef) { // Cannot read property 'then' of undefined
    console.log(itemDef);
});
</code>```

答:
You need to call the then method on the save response directly:

```<code>var saveResult = itemService.saveItem(item);

saveResult.then(function(itemDef) { ... });
</code>```

Title: Angular Resource Save Promise

Body:
I am trying to resolve a promise from angular $resource save.

The docs specify that I can access the raw $http promise via the $promise property on the object returned as follows:

var User = $resource('/user/:userId', {userId:'@id'});
User.get({userId:123})
    .$promise.then(function(user) {
      $scope.user = user;
    });

This works for the get, however, when I attempt to access the promise on the save, I get an error. What am I doing wrong and why would resolving the save work differently than resolving the get?

Note: The POST request is working and I can see the correct response being returned from the server in the browser's Network tool. I just can't access the results in the promise.

In My Service

var itemResource = $resource('/api/myUrl/:id/:action', { id: '@id', action: '@action' });

function getItem(id) {
    return itemResource.get({ id: id });
}

function saveItem(item) {
    return itemResource.save(item);
}

In My Controller

var getResult = itemService.getItem({ id: 1560 });
getResult.$promise.then(function (itemDef) { // THIS WORKS!!!
    console.log(itemDef);
});

var saveResult = itemService.saveItem(item);
saveResult.$promise.then(function (itemDef) { // Cannot read property 'then' of undefined
    console.log(itemDef);
});

Body:
You need to call the then method on the save response directly:

var saveResult = itemService.saveItem(item);

saveResult.then(function(itemDef) { ... });


问:
how to jump from signup page to the next activity on the click of the signup button
ok, so I made a signup page in my application that shows up when the app starts. I used if and else statement that if none of the fields are empty, then it shows "login successful" on the click of the sign-up button on the screen else it shows"Login unsuccessful". i want to add a code in the if portion that if none of the fields are empty, then it shows"login successful" on the click of the sign up button and proceeds to the next activity which is actually the real application supposed to be displayed after the sign up page else it shows "Login unsuccessful" but can't figure out how. and I'm a beginner in android programming too.</p>

```<code> Button mShowdialog = (Button) findViewById(R.id.btnShowDialog);

    mShowdialog.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
            View mView = getLayoutInflater().inflate(R.layout.dialog_login,null);
            final EditText mEmail = (EditText) mView.findViewById(R.id.edtEmail);
            final EditText mPassword = (EditText) mView.findViewById(R.id.edtPassword);
            Button mLogin = (Button) mView.findViewById(R.id.btnLogin);
            mLogin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (!mEmail.getText().toString().isEmpty()
                            && !mPassword.getText().toString().isEmpty()) {

                        Toast.makeText(MainActivity.this,
                                R.string.Success_Login_msg,
                                Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this,
                                R.string.error_login_msg,
                                Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    });
</code>```

答:
Use intents.
Create explicit intent with class name and use putExtra to pass data of username and password to that activity.</p>

Body:
ok, so I made a signup page in my application that shows up when the app starts. I used if and else statement that if none of the fields are empty, then it shows "login successful" on the click of the sign-up button on the screen else it shows"Login unsuccessful". i want to add a code in the if portion that if none of the fields are empty, then it shows"login successful" on the click of the sign up button and proceeds to the next activity which is actually the real application supposed to be displayed after the sign up page else it shows "Login unsuccessful" but can't figure out how. and I'm a beginner in android programming too.

 Button mShowdialog = (Button) findViewById(R.id.btnShowDialog);

    mShowdialog.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
            View mView = getLayoutInflater().inflate(R.layout.dialog_login,null);
            final EditText mEmail = (EditText) mView.findViewById(R.id.edtEmail);
            final EditText mPassword = (EditText) mView.findViewById(R.id.edtPassword);
            Button mLogin = (Button) mView.findViewById(R.id.btnLogin);
            mLogin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (!mEmail.getText().toString().isEmpty()
                            && !mPassword.getText().toString().isEmpty()) {

                        Toast.makeText(MainActivity.this,
                                R.string.Success_Login_msg,
                                Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this,
                                R.string.error_login_msg,
                                Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    });


问:
RabbitMQ command doesn't exist?
OS: Mac OSX 10.9

I have rabbitmq installed via home brew and when I go to /usr/local/sbin and run rabbitmq-server it states that: rabbitmq-server: command not found even as sudo it states the same error.

How do I get rabbitmq to start if it's not a command? I have also tried chmod +x rabbitmq-server in that directory to get it be an executable, same issue.

答:
My OS: macOS Sierra 10.12.5

My RabbitMQ was installed using:

```<code>brew install rabbitmq
</code>```

And it was installed into /usr/local/Cellar, just in case if someone has same situation with me, you would need to do similarly:

In terminal:

```<code>ls /usr/local/Cellar/rabbitmq/
</code>```

to check which version you have installed, and then add to .bash_profile:

```<code>export PATH=/usr/local/Cellar/rabbitmq/<version>/sbin:$PATH
</code>```

Title: RabbitMQ command doesn't exist?

Body:
My OS: macOS Sierra 10.12.5

My RabbitMQ was installed using:

brew install rabbitmq

And it was installed into /usr/local/Cellar, just in case if someone has same situation with me, you would need to do similarly:

In terminal:

ls /usr/local/Cellar/rabbitmq/

to check which version you have installed, and then add to .bash_profile:

export PATH=/usr/local/Cellar/rabbitmq/<version>/sbin:$PATH

ContentLicense: CC BY-SA 4.0


问:
Docker not found when building docker image using Docker Jenkins container pipeline
I have a Jenkins running as a docker container, now I want to build a Docker image using pipeline, but Jenkins container always tells Docker not found.

```<code>[simple-tdd-pipeline] Running shell script
+ docker build -t simple-tdd .
/var/jenkins_home/workspace/simple-tdd-pipeline@tmp/durable-
ebc35179/script.sh: 2: /var/jenkins_home/workspace/simple-tdd-
pipeline@tmp/durable-ebc35179/script.sh: docker: not found
</code>```

Here is how I run my Jenkins image:

```<code>docker run --name myjenkins -p 8080:8080 -p 50000:50000 -v
/var/jenkins_home -v /var/run/docker.sock:/var/run/docker.sock
jenkins
</code>```

And the DockerFile of Jenkins image is:
https://github.com/jenkinsci/docker/blob/9f29488b77c2005bbbc5c936d47e697689f8ef6e/Dockerfile

答:
Edit: May 2018

As pointed by Guillaume Husta, this jpetazzo's blog article discourages this technique:

Former versions of this post advised to bind-mount the docker binary from the host to the container. This is not reliable anymore, because the Docker Engine is no longer distributed as (almost) static libraries.

Docker client should be installed inside a container as described here. Also, jenkins user should be in docker group, so execute following:

```<code>$ docker exec -it -u root my-jenkins /bin/bash
# usermod -aG docker jenkins
</code>```

and finally restart my-jenkins container.

Original answer:

You could use host's docker engine like in this @Adrian Mouat blog article.

```<code> docker run -d \
   --name my-jenkins \
   -v /var/jenkins_home:~/.jenkins \
   -v /var/run/docker.sock:/var/run/docker.sock \
   -p 8080:8080 jenkins
</code>```

This avoids having multiple docker engine version on host and jenkins container.

Body:
I have a Jenkins running as a docker container, now I want to build a Docker image using pipeline, but Jenkins container always tells Docker not found.

[simple-tdd-pipeline] Running shell script
+ docker build -t simple-tdd .
/var/jenkins_home/workspace/simple-tdd-pipeline@tmp/durable-
ebc35179/script.sh: 2: /var/jenkins_home/workspace/simple-tdd-
pipeline@tmp/durable-ebc35179/script.sh: docker: not found

Here is how I run my Jenkins image:

docker run --name myjenkins -p 8080:8080 -p 50000:50000 -v
/var/jenkins_home -v /var/run/docker.sock:/var/run/docker.sock
jenkins

And the DockerFile of Jenkins image is:
https://github.com/jenkinsci/docker/blob/9f29488b77c2005bbbc5c936d47e697689f8ef6e/Dockerfile

Body:
Edit: May 2018

As pointed by Guillaume Husta, this jpetazzo's blog article discourages this technique:

Former versions of this post advised to bind-mount the docker binary from the host to the container. This is not reliable anymore, because the Docker Engine is no longer distributed as (almost) static libraries.

Docker client should be installed inside a container as described here. Also, jenkins user should be in docker group, so execute following:

$ docker exec -it -u root my-jenkins /bin/bash
# usermod -aG docker jenkins

and finally restart my-jenkins container.

Original answer:

You could use host's docker engine like in this @Adrian Mouat blog article.

 docker run -d \
   --name my-jenkins \
   -v /var/jenkins_home:~/.jenkins \
   -v /var/run/docker.sock:/var/run/docker.sock \
   -p 8080:8080 jenkins

This avoids having multiple docker engine version on host and jenkins container.


答:
Your method is missing the return type (the first 'string' word in this fixed code sample).

return instructs the runtime to calculate the value after the keyword 'return' and then stop executing the method and return to the method that called this method. It's redundant when it is the last line of a method, which is why some languages don't need it at all, but it is necessary for CSharp.

```<code>public static string NameGenerator(string x)
{
    Random r = new Random();
    string[] randomNamePossibilities = new string[15]
    {
        "John", "Billy", "Tommy", "Kyle", "Jackson", "George", "Paco",
        "Sruy", "Mateus", "Matt",
        "Jared", "Sage", "Kai", "Trent", "Dillon"
    };
    int randomNumberPicker = r.Next(15);
    return randomNamePossibilities[randomNumberPicker];
}
</code>```

Title: Explicit explanation as to what a return type is, why void is necessary

Body:
Your method is missing the return type (the first 'string' word in this fixed code sample).

return instructs the runtime to calculate the value after the keyword 'return' and then stop executing the method and return to the method that called this method. It's redundant when it is the last line of a method, which is why some languages don't need it at all, but it is necessary for CSharp.

public static string NameGenerator(string x)
{
    Random r = new Random();
    string[] randomNamePossibilities = new string[15]
    {
        "John", "Billy", "Tommy", "Kyle", "Jackson", "George", "Paco",
        "Sruy", "Mateus", "Matt",
        "Jared", "Sage", "Kai", "Trent", "Dillon"
    };
    int randomNumberPicker = r.Next(15);
    return randomNamePossibilities[randomNumberPicker];
}


问:
Role of eternal and maxElementsInMemory in ehcache?
I have below configuration in my project

```<code><defaultCache maxElementsInMemory="100" eternal="false" overflowToDisk="false" memoryStoreEvictionPolicy="LRU" statistics="false" />

<cache name="customerList" maxElementsInMemory="1000" eternal="false" overflowToDisk="false" memoryStoreEvictionPolicy="LRU" />
</code>```

As per my understanding eternal =true attribute explains cache will never expire. But when i mention eternal =false, how long cache will remain active?

Also i have mentioned maxElementsInMemory=1000, what will happen when i have more than 1000 elements to put in cache. Will not they be stored in cache and discarded ?

答:
I'm very late to answer this question. But as i have also gone through this issue so want to share my experience.

Hi @emilly, I'm answering specifically to your questions and we will use config. that is shared by @RCB.

```<code><cache name="customerList" maxElementsInMemory="1000" eternal="false" timeToLiveSeconds="60" overflowToDisk="false" memoryStoreEvictionPolicy="LRU" />
</code>```

Question 1:

As timeToLiveSeconds="60" so it's the maximum time for which "customerList" data will be there in cache(L2). Cache Eviction is not directly related to the value of this attribute(timeToLiveSeconds).

e.g. If customerList is created on 12:00:00, it will be available till 12:00:59.

Question 2:
say I want to add one more element after 1000. I cache will evict least recently used one and stored the latest element in list as I mentioned memoryStoreEvictionPolicy. Is that right ?

yes, this is the cache(L2) eviction and it will be according to the memoryStoreEvictionPolicy="LRU" and in this example it will a valid operation before TTL(60 seconds).

Body:
I have below configuration in my project

<defaultCache maxElementsInMemory="100" eternal="false" overflowToDisk="false" memoryStoreEvictionPolicy="LRU" statistics="false" />

<cache name="customerList" maxElementsInMemory="1000" eternal="false" overflowToDisk="false" memoryStoreEvictionPolicy="LRU" />

As per my understanding eternal =true attribute explains cache will never expire. But when i mention eternal =false, how long cache will remain active?

Also i have mentioned maxElementsInMemory=1000, what will happen when i have more than 1000 elements to put in cache. Will not they be stored in cache and discarded ?

Body:
I'm very late to answer this question. But as i have also gone through this issue so want to share my experience.

Hi @emilly, I'm answering specifically to your questions and we will use config. that is shared by @RCB.

<cache name="customerList" maxElementsInMemory="1000" eternal="false" timeToLiveSeconds="60" overflowToDisk="false" memoryStoreEvictionPolicy="LRU" />

Question 1:

As timeToLiveSeconds="60" so it's the maximum time for which "customerList" data will be there in cache(L2). Cache Eviction is not directly related to the value of this attribute(timeToLiveSeconds).

e.g. If customerList is created on 12:00:00, it will be available till 12:00:59.

Question 2:
say I want to add one more element after 1000. I cache will evict least recently used one and stored the latest element in list as I mentioned memoryStoreEvictionPolicy. Is that right ?

yes, this is the cache(L2) eviction and it will be according to the memoryStoreEvictionPolicy="LRU" and in this example it will a valid operation before TTL(60 seconds).


问:
Spinner with different view for each item
I try to make a Spinner where the first item in the dropdownview has no radio button. I override the viewtypes of the arrayadapter to make sure there are two different views in the spinner and the views don't get recycled for the wrong item. Then I override getDropDownView of the arrayadapter to remove the radio button from the first item. This is working, but the selected item doesn't show the radio button. I think I wouldn't have to setCheckMarkDrawable(android.R.drawable.btn_radio), because it should always be there, but this is not the case. Any Ideas? Thank you!</p>

```<code>        @Override
        public int getViewTypeCount()
        {
            return 2;
        }

        @Override
        public int getItemViewType(int position)
        {
            if (position == 0)
                return 0;
            else
                return 1;
        }

        @Override
        public View getDropDownView(int position, View convertView, android.view.ViewGroup parent)
        {
            if (position == 0)
            {
                View vw = super.getDropDownView(position, convertView, parent);
                CheckedTextView tv = (CheckedTextView) vw;
                if (tv != null)
                {
                    tv.setCheckMarkDrawable(null);
                    tv.setTextColor(Color.GRAY);
                    return tv;
                }
                return vw;
            } else
            {
                View vw = super.getDropDownView(position, convertView, parent);
                CheckedTextView tv = (CheckedTextView) vw;
                if (tv != null)
                {
                    tv.setCheckMarkDrawable(android.R.drawable.btn_radio);
                    tv.setTextColor(Color.BLACK);
                    return tv;
                }
                return vw;
            }
        }
</code>```

答:
Due to the fact that view recycling doesn't work for Spinner, don't use Spinner if you have multiple views.  Instead use a TextView styled as a Spinner and in onClick opens your custom dialog showing the dropdown.</p>

```<code><TextView android:id="@+id/labels_spinner"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      style="@style/Base.Widget.AppCompat.Spinner.Underlined"/>

@OnClick(R.id.labels_spinner)
public void onSpinnerClick(View view) {
    // Open dropdown dialog
}
</code>```

Body:
I try to make a Spinner where the first item in the dropdownview has no radio button. I override the viewtypes of the arrayadapter to make sure there are two different views in the spinner and the views don't get recycled for the wrong item. Then I override getDropDownView of the arrayadapter to remove the radio button from the first item. This is working, but the selected item doesn't show the radio button. I think I wouldn't have to setCheckMarkDrawable(android.R.drawable.btn_radio), because it should always be there, but this is not the case. Any Ideas? Thank you!

        @Override
        public int getViewTypeCount()
        {
            return 2;
        }

        @Override
        public int getItemViewType(int position)
        {
            if (position == 0)
                return 0;
            else
                return 1;
        }

        @Override
        public View getDropDownView(int position, View convertView, android.view.ViewGroup parent)
        {
            if (position == 0)
            {
                View vw = super.getDropDownView(position, convertView, parent);
                CheckedTextView tv = (CheckedTextView) vw;
                if (tv != null)
                {
                    tv.setCheckMarkDrawable(null);
                    tv.setTextColor(Color.GRAY);
                    return tv;
                }
                return vw;
            } else
            {
                View vw = super.getDropDownView(position, convertView, parent);
                CheckedTextView tv = (CheckedTextView) vw;
                if (tv != null)
                {
                    tv.setCheckMarkDrawable(android.R.drawable.btn_radio);
                    tv.setTextColor(Color.BLACK);
                    return tv;
                }
                return vw;
            }
        }

Body:
Due to the fact that view recycling doesn't work for Spinner, don't use Spinner if you have multiple views.  Instead use a TextView styled as a Spinner and in onClick opens your custom dialog showing the dropdown.

<TextView android:id="@+id/labels_spinner"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      style="@style/Base.Widget.AppCompat.Spinner.Underlined"/>

@OnClick(R.id.labels_spinner)
public void onSpinnerClick(View view) {
    // Open dropdown dialog
}


问:
Linking to boost through SConstruct
I'm trying to work on a cross-platform project that uses boost for the file/directory operations.  I've been using visual studio, but in order to compile on linux, I've decided to switch to SConstruct.

I cannot [correctly?] link to the filesystem library however.

my SConstruct file is as follow:

```<code>vLibs = [
            'libboost_system-vc100-mt-1_44.lib',
            'libboost_filesystem-vc100-mt-1_44.lib'];
# LIBS=vLibs,
env = Environment();

env.AppendUnique(CXXFLAGS=Split("/EHsc"));
env.Append(CPPPATH = ["C:\\Program Files (x86)\\boost\\boost_1_44"]);
env.Append(LIBPATH = ["C:\\Program Files (x86)\\boost\\boost_1_44\\lib"]);

env.Program( Glob('test.cpp'),LIBS=vLibs)
</code>```

I keep getting errors like

test.obj : error LNK2019: unresolved external symbol "class boost::system::error_category const & __cdecl boost::system::generic_category(void)" (?generic_category@system@boost@@YAAEBVerror_category@12@XZ) referenced in function "void __cdecl boost::system::`dynamic initializer for 'posix_category''(void)" (??__Eposix_category@system@boost@@YAXXZ)

If I use visual studio, I get similar errors:

Error 2   error LNK2001: unresolved external symbol "class boost::system::error_category const & __cdecl boost::system::generic_category(void)" (?generic_category@system@boost@@YAABVerror_category@12@XZ)   T:\VS\temp\test.obj temp

Until I add the libraries to the project, after which the errors go away and it compiles fine (in visual studio not SConstruct).

I've tried every combination of the libraries (shared/unshared/runtime-shared/runtime-unshared/debug), but I always get the same errors.

I've been searching for an answer for the last 6+ hours, so I'm grateful for any help.

NOTE: I'm not using autolinking (#define BOOST_ALL_NO_LIB) because gcc doesn't support it)

Here's the output of Scons:

```<code>scons: Reading SConscript files ...
scons: done reading SConscript files.
scons: Building targets ...

link /nologo /OUT:build\test.exe "/LIBPATH:C:\Program Files (x86)\boost\boost_1_44\lib" libboost_system-vc100-mt-1_44.lib     libboost_filesystem-vc100-mt-1_44.lib build\test.obj
test.obj : error LNK2019: unresolved external symbol "class boost::system::error_category const & __cdecl     boost::system::generic_category(void)" (?generic_category@system@boost@@YAAEBVerror_category@12@XZ) referenced in function "void __cdecl boost::system::`dynamic initializer for 'posix_category''(void)" (??    __Eposix_category@system@boost@@YAXXZ)
test.obj : error LNK2019: unresolved external symbol "class boost::system::error_category const & __cdecl     boost::system::system_category(void)" (?system_category@system@boost@@YAAEBVerror_category@12@XZ) referenced in function "void __cdecl boost::system::`dynamic initializer for 'native_ecat''(void)" (??    __Enative_ecat@system@boost@@YAXXZ)
build\test.exe : fatal error LNK1120: 2 unresolved externals
scons: *** [build\test.exe] Error 1120
scons: building terminated because of errors.
</code>```

答:
I don't think the lib prefix nor suffix should be present.  Try these it like this in your SCons LIBS:</p>

```<code>boost_filesystem-vc100-mt-1_44
</code>```

ContentLicense: CC BY-SA 2.5

Title: Linking to boost through SConstruct

Body:
I'm trying to work on a cross-platform project that uses boost for the file/directory operations.  I've been using visual studio, but in order to compile on linux, I've decided to switch to SConstruct.

I cannot [correctly?] link to the filesystem library however.

my SConstruct file is as follow:

vLibs = [
            'libboost_system-vc100-mt-1_44.lib',
            'libboost_filesystem-vc100-mt-1_44.lib'];
# LIBS=vLibs,
env = Environment();

env.AppendUnique(CXXFLAGS=Split("/EHsc"));
env.Append(CPPPATH = ["C:\\Program Files (x86)\\boost\\boost_1_44"]);
env.Append(LIBPATH = ["C:\\Program Files (x86)\\boost\\boost_1_44\\lib"]);

env.Program( Glob('test.cpp'),LIBS=vLibs)

I keep getting errors like

test.obj : error LNK2019: unresolved external symbol "class boost::system::error_category const & __cdecl boost::system::generic_category(void)" (?generic_category@system@boost@@YAAEBVerror_category@12@XZ) referenced in function "void __cdecl boost::system::`dynamic initializer for 'posix_category''(void)" (??__Eposix_category@system@boost@@YAXXZ)

If I use visual studio, I get similar errors:

Error 2   error LNK2001: unresolved external symbol "class boost::system::error_category const & __cdecl boost::system::generic_category(void)" (?generic_category@system@boost@@YAABVerror_category@12@XZ)   T:\VS\temp\test.obj temp

Until I add the libraries to the project, after which the errors go away and it compiles fine (in visual studio not SConstruct).

I've tried every combination of the libraries (shared/unshared/runtime-shared/runtime-unshared/debug), but I always get the same errors.

I've been searching for an answer for the last 6+ hours, so I'm grateful for any help.

NOTE: I'm not using autolinking (#define BOOST_ALL_NO_LIB) because gcc doesn't support it)

Here's the output of Scons:

scons: Reading SConscript files ...
scons: done reading SConscript files.
scons: Building targets ...

link /nologo /OUT:build\test.exe "/LIBPATH:C:\Program Files (x86)\boost\boost_1_44\lib" libboost_system-vc100-mt-1_44.lib     libboost_filesystem-vc100-mt-1_44.lib build\test.obj
test.obj : error LNK2019: unresolved external symbol "class boost::system::error_category const & __cdecl     boost::system::generic_category(void)" (?generic_category@system@boost@@YAAEBVerror_category@12@XZ) referenced in function "void __cdecl boost::system::`dynamic initializer for 'posix_category''(void)" (??    __Eposix_category@system@boost@@YAXXZ)
test.obj : error LNK2019: unresolved external symbol "class boost::system::error_category const & __cdecl     boost::system::system_category(void)" (?system_category@system@boost@@YAAEBVerror_category@12@XZ) referenced in function "void __cdecl boost::system::`dynamic initializer for 'native_ecat''(void)" (??    __Enative_ecat@system@boost@@YAXXZ)
build\test.exe : fatal error LNK1120: 2 unresolved externals
scons: *** [build\test.exe] Error 1120
scons: building terminated because of errors.

Body:
I don't think the lib prefix nor suffix should be present.  Try these it like this in your SCons LIBS:

boost_filesystem-vc100-mt-1_44


答:
The main issue of your snippet is, that your method signatur does not define a Return type. Either use void then you have a method and nothing is returned from this method (and no return keyword is allowed in the body. Or you define a return type such as String, int etc and you'll have a function returning some value/object. (return keyword required in the body).

Your method signature should look like

```<code>public static string GenerateRandonName()
</code>```

Body:
The main issue of your snippet is, that your method signatur does not define a Return type. Either use void then you have a method and nothing is returned from this method (and no return keyword is allowed in the body. Or you define a return type such as String, int etc and you'll have a function returning some value/object. (return keyword required in the body).

Your method signature should look like

public static string GenerateRandonName()


问:
Why does Pycharm keep telling me some of my variables aren't defined?
I'm trying to boost my experience in Python using a tutorial on how to make a calculator in Python that i found on youtube, here's the link: https://www.youtube.com/watch?v=J-mvqlkHOHY . The reason why i ask here is because commenting is disabled there. The problem i have with my code is that no matter how identical my code is to his, PyCharm keeps telling me that the variable "side" in my functions i_calc() and button() is unfilled.
Every time i click on the variable to highlight it, i can see a connection between the parameter and the value of the variable but not the same for the variable name.

Here's the code block that caused the problem:

```<code>from Tkinter import*

def i_calc(source, side):
    store_obj = Frame(source, borderwidth=1, bd=4, bg="powder blue")
    store_obj.pack(side=side, expand=YES, fill=BOTH)
    return store_obj

def button(source, side, text, command=None):
    store_obj = button(source, text=text, command=command)
    store_obj.pack(side=side, expand=YES, fill=BOTH)
    return store_obj
</code>```

答: This means that when you called the function, you didn't input a value for side. (Or at least I assume so, since I can't look at the code where you called it.) You need to make sure when you call i_calc, you input 2 values.</p>

Body:
I'm trying to boost my experience in Python using a tutorial on how to make a calculator in Python that i found on youtube, here's the link: https://www.youtube.com/watch?v=J-mvqlkHOHY . The reason why i ask here is because commenting is disabled there. The problem i have with my code is that no matter how identical my code is to his, PyCharm keeps telling me that the variable "side" in my functions i_calc() and button() is unfilled.
Every time i click on the variable to highlight it, i can see a connection between the parameter and the value of the variable but not the same for the variable name.

Here's the code block that caused the problem:

from Tkinter import*

def i_calc(source, side):
    store_obj = Frame(source, borderwidth=1, bd=4, bg="powder blue")
    store_obj.pack(side=side, expand=YES, fill=BOTH)
    return store_obj

def button(source, side, text, command=None):
    store_obj = button(source, text=text, command=command)
    store_obj.pack(side=side, expand=YES, fill=BOTH)
    return store_obj


问:
Include momentjs in own definition files in typescript
I write my own *.d.ts definition files for my project. Some type definitions relay on the javascript library moment.

In the (normal) *.ts files i can import moment with import * as moment from 'moment' and refer to the moment object as moment.Moment but i didn't get it work in the definition files.

i tried
/// <reference path="<path-to-modules>/node_modules/moment/moment.d.ts" /> (with no effect)

import * as moment from 'moment' (with the effect that the following declarations can't be used anymore)

So, what is the right way to import the moment namespace to my own definition files?

答:
what is the right way to import the moment namespace to my own definition files

The right way is what you mentioned :

```<code>import * as moment from 'moment'
</code>```

(with the effect that the following declarations can't be used anymore

They can be used. Your library depends on moment and npm install should install moment for your users. Alternatively have moment as a peerDependency and mention users that they should install moment (if they don't they will get TypeScript errors anyways )

Body:
what is the right way to import the moment namespace to my own definition files

The right way is what you mentioned :

import * as moment from 'moment'

(with the effect that the following declarations can't be used anymore

They can be used. Your library depends on moment and npm install should install moment for your users. Alternatively have moment as a peerDependency and mention users that they should install moment (if they don't they will get TypeScript errors anyways )


答:
So you should use something called Intent.

```<code>if (login successful) {
     Intent intent = Intent(activityYourIn.this, nextactivity.class);
startActivity(intent):
}
</code>```

Just fill out the activity your in, and the next activity. Hope this helps.

Title: how to jump from signup page to the next activity on the click of the signup button

Body:
So you should use something called Intent.

if (login successful) {
     Intent intent = Intent(activityYourIn.this, nextactivity.class);
startActivity(intent):
}

Just fill out the activity your in, and the next activity. Hope this helps.


问:
Wait until all Ajax finish processing inside another Ajax, then send data
I'm trying to send data off with data from multiple other Ajax requests. The issues comes when sendDataOffAjax() is called, no actual data was sent, because it fires off before any of the other functions have a change to add data. I could easily fix this by just using asyn: false everywhere, but from what I read, that's bad practice.

Here is my code:

```<code>let requests = [];
$.ajax({
    url: someUrl,
    method: 'GET',
    dataType: 'json',
    complete: function (data) {
        if (data.exists) {
            if (condition) {
                requests.push(anotherAjax());
            }
            if (condition) {
                requests.push(someDifferentAjax());
            }
        }
        requests.push(alwaysRunAjax());
    }
}).done(function () {
    $.when.apply($, requests).done(function () {
        sendDataOffAjax();
    });
});
</code>```

Heres what anotherAjax() looks like (All the other Ajax requests also look like this):

```<code>function anotherAjax() {
    return $.ajax({
        url: someUrl,
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        method: 'GET',
        dataType: 'json',
        complete: function (data) {
            if (data.exists) {
                toSendData.data['NEW_DATA'] = {
                    'data': data.responseJSON
                }
            }
            //send complete signal?
        }
    })
}
</code>```

How could I make it wait until all the data is added through the other Ajax requests, then launch sendDataOffAjax().

The log looks like this:

```<code>Data sent
anotherAjax Data added
alwaysRunAjax Data added
someDifferentAjax Data added
</code>```

答:
When it comes to ajax requests, .complete(), according to jQuery's docs, runs only after the success or error callback is run and .done() is the same as calling .success(). So with this in mind you can see why the code in your done callback is running first. You should be able to switch the code from your complete callback to your done callback and vice-versa to get the desired effect.

So Try:

```<code>let requests = [];
$.ajax({
  url: someUrl,
  method: 'GET',
  dataType: 'json',
  complete: function () {
    $.when.apply($, requests).done(function () {
      sendDataOffAjax();
    });
  }
}).done(function (data) {
  if (data) {
    if (condition) {
      requests.push(anotherAjax());
    }
    if (condition) {
      requests.push(someDifferentAjax());
    }
 }
 requests.push(alwaysRunAjax());
});
</code>```

Now, as long as all of your ajax functions you are calling here return deferred objects your requests array should be filled and $.when() should wait until all the deferred objects resolve.

Body:
I'm trying to send data off with data from multiple other Ajax requests. The issues comes when sendDataOffAjax() is called, no actual data was sent, because it fires off before any of the other functions have a change to add data. I could easily fix this by just using asyn: false everywhere, but from what I read, that's bad practice.

Here is my code:

let requests = [];
$.ajax({
    url: someUrl,
    method: 'GET',
    dataType: 'json',
    complete: function (data) {
        if (data.exists) {
            if (condition) {
                requests.push(anotherAjax());
            }
            if (condition) {
                requests.push(someDifferentAjax());
            }
        }
        requests.push(alwaysRunAjax());
    }
}).done(function () {
    $.when.apply($, requests).done(function () {
        sendDataOffAjax();
    });
});

Heres what anotherAjax() looks like (All the other Ajax requests also look like this):

function anotherAjax() {
    return $.ajax({
        url: someUrl,
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        method: 'GET',
        dataType: 'json',
        complete: function (data) {
            if (data.exists) {
                toSendData.data['NEW_DATA'] = {
                    'data': data.responseJSON
                }
            }
            //send complete signal?
        }
    })
}

How could I make it wait until all the data is added through the other Ajax requests, then launch sendDataOffAjax().

The log looks like this:

Data sent
anotherAjax Data added
alwaysRunAjax Data added
someDifferentAjax Data added

Body:
When it comes to ajax requests, .complete(), according to jQuery's docs, runs only after the success or error callback is run and .done() is the same as calling .success(). So with this in mind you can see why the code in your done callback is running first. You should be able to switch the code from your complete callback to your done callback and vice-versa to get the desired effect.

So Try:

let requests = [];
$.ajax({
  url: someUrl,
  method: 'GET',
  dataType: 'json',
  complete: function () {
    $.when.apply($, requests).done(function () {
      sendDataOffAjax();
    });
  }
}).done(function (data) {
  if (data) {
    if (condition) {
      requests.push(anotherAjax());
    }
    if (condition) {
      requests.push(someDifferentAjax());
    }
 }
 requests.push(alwaysRunAjax());
});

Now, as long as all of your ajax functions you are calling here return deferred objects your requests array should be filled and $.when() should wait until all the deferred objects resolve.


问:
Rotation matrix openCV
I would like to know how to find the rotation matrix for a set of features in a frame.
I will be more specific. I have 2 frames with 20 features, let's say frame 1 and frame 2. I could estimate the location of the features in both frames. For example let say a certain frame 1 feature at location (x, y) and I know exactly where it is so let's say (x',y').

My question is that the features are moved and probably rotated so I wanna know how to compute the rotation matrix, I know the rotation matrix for 2D:

But I don't know how to compute the angle, and how to do that? I tried a function in OpenCV which is cv2DRotationMatrix(); but the problem which as I mentioned above I don't know how to compute the angle for the rotation matrix and  another problem which it gives 2*3 matrix, so it won't work out cause if I will take this  20*2 matrix, (20 is the number of features and 2 are the location in (x,y)) and multiply it by the matrix by 2*3 which is the results from the function then I will get 20*3 matrix which it doesn't seem to be realistic cause I'm working with 2D.

So what should I do? To be more specific again, show me how to compute the angle to use it in the matrix?

答:
Have a look at this function:

cvGetAffineTransform

You give it three points in the first frame and three in the second. And it computes the affine transformation matrix (translation + rotation)

If you want, you could also try

cvGetPerspectiveTransform

With that, you can get translation+rotation+skew+lot of others.

Title: Rotation matrix openCV


问:
update one json file with a second json based on third json with jq
I have three JSON files:

vault.json:

```<code>{
  "aws":
  {
    "access_key_id": "My-Key-id",
    "secret_access_key": "My-Access-Key"
  },
  "ssl":
  {
    "crt": "My-Crt",
    "key": "My-Key",
    "req": "My-Req"
  }
}
</code>```

input.json:

```<code>{
  ".cloud_cpi_key": {
    "type": "wildcard_domain",
    "configurable": true,
    "credential": false,
    "value": "vault-supplied-value",
    "optional": false
  },
  ".cloud_cpi_secret": {
    "type": "wildcard_domain",
    "configurable": true,
    "credential": false,
    "value": "vault-supplied-value",
    "optional": false
  },
  ".properties.networking_point_of_entry": {
    "type": "selector",
    "configurable": true,
    "credential": false,
    "value": "external_ssl",
    "optional": false
  },
  ".properties.networking_point_of_entry.external_ssl.ssl_rsa_certificate": {
    "type": "rsa_cert_credentials",
    "configurable": true,
    "credential": true,
    "value": {
      "private_key_pem": "vault-supplied-value",
      "cert_pem": "vault-supplied-value"
    },
    "optional": false
  }
}
</code>```

keyfile.json

```<code>{
  ".cloud_cpi_key.value": "aws.access_key_id",
  ".cloud_cpi_secret": "secret_access_key",
  ".properties.networking_point_of_entry.external_ssl.ssl_rsa_certificate.value.private_key_pem": "ssl.key",
  ".properties.networking_point_of_entry.external_ssl.ssl_rsa_certificate.value.cert_pem": "ssl.crt"
}
</code>```

I'd like to update the second json file, with the values from the first json, based on the third json.
can this be done via JQ to provide output.json?

output.json:

```<code>{
  ".cloud_cpi_key": {
    "type": "string",
    "configurable": true,
    "credential": true,
    "value": "My-Key-id",
    "optional": false
  },
  ".cloud_cpi_secret": {
    "type": "string",
    "configurable": true,
    "credential": true,
    "value": "My-Access-Key",
    "optional": false
  },
  ".properties.networking_point_of_entry": {
    "type": "selector",
    "configurable": true,
    "credential": false,
    "value": "external_ssl",
    "optional": false
  },

".properties.networking_point_of_entry.external_ssl.ssl_rsa_certificate": {
    "type": "rsa_cert_credentials",
    "configurable": true,
    "credential": true,
    "value": {
      "private_key_pem": "My-Key",
      "cert_pem": "My-Crt"
    },
    "optional": false
  }
}
</code>```

I can modify keyfile.json any way I like to make things easier, like

```<code>{
    "fromkey": "aws.access_key_id"
    "tokey": ".cloud_cpi_key.value"
},
{   "fromkey": ....
}
</code>```

But no values may be placed in keyfile.json, only key names.

And I can modify vault.json, to put things in arrays, or what-have-you, but I cannot change the lowest levels, i.e. I cannot change:

```<code>{
    "access_key_id": "My-Key-id",
    "secret_access_key": "My-Access-Key"
}
</code>```

I cannot modify input.json.
How can I accomplish this with JQ?

答:
You don't give details about the transformation you have in mind, but if you can specify the algorithm, then rest assured, it can be done in jq.

Perhaps the thing you're missing is how to get jq to read the three files.  One way to proceed would be to use the invocation:

```<code>jq --argfile keyfile keyfile.json --argfile vault vault.json -f vault.jq input.json
</code>```

where vault.jq is the file containing your jq program, in which you would refer to the contents of keyfile.json as $keyfile, and similarly for the contents of vault.json

Simplifying keyfile.json

Since you indicate you have some flexibility about the format of keyfile.json, and since it appears to hold path information, I would recommend considering adopting path specifications that can be used directly with the jq builtins getpath and setpath.

For example, consider this format for keyfile.json:

```<code>[ [<path in input.json>], [<path in vault.json> ], ... ]
</code>```

The first two entries corresponding to your example would thus be:

```<code>[
  [ [".cloud_cpi_key","value"], ["aws","access_key_id"]],
  [ [".cloud_cpi_secret"], ["aws", "secret_access_key"]]
]
</code>```

To use the "vault" as the basis for updates, your jq program would then be the one-liner:

```<code>reduce $keyfile[] as $p (.; setpath(($p|.[0]); $vault|getpath($p|.[1])))
</code>```

Body:
I have three JSON files:

vault.json:

{
  "aws":
  {
    "access_key_id": "My-Key-id",
    "secret_access_key": "My-Access-Key"
  },
  "ssl":
  {
    "crt": "My-Crt",
    "key": "My-Key",
    "req": "My-Req"
  }
}

input.json:

{
  ".cloud_cpi_key": {
    "type": "wildcard_domain",
    "configurable": true,
    "credential": false,
    "value": "vault-supplied-value",
    "optional": false
  },
  ".cloud_cpi_secret": {
    "type": "wildcard_domain",
    "configurable": true,
    "credential": false,
    "value": "vault-supplied-value",
    "optional": false
  },
  ".properties.networking_point_of_entry": {
    "type": "selector",
    "configurable": true,
    "credential": false,
    "value": "external_ssl",
    "optional": false
  },
  ".properties.networking_point_of_entry.external_ssl.ssl_rsa_certificate": {
    "type": "rsa_cert_credentials",
    "configurable": true,
    "credential": true,
    "value": {
      "private_key_pem": "vault-supplied-value",
      "cert_pem": "vault-supplied-value"
    },
    "optional": false
  }
}

keyfile.json

{
  ".cloud_cpi_key.value": "aws.access_key_id",
  ".cloud_cpi_secret": "secret_access_key",
  ".properties.networking_point_of_entry.external_ssl.ssl_rsa_certificate.value.private_key_pem": "ssl.key",
  ".properties.networking_point_of_entry.external_ssl.ssl_rsa_certificate.value.cert_pem": "ssl.crt"
}

I'd like to update the second json file, with the values from the first json, based on the third json.
can this be done via JQ to provide output.json?

output.json:

{
  ".cloud_cpi_key": {
    "type": "string",
    "configurable": true,
    "credential": true,
    "value": "My-Key-id",
    "optional": false
  },
  ".cloud_cpi_secret": {
    "type": "string",
    "configurable": true,
    "credential": true,
    "value": "My-Access-Key",
    "optional": false
  },
  ".properties.networking_point_of_entry": {
    "type": "selector",
    "configurable": true,
    "credential": false,
    "value": "external_ssl",
    "optional": false
  },

".properties.networking_point_of_entry.external_ssl.ssl_rsa_certificate": {
    "type": "rsa_cert_credentials",
    "configurable": true,
    "credential": true,
    "value": {
      "private_key_pem": "My-Key",
      "cert_pem": "My-Crt"
    },
    "optional": false
  }
}

I can modify keyfile.json any way I like to make things easier, like

{
    "fromkey": "aws.access_key_id"
    "tokey": ".cloud_cpi_key.value"
},
{   "fromkey": ....
}

But no values may be placed in keyfile.json, only key names.

And I can modify vault.json, to put things in arrays, or what-have-you, but I cannot change the lowest levels, i.e. I cannot change:

{
    "access_key_id": "My-Key-id",
    "secret_access_key": "My-Access-Key"
}

I cannot modify input.json.
How can I accomplish this with JQ?

Body:
You don't give details about the transformation you have in mind, but if you can specify the algorithm, then rest assured, it can be done in jq.

Perhaps the thing you're missing is how to get jq to read the three files.  One way to proceed would be to use the invocation:

jq --argfile keyfile keyfile.json --argfile vault vault.json -f vault.jq input.json

where vault.jq is the file containing your jq program, in which you would refer to the contents of keyfile.json as $keyfile, and similarly for the contents of vault.json

Simplifying keyfile.json

Since you indicate you have some flexibility about the format of keyfile.json, and since it appears to hold path information, I would recommend considering adopting path specifications that can be used directly with the jq builtins getpath and setpath.

For example, consider this format for keyfile.json:

[ [<path in input.json>], [<path in vault.json> ], ... ]

The first two entries corresponding to your example would thus be:

[
  [ [".cloud_cpi_key","value"], ["aws","access_key_id"]],
  [ [".cloud_cpi_secret"], ["aws", "secret_access_key"]]
]

To use the "vault" as the basis for updates, your jq program would then be the one-liner:

reduce $keyfile[] as $p (.; setpath(($p|.[0]); $vault|getpath($p|.[1])))


问:
How to fetch data from same class for different objects
I have a two component in ExtJS. I am creating one class separately.

```<code>{
    xtype: 'component',
    id: 'myComponentId',
    listeners: {
        afterrender: function(me, eOpts) {
            var myObj = new SomeClass({
                "divID": this.id,
                "url": "data.json"
            });
        }
    }
}, {
    xtype: 'component',
    width: 30,
    style: {
        color: '#FFFFFF',
        backgroundColor: '#000000'
    }
}, {
    xtype: 'component',
    id: 'myComponentId2',
    listeners: {
        afterrender: function(me, eOpts) {
            var myObj = new SomeClass({
                "divID": this.id,
                "url": "data2.json"
            });
        }
    }
}
</code>```

Afterrendering I am creating an object of a that class.

```<code>SomeClass = function(args) {
    var dataUrl = args.url;
    var divID = args.divID;
    var div = document.getElementById(divID);

    var myTable = '<input type="text" id="myInput"  list="myUL" myOpen = "openingList()" myOpen="openingList()" style="width:100% " >' +
        '<ul id="myUL" hidden=false>' + '<li>' + '<a href="#" ></a>' + '</li>' + '</ul>';
    div.innerHTML = myTable;

    function getData(callback) {
        var httpRequest = new XMLHttpRequest();
        httpRequest.open('GET', dataUrl, true);
        httpRequest.onreadystatechange = function() {
            if (httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200) {
                callback(httpRequest.responseText);
            }
        };
        httpRequest.send();
    }
    getData(function(data) {
        var jsonc = JSON.parse(data);
        var new_opt = "";
        for (i = 0; i < jsonc.length; i++) {
            new_opt += '<li><a href="#">' + jsonc[i]['VALUE'] + '</a></li>';
        }
        document.getElementById('myUL').innerHTML = new_opt;
    });
    myOpen = function() {
        var input, filter, ul, li, a, i;
        ul = document.getElementById("myUL");
        ul.hidden = false;
        input = document.getElementById("myInput");
        filter = input.value.toUpperCase();
        var splitedVal = filter.split(";");
        filter = (splitedVal[splitedVal.length - 1]);
        li = ul.getElementsByTagName("li");
        for (i = 0; i < li.length; i++) {
            a = li[i].getElementsByTagName("a")[0];
            if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
                li[i].style.display = "";
            } else {
                li[i].style.display = "none";

            }
        }
    }
    return div;
}
</code>```

Now I am creating two object with two different divID for two different component. When I creating second object the data (which is coming from data.json) is getting lost and second object data is appeared. Also ul tag for the second objecte is not shown.

Can anybody help me to solve this. Or explain me where I am doing wrong.

答:
After looking at your code briefly it seems like you are loading your data and the displaying that data in 2 components. If so then you can simplify this code a lot. Please look at following examples. http://examples.sencha.com/extjs/6.5.0/examples/classic/view/data-view.html

This examples shows how to load the data via Ajax and then display in a component. Though I understand you have 2 components here but the concept is similar (decouple data and component).

Body:
I have a two component in ExtJS. I am creating one class separately.

{
    xtype: 'component',
    id: 'myComponentId',
    listeners: {
        afterrender: function(me, eOpts) {
            var myObj = new SomeClass({
                "divID": this.id,
                "url": "data.json"
            });
        }
    }
}, {
    xtype: 'component',
    width: 30,
    style: {
        color: '#FFFFFF',
        backgroundColor: '#000000'
    }
}, {
    xtype: 'component',
    id: 'myComponentId2',
    listeners: {
        afterrender: function(me, eOpts) {
            var myObj = new SomeClass({
                "divID": this.id,
                "url": "data2.json"
            });
        }
    }
}

Afterrendering I am creating an object of a that class.

SomeClass = function(args) {
    var dataUrl = args.url;
    var divID = args.divID;
    var div = document.getElementById(divID);

    var myTable = '<input type="text" id="myInput"  list="myUL" myOpen = "openingList()" myOpen="openingList()" style="width:100% " >' +
        '
' + '
' + '' + '
' + '
';
    div.innerHTML = myTable;

    function getData(callback) {
        var httpRequest = new XMLHttpRequest();
        httpRequest.open('GET', dataUrl, true);
        httpRequest.onreadystatechange = function() {
            if (httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200) {
                callback(httpRequest.responseText);
            }
        };
        httpRequest.send();
    }
    getData(function(data) {
        var jsonc = JSON.parse(data);
        var new_opt = "";
        for (i = 0; i < jsonc.length; i++) {
            new_opt += '
' + jsonc[i]['VALUE'] + '
';
        }
        document.getElementById('myUL').innerHTML = new_opt;
    });
    myOpen = function() {
        var input, filter, ul, li, a, i;
        ul = document.getElementById("myUL");
        ul.hidden = false;
        input = document.getElementById("myInput");
        filter = input.value.toUpperCase();
        var splitedVal = filter.split(";");
        filter = (splitedVal[splitedVal.length - 1]);
        li = ul.getElementsByTagName("li");
        for (i = 0; i
 -1) {
                li[i].style.display = "";
            } else {
                li[i].style.display = "none";

            }
        }
    }
    return div;
}

Now I am creating two object with two different divID for two different component. When I creating second object the data (which is coming from data.json) is getting lost and second object data is appeared. Also ul tag for the second objecte is not shown.

Can anybody help me to solve this. Or explain me where I am doing wrong.


问:
Ruby case statement not returning when condition evaluates to true
Ruby newbie here. I've written a case statement to check whether a string parameter ends with "?", and I don't understand the result. Here's my code:

```<code>class Bob
  def self.hey(phrase)
    case phrase
    when phrase.chars.last == "?"
      'Sure.'
    else
      'Whatever.'
    end
  end
end
</code>```

When I call Bob.hey("Does this cryogenic chamber make me look fat?") I get back Whatever., despite "Does this cryogenic chamber make me look fat?".chars.last == "?" evaluating to true in IRB. I can't figure out what I'm missing. Any help would be appreciated.

答:
There's two forms of the case statement, one where you specify case expr and another where you don't. In the first form the expr value is tested against all of the branches with ===. In the second form each branch is evaluated like an if would be.

This means there's two ways to fix this. Either drop the term from the case part:

```<code>def self.hey(phrase)
  case
  when phrase.chars.last == "?"
    'Sure.'
  else
    'Whatever.'
  end
end
</code>```

Or switch the case to focus on the important part:

```<code>def self.hey(phrase)
  case phrase.chars.last
  when "?"
    'Sure.'
  else
    'Whatever.'
  end
end
</code>```

Another way to do this is to use a regular expression:

```<code>def self.hey(phrase)
  case phrase
  when /\?\z/
    'Sure.'
  else
    'Whatever.'
  end
end
</code>```

Where /\?\z/ means "question mark character at end of string.

Body:
Ruby newbie here. I've written a case statement to check whether a string parameter ends with "?", and I don't understand the result. Here's my code:

class Bob
  def self.hey(phrase)
    case phrase
    when phrase.chars.last == "?"
      'Sure.'
    else
      'Whatever.'
    end
  end
end

When I call Bob.hey("Does this cryogenic chamber make me look fat?") I get back Whatever., despite "Does this cryogenic chamber make me look fat?".chars.last == "?" evaluating to true in IRB. I can't figure out what I'm missing. Any help would be appreciated.

Body:
There's two forms of the case statement, one where you specify case expr and another where you don't. In the first form the expr value is tested against all of the branches with ===. In the second form each branch is evaluated like an if would be.

This means there's two ways to fix this. Either drop the term from the case part:

def self.hey(phrase)
  case
  when phrase.chars.last == "?"
    'Sure.'
  else
    'Whatever.'
  end
end

Or switch the case to focus on the important part:

def self.hey(phrase)
  case phrase.chars.last
  when "?"
    'Sure.'
  else
    'Whatever.'
  end
end

Another way to do this is to use a regular expression:

def self.hey(phrase)
  case phrase
  when /\?\z/
    'Sure.'
  else
    'Whatever.'
  end
end

Where /\?\z/ means "question mark character at end of string.


问:
PyCharm doesn't recognize module gc
I am trying to use gc module and it works both in debug and normal runs. Unfortunately, PyCharm itself doesn't see this module exists and complains on it:

UPDATE

I was unable to install gc with neither pip install gc, not conda install gc, although it is working. I decided this package is built-in.

答: If it runs, but PyCharm is complaining, go to file and do invalidate caches / restart.

Title: PyCharm doesn't recognize module gc


问:
Ruby RegEx to Match between . and :
I have this string: "51. some thing:"
 and would like to extract just "some thing" using reg ex in ruby. Can anyone point me in the right direction to match between a . and a : and discard everything else?

答:
This should do it:

```<code>(?<=\.).+?(?=:)
</code>```

If you want to avoid leading and trailing spaces in the match, you can use this:

```<code>(?<=\.\s*)\S.*?(?=\s*:)
</code>```

Edit: I just checked and noticed that Ruby doesn't support lookbehind, which is used here. Alternatively, you can use this and take the capture of the regex as result:

```<code>\.\s*(\S.*?)\s*:
</code>```

Title: Ruby RegEx to Match between . and :

Body:
This should do it:

(?<=\.).+?(?=:)

If you want to avoid leading and trailing spaces in the match, you can use this:

(?<=\.\s*)\S.*?(?=\s*:)

Edit: I just checked and noticed that Ruby doesn't support lookbehind, which is used here. Alternatively, you can use this and take the capture of the regex as result:

\.\s*(\S.*?)\s*:


问:
How can I change Windows auth for a method based on the parameters it is passed?
Right now in my MVC application, I am using Windows Auth to restrict access to certain methods, like so:

```<code>   [Authorize(Roles = SystemRole.AppAdmin)]

    public ActionResult Edit(int? id)
    {
        //Find group by id in db
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    [Authorize(Roles = SystemRole.AppAdmin)]
    public ActionResult Edit([Bind(Include = "id, otherParam")] Item thisItem)
        //Post changes to db
    }
</code>```

I would like to have my code so that another AD group has limited admin rights to edit ONLY an item with a certain id (e.g. item 7), not allow them to access this method to try to edit other items.

I've tried Googling/searching Stack Overflow/reading Windows Auth documentation but must not be using good keywords, because I surely can't be the first person to want to do something like this.

答:
From what I understand, what you want is to, based on their AD group, allow groups to make changes to specific groups.

If that is the case, see if there is an AD group that encompasses all these admins, have that be the authorize attribute

```<code>[Authorize(Roles = SystemRole.SomeBaseAdminGroup)]
</code>```

Then fetch their claims and do a case switch based on the return into specific methods or specialized method calls. Since all roles are translated into Claims for Identity,

Body:
Right now in my MVC application, I am using Windows Auth to restrict access to certain methods, like so:

   [Authorize(Roles = SystemRole.AppAdmin)]

    public ActionResult Edit(int? id)
    {
        //Find group by id in db
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    [Authorize(Roles = SystemRole.AppAdmin)]
    public ActionResult Edit([Bind(Include = "id, otherParam")] Item thisItem)
        //Post changes to db
    }

I would like to have my code so that another AD group has limited admin rights to edit ONLY an item with a certain id (e.g. item 7), not allow them to access this method to try to edit other items.

I've tried Googling/searching Stack Overflow/reading Windows Auth documentation but must not be using good keywords, because I surely can't be the first person to want to do something like this.

Body:
From what I understand, what you want is to, based on their AD group, allow groups to make changes to specific groups.

If that is the case, see if there is an AD group that encompasses all these admins, have that be the authorize attribute

[Authorize(Roles = SystemRole.SomeBaseAdminGroup)]

Then fetch their claims and do a case switch based on the return into specific methods or specialized method calls. Since all roles are translated into Claims for Identity,


问:
Find missing rows in number range in SQL Server
I am using PHP to access a SQL server database and I have 2 numbers stored as PHP variables.

For example one variable is 10 and the other variable is 15.

I need to output a list of 'missing' documents i.e rows where a certain column col1 does not contain numbers between 10 and 15.

Is it possible to do this in SQL i.e. something like ... WHERE col1 NOT IN (10..15)?

Example:

```<code>col1
----
2
4
6
8
10
12
14
16
18
20
</code>```

Variables:

```<code>$start = 10
$end = 15
</code>```

Desired result using SQL only:

```<code>result
------
11
13
15
</code>```

答:
If you're using PHP and variables have you defined them as variables?

Where are you getting the variables from? For example if you are submitting a form you need to output that information:

```<code><form>
<input type="text" name="search1">
<input type="text" name="search2">
</code>```

...etc.

Then you can on your php define this as:

```<code>$var1 = $_POST['search1'];
$var2 = $_POST['search2'];
</code>```

Then in your MySQL statement (as above answer would work)

```<code>SELECT * FROM TABLE_NAME
WHERE col1 NOT IN ('%".$search1."%', '%".$search2."%')
</code>```

I hope that helps in any case. Your question was a little vague so thought I'd try and cover a couple of bases.

Body:
I am using PHP to access a SQL server database and I have 2 numbers stored as PHP variables.

For example one variable is 10 and the other variable is 15.

I need to output a list of 'missing' documents i.e rows where a certain column col1 does not contain numbers between 10 and 15.

Is it possible to do this in SQL i.e. something like ... WHERE col1 NOT IN (10..15)?

Example:

col1
----
2
4
6
8
10
12
14
16
18
20

Variables:

$start = 10
$end = 15

Desired result using SQL only:

result
------
11
13
15

Body:
If you're using PHP and variables have you defined them as variables?

Where are you getting the variables from? For example if you are submitting a form you need to output that information:

<form>
<input type="text" name="search1">
<input type="text" name="search2">

...etc.

Then you can on your php define this as:

$var1 = $_POST['search1'];
$var2 = $_POST['search2'];

Then in your MySQL statement (as above answer would work)

SELECT * FROM TABLE_NAME
WHERE col1 NOT IN ('%".$search1."%', '%".$search2."%')

I hope that helps in any case. Your question was a little vague so thought I'd try and cover a couple of bases.


问:
Saving collection of viewed elements in Unity / Vuforia
I have a scavenger hunt going where you find 9 different elements.  Only 4 have the special 'token'.  When you view the specific elements there is a token on the bottom of the screen that shows up as collected.  Problem is, I can't figure out how to save this using playerprefs so that you can collect all 4 tokens, even if you close out of the game.  Here is the token script

```<code>using UnityEngine;
</code>```

using Vuforia;
using System.Collections;

public class token_icon : MonoBehaviour, ITrackableEventHandler
{

```<code>private TrackableBehaviour mTrackableBehaviour;

public GameObject token;
public GameObject lime_token;
public GameObject loconut_token;
public GameObject crown_token;
public GameObject gin_token;

void Start()
{
    mTrackableBehaviour = GetComponent<TrackableBehaviour>();
    if (mTrackableBehaviour)
    {
        mTrackableBehaviour.RegisterTrackableEventHandler(this);
    }
}

public void OnTrackableStateChanged(
                                TrackableBehaviour.Status previousStatus,
                                TrackableBehaviour.Status newStatus)
{
    if (newStatus == TrackableBehaviour.Status.DETECTED ||
        newStatus == TrackableBehaviour.Status.TRACKED)
    {
        token.SetActive(true);
    }
    else
    {
        token.SetActive(false);
    }
}
</code>```

}

答:
The PlayerPrefs class only saves and loads data of types int, float, and string. To save the state of each token, you can cast the local newStatus enum to an int and use that as the value saved by PlayerPrefs. In addition, you should create new functions to save and load to and from PlayerPrefs. When loading back simply cast PlayerPrefs.GetInt("Key") back to the TrackableBehaviour.Status enum. Here is the link to the documentation for PlayerPrefs in case you haven't seen it already: https://docs.unity3d.com/ScriptReference/PlayerPrefs.html

I modified your source code by adding two new functions to show how you could get started.

public class token_icon : MonoBehaviour, ITrackableEventHandler
{

```<code>private TrackableBehaviour mTrackableBehaviour;

public GameObject token;
public GameObject lime_token;
public GameObject loconut_token;
public GameObject crown_token;
public GameObject gin_token;

void Start()
{
    //Inserted Function
    LoadStatus();

    mTrackableBehaviour = GetComponent<TrackableBehaviour>();
    if (mTrackableBehaviour)
    {
        mTrackableBehaviour.RegisterTrackableEventHandler(this);
    }
}

public void OnTrackableStateChanged(
                                TrackableBehaviour.Status previousStatus,
                                TrackableBehaviour.Status newStatus)
{
    if (newStatus == TrackableBehaviour.Status.DETECTED ||
        newStatus == TrackableBehaviour.Status.TRACKED)
    {
        token.SetActive(true);
    }
    else
    {
        token.SetActive(false);
    }
    //Inserted Function
    SaveStatus();
}

//Save to PlayerPrefs
private void SaveStatus()
{
    PlayerPrefs.SetInt("Token", (int)newStatus);
    PlayerPrefs.Save();
}

//Load from PlayerPrefs
private void LoadStatus()
{
    if (PlayerPrefs.HasKey("Token"))
    {
        TrackableBehaviour.Status loadStatus = (TrackableBehaviour.Status)PlayerPrefs.GetInt("Token");

        if (loadStatus == TrackableBehaviour.Status.DETECTED ||
            loadStatus == TrackableBehaviour.Status.TRACKED)
        {
            token.SetActive(true);
        }
        else
        {
            token.SetActive(false);
        }
    }
}
</code>```

}

Obviously this can be written in a more general fashion to work for more than just a single token GameObject, but I don't know enough about your workflow to make any guesses about the best way to go about that.

Body:
I have a scavenger hunt going where you find 9 different elements.  Only 4 have the special 'token'.  When you view the specific elements there is a token on the bottom of the screen that shows up as collected.  Problem is, I can't figure out how to save this using playerprefs so that you can collect all 4 tokens, even if you close out of the game.  Here is the token script

using UnityEngine;

using Vuforia;
using System.Collections;

public class token_icon : MonoBehaviour, ITrackableEventHandler
{

private TrackableBehaviour mTrackableBehaviour;

public GameObject token;
public GameObject lime_token;
public GameObject loconut_token;
public GameObject crown_token;
public GameObject gin_token;

void Start()
{
    mTrackableBehaviour = GetComponent<TrackableBehaviour>();
    if (mTrackableBehaviour)
    {
        mTrackableBehaviour.RegisterTrackableEventHandler(this);
    }
}

public void OnTrackableStateChanged(
                                TrackableBehaviour.Status previousStatus,
                                TrackableBehaviour.Status newStatus)
{
    if (newStatus == TrackableBehaviour.Status.DETECTED ||
        newStatus == TrackableBehaviour.Status.TRACKED)
    {
        token.SetActive(true);
    }
    else
    {
        token.SetActive(false);
    }
}

}

Body:
The PlayerPrefs class only saves and loads data of types int, float, and string. To save the state of each token, you can cast the local newStatus enum to an int and use that as the value saved by PlayerPrefs. In addition, you should create new functions to save and load to and from PlayerPrefs. When loading back simply cast PlayerPrefs.GetInt("Key") back to the TrackableBehaviour.Status enum. Here is the link to the documentation for PlayerPrefs in case you haven't seen it already: https://docs.unity3d.com/ScriptReference/PlayerPrefs.html

I modified your source code by adding two new functions to show how you could get started.

public class token_icon : MonoBehaviour, ITrackableEventHandler
{

private TrackableBehaviour mTrackableBehaviour;

public GameObject token;
public GameObject lime_token;
public GameObject loconut_token;
public GameObject crown_token;
public GameObject gin_token;

void Start()
{
    //Inserted Function
    LoadStatus();

    mTrackableBehaviour = GetComponent<TrackableBehaviour>();
    if (mTrackableBehaviour)
    {
        mTrackableBehaviour.RegisterTrackableEventHandler(this);
    }
}

public void OnTrackableStateChanged(
                                TrackableBehaviour.Status previousStatus,
                                TrackableBehaviour.Status newStatus)
{
    if (newStatus == TrackableBehaviour.Status.DETECTED ||
        newStatus == TrackableBehaviour.Status.TRACKED)
    {
        token.SetActive(true);
    }
    else
    {
        token.SetActive(false);
    }
    //Inserted Function
    SaveStatus();
}

//Save to PlayerPrefs
private void SaveStatus()
{
    PlayerPrefs.SetInt("Token", (int)newStatus);
    PlayerPrefs.Save();
}

//Load from PlayerPrefs
private void LoadStatus()
{
    if (PlayerPrefs.HasKey("Token"))
    {
        TrackableBehaviour.Status loadStatus = (TrackableBehaviour.Status)PlayerPrefs.GetInt("Token");

        if (loadStatus == TrackableBehaviour.Status.DETECTED ||
            loadStatus == TrackableBehaviour.Status.TRACKED)
        {
            token.SetActive(true);
        }
        else
        {
            token.SetActive(false);
        }
    }
}

}

Obviously this can be written in a more general fashion to work for more than just a single token GameObject, but I don't know enough about your workflow to make any guesses about the best way to go about that.