问:
Error when my selenium script is launching Internet Explorer
When my test script try to open Internet Explorer, I have an error.

Here is my test script :

```<code>package selenium;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.Select;

public class RegistrationTest{

public  int a = 1;

@Test //This is JUnit annotation

public void testRegister(){

        WebDriver driver ;
        System.setProperty("webdriver.ie.driver","IEDriverServer.exe");

        DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
        capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);

        driver = new InternetExplorerDriver(capabilities);

        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);

        driver.navigate().to("http://newtours.demoaut.com/");

        driver.findElement(By.linkText("REGISTER")).click();
        driver.findElement(By.name("firstName")).sendKeys("User1");
        driver.findElement(By.name("lastName")).sendKeys("Surname1");
        driver.findElement(By.name("phone")).sendKeys("123456789");
        driver.findElement(By.name("userName")).sendKeys("user1@test.com");
        driver.findElement(By.name("address1")).sendKeys("Test Address");
        driver.findElement(By.name("city")).sendKeys("Test City");
        Select select = new Select(driver.findElement(By.name("country")));
        select.selectByVisibleText("ANGOLA");
        driver.findElement(By.name("email")).sendKeys("user1@test.com");
        driver.findElement(By.name("password")).sendKeys("user1");
        driver.findElement(By.name("confirmPassword")).sendKeys("user1");
        driver.findElement(By.name("register")).click();

        driver.quit();

}

 }
</code>```

My POM.xml is :

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cgi.nouguierc</groupId>
<artifactId>WD-Automation</artifactId>
<version>1.0.0-SNAPSHOT</version>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.5.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
        <plugin>
            <!-- Build an executable JAR -->
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>3.0.2</version>
            <configuration>
                <archive>
                    <manifest>
                        <addClasspath>true</addClasspath>
                        <classpathPrefix>lib/</classpathPrefix>
                        <mainClass>selenium.MainJar</mainClass>
                    </manifest>
                </archive>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <executions>
               <execution>
                     <id>copy-dependencies</id>
                     <phase>prepare-package</phase>
                     <goals>
                        <goal>copy-dependencies</goal>
                     </goals>
                     <configuration>
                        <outputDirectory>${project.build.directory}/lib</outputDirectory>
                        <overWriteReleases>false</overWriteReleases>
                        <overWriteSnapshots>false</overWriteSnapshots>
                        <overWriteIfNewer>true</overWriteIfNewer>
                     </configuration>
               </execution>
            </executions>
        </plugin>
    </plugins>
</build>
<dependencies>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.3.1</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
    </dependency>
</dependencies>
</project>
</code>```

When I launch RegistrationTest, Internet is opening, going to the adress "http://newtours.demoaut.com/" and then doing nothing.

And in the console I have some errors :

```<code>Started InternetExplorerDriver server (64-bit)
3.0.0.0
Listening on port 44920
Only local connections are allowed
mars 29, 2017 3:16:07 PM org.openqa.selenium.remote.ProtocolHandshake    createSession
INFOS: Detected dialect: OSS
</code>```

Point is that I can't check or uncheck the box "Enable protected..." (see the screenshot below) because I am on a work network so I can't do what I want.

Screenshot of the checkbox

Maybe someone can help me :)

答:
Here is the solution to your Question-

Replace your code by this:

```<code>    DesiredCapabilities capabilities = new DesiredCapabilities().internetExplorer();
    capabilities.setCapability("platform", "WIN8");
    capabilities.setCapability("version", "11");
    capabilities.setCapability("browserName", "internet explorer");
    capabilities.setCapability("ignoreProtectedModeSettings",1);
    capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);
    driver = new InternetExplorerDriver(capabilities);
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);

    driver.navigate().to("http://newtours.demoaut.com/");

    driver.findElement(By.linkText("REGISTER")).click();
    driver.findElement(By.name("firstName")).sendKeys("User1");
    driver.findElement(By.name("lastName")).sendKeys("Surname1");
    driver.findElement(By.name("phone")).sendKeys("123456789");
    driver.findElement(By.name("userName")).sendKeys("user1@test.com");
    driver.findElement(By.name("address1")).sendKeys("Test Address");
    driver.findElement(By.name("city")).sendKeys("Test City");
    Select select = new Select(driver.findElement(By.name("country")));
    select.selectByVisibleText("ANGOLA");
    driver.findElement(By.name("email")).sendKeys("user1@test.com");
    driver.findElement(By.name("password")).sendKeys("user1");
    driver.findElement(By.name("confirmPassword")).sendKeys("user1");
    driver.findElement(By.name("register")).click();

    driver.quit();
</code>```

The last effort would be : Look in your registry under the HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet
Settings\Zones key. Under there, you should see keys number 0-5. Under keys 1-4, look for a value named 2500, and list either the value for each of the keys, or if the value does not exist.

Having said that I would like you to go through this link where the issue is clearly discussed within Selenium User Group.

Also you may like you to go through this link where the issue is being discussed within Selenium Developers Group.

Let me know if it helps you.

Body:
When my test script try to open Internet Explorer, I have an error.

Here is my test script :

package selenium;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.Select;

public class RegistrationTest{

public  int a = 1;

@Test //This is JUnit annotation

public void testRegister(){

        WebDriver driver ;
        System.setProperty("webdriver.ie.driver","IEDriverServer.exe");

        DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
        capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);

        driver = new InternetExplorerDriver(capabilities);

        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);

        driver.navigate().to("http://newtours.demoaut.com/");

        driver.findElement(By.linkText("REGISTER")).click();
        driver.findElement(By.name("firstName")).sendKeys("User1");
        driver.findElement(By.name("lastName")).sendKeys("Surname1");
        driver.findElement(By.name("phone")).sendKeys("123456789");
        driver.findElement(By.name("userName")).sendKeys("user1@test.com");
        driver.findElement(By.name("address1")).sendKeys("Test Address");
        driver.findElement(By.name("city")).sendKeys("Test City");
        Select select = new Select(driver.findElement(By.name("country")));
        select.selectByVisibleText("ANGOLA");
        driver.findElement(By.name("email")).sendKeys("user1@test.com");
        driver.findElement(By.name("password")).sendKeys("user1");
        driver.findElement(By.name("confirmPassword")).sendKeys("user1");
        driver.findElement(By.name("register")).click();

        driver.quit();

}

 }

My POM.xml is :

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cgi.nouguierc</groupId>
<artifactId>WD-Automation</artifactId>
<version>1.0.0-SNAPSHOT</version>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.5.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
        <plugin>

            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>3.0.2</version>
            <configuration>
                <archive>
                    <manifest>
                        <addClasspath>true</addClasspath>
                        <classpathPrefix>lib/</classpathPrefix>
                        <mainClass>selenium.MainJar</mainClass>
                    </manifest>
                </archive>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <executions>
               <execution>
                     <id>copy-dependencies</id>
                     <phase>prepare-package</phase>
                     <goals>
                        <goal>copy-dependencies</goal>
                     </goals>
                     <configuration>
                        <outputDirectory>${project.build.directory}/lib</outputDirectory>
                        <overWriteReleases>false</overWriteReleases>
                        <overWriteSnapshots>false</overWriteSnapshots>
                        <overWriteIfNewer>true</overWriteIfNewer>
                     </configuration>
               </execution>
            </executions>
        </plugin>
    </plugins>
</build>
<dependencies>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.3.1</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
    </dependency>
</dependencies>
</project>

When I launch RegistrationTest, Internet is opening, going to the adress "http://newtours.demoaut.com/" and then doing nothing.

And in the console I have some errors :

Started InternetExplorerDriver server (64-bit)
3.0.0.0
Listening on port 44920
Only local connections are allowed
mars 29, 2017 3:16:07 PM org.openqa.selenium.remote.ProtocolHandshake    createSession
INFOS: Detected dialect: OSS

Point is that I can't check or uncheck the box "Enable protected..." (see the screenshot below) because I am on a work network so I can't do what I want.

Screenshot of the checkbox

Maybe someone can help me :)

Body:
Here is the solution to your Question-

Replace your code by this:

    DesiredCapabilities capabilities = new DesiredCapabilities().internetExplorer();
    capabilities.setCapability("platform", "WIN8");
    capabilities.setCapability("version", "11");
    capabilities.setCapability("browserName", "internet explorer");
    capabilities.setCapability("ignoreProtectedModeSettings",1);
    capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);
    driver = new InternetExplorerDriver(capabilities);
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);

    driver.navigate().to("http://newtours.demoaut.com/");

    driver.findElement(By.linkText("REGISTER")).click();
    driver.findElement(By.name("firstName")).sendKeys("User1");
    driver.findElement(By.name("lastName")).sendKeys("Surname1");
    driver.findElement(By.name("phone")).sendKeys("123456789");
    driver.findElement(By.name("userName")).sendKeys("user1@test.com");
    driver.findElement(By.name("address1")).sendKeys("Test Address");
    driver.findElement(By.name("city")).sendKeys("Test City");
    Select select = new Select(driver.findElement(By.name("country")));
    select.selectByVisibleText("ANGOLA");
    driver.findElement(By.name("email")).sendKeys("user1@test.com");
    driver.findElement(By.name("password")).sendKeys("user1");
    driver.findElement(By.name("confirmPassword")).sendKeys("user1");
    driver.findElement(By.name("register")).click();

    driver.quit();

The last effort would be : Look in your registry under the HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet
Settings\Zones key. Under there, you should see keys number 0-5. Under keys 1-4, look for a value named 2500, and list either the value for each of the keys, or if the value does not exist.

Having said that I would like you to go through this link where the issue is clearly discussed within Selenium User Group.

Also you may like you to go through this link where the issue is being discussed within Selenium Developers Group.

Let me know if it helps you.


来源: stackexchange

问:
Tokens and wildcards in for loops
I am trying to create a txt file called "index" which contains a list of the names of a set of files. The files follow the same naming format: 01 - aaa; 02 - bbb; 03 - ccc etc where the letters represent whatever the name of the file is. I want to create a txt file with the names as follows:

aaa

bbb

ccc

i.e removing the numbers, hyphen and extension in a vertical list which I can then copy elsewhere.

This is the code I have written so far:

```<code>@echo off & setlocal EnableDelayedExpansion
for /f "tokens=3* delims= " %%g in ('dir /b /o:n') do (
    if not %%~nxg==index.bat (
        echo %%g >> index.txt
    )
)
endlocal
</code>```

This correctly loops through the files and ignores index.bat (which is the file I'm running) but it outputs the third token only and not all subsequent tokens. The * wildcard should mean it outputs the entire rest of the string but it doesn't seem to work?

Any other general improvements would be appreciated - only been learning batch for a week or so.

EDIT: Magoo and npocmaka's answers below solved it. %%h contains the wildcard information. "tokens=2* delims= " will assign the 2nd token to %%g and the 3rd + the rest to %%h.

The working code is as follows:

```<code>@echo off & setlocal EnableDelayedExpansion
for /f "tokens=2* delims= " %%g in ('dir /b /o:n') do (
    if not %%~nxg==%%~nx0 (
        set name=%%h
        echo !name:~0,-4! >> index.txt
    )
)
endlocal
</code>```

if not %%~nxg==%%~nx0 excludes the batch file from the loop, set name=%%h creates a new variable so that I can do a substring to remove the extension. echo !name:~0,-4! is the substring and it selects the entire string except the last 4 characters so as to exclude the file extension and then >> index.txt creates a new text file in the same directory with only the required characters.

答:
This works for me, just change:

```<code>"tokens=2* delims=-"
</code>```

If you can only use pre-installed apps, this is a nice powershell one liner:

```<code>gci C:\folder -Exclude "index" | % {($_ -split "-")[1]} | out-file C:\index.txt
</code>```

It may need modifying depending on your needs though.

ContentLicense: CC BY-SA 3.0

Title: Tokens and wildcards in for loops

Body:
I am trying to create a txt file called "index" which contains a list of the names of a set of files. The files follow the same naming format: 01 - aaa; 02 - bbb; 03 - ccc etc where the letters represent whatever the name of the file is. I want to create a txt file with the names as follows:

aaa

bbb

ccc

i.e removing the numbers, hyphen and extension in a vertical list which I can then copy elsewhere.

This is the code I have written so far:

@echo off & setlocal EnableDelayedExpansion
for /f "tokens=3* delims= " %%g in ('dir /b /o:n') do (
    if not %%~nxg==index.bat (
        echo %%g >> index.txt
    )
)
endlocal

This correctly loops through the files and ignores index.bat (which is the file I'm running) but it outputs the third token only and not all subsequent tokens. The * wildcard should mean it outputs the entire rest of the string but it doesn't seem to work?

Any other general improvements would be appreciated - only been learning batch for a week or so.

EDIT: Magoo and npocmaka's answers below solved it. %%h contains the wildcard information. "tokens=2* delims= " will assign the 2nd token to %%g and the 3rd + the rest to %%h.

The working code is as follows:

@echo off & setlocal EnableDelayedExpansion
for /f "tokens=2* delims= " %%g in ('dir /b /o:n') do (
    if not %%~nxg==%%~nx0 (
        set name=%%h
        echo !name:~0,-4! >> index.txt
    )
)
endlocal

if not %%~nxg==%%~nx0 excludes the batch file from the loop, set name=%%h creates a new variable so that I can do a substring to remove the extension. echo !name:~0,-4! is the substring and it selects the entire string except the last 4 characters so as to exclude the file extension and then >> index.txt creates a new text file in the same directory with only the required characters.

Body:
This works for me, just change:

"tokens=2* delims=-"

If you can only use pre-installed apps, this is a nice powershell one liner:

gci C:\folder -Exclude "index" | % {($_ -split "-")[1]} | out-file C:\index.txt

It may need modifying depending on your needs though.


问:
Junit testing with two,three dependency classes mocking, stubs. any recommendation for Junit tutorial and examples
I am new to Junit testing, and i will like to learn about the two,three dependency classes mocking, stubs. any recommendation for Junit tutorial and examples?</p>

答: Here you can find a good tutorial that talks about JUnit and Mockito, which is what I like to use to mock dependencies.</p>


问:
Printing debug values in a cryptographic exchange
I have created this basic program to implement the Diffie-Hellman algorithm. I want s to be a randomly generated prime number, and q to be a randomly generated integer. sk1 and sk2 are shared keys which are also generated randomly. pk1 and pk2 are modulus calculated values which I have to prove are equal to each other. I think my formula is correct but I am not sure how to print the values of s, q, sk1, sk2, pk1 and pk2 to verify my requirements. My code is pasted below and I would really appreciate if anyone could help me with the print statements.

package javaapplication1;
import java.util.Random;
import java.math.*;

public class DH {
    public static void main(String [] arg) {

        int s, q;
        double sk1, sk2, pk1 = 0, pk2 = 0;
        Random generator = new Random();
        s = generator.nextInt(50000);
        q = generator.nextInt(50000);

        sk1 = generator.nextInt();
        sk2 = generator.nextInt();

        if(s==1 || s==2) {
            for(int i = 2; i< (int)(s/2); i++) {
                if(s/i != (int)(s/i)) {
                    double a= Math.pow(q,sk1);
                    pk1 = a%s;

                    double b= Math.pow(q, sk2);
                    pk2 = b%s;

                    if(pk1==pk2) {
                        System.out.println("true");
                    }

                    System.out.println(s);
                    System.out.println(q);
                    System.out.println(sk1);
                    System.out.println(sk2);
                    System.out.println(pk1);
                    System.out.println(pk2);
                }
            }
        }
    }
}
```

答:
You're only ever doing anything if  if(s/i != (int)(s/i)). Since both s and i are integers, it's unlikely that this condition will ever be true.

(To clarify: With "unlikely", I mean that this condition couldn't possibly be true. s/i returns an integer, and (int)(s/i) will return the exact same integer.)

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


问:
when view visibility is set to View.GONE-layout changes its size
How to prevent changing size of layout when its view object visibility set to View.GONE? View.INVISIBLE is not what is needed. What is needed is:

View object should be taken off view hierarchy.

Layout's size shouldn't be changed.

答: You have to make a custom ViewGroup and override onMeasure() where you'd specify how much height/width you'd like your ViewGroup to have.


问:
Laravel : AJAX not updating Database table
What i'm trying to achieve here is whenever the user clicks on a radio button, it changes the task's status accordingly

```<code><input type="radio" name="status"
<?php if($task->status == 'todo'){echo('checked');}?>
onchange = "change('todo')">Todo

<input type="radio" name="status"
<?php if($task->status == 'doing'){echo('checked');}?>
onchange = "change('doing')">Doing

<input type="radio" name="status"
<?php if($task->status == 'done'){echo('checked');}?>
onchange = "change('done')">Done

<script>
  function change(status){
  $.ajax({
      url: "/changeStatus.php/",
      type: "POST",
      data: { 'status': status, 'task_id': '<?php echo($task->id); ?>' },
  });
  }
</script>
</code>```

and in my "changeStatus.php" file

```<code><?php
    dd($_GET['status']);
    $con=mysqli_connect("127.0.0.1","root","","project_management");
    // Check connection
    if (mysqli_connect_errno()){
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    $status = $_POST['status'];
    $task_id = $_POST['task_id'];
    dd($status,$task_id);
    $sql = "UPDATE 'tasks' SET 'status' = '$status' WHERE 'id' = 'task_id'";

    if (!mysqli_query($con,$sql))
    {
        die('Error: ' . mysqli_error($con));
    }

    mysqli_close($con);

?>
</code>```

the problem is that the Database is not updated when i click on the radio buttons, and there's no error too!
any help is appreciated!

note: the reason why "laravel" is in the tag; is because the error when i changed it to using POST method (which should be the correct method) is returning an error in my app.js file (from laravel).

conclusion :
Thanks to the answer by Loren bellow (apporoved), i also made some changes to the code, as follows
-in my changeStatus.php i removed the dd, and var_dump function; as it was       creating errors.
-changed the submission method from GET to POST
-and fixed the query into:

```<code>$sql = "UPDATE tasks SET status = '$status' WHERE id = '$task_id'";
</code>```

答:
It seems to me that your problem is here:

```<code>$sql = "UPDATE 'tasks' SET 'status' = '$status' WHERE 'id' = 'task_id'";
</code>```

should be

```<code>$sql = "UPDATE 'tasks' SET 'status' = '$status' WHERE 'id' = '$task_id'";
</code>```

Note: This is not the Laravel way to edit a database entry and is a very insecure way to run database queries.  Please, please, validate status and task_id so you don't get database injection attacks.  (It does, however, seem to be a Laravel view.)

Body:
What i'm trying to achieve here is whenever the user clicks on a radio button, it changes the task's status accordingly

<input type="radio" name="status"
<?php if($task->status == 'todo'){echo('checked');}?>
onchange = "change('todo')">Todo

<input type="radio" name="status"
<?php if($task->status == 'doing'){echo('checked');}?>
onchange = "change('doing')">Doing

<input type="radio" name="status"
<?php if($task->status == 'done'){echo('checked');}?>
onchange = "change('done')">Done

and in my "changeStatus.php" file

<?php
    dd($_GET['status']);
    $con=mysqli_connect("127.0.0.1","root","","project_management");
    // Check connection
    if (mysqli_connect_errno()){
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    $status = $_POST['status'];
    $task_id = $_POST['task_id'];
    dd($status,$task_id);
    $sql = "UPDATE 'tasks' SET 'status' = '$status' WHERE 'id' = 'task_id'";

    if (!mysqli_query($con,$sql))
    {
        die('Error: ' . mysqli_error($con));
    }

    mysqli_close($con);

?>

the problem is that the Database is not updated when i click on the radio buttons, and there's no error too!
any help is appreciated!

note: the reason why "laravel" is in the tag; is because the error when i changed it to using POST method (which should be the correct method) is returning an error in my app.js file (from laravel).

conclusion :
Thanks to the answer by Loren bellow (apporoved), i also made some changes to the code, as follows
-in my changeStatus.php i removed the dd, and var_dump function; as it was       creating errors.
-changed the submission method from GET to POST
-and fixed the query into:

$sql = "UPDATE tasks SET status = '$status' WHERE id = '$task_id'";

Body:
It seems to me that your problem is here:

$sql = "UPDATE 'tasks' SET 'status' = '$status' WHERE 'id' = 'task_id'";

should be

$sql = "UPDATE 'tasks' SET 'status' = '$status' WHERE 'id' = '$task_id'";

Note: This is not the Laravel way to edit a database entry and is a very insecure way to run database queries.  Please, please, validate status and task_id so you don't get database injection attacks.  (It does, however, seem to be a Laravel view.)


问:
Sort string-array according to given input values and set it into spinner accordingly
I've set string-array of resource into Spinner. The string-array is like below,

```<code><string-array name="gender">
        <item>Male</item>
        <item>Female</item>
    </string-array>
</code>```

The first element showing into Spinner "Male" and second "Female". Now i want to change this order as "Female" value first and "Male" value second if my input value is "Female".

Kindly tell me how to sort as above mentioned order.

答:
You can sort the values in onItemSelected as follows :</p>

```<code>spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                       // if value is Female
                       String[] list = getResources().getStringArray(R.array.gender);
                       Arrays.sort(list);
                       // set the sorted list back again into the spinner adapter
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {

                    }
                });
</code>```

Body:
I've set string-array of resource into Spinner. The string-array is like below,

<string-array name="gender">
        <item>Male</item>
        <item>Female</item>
    </string-array>

The first element showing into Spinner "Male" and second "Female". Now i want to change this order as "Female" value first and "Male" value second if my input value is "Female".

Kindly tell me how to sort as above mentioned order.

Body:
You can sort the values in onItemSelected as follows :

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                       // if value is Female
                       String[] list = getResources().getStringArray(R.array.gender);
                       Arrays.sort(list);
                       // set the sorted list back again into the spinner adapter
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {

                    }
                });


问:
Multiple binding files in gradle xjc task
I want to specify a few files binding files in gradle task.

I've read doc.

Also I've checked this link.

So, all works in such way:

```<code>          xjc(destdir: sourcesDir, schema: schema, binding: 'src/main/resources/A.xjb')
</code>```

And not works in such way:

```<code>   xjc(destdir: sourcesDir, schema: schema, binding: binding(dir:'src/main/resources', includes:'A.xjb,B.xjb')      or
   xjc(destdir: sourcesDir, schema: schema, binding(dir:'src/main/resources', includes:'A.xjb,B.xjb')
</code>```

Logs

答:
```<code>xjc(destdir: sourcesDir, schema: schema) {
    binding(dir:'src/main/resources', includes:'A.xjb,B.xjb')
}
</code>```

Body:
I want to specify a few files binding files in gradle task.

I've read doc.

Also I've checked this link.

So, all works in such way:

          xjc(destdir: sourcesDir, schema: schema, binding: 'src/main/resources/A.xjb')

And not works in such way:

   xjc(destdir: sourcesDir, schema: schema, binding: binding(dir:'src/main/resources', includes:'A.xjb,B.xjb')      or
   xjc(destdir: sourcesDir, schema: schema, binding(dir:'src/main/resources', includes:'A.xjb,B.xjb')

Logs


问:
Setting truncation mode for UINavigation title text
I want to configure the truncation mode for the text that appears in UINavigationItem.

I've come across a couple of different solutions of configuring the font size but not sure how to make use of the UILineBreakModeHeadTruncation that exists on NSString.

How I've been able to configure the font size:

```<code>UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 120, 30)];
[label setFont:[UIFont boldSystemFontOfSize:16.0]];
[label setBackgroundColor:[UIColor clearColor]];
[label setTextColor:[UIColor whiteColor]];
[label setText:self.title];
[self.navigationController.navigationBar.topItem setTitleView:label];
[label release];
</code>```

(Based on the recommendation from here)

If I call this in loadView or viewDidLoad, it seems to work but outside of that method, after the view has been loaded, it doesn't seem to work. Not sure why though.

答:
What have you tried, and what's not working? You should be able to do:

```<code>label.lineBreakMode = UILineBreakModeHeadTruncation;
</code>```

Or to wrap to multiple lines:

```<code>label.lineBreakMode = UILineBreakModeWordWrap;
label.numberOfLines = 0;
</code>```

Body:
I want to configure the truncation mode for the text that appears in UINavigationItem.

I've come across a couple of different solutions of configuring the font size but not sure how to make use of the UILineBreakModeHeadTruncation that exists on NSString.

How I've been able to configure the font size:

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 120, 30)];
[label setFont:[UIFont boldSystemFontOfSize:16.0]];
[label setBackgroundColor:[UIColor clearColor]];
[label setTextColor:[UIColor whiteColor]];
[label setText:self.title];
[self.navigationController.navigationBar.topItem setTitleView:label];
[label release];

(Based on the recommendation from here)

If I call this in loadView or viewDidLoad, it seems to work but outside of that method, after the view has been loaded, it doesn't seem to work. Not sure why though.

Body:
What have you tried, and what's not working? You should be able to do:

label.lineBreakMode = UILineBreakModeHeadTruncation;

Or to wrap to multiple lines:

label.lineBreakMode = UILineBreakModeWordWrap;
label.numberOfLines = 0;


问:
Viewpager within a fragment
I want inside my Fragment I can create a viewpager with 3 fragments, being type carousel. By the activie I can do more for a fragment I can not do, how can I do this?

sorry the English

答:
If I understand you correctly,You want a activity which have more
than one fragments ,yes it possible, there are many examples on
internet

In addition, you wanna create  a view pager,and  it occur
fragments,Yes it is possible you can create FragmentPagerAdapter
then,set view pager.adapter your's adapter,this adapter returns
fragments according to view pager position

Title: Viewpager within a fragment


问:
How to force an element above another
I have two slightly overlapping (breadcrumb) elements, side-by-side, and I want to make the one on the left to clip the one on the right. Setting z-index didn't appear to work. Is there a better way?

DEMO:https://plnkr.co/edit/5RCH9hswONT16QJeK3KE?p=preview

    .arrow-point {
        display: inline-block;
        border-top: 12px solid transparent;
        border-bottom: 12px solid transparent;
        border-left: 15px solid #777;
        /* z-index:10; */
    }
    .arrow-body {
        font-family: verdana;
        font-size:15px;
        display: inline-block;
        background-color: #777;
        color:white;
        padding:2px 6px 2px 20px;
        height:20px;
        vertical-align:top;
        /* z-index:-3; */
    }
    .arrow-tail {
        position: absolute;
        display: inline-block;
        border-top: 12px solid transparent;
        border-bottom: 12px solid transparent;
        border-left: 15px solid #FFF;
        /* z-index:-2; */
        /* margin-left:-6px; */
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div style="font-size:0;display:inline-block">
        <div class="arrow-tail"></div>
        <div class="arrow-body">Submenu A</div>
        <div class="arrow-point"></div>
    </div>
    <div style="font-size:0;float:left;margin-right:-6px;display:inline-block">
        <div class="arrow-body">Main Menu</div>
        <div class="arrow-point"></div>
    </div></code>```

答:
Set position to relative. Than set z-index: 9999.

The position property specifies the type of positioning method used for an element.

.arrow-point {
        display: inline-block;
        border-top: 12px solid transparent;
        border-bottom: 12px solid transparent;
        border-left: 15px solid #777;
        /* z-index:10; */
    }
    .arrow-body {
        font-family: verdana;
        font-size:15px;
        display: inline-block;
        background-color: #777;
        color:white;
        padding:2px 6px 2px 20px;
        height:20px;
        vertical-align:top;
        /* z-index:-3; */
    }
    .arrow-tail {
        position: absolute;
        display: inline-block;
        border-top: 12px solid transparent;
        border-bottom: 12px solid transparent;
        border-left: 15px solid #FFF;
        /* z-index:-2; */
        /* margin-left:-6px; */
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="font-size:0;display:inline-block">
        <div class="arrow-tail"></div>
        <div class="arrow-body">Submenu A</div>
        <div class="arrow-point"></div>
    </div>
    <div style="font-size:0;float:left;margin-right:-6px;display:inline-block;position: relative;z-index: 9999;">
        <div class="arrow-body">Main Menu</div>
        <div class="arrow-point"></div>
    </div></code>```

Title: How to force an element above another

Body:
I have two slightly overlapping (breadcrumb) elements, side-by-side, and I want to make the one on the left to clip the one on the right. Setting z-index didn't appear to work. Is there a better way?

DEMO:https://plnkr.co/edit/5RCH9hswONT16QJeK3KE?p=preview

    .arrow-point {
        display: inline-block;
        border-top: 12px solid transparent;
        border-bottom: 12px solid transparent;
        border-left: 15px solid #777;
        /* z-index:10; */
    }
    .arrow-body {
        font-family: verdana;
        font-size:15px;
        display: inline-block;
        background-color: #777;
        color:white;
        padding:2px 6px 2px 20px;
        height:20px;
        vertical-align:top;
        /* z-index:-3; */
    }
    .arrow-tail {
        position: absolute;
        display: inline-block;
        border-top: 12px solid transparent;
        border-bottom: 12px solid transparent;
        border-left: 15px solid #FFF;
        /* z-index:-2; */
        /* margin-left:-6px; */
    }

Submenu A

Main Menu

Body:
Set position to relative. Than set z-index: 9999.

The position property specifies the type of positioning method used for an element.

.arrow-point {
        display: inline-block;
        border-top: 12px solid transparent;
        border-bottom: 12px solid transparent;
        border-left: 15px solid #777;
        /* z-index:10; */
    }
    .arrow-body {
        font-family: verdana;
        font-size:15px;
        display: inline-block;
        background-color: #777;
        color:white;
        padding:2px 6px 2px 20px;
        height:20px;
        vertical-align:top;
        /* z-index:-3; */
    }
    .arrow-tail {
        position: absolute;
        display: inline-block;
        border-top: 12px solid transparent;
        border-bottom: 12px solid transparent;
        border-left: 15px solid #FFF;
        /* z-index:-2; */
        /* margin-left:-6px; */
    }

<div style="font-size:0;display:inline-block">
        <div class="arrow-tail"></div>
        <div class="arrow-body">Submenu A</div>
        <div class="arrow-point"></div>
    </div>
    <div style="font-size:0;float:left;margin-right:-6px;display:inline-block;position: relative;z-index: 9999;">
        <div class="arrow-body">Main Menu</div>
        <div class="arrow-point"></div>
    </div>


问:
Why does C++17 character class [:blank:] match newlines and carriage returns?
When working with the POSIX character class [:blank:] in Visual Studio 2015, I would expect newlines and carriage returns to not match but that's not the behavior I'm seeing.

http://www.cplusplus.com/reference/regex/ECMAScript/ indicates that the POSIX character class [:blank:] is the equivalent of isblank but they aren't lining up. isblank returns positive for space and tab, but false for carriage return and newline whereas [:blank:] is matching space, tab, newline, and carriage return.

Here's my sample code:

```<code>#include <cctype>
#include <iostream>
#include <regex>
#include <string>

using namespace std;

bool reMatches( const regex &re, const char c )
{
    return regex_search( string( 1, c ), re );
}

bool isBlank( const char c )
{
    return isblank( c ) != 0;
}

int main() {
    const char testChars[] = { ' ', '\t', '\r', '\n', '.' };
    const char *dispChars[] = { " ", "\\t", "\\r", "\\n", "." };
    regex explicitClass( "[ \t]" );
    regex posixClass( "[[:blank:]]" );

    for ( unsigned i = 0; i < sizeof( testChars ); ++i )
    {
        char c = testChars[i];
        if ( isBlank( c ) != reMatches( explicitClass, c ) )
            cout << "Mismatch found between isblank & [ \t] for " << dispChars[i] << std::endl;
        if ( isBlank( c ) != reMatches( posixClass, c ) )
            cout << "Mismatch found between isblank & [[:blank:]] for " << dispChars[i] << std::endl;
    }
}
</code>```

Here's the resulting output:

```<code>Mismatch found between isblank & [[:blank:]] for \r
Mismatch found between isblank & [[:blank:]] for \n
</code>```

[ \t] acts as expected, but [[:blank:]] matches \r and \n! Am I doing something wrong?

答:
Turns out, it's a bug in VC++. Running this code under clang or gcc exhibits the proper behavior (no output).

Code Tested: http://rextester.com/MCP44517

Bug Submitted: https://connect.microsoft.com/VisualStudio/feedback/details/3131111/std-regex-posix-character-class-blank-matches-newlines

Body:
When working with the POSIX character class [:blank:] in Visual Studio 2015, I would expect newlines and carriage returns to not match but that's not the behavior I'm seeing.

http://www.cplusplus.com/reference/regex/ECMAScript/ indicates that the POSIX character class [:blank:] is the equivalent of isblank but they aren't lining up. isblank returns positive for space and tab, but false for carriage return and newline whereas [:blank:] is matching space, tab, newline, and carriage return.

Here's my sample code:

#include <cctype>
#include <iostream>
#include <regex>
#include <string>

using namespace std;

bool reMatches( const regex &re, const char c )
{
    return regex_search( string( 1, c ), re );
}

bool isBlank( const char c )
{
    return isblank( c ) != 0;
}

int main() {
    const char testChars[] = { ' ', '\t', '\r', '\n', '.' };
    const char *dispChars[] = { " ", "\\t", "\\r", "\\n", "." };
    regex explicitClass( "[ \t]" );
    regex posixClass( "[[:blank:]]" );

    for ( unsigned i = 0; i < sizeof( testChars ); ++i )
    {
        char c = testChars[i];
        if ( isBlank( c ) != reMatches( explicitClass, c ) )
            cout << "Mismatch found between isblank & [ \t] for " << dispChars[i] << std::endl;
        if ( isBlank( c ) != reMatches( posixClass, c ) )
            cout << "Mismatch found between isblank & [[:blank:]] for " << dispChars[i] << std::endl;
    }
}

Here's the resulting output:

Mismatch found between isblank & [[:blank:]] for \r
Mismatch found between isblank & [[:blank:]] for \n

[ \t] acts as expected, but [[:blank:]] matches \r and \n! Am I doing something wrong?


问:
eval error in python with trig values
I'm designing a calculator in using Tkinter. Before I added trig functions to my code, the eval function worked perfectly fine. However, I discovered that it doesn't work for the trig values that I give it. Am I using the eval function wrong, or does it not work for trig values? The eval function is used in my equalButtonFunction on line 47. If I'm using it wrong, can you tell me how to fix it, or if eval doesn't work for trig, could you recommend an alternative way to do it? Thanks! </p>

```<code>from __future__ import division
from Tkinter import *
import math

main = Tk()
main.title("Calculator")
main.geometry("375x550")

entry = Text(main)
entry.configure(width=17,height=1)
entry.place(x=13, y=5)
entry.config(font=("Courier", 25))

def oneButtonFunction(event):
    entry.insert(END, '1')
def twoButtonFunction(event):
    entry.insert(END, '2')
def threeButtonFunction(event):
    entry.insert(END, '3')
def fourButtonFunction(event):
    entry.insert(END, '4')
def fiveButtonFunction(event):
    entry.insert(END, '5')
def sixButtonFunction(event):
    entry.insert(END, '6')
def sevenButtonFunction(event):
    entry.insert(END, '7')
def eightButtonFunction(event):
    entry.insert(END, '8')
def nineButtonFunction(event):
    entry.insert(END, '9')
def zeroButtonFunction(event):
    entry.insert(END, '0')
def addButtonFunction(event):
    entry.insert(END, '+')
def subButtonFunction(event):
    entry.insert(END, '-')
def multButtonFunction(event):
    entry.insert(END, '*')
def divButtonFunction(event):
    entry.insert(END, '/')
def decimalButtonFunction(event):
    entry.insert(END, '.')
def equalButtonFunction(event):
    x = entry.get("1.0", "end-1c")
    entry.delete("1.0", END)
    entry.insert(END, eval(x))#causes error for trig function

def clearButtonFunction(event):
    entry.delete("1.0", END)
def parentheses1ButtonFuction(event):
    entry.insert(END, '(')
def parentheses2ButtonFuction(event):
    entry.insert(END, ')')
def trigButtonFunction(event):
    sinButton.place(x=280, y=50)
    cosButton.place(x=280, y=150)
    tanButton.place(x=280, y=250)
    backButton.place(x=280, y=450)
def sinButtonFunction(event):
    entry.insert(END, 'sin(')
def cosButtonFunction(event):
    entry.insert(END, 'cos(')
def tanButtonFunction(event):
    entry.insert(END, 'tan(')
def backButtonFunction(event):
    sinButton.place_forget()
    cosButton.place_forget()
    tanButton.place_forget()
    backButton.place_forget()

oneButton = Button(main, text="1", width=10, height=5)
oneButton.place(x=10, y=50)
oneButton.bind('<Button-1>', oneButtonFunction)

twoButton = Button(main, text="2", width=10, height=5)
twoButton.place(x=100, y=50)
twoButton.bind('<Button-1>', twoButtonFunction)

threeButton = Button(main, text="3", width=10, height=5)
threeButton.place(x=190, y=50)
threeButton.bind('<Button-1>', threeButtonFunction)

fourButton = Button(main, text="4", width=10, height=5)
fourButton.place(x=10, y=150)
fourButton.bind('<Button-1>', fourButtonFunction)

fiveButton = Button(main, text="5", width=10, height=5)
fiveButton.place(x=100, y=150)
fiveButton.bind('<Button-1>', fiveButtonFunction)

sixButton = Button(main, text="6", width=10, height=5)
sixButton.place(x=190, y=150)
sixButton.bind('<Button-1>', sixButtonFunction)

sevenButton = Button(main, text="7", width=10, height=5)
sevenButton.place(x=10, y=250)
sevenButton.bind('<Button-1>', sevenButtonFunction)

eightButton = Button(main, text="8", width=10, height=5)
eightButton.place(x=100, y=250)
eightButton.bind('<Button-1>', eightButtonFunction)

nineButton = Button(main, text="9", width=10, height=5)
nineButton.place(x=190, y=250)
nineButton.bind('<Button-1>', nineButtonFunction)

zeroButton = Button(main, text="0", width=10, height=5)
zeroButton.place(x=100, y=350)
zeroButton.bind('<Button-1>', zeroButtonFunction)

decimalButton = Button(main, text=".", width=10, height=5)
decimalButton.place(x=10, y=350)
decimalButton.bind('<Button-1>', decimalButtonFunction)

equalButton = Button(main, text="=", width=10, height=5)
equalButton.place(x=190, y=350)
equalButton.bind('<Button-1>', equalButtonFunction)

addButton = Button(main, text="+", width=10, height=5)
addButton.place(x=280, y=50)
addButton.bind('<Button-1>', addButtonFunction)

subButton = Button(main, text="-", width=10, height=5)
subButton.place(x=280, y=150)
subButton.bind('<Button-1>', subButtonFunction)

multButton = Button(main, text="X", width=10, height=5)
multButton.place(x=280, y=250)
multButton.bind('<Button-1>', multButtonFunction)

divButton = Button(main, text="/", width=10, height=5)
divButton.place(x=280, y=350)
divButton.bind('<Button-1>', divButtonFunction)

clearButton = Button(main, text="Clear", width=10, height=5)
clearButton.place(x=10, y=450)
clearButton.bind('<Button-1>', clearButtonFunction)

parentheses1Button = Button(main, text="(", width=10, height=5)
parentheses1Button.place(x=100, y=450)
parentheses1Button.bind('<Button-1>', parentheses1ButtonFuction)

parentheses2Button = Button(main, text=")", width=10, height=5)
parentheses2Button.place(x=190, y=450)
parentheses2Button.bind('<Button-1>', parentheses2ButtonFuction)

trigButton = Button(main, text="Trig", width=10, height=5)
trigButton.place(x=280, y=450)
trigButton.bind('<Button-1>', trigButtonFunction)

sinButton = Button(main, text="Sin", width=10, height=5)
sinButton.bind('<Button-1>', sinButtonFunction)

cosButton = Button(main, text="Cos", width=10, height=5)
cosButton.bind('<Button-1>', cosButtonFunction)

tanButton = Button(main, text="Tan", width=10, height=5)
tanButton.bind('<Button-1>', tanButtonFunction)

backButton = Button(main, text="Back", width=10, height=5)
backButton.bind('<Button-1>', backButtonFunction)

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

答:
```<code>def cos(x):
    return math.cos(x)
def sin(x):
    return math.sin(x)
def tan(x):
    return math.tan(x)
</code>```

<p>or as Eric mentions </p>

```<code>from math import sin, cos, tan
</code>```

Title: eval error in python with trig values

Body:
I'm designing a calculator in using Tkinter. Before I added trig functions to my code, the eval function worked perfectly fine. However, I discovered that it doesn't work for the trig values that I give it. Am I using the eval function wrong, or does it not work for trig values? The eval function is used in my equalButtonFunction on line 47. If I'm using it wrong, can you tell me how to fix it, or if eval doesn't work for trig, could you recommend an alternative way to do it? Thanks!

from __future__ import division
from Tkinter import *
import math

main = Tk()
main.title("Calculator")
main.geometry("375x550")

entry = Text(main)
entry.configure(width=17,height=1)
entry.place(x=13, y=5)
entry.config(font=("Courier", 25))

def oneButtonFunction(event):
    entry.insert(END, '1')
def twoButtonFunction(event):
    entry.insert(END, '2')
def threeButtonFunction(event):
    entry.insert(END, '3')
def fourButtonFunction(event):
    entry.insert(END, '4')
def fiveButtonFunction(event):
    entry.insert(END, '5')
def sixButtonFunction(event):
    entry.insert(END, '6')
def sevenButtonFunction(event):
    entry.insert(END, '7')
def eightButtonFunction(event):
    entry.insert(END, '8')
def nineButtonFunction(event):
    entry.insert(END, '9')
def zeroButtonFunction(event):
    entry.insert(END, '0')
def addButtonFunction(event):
    entry.insert(END, '+')
def subButtonFunction(event):
    entry.insert(END, '-')
def multButtonFunction(event):
    entry.insert(END, '*')
def divButtonFunction(event):
    entry.insert(END, '/')
def decimalButtonFunction(event):
    entry.insert(END, '.')
def equalButtonFunction(event):
    x = entry.get("1.0", "end-1c")
    entry.delete("1.0", END)
    entry.insert(END, eval(x))#causes error for trig function

def clearButtonFunction(event):
    entry.delete("1.0", END)
def parentheses1ButtonFuction(event):
    entry.insert(END, '(')
def parentheses2ButtonFuction(event):
    entry.insert(END, ')')
def trigButtonFunction(event):
    sinButton.place(x=280, y=50)
    cosButton.place(x=280, y=150)
    tanButton.place(x=280, y=250)
    backButton.place(x=280, y=450)
def sinButtonFunction(event):
    entry.insert(END, 'sin(')
def cosButtonFunction(event):
    entry.insert(END, 'cos(')
def tanButtonFunction(event):
    entry.insert(END, 'tan(')
def backButtonFunction(event):
    sinButton.place_forget()
    cosButton.place_forget()
    tanButton.place_forget()
    backButton.place_forget()

oneButton = Button(main, text="1", width=10, height=5)
oneButton.place(x=10, y=50)
oneButton.bind('<Button-1>', oneButtonFunction)

twoButton = Button(main, text="2", width=10, height=5)
twoButton.place(x=100, y=50)
twoButton.bind('<Button-1>', twoButtonFunction)

threeButton = Button(main, text="3", width=10, height=5)
threeButton.place(x=190, y=50)
threeButton.bind('<Button-1>', threeButtonFunction)

fourButton = Button(main, text="4", width=10, height=5)
fourButton.place(x=10, y=150)
fourButton.bind('<Button-1>', fourButtonFunction)

fiveButton = Button(main, text="5", width=10, height=5)
fiveButton.place(x=100, y=150)
fiveButton.bind('<Button-1>', fiveButtonFunction)

sixButton = Button(main, text="6", width=10, height=5)
sixButton.place(x=190, y=150)
sixButton.bind('<Button-1>', sixButtonFunction)

sevenButton = Button(main, text="7", width=10, height=5)
sevenButton.place(x=10, y=250)
sevenButton.bind('<Button-1>', sevenButtonFunction)

eightButton = Button(main, text="8", width=10, height=5)
eightButton.place(x=100, y=250)
eightButton.bind('<Button-1>', eightButtonFunction)

nineButton = Button(main, text="9", width=10, height=5)
nineButton.place(x=190, y=250)
nineButton.bind('<Button-1>', nineButtonFunction)

zeroButton = Button(main, text="0", width=10, height=5)
zeroButton.place(x=100, y=350)
zeroButton.bind('<Button-1>', zeroButtonFunction)

decimalButton = Button(main, text=".", width=10, height=5)
decimalButton.place(x=10, y=350)
decimalButton.bind('<Button-1>', decimalButtonFunction)

equalButton = Button(main, text="=", width=10, height=5)
equalButton.place(x=190, y=350)
equalButton.bind('<Button-1>', equalButtonFunction)

addButton = Button(main, text="+", width=10, height=5)
addButton.place(x=280, y=50)
addButton.bind('<Button-1>', addButtonFunction)

subButton = Button(main, text="-", width=10, height=5)
subButton.place(x=280, y=150)
subButton.bind('<Button-1>', subButtonFunction)

multButton = Button(main, text="X", width=10, height=5)
multButton.place(x=280, y=250)
multButton.bind('<Button-1>', multButtonFunction)

divButton = Button(main, text="/", width=10, height=5)
divButton.place(x=280, y=350)
divButton.bind('<Button-1>', divButtonFunction)

clearButton = Button(main, text="Clear", width=10, height=5)
clearButton.place(x=10, y=450)
clearButton.bind('<Button-1>', clearButtonFunction)

parentheses1Button = Button(main, text="(", width=10, height=5)
parentheses1Button.place(x=100, y=450)
parentheses1Button.bind('<Button-1>', parentheses1ButtonFuction)

parentheses2Button = Button(main, text=")", width=10, height=5)
parentheses2Button.place(x=190, y=450)
parentheses2Button.bind('<Button-1>', parentheses2ButtonFuction)

trigButton = Button(main, text="Trig", width=10, height=5)
trigButton.place(x=280, y=450)
trigButton.bind('<Button-1>', trigButtonFunction)

sinButton = Button(main, text="Sin", width=10, height=5)
sinButton.bind('<Button-1>', sinButtonFunction)

cosButton = Button(main, text="Cos", width=10, height=5)
cosButton.bind('<Button-1>', cosButtonFunction)

tanButton = Button(main, text="Tan", width=10, height=5)
tanButton.bind('<Button-1>', tanButtonFunction)

backButton = Button(main, text="Back", width=10, height=5)
backButton.bind('<Button-1>', backButtonFunction)

main.mainloop()

Body:
def cos(x):
    return math.cos(x)
def sin(x):
    return math.sin(x)
def tan(x):
    return math.tan(x)

or as Eric mentions

from math import sin, cos, tan


问:
Getting data from main program
I cannot figure out how to get the double balance1 in my main method to equal the double acctBal in my menu method. I assigned 0 to acctBal because i am not sure how to have it equivalent to whatever balance1 is. I put some asterisks next to the lines i am talking about.

public class ATM {

```<code>public static Scanner kbd;

public static void main(String[] args) {
    String acctNum, acctPword;
    String balance;
    int x = 1;
    kbd = new Scanner(System.in);

    System.out.print("Enter your account number: ");
    acctNum = kbd.nextLine();

    System.out.print("Enter your account password: ");
    acctPword = kbd.nextLine();
    balance = checkID(acctNum, acctPword);
    double balance1 = Double.parseDouble(balance);
    System.out.println("You currently have $" + String.format("%.2f",balance1));*********************************

    while (balance.equals("error") && x <4){
        System.out.println("Wrong password try again.");
        System.out.print("Enter your account password: ");
        acctPword = kbd.nextLine();
        x++;
    }

    if (x == 4)
        System.out.println("Maximum number of attempts reached, Please try again later.");

    if (x == 1){
        menu();
    }

    kbd.close();
}

/**
 * Determines if acctNum is a valid account number, and pwd is the correct
 * password for the account.
 * @param acctNum The account number to be checked
 * @param pwd The password to be checked
 * @return If the account information is valid, returns the current account
 * balance, as a string. If the account information is invalid, returns
 * the string "error".
 */
public static String checkID(String acctNum, String pwd)
{
    String result = "error";

    // Strings a, b, and c contain the valid account numbers and passwords.
    // For each string, the account number is listed first, followed by
    // a space, followed by the password for the account, followed by a space,
    // followed by the current balance.
    String a = "44567-5 mypassword 520.36";
    String b = "1234567-6 anotherpassword 48.20";
    String c = "4321-0 betterpassword 96.74";

    if (acctNum.equals("44567-5") && pwd.equals("mypassword")){
        result = "520.36";
        return result;
    }

    if (acctNum.equals("1234567-6") && pwd.equals("anotherpassword")){
        result = "48.20";
        return result;
    }

    if (acctNum.equals("4321-0") && pwd.equals("betterpassword")){
        result = "96.74";
        return result;
    }

    return result;
}

public static void menu(){
    int x = 0;
    double acctBal = 0.0, deposit = 0.0, withAmnt = 0.0;**********this acctBal needs to equal balance1.

    System.out.println("1. Display Balance \n2. Deposit\n3. Withdraw\n4. Log Out");
    x = kbd.nextInt();
    switch(x){
    case 1:
        displayBalance(acctBal);
        break;
    case 2:
        deposit(acctBal, deposit);
        break;
    case 3:
        withdraw(acctBal, withAmnt);
        break;
    case 4:
        System.out.println("Have a nice day.");
        break;
    }

}

public static double deposit(double acctBal, double depAmnt){

    System.out.print("How much money would you like to deposit? $");
    depAmnt = kbd.nextDouble();
    acctBal = acctBal + depAmnt;
    System.out.println("Your balance is now at $" + String.format("%.2f", acctBal));
    return acctBal;
}

public static double withdraw(double acctBal, double withAmnt){

    System.out.print("How much money would you like to withdraw? $");
    withAmnt = kbd.nextDouble();

    if (acctBal <= 0){
        System.out.println("You do not have any money.");
        return acctBal;
    }

    if (acctBal < withAmnt){
        System.out.print("You do not have enough money.\nHow much money would you like to withdraw? $");
        withAmnt = kbd.nextDouble();
    }
    else{
        acctBal = acctBal - withAmnt;
    }

    return acctBal;
}

public static double displayBalance(double balance){
    System.out.println("Your balance is $" + String.format("%.2f", balance));
    return balance;
}
</code>```

答:
You can change the menu() method to accept a parameter (called balance) and pass the value from main while calling menu() method, e.g.:

```<code>public static void menu(double acctBal){
    double deposit = 0.0; //Other variables
}
</code>```

And call it from main with balance, e.g.:

```<code>if (x == 1){
    menu(balance);
}
</code>```

Title: Getting data from main program

Body:
I cannot figure out how to get the double balance1 in my main method to equal the double acctBal in my menu method. I assigned 0 to acctBal because i am not sure how to have it equivalent to whatever balance1 is. I put some asterisks next to the lines i am talking about.

public class ATM {

public static Scanner kbd;

public static void main(String[] args) {
    String acctNum, acctPword;
    String balance;
    int x = 1;
    kbd = new Scanner(System.in);

    System.out.print("Enter your account number: ");
    acctNum = kbd.nextLine();

    System.out.print("Enter your account password: ");
    acctPword = kbd.nextLine();
    balance = checkID(acctNum, acctPword);
    double balance1 = Double.parseDouble(balance);
    System.out.println("You currently have $" + String.format("%.2f",balance1));*********************************

    while (balance.equals("error") && x <4){
        System.out.println("Wrong password try again.");
        System.out.print("Enter your account password: ");
        acctPword = kbd.nextLine();
        x++;
    }

    if (x == 4)
        System.out.println("Maximum number of attempts reached, Please try again later.");

    if (x == 1){
        menu();
    }

    kbd.close();
}

/**
 * Determines if acctNum is a valid account number, and pwd is the correct
 * password for the account.
 * @param acctNum The account number to be checked
 * @param pwd The password to be checked
 * @return If the account information is valid, returns the current account
 * balance, as a string. If the account information is invalid, returns
 * the string "error".
 */
public static String checkID(String acctNum, String pwd)
{
    String result = "error";

    // Strings a, b, and c contain the valid account numbers and passwords.
    // For each string, the account number is listed first, followed by
    // a space, followed by the password for the account, followed by a space,
    // followed by the current balance.
    String a = "44567-5 mypassword 520.36";
    String b = "1234567-6 anotherpassword 48.20";
    String c = "4321-0 betterpassword 96.74";

    if (acctNum.equals("44567-5") && pwd.equals("mypassword")){
        result = "520.36";
        return result;
    }

    if (acctNum.equals("1234567-6") && pwd.equals("anotherpassword")){
        result = "48.20";
        return result;
    }

    if (acctNum.equals("4321-0") && pwd.equals("betterpassword")){
        result = "96.74";
        return result;
    }

    return result;
}

public static void menu(){
    int x = 0;
    double acctBal = 0.0, deposit = 0.0, withAmnt = 0.0;**********this acctBal needs to equal balance1.

    System.out.println("1. Display Balance \n2. Deposit\n3. Withdraw\n4. Log Out");
    x = kbd.nextInt();
    switch(x){
    case 1:
        displayBalance(acctBal);
        break;
    case 2:
        deposit(acctBal, deposit);
        break;
    case 3:
        withdraw(acctBal, withAmnt);
        break;
    case 4:
        System.out.println("Have a nice day.");
        break;
    }

}

public static double deposit(double acctBal, double depAmnt){

    System.out.print("How much money would you like to deposit? $");
    depAmnt = kbd.nextDouble();
    acctBal = acctBal + depAmnt;
    System.out.println("Your balance is now at $" + String.format("%.2f", acctBal));
    return acctBal;
}

public static double withdraw(double acctBal, double withAmnt){

    System.out.print("How much money would you like to withdraw? $");
    withAmnt = kbd.nextDouble();

    if (acctBal <= 0){
        System.out.println("You do not have any money.");
        return acctBal;
    }

    if (acctBal < withAmnt){
        System.out.print("You do not have enough money.\nHow much money would you like to withdraw? $");
        withAmnt = kbd.nextDouble();
    }
    else{
        acctBal = acctBal - withAmnt;
    }

    return acctBal;
}

public static double displayBalance(double balance){
    System.out.println("Your balance is $" + String.format("%.2f", balance));
    return balance;
}

Body:
You can change the menu() method to accept a parameter (called balance) and pass the value from main while calling menu() method, e.g.:

public static void menu(double acctBal){
    double deposit = 0.0; //Other variables
}

And call it from main with balance, e.g.:

if (x == 1){
    menu(balance);
}


问:
How to run a script as root in Jenkins?
I need to run a shell script in Jenkins as root instead of the default user. What do I need to change?

My sudoers file is like this:

```<code># User privilege specification
root    ALL=(ALL) ALL
igx     ALL=(ALL) ALL
%wheel  ALL=(ALL) ALL

# Allow members of group sudo to execute any command
# (Note that later entries override this, so you might need to move
%sudo   ALL=(ALL) ALL
#
#includedir /etc/sudoers.d

# Members of the admin group may gain root privileges
%admin  ALL=(ALL) NOPASSWD:ALL
root    ALL=(ALL) ALL
jenkins ALL=NOPASSWD: /var/lib/jenkins/workspace/ing00112/trunk/source/
jenkins ALL=(ALL) NOPASSWD:ALL
#Defaults:jenkins !requiretty
</code>```

答:
@Igor Chubin's answer is 100% correct, but never open sudoer file with a normal editor. always use visudo

just type

```<code>sudo visudo
</code>```

this will take you to /etc/sudoers and upon saving it will make sure that there is no error in formatting.

if you make an error in sudoer file, you will lose sudo access, so always use visudo

Title: How to run a script as root in Jenkins?

Body:
I need to run a shell script in Jenkins as root instead of the default user. What do I need to change?

My sudoers file is like this:

# User privilege specification
root    ALL=(ALL) ALL
igx     ALL=(ALL) ALL
%wheel  ALL=(ALL) ALL

# Allow members of group sudo to execute any command
# (Note that later entries override this, so you might need to move
%sudo   ALL=(ALL) ALL
#
#includedir /etc/sudoers.d

# Members of the admin group may gain root privileges
%admin  ALL=(ALL) NOPASSWD:ALL
root    ALL=(ALL) ALL
jenkins ALL=NOPASSWD: /var/lib/jenkins/workspace/ing00112/trunk/source/
jenkins ALL=(ALL) NOPASSWD:ALL
#Defaults:jenkins !requiretty

Body:
@Igor Chubin's answer is 100% correct, but never open sudoer file with a normal editor. always use visudo

just type

sudo visudo

this will take you to /etc/sudoers and upon saving it will make sure that there is no error in formatting.

if you make an error in sudoer file, you will lose sudo access, so always use visudo


答:
Don't ever use floating point arithmetics for cryptography. Especially for exponentiation you need results with more precision than a double can give you. Use BigInteger instead.

While you are testing, you should not use "new" random numbers each time. Use new Random(0) instead so that you can reproduce your computations the next time you start the debugger.

How do you guarantee that s is a prime number? I cannot see it from the code.

Please indent your code properly and consistently. Since you are using Eclipse, all you need to do is to press Ctrl-Shift-F once.

Title: Printing debug values in a cryptographic exchange

Body:
I have created this basic program to implement the Diffie-Hellman algorithm. I want s to be a randomly generated prime number, and q to be a randomly generated integer. sk1 and sk2 are shared keys which are also generated randomly. pk1 and pk2 are modulus calculated values which I have to prove are equal to each other. I think my formula is correct but I am not sure how to print the values of s, q, sk1, sk2, pk1 and pk2 to verify my requirements. My code is pasted below and I would really appreciate if anyone could help me with the print statements.

package javaapplication1;
import java.util.Random;
import java.math.*;

public class DH {
    public static void main(String [] arg) {

        int s, q;
        double sk1, sk2, pk1 = 0, pk2 = 0;
        Random generator = new Random();
        s = generator.nextInt(50000);
        q = generator.nextInt(50000);

        sk1 = generator.nextInt();
        sk2 = generator.nextInt();

        if(s==1 || s==2) {
            for(int i = 2; i< (int)(s/2); i++) {
                if(s/i != (int)(s/i)) {
                    double a= Math.pow(q,sk1);
                    pk1 = a%s;

                    double b= Math.pow(q, sk2);
                    pk2 = b%s;

                    if(pk1==pk2) {
                        System.out.println("true");
                    }

                    System.out.println(s);
                    System.out.println(q);
                    System.out.println(sk1);
                    System.out.println(sk2);
                    System.out.println(pk1);
                    System.out.println(pk2);
                }
            }
        }
    }
}


问:
Filter after a foreach statement in pig
So i have table with one column, U and has column name u_id.

```<code>filter_out = filter A BY s_id == (FOREACH u GENERATE u_id);
</code>```

I am basically trying to filter A table by match of every row in u table.
So essentially if s_id from A(table1) matches u_id from 2nd tables, filter it out

I keep getting  mismatched input 'u' expecting LEFT_PAREN error

-------------2nd approach----------------

And also have tried converting u to a tuple

```<code>totuple = FOREACH u GENERATE TOTUPLE (u_id);

filter_out = filter A BY s_id in (totuple);
</code>```

and error A column needs to be projected from a relation for it to be used as a scalar

答:
Instead, JOIN the two tables.Doing so will only match the records from table A with the records from table U.Finally generate the columns needed.</p>

```<code>B = JOIN A BY s_id,U BY u_id;
C = FOREACH B GENERATE B.$0; -- Select the needed columns from the joined relation.
DUMP C;
</code>```

Title: Filter after a foreach statement in pig

Body:
So i have table with one column, U and has column name u_id.

filter_out = filter A BY s_id == (FOREACH u GENERATE u_id);

I am basically trying to filter A table by match of every row in u table.
So essentially if s_id from A(table1) matches u_id from 2nd tables, filter it out

I keep getting  mismatched input 'u' expecting LEFT_PAREN error

-------------2nd approach----------------

And also have tried converting u to a tuple

totuple = FOREACH u GENERATE TOTUPLE (u_id);

filter_out = filter A BY s_id in (totuple);

and error A column needs to be projected from a relation for it to be used as a scalar

Body:
Instead, JOIN the two tables.Doing so will only match the records from table A with the records from table U.Finally generate the columns needed.

B = JOIN A BY s_id,U BY u_id;
C = FOREACH B GENERATE B.$0; -- Select the needed columns from the joined relation.
DUMP C;


问:
Equal size subset of a data frame in R
I have a data frame like this :

```<code>     A  B C  D  E
e1   4  3 2  3 13
e2  21 17 5 12 19
e3  13  5 4 12  9
e4  30 18 7  7 30
e5   6 20 1  1 11
e6  16 12 6  8 23
e7  22 16 6  6 22
e8   2 11 1  2 11
e9   5 15 5  0 26
e10 21 19 6  2 22
e11 14 20 6  6 21
</code>```

And given a number X, if want to do subsets of this data frame of size X rows. For example, il X = 2, I would like to have e1+e2, e3+e4, etc.

Is there a simple way to do this ?

Title: Equal size subset of a data frame in R

Body:
I have a data frame like this :

     A  B C  D  E
e1   4  3 2  3 13
e2  21 17 5 12 19
e3  13  5 4 12  9
e4  30 18 7  7 30
e5   6 20 1  1 11
e6  16 12 6  8 23
e7  22 16 6  6 22
e8   2 11 1  2 11
e9   5 15 5  0 26
e10 21 19 6  2 22
e11 14 20 6  6 21

And given a number X, if want to do subsets of this data frame of size X rows. For example, il X = 2, I would like to have e1+e2, e3+e4, etc.

Is there a simple way to do this ?

Body:
You can use split like this. You can then access the lists elements like this: df1[[1]].

df1 <- read.table(text="row     A  B C  D  E
e1   4  3 2  3 13
e2  21 17 5 12 19
e3  13  5 4 12  9
e4  30 18 7  7 30
e5   6 20 1  1 11
e6  16 12 6  8 23
e7  22 16 6  6 22
e8   2 11 1  2 11
e9   5 15 5  0 26
e10 21 19 6  2 22
e11 14 20 6  6 21",header=TRUE,stringsAsFactors=FALSE)

n <- 2
split(df1, rep(1:(nrow(df1)/n+nrow(df1)%%n),each=n))
$`1`
  row  A  B C  D  E
1  e1  4  3 2  3 13
2  e2 21 17 5 12 19

$`2`
  row  A  B C  D  E
3  e3 13  5 4 12  9
4  e4 30 18 7  7 30

$`3`
  row  A  B C D  E
5  e5  6 20 1 1 11
6  e6 16 12 6 8 23

$`4`
  row  A  B C D  E
7  e7 22 16 6 6 22
8  e8  2 11 1 2 11

$`5`
   row  A  B C D  E
9   e9  5 15 5 0 26
10 e10 21 19 6 2 22

$`6`
   row  A  B C D  E
11 e11 14 20 6 6 21


问:
Set cookie for root page only
There seems to be very little info covering this. The site's homepage is simply '/' as opposed to '/index.php'. When using:

```<code>setcookie('values[value]', $_POST['value'], time()+99999, '/' );
</code>```

The above line will overwrite all cookies for every path on the domain. However I want this cookie to be set for the homepage only. Can anyone shed some light on this?

答:
This isn't possible. The path section for the RFC says:

A request-path path-matches a given cookie-path if at least one of
the following conditions holds:

The cookie-path and the request-path are identical.

The
cookie-path is a prefix of the request-path, and the last
character of the cookie-path is %x2F ("/").

The cookie-path is a prefix of the request-path, and the first
character of the request-path that is not included in the cookie-
path is a %x2F ("/") character.

That provides no provision to match / without matching /foo.

Title: Set cookie for root page only

Body:
There seems to be very little info covering this. The site's homepage is simply '/' as opposed to '/index.php'. When using:

setcookie('values[value]', $_POST['value'], time()+99999, '/' );

The above line will overwrite all cookies for every path on the domain. However I want this cookie to be set for the homepage only. Can anyone shed some light on this?


问:
Determine whether has NotificationListener needed permission. Android
I have a service:

```<code>public class NotificationCatcher extends NotificationListenerService
</code>```

which has declared permission in the manifest like:

```<code><service
        android:name=".tasks.NotificationCatcher"
        android:enabled="true"
        android:exported="true"
        android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
        <intent-filter>
            <action android:name="android.service.notification.NotificationListenerService" />
        </intent-filter>
    </service>
</code>```

How can I determine whether is PackageManager.PERMISSION_GRANTED? When I can't use checkCallingOrSelfPermission(permission) because I don't have Context.
When I use Context from MainActivity I get exception and my Android app crashes.

What I want to achieve:
MainActivity determines whether has NotificationCatcher android.permission.BIND_NOTIFICATION_LISTENER_SERVICE and then perform action.

答:
You can get Context in service

Call to getApplicationContext() function.

Body:
I have a service:

public class NotificationCatcher extends NotificationListenerService

which has declared permission in the manifest like:

<service
        android:name=".tasks.NotificationCatcher"
        android:enabled="true"
        android:exported="true"
        android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
        <intent-filter>
            <action android:name="android.service.notification.NotificationListenerService" />
        </intent-filter>
    </service>

How can I determine whether is PackageManager.PERMISSION_GRANTED? When I can't use checkCallingOrSelfPermission(permission) because I don't have Context.
When I use Context from MainActivity I get exception and my Android app crashes.

What I want to achieve:
MainActivity determines whether has NotificationCatcher android.permission.BIND_NOTIFICATION_LISTENER_SERVICE and then perform action.


问:
How to inverse a conditional in JavaScript
I have a function that changes the case of some text and returns it, based on the value of capitalisation. I would like to pass another parameter called inverse, which if true, basically performs the opposite; so if capitalisation is lowercase, it will make the text lower case instead of uppercase.

It's important that the value of capitalisation does not change, because it's used by other parts of the application.

I'm looking for a really succinct way to do this with minimal code.

```<code>       capitalisation = "lowercase";

       function switchCase(text, inverse) {
            if (capitalisation === "lowercase") {
                text = text.toLowerCase();
            } else {
                text = text.toUpperCase();
            }
            return text;
        }
</code>```

答:
How about this?  </p>

```<code> var CAPITALISATION_LOWERCASE = "lowercase"
 var CAPITALISATION_UPPERCASE = "uppercase"

 capitalisation = "lowercase";

       function switchCase(text, inverse) {
            if (CAPITALISATION_LOWERCASE == capitalisation && inverse) {
                text = text.toUpperCase();
            } else {
                text = text.toLowerCase();
            }
            return text;
        }
</code>```

Body:
I have a function that changes the case of some text and returns it, based on the value of capitalisation. I would like to pass another parameter called inverse, which if true, basically performs the opposite; so if capitalisation is lowercase, it will make the text lower case instead of uppercase.

It's important that the value of capitalisation does not change, because it's used by other parts of the application.

I'm looking for a really succinct way to do this with minimal code.

       capitalisation = "lowercase";

       function switchCase(text, inverse) {
            if (capitalisation === "lowercase") {
                text = text.toLowerCase();
            } else {
                text = text.toUpperCase();
            }
            return text;
        }

Body:
How about this?

 var CAPITALISATION_LOWERCASE = "lowercase"
 var CAPITALISATION_UPPERCASE = "uppercase"

 capitalisation = "lowercase";

       function switchCase(text, inverse) {
            if (CAPITALISATION_LOWERCASE == capitalisation && inverse) {
                text = text.toUpperCase();
            } else {
                text = text.toLowerCase();
            }
            return text;
        }


问:
Return setof record (virtual table) from function
I need a Postgres function to return a virtual table (like in Oracle) with custom content. The table would have 3 columns and an unknown number of rows.

I just couldn't find the correct syntax on the internet.

Imagine this:

```<code>CREATE OR REPLACE FUNCTION "public"."storeopeninghours_tostring" (numeric)
  RETURNS setof record AS
DECLARE
  open_id ALIAS FOR $1;
  returnrecords setof record;
BEGIN
  insert into returnrecords('1', '2', '3');
  insert into returnrecords('3', '4', '5');
  insert into returnrecords('3', '4', '5');
  RETURN returnrecords;
END;
</code>```

How is this written correctly?

答:
To those who have landed here looking for the MSSQL equivalent of creating a temp table and dumping out its records as your return... that doesn't exist in PostgreSQL :( - you must define the return type. There are two ways to do this, at the time of the function creation or at the time of the query creation.

See here:
http://wiki.postgresql.org/wiki/Return_more_than_one_row_of_data_from_PL/pgSQL_functions

Body:
I need a Postgres function to return a virtual table (like in Oracle) with custom content. The table would have 3 columns and an unknown number of rows.

I just couldn't find the correct syntax on the internet.

Imagine this:

CREATE OR REPLACE FUNCTION "public"."storeopeninghours_tostring" (numeric)
  RETURNS setof record AS
DECLARE
  open_id ALIAS FOR $1;
  returnrecords setof record;
BEGIN
  insert into returnrecords('1', '2', '3');
  insert into returnrecords('3', '4', '5');
  insert into returnrecords('3', '4', '5');
  RETURN returnrecords;
END;

How is this written correctly?


问:
How can I return records with calendar dates based on day of the week?
I have the following schema:

Schedules represent a schedule for a recurring event.

```<code># Table name: schedules
#
#  id         :integer          not null, primary key
#  start_date :date
#  end_date   :date
</code>```

Days represent the WEEKdays of the schedule on which an activity occurs.

```<code># Table name: days
#
#  id          :integer          not null, primary key
#  schedule_id :integer
#  wday        :integer
</code>```

TimeSlots represent the hours that an activity may occur at (may be many per day).

```<code># Table name: time_slots
#
#  id           :integer          not null, primary key
#  day_id       :integer
#  start_time   :time             not null
#  end_time     :time             not null
</code>```

An example dataset, could be:

1 Schedule with start date 1st of June, and end date 30th of June

1 Day, width wday = 0 (activity happens every Monday in June)

2 TimeSlots. 1 with start_hour 8am and end_hour 11am. Another with start_hour 1pm and end_hour 3pm

Given the above example (represented in SQL below), I would like to return one record for EACH Monday in June, WITH their calendar date included.

June 2017 has 4 Mondays, so the above example would look something like:

```<code> id | wday | calendar_date |
----+------+---------------+
  1 |    2 |    2017-06-05 |
  1 |    2 |    2017-06-12 |
  1 |    2 |    2017-06-19 |
  1 |    2 |    2017-06-26 |
</code>```

Can anybody steer me in the right direction?

Setup PSQL below:

```<code>CREATE TABLE schedules (
    id integer NOT NULL,
    start_date date,
    end_date date);

CREATE TABLE days (
    id integer NOT NULL,
    schedule_id integer,
    wday integer);

CREATE TABLE time_slots (
    id integer NOT NULL,
    start_time time,
    end_time time,
    day_id integer);

INSERT INTO schedules (id, start_date, end_date) VALUES (1, '2017-06-01', '2017-06-30');
INSERT INTO days (id, schedule_id, wday) VALUES (1, 1, 0);
INSERT INTO time_slots (id, start_time, end_time, day_id) VALUES (1, '18:00', '19:00', 1);
</code>```

答:
```<code>select     s.id, wday, start_date + g calendar_date
from       schedules s
cross join generate_series(0, end_date - start_date) g
join       days d on d.schedule_id = s.id
where      extract(isodow from start_date + g) - 1 = wday
</code>```

http://rextester.com/GTPQ53700

Notes:

with generate_series() you can generate rows, where there is no data in the DB

I assumed you want weeks to start on Monday (because it is represented by 0 in your tables). The closest to this is ISODOW in PostgreSQL, but that uses 1-7 for Monday-Sunday. (DOW, on the other hand, uses 0-6 for Sunday-Monday: so weeks starts on Sunday with DOW.)

this won't actually look into time_slots. If you need that, add the following predicate to your WHERE clause:

```<code>and exists(select 1 from time_slots t where t.day_id = d.id)
</code>```

Body:
I have the following schema:

Schedules represent a schedule for a recurring event.

# Table name: schedules
#
#  id         :integer          not null, primary key
#  start_date :date
#  end_date   :date

Days represent the WEEKdays of the schedule on which an activity occurs.

# Table name: days
#
#  id          :integer          not null, primary key
#  schedule_id :integer
#  wday        :integer

TimeSlots represent the hours that an activity may occur at (may be many per day).

# Table name: time_slots
#
#  id           :integer          not null, primary key
#  day_id       :integer
#  start_time   :time             not null
#  end_time     :time             not null

An example dataset, could be:

1 Schedule with start date 1st of June, and end date 30th of June

1 Day, width wday = 0 (activity happens every Monday in June)

2 TimeSlots. 1 with start_hour 8am and end_hour 11am. Another with start_hour 1pm and end_hour 3pm

Given the above example (represented in SQL below), I would like to return one record for EACH Monday in June, WITH their calendar date included.

June 2017 has 4 Mondays, so the above example would look something like:

 id | wday | calendar_date |
----+------+---------------+
  1 |    2 |    2017-06-05 |
  1 |    2 |    2017-06-12 |
  1 |    2 |    2017-06-19 |
  1 |    2 |    2017-06-26 |

Can anybody steer me in the right direction?

Setup PSQL below:

CREATE TABLE schedules (
    id integer NOT NULL,
    start_date date,
    end_date date);

CREATE TABLE days (
    id integer NOT NULL,
    schedule_id integer,
    wday integer);

CREATE TABLE time_slots (
    id integer NOT NULL,
    start_time time,
    end_time time,
    day_id integer);

INSERT INTO schedules (id, start_date, end_date) VALUES (1, '2017-06-01', '2017-06-30');
INSERT INTO days (id, schedule_id, wday) VALUES (1, 1, 0);
INSERT INTO time_slots (id, start_time, end_time, day_id) VALUES (1, '18:00', '19:00', 1);

Body:
select     s.id, wday, start_date + g calendar_date
from       schedules s
cross join generate_series(0, end_date - start_date) g
join       days d on d.schedule_id = s.id
where      extract(isodow from start_date + g) - 1 = wday

http://rextester.com/GTPQ53700

Notes:

with generate_series() you can generate rows, where there is no data in the DB

I assumed you want weeks to start on Monday (because it is represented by 0 in your tables). The closest to this is ISODOW in PostgreSQL, but that uses 1-7 for Monday-Sunday. (DOW, on the other hand, uses 0-6 for Sunday-Monday: so weeks starts on Sunday with DOW.)

this won't actually look into time_slots. If you need that, add the following predicate to your WHERE clause:

and exists(select 1 from time_slots t where t.day_id = d.id)


问:
Search for any number of unknown substrings in place of * in a list of string
First of all, sorry if the title isn't very explicit, it's hard for me to formulate it properly. That's also why I haven't found if the question has already been asked, if it has.

So, I have a list of string, and I want to perform a "procedural" search replacing every * in my target-substring by any possible substring.

Here is an example:

```<code>strList = ['obj_1_mesh',
           'obj_2_mesh',
           'obj_TMP',
           'mesh_1_TMP',
           'mesh_2_TMP',
           'meshTMP']

searchFor('mesh_*')
# should return: ['mesh_1_TMP', 'mesh_2_TMP']
</code>```

In this case where there is just one * I just split each string with * and use startswith() and/or endswith(), so that's ok.
But I don't know how to do the same thing if there are multiple * in the search string.

So my question is, how do I search for any number of unknown substrings in place of * in a list of string?

For example:

```<code>strList = ['obj_1_mesh',
           'obj_2_mesh',
           'obj_TMP',
           'mesh_1_TMP',
           'mesh_2_TMP',
           'meshTMP']

searchFor('*_1_*')
# should return: ['obj_1_mesh', 'mesh_1_TMP']
</code>```

Hope everything is clear enough. Thanks.

答:
The simplest way to do this is to use fnmatch, as shown in ma3oun's answer. But here's a way to do it using Regular Expressions, aka regex.

First we transform your searchFor pattern so it uses '.+?' as the "wildcard" instead of '*'. Then we compile the result into a regex pattern object so we can efficiently use it multiple tests.

For an explanation of regex syntax, please see the docs. But briefly, the dot means any character (on this line), the + means look for one or more of them, and the ? means do non-greedy matching, i.e., match the smallest string that conforms to the pattern rather than the longest, (which is what greedy matching does).

```<code>import re

strList = ['obj_1_mesh',
           'obj_2_mesh',
           'obj_TMP',
           'mesh_1_TMP',
           'mesh_2_TMP',
           'meshTMP']

searchFor = '*_1_*'
pat = re.compile(searchFor.replace('*', '.+?'))

result = [s for s in strList if pat.match(s)]
print(result)
</code>```

output

```<code>['obj_1_mesh', 'mesh_1_TMP']
</code>```

If we use searchFor = 'mesh_*' the result is

```<code>['mesh_1_TMP', 'mesh_2_TMP']
</code>```

Please note that this solution is not robust. If searchFor contains other characters that have special meaning in a regex they need to be escaped. Actually, rather than doing that searchFor.replace transformation, it would be cleaner to just write the pattern using regex syntax in the first place.

Body:
First of all, sorry if the title isn't very explicit, it's hard for me to formulate it properly. That's also why I haven't found if the question has already been asked, if it has.

So, I have a list of string, and I want to perform a "procedural" search replacing every * in my target-substring by any possible substring.

Here is an example:

strList = ['obj_1_mesh',
           'obj_2_mesh',
           'obj_TMP',
           'mesh_1_TMP',
           'mesh_2_TMP',
           'meshTMP']

searchFor('mesh_*')
# should return: ['mesh_1_TMP', 'mesh_2_TMP']

In this case where there is just one * I just split each string with * and use startswith() and/or endswith(), so that's ok.
But I don't know how to do the same thing if there are multiple * in the search string.

So my question is, how do I search for any number of unknown substrings in place of * in a list of string?

For example:

strList = ['obj_1_mesh',
           'obj_2_mesh',
           'obj_TMP',
           'mesh_1_TMP',
           'mesh_2_TMP',
           'meshTMP']

searchFor('*_1_*')
# should return: ['obj_1_mesh', 'mesh_1_TMP']

Hope everything is clear enough. Thanks.

Body:
The simplest way to do this is to use fnmatch, as shown in ma3oun's answer. But here's a way to do it using Regular Expressions, aka regex.

First we transform your searchFor pattern so it uses '.+?' as the "wildcard" instead of '*'. Then we compile the result into a regex pattern object so we can efficiently use it multiple tests.

For an explanation of regex syntax, please see the docs. But briefly, the dot means any character (on this line), the + means look for one or more of them, and the ? means do non-greedy matching, i.e., match the smallest string that conforms to the pattern rather than the longest, (which is what greedy matching does).

import re

strList = ['obj_1_mesh',
           'obj_2_mesh',
           'obj_TMP',
           'mesh_1_TMP',
           'mesh_2_TMP',
           'meshTMP']

searchFor = '*_1_*'
pat = re.compile(searchFor.replace('*', '.+?'))

result = [s for s in strList if pat.match(s)]
print(result)

output

['obj_1_mesh', 'mesh_1_TMP']

If we use searchFor = 'mesh_*' the result is

['mesh_1_TMP', 'mesh_2_TMP']

Please note that this solution is not robust. If searchFor contains other characters that have special meaning in a regex they need to be escaped. Actually, rather than doing that searchFor.replace transformation, it would be cleaner to just write the pattern using regex syntax in the first place.


问:
Started to receive the error: Error signing assembly -- Unknown error (8013141c)
Visual Studio 2013 - Started to receive the error: "Error signing assembly -- Unknown error (8013141c)" when compiling. Few of the projects are signed using a snk file. It used to compile and has been in production for quite some time.</p>

答: Run Visual Studio with elevated permissions, as an Administrator.</p>


问:
What causes "Timer Installed" or "Timer removed" in Firebase app?
I have a Cordova/AngularJS/Firebase app that makes use of angular fire library.

I am trying to fix some performance issues, mostly on the "resume" function when the app is re-opened from the background it appears to freeze for a couple seconds.

My profiling remotely in safari shows that several "timer installed" and "timer removed" are being called, as many as 50 in a row. During this process the app is frozen, can anybody point me in a direction to try and fix this? Do I need to be disposing of some resource? Angular fire documentation says that all watches are destroyed when the controller scope that contains them is destroyed. How can I further debug this to find out what is going on?

I have several services classes that follow a pattern like this for opening connections:

```<code>(function () {

angular.module('myApp').service('someService',
          ['$firebaseObject',
           '$firebaseArray',
           '$rootScope',
 function ($firebaseObject, $firebaseArray, $rootScope) {

    this.dbUsers = firebase.database().ref('users');
    this.dbNotifications = firebase.database().ref('notifications');
    this.dbMessages = firebase.database().ref('messages');

}]);//fireService

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

Should I be disposing of these connections or closing them somehow? My controllers access these services frequently, all which open connections in the beginning like this example

答:
From this sentence from your question:

I am trying to fix some performance issues, mostly on the "resume" function when the app is re-opened from the background it appears to
freeze for a couple seconds.

It really seems you are loading a lot of data that freeze the app. A real solution would be to limit the number of rows you are trying to display.

There are two common solutions:

Paginate the result

You can use for exemple the AngularUI pagination directive. See also this question dealing with how to use it on an Angular app.

Use the limitTo filter

This solution will be less good in terms of performance, but maybe better adapted to your needs (as you may not be able to edit server side).

limitTo is a core Angular directive that allow you limit the amount of lines displayed by a ng-repeat (in the following example, 50):

```<code><tr ng-repeat="item in items | limitTo: 50">{{item}}</tr>
</code>```

Note that you can move the limit value to a scope variable. You can modify it to update the number of items you want to display:

var myApp = angular.module('app', []);
myApp.controller('MyCtrl', ['$scope', function($scope) {
  $scope.items = [];
  $scope.limit = 5; // default limit

  for(let i = 0; i < 100; i++) $scope.items.push(i); // generate data
}]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MyCtrl">
    <ul>
        <li ng-repeat="i in items | limitTo: limit">{{i}}</li>
    </ul>
    <button ng-click="limit = limit + 5">Show more results</button>
</div></code>```

Body:
I have a Cordova/AngularJS/Firebase app that makes use of angular fire library.

I am trying to fix some performance issues, mostly on the "resume" function when the app is re-opened from the background it appears to freeze for a couple seconds.

My profiling remotely in safari shows that several "timer installed" and "timer removed" are being called, as many as 50 in a row. During this process the app is frozen, can anybody point me in a direction to try and fix this? Do I need to be disposing of some resource? Angular fire documentation says that all watches are destroyed when the controller scope that contains them is destroyed. How can I further debug this to find out what is going on?

I have several services classes that follow a pattern like this for opening connections:

(function () {

angular.module('myApp').service('someService',
          ['$firebaseObject',
           '$firebaseArray',
           '$rootScope',
 function ($firebaseObject, $firebaseArray, $rootScope) {

    this.dbUsers = firebase.database().ref('users');
    this.dbNotifications = firebase.database().ref('notifications');
    this.dbMessages = firebase.database().ref('messages');

}]);//fireService

})();

Should I be disposing of these connections or closing them somehow? My controllers access these services frequently, all which open connections in the beginning like this example

Body:
From this sentence from your question:

I am trying to fix some performance issues, mostly on the "resume" function when the app is re-opened from the background it appears to
freeze for a couple seconds.

It really seems you are loading a lot of data that freeze the app. A real solution would be to limit the number of rows you are trying to display.

There are two common solutions:

Paginate the result

You can use for exemple the AngularUI pagination directive. See also this question dealing with how to use it on an Angular app.

Use the limitTo filter

This solution will be less good in terms of performance, but maybe better adapted to your needs (as you may not be able to edit server side).

limitTo is a core Angular directive that allow you limit the amount of lines displayed by a ng-repeat (in the following example, 50):

<tr ng-repeat="item in items | limitTo: 50">{{item}}</tr>

Note that you can move the limit value to a scope variable. You can modify it to update the number of items you want to display:

var myApp = angular.module('app', []);
myApp.controller('MyCtrl', ['$scope', function($scope) {
  $scope.items = [];
  $scope.limit = 5; // default limit

  for(let i = 0; i < 100; i++) $scope.items.push(i); // generate data
}]);

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MyCtrl">
    <ul>
        <li ng-repeat="i in items | limitTo: limit">{{i}}</li>
    </ul>
    <button ng-click="limit = limit + 5">Show more results</button>
</div>