问:
My java code resulted in a double spaced output
I'm doing an assignment in MyProgrammingLab for JAVA and my code resulted in an error. The output is double spaced and I can't figure out why. I thought it might have something to do with the 'System.out.println' from reading other discussions, but I was not successful when I left off the 'ln'. This is my first course in JAVA. I apologize if the solution is obvious. Any hint would be helpful. Thank you!

```<code>CODELAB ANALYSIS: LOGICAL ERROR(S)
Problems Detected:
     ⇒     The contents of your standard output is incorrect.

Given the following was entered from the keyboard:
!!!!!If you built your letter counter properly it will not count anything
but proper letters@@@@@@.
AlsO The DegRee OF captilization SHOULD NOT AFFECT YOUR COUNTER in any way
shape or form.
Multiple sentences on one line are fine. As long as the line ends with a
period.
aaaaa bbbbb ttttt uuuuuuuuuu.
Goodbye

you displayed:
...
The letter B occurred 2 times in the sentence.

The letter C occurred 2 times in the sentence.

The letter E occurred 7 times in the sentence.

The letter F occurred 1 times in the sentence.

...
instead of:
...
The letter B occurred 2 times in the sentence.
The letter C occurred 2 times in the sentence.
The letter E occurred 7 times in the sentence.
The letter F occurred 1 times in the sentence.
The letter G occurred 1 times in the sentence.
The letter H occurred 1 times in the sentence.
The letter I occurred 5 times in the sentence.
The letter L occurred 6 times in the sentence.
The letter N occurred 5 times in the sentence.
...

     ⇒     Failed 4 out of 4 test runs.

Failed Test Run #1

     ⇒     The contents of your standard output is incorrect.
     ⇒     There is an error in your prompts.

Hide Invisibles
Expected Result:
</code>```

Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:

The·letter·A·occurred·4·times·in·the·sentence.↵
      The·letter·B·occurred·1·times·in·the·sentence.↵
      The·letter·C·occurred·1·times·in·the·sentence.↵
      The·letter·E·occurred·9·times·in·the·sentence.↵
      The·letter·H·occurred·3·times·in·the·sentence.↵
      The·letter·I·occurred·1·times·in·the·sentence.↵
      The·letter·N·occurred·4·times·in·the·sentence.↵
      The·letter·O·occurred·2·times·in·the·sentence.↵
      The·letter·R·occurred·4·times·in·the·sentence.↵
      The·letter·S·occurred·4·times·in·the·sentence.↵
      The·letter·T·occurred·1·times·in·the·sentence.↵
      The·letter·U·occurred·1·times·in·the·sentence.↵
      The·letter·V·occurred·2·times·in·the·sentence.↵
      The·letter·W·occurred·1·times·in·the·sentence.↵ Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:
      The·letter·A·occurred·15·times·in·the·sentence.↵
      The·letter·B·occurred·5·times·in·the·sentence.↵
      The·letter·C·occurred·10·times·in·the·sentence.↵ Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:
      The·letter·Z·occurred·5·times·in·the·sentence.↵ Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:
      The·letter·G·occurred·8·times·in·the·sentence.↵
      The·letter·R·occurred·9·times·in·the·sentence.↵ Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:
      The·letter·A·occurred·1·times·in·the·sentence.↵
      The·letter·C·occurred·1·times·in·the·sentence.↵
      The·letter·D·occurred·1·times·in·the·sentence.↵
      The·letter·E·occurred·4·times·in·the·sentence.↵
      The·letter·G·occurred·2·times·in·the·sentence.↵
      The·letter·H·occurred·3·times·in·the·sentence.↵
      The·letter·I·occurred·2·times·in·the·sentence.↵
      The·letter·L·occurred·4·times·in·the·sentence.↵
      The·letter·M·occurred·1·times·in·the·sentence.↵
      The·letter·N·occurred·4·times·in·the·sentence.↵
      The·letter·O·occurred·5·times·in·the·sentence.↵
      The·letter·P·occurred·1·times·in·the·sentence.↵
      The·letter·R·occurred·3·times·in·the·sentence.↵
      The·letter·S·occurred·4·times·in·the·sentence.↵
      The·letter·T·occurred·5·times·in·the·sentence.↵
      The·letter·U·occurred·2·times·in·the·sentence.↵
      The·letter·Y·occurred·1·times·in·the·sentence.↵ Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:
      The·letter·A·occurred·9·times·in·the·sentence.↵
      The·letter·B·occurred·2·times·in·the·sentence.↵
      The·letter·C·occurred·3·times·in·the·sentence.↵
      The·letter·E·occurred·24·times·in·the·sentence.↵
      The·letter·F·occurred·3·times·in·the·sentence.↵
      The·letter·G·occurred·7·times·in·the·sentence.↵
      The·letter·H·occurred·14·times·in·the·sentence.↵
      The·letter·I·occurred·12·times·in·the·sentence.↵
      The·letter·K·occurred·1·times·in·the·sentence.↵
      The·letter·L·occurred·7·times·in·the·sentence.↵
      The·letter·M·occurred·2·times·in·the·sentence.↵
      The·letter·N·occurred·10·times·in·the·sentence.↵
      The·letter·O·occurred·9·times·in·the·sentence.↵
      The·letter·P·occurred·4·times·in·the·sentence.↵
      The·letter·Q·occurred·1·times·in·the·sentence.↵
      The·letter·R·occurred·5·times·in·the·sentence.↵
      The·letter·S·occurred·9·times·in·the·sentence.↵
      The·letter·T·occurred·22·times·in·the·sentence.↵
      The·letter·U·occurred·8·times·in·the·sentence.↵
      The·letter·V·occurred·1·times·in·the·sentence.↵
      The·letter·W·occurred·3·times·in·the·sentence.↵
      The·letter·X·occurred·1·times·in·the·sentence.↵
      The·letter·Y·occurred·5·times·in·the·sentence.↵ Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:
      The·letter·A·occurred·6·times·in·the·sentence.↵
      The·letter·B·occurred·1·times·in·the·sentence.↵
      The·letter·C·occurred·1·times·in·the·sentence.↵
      The·letter·D·occurred·2·times·in·the·sentence.↵
      The·letter·E·occurred·7·times·in·the·sentence.↵
      The·letter·G·occurred·2·times·in·the·sentence.↵
      The·letter·H·occurred·5·times·in·the·sentence.↵
      The·letter·I·occurred·6·times·in·the·sentence.↵
      The·letter·L·occurred·2·times·in·the·sentence.↵
      The·letter·M·occurred·2·times·in·the·sentence.↵
      The·letter·N·occurred·5·times·in·the·sentence.↵
      The·letter·O·occurred·5·times·in·the·sentence.↵
      The·letter·P·occurred·2·times·in·the·sentence.↵
      The·letter·R·occurred·4·times·in·the·sentence.↵
      The·letter·S·occurred·2·times·in·the·sentence.↵
      The·letter·T·occurred·12·times·in·the·sentence.↵
      The·letter·U·occurred·3·times·in·the·sentence.↵
      The·letter·W·occurred·2·times·in·the·sentence.↵
      The·letter·Y·occurred·1·times·in·the·sentence.↵ Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:↵

Your Code's Actual Result:

Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:
      The·letter·A·occurred·4·times·in·the·sentence.↵
      ↵
      The·letter·B·occurred·1·times·in·the·sentence.↵
      ↵
      The·letter·C·occurred·1·times·in·the·sentence.↵
      ↵
      The·letter·E·occurred·9·times·in·the·sentence.↵
      ↵
      The·letter·H·occurred·3·times·in·the·sentence.↵
      ↵
      The·letter·I·occurred·1·times·in·the·sentence.↵
      ↵
      The·letter·N·occurred·4·times·in·the·sentence.↵
      ↵
      The·letter·O·occurred·2·times·in·the·sentence.↵
      ↵
      The·letter·R·occurred·4·times·in·the·sentence.↵
      ↵
      The·letter·S·occurred·4·times·in·the·sentence.↵
      ↵
      The·letter·T·occurred·1·times·in·the·sentence.↵
      ↵
      The·letter·U·occurred·1·times·in·the·sentence.↵
      ↵
      The·letter·V·occurred·2·times·in·the·sentence.↵
      ↵
      The·letter·W·occurred·1·times·in·the·sentence.↵
      ↵
      ↵

Here is my code:

```<code>import java.util.Scanner;
public class LetterFreq
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        String input = "";
        int a[] = new int[26];
        System.out.print("Enter a sentence ending with a period or anything not ending in a period to end:");
        input = sc.nextLine();
        char[] c = input.toCharArray();
        for(int i = 0; i < c.length; i++)
        {
            if(Character.isDigit(c[i]))
            {
                System.out.println();
                System.exit(0);
            }
            if(Character.isLetter(c[i]))
            {
                if(Character.isLowerCase(c[i]))
                    c[i] = Character.toUpperCase(c[i]);
                int index = c[i] - 'A';
                int b = a[index];
                b++;
                a[index] = b;
            }
        }
        for(int i = 0; i < a.length; i++)
        {
            if(a[i] > 0)
            {
                System.out.println("The letter " + (char)(i + 'A') + " occurred " + a[i] + " times in the sentence.");
                System.out.println();
            }
        }
        System.out.println();
    }
}
</code>```

UPDATE:
When I remove the 'System.out.println();' that appears after the one with '"The letter "', I get another output error:
    CODELAB ANALYSIS: LOGICAL ERROR(S)

```<code>Problems Detected:
     ⇒     The contents of your standard output is incorrect.

Given the following was entered from the keyboard:
!!!!!If you built your letter counter properly it will not count anything
</code>```

but proper letters@@@@@@.
    AlsO The DegRee OF captilization SHOULD NOT AFFECT YOUR COUNTER in any way shape or form.
    Multiple sentences on one line are fine. As long as the line ends with a period.
    aaaaa bbbbb ttttt uuuuuuuuuu.
    Goodbye

```<code>you displayed:
...

instead of:
...
Enter a sentence ending with a period or anything not ending in a period to
end:The letter A occurred 7 times in the sentence.
The letter C occurred 3 times in the sentence.
The letter D occurred 2 times in the sentence.
The letter E occurred 7 times in the sentence.
The letter F occurred 4 times in the sentence.
The letter G occurred 1 times in the sentence.
The letter H occurred 3 times in the sentence.
The letter I occurred 4 times in the sentence.
The letter L occurred 3 times in the sentence.
...

     ⇒     Failed 4 out of 4 test runs.

     ⇒     The contents of your standard output is incorrect.
     ⇒     There is an error in your prompts.
</code>```

The output for my code shows up far down the page on the test runs, but the double-spacing has been corrected. I'm not sure how to fix the error mentioned above. Thoughts?

答:
Look at your code:

```<code>System.out.println("The letter " + (char)(i + 'A') + " occurred " + a[i] + " times in the sentence.");
System.out.println();
</code>```

What do you think that second System.out.println() is doing?

You're getting "double-spaced" because that's what you're explicitely declaring with the line:

```<code>System.out.println();
</code>```

Remove it, and you'll remove the double-spacing.

Body:
I'm doing an assignment in MyProgrammingLab for JAVA and my code resulted in an error. The output is double spaced and I can't figure out why. I thought it might have something to do with the 'System.out.println' from reading other discussions, but I was not successful when I left off the 'ln'. This is my first course in JAVA. I apologize if the solution is obvious. Any hint would be helpful. Thank you!

CODELAB ANALYSIS: LOGICAL ERROR(S)
Problems Detected:
     ⇒     The contents of your standard output is incorrect.

Given the following was entered from the keyboard:
!!!!!If you built your letter counter properly it will not count anything
but proper letters@@@@@@.
AlsO The DegRee OF captilization SHOULD NOT AFFECT YOUR COUNTER in any way
shape or form.
Multiple sentences on one line are fine. As long as the line ends with a
period.
aaaaa bbbbb ttttt uuuuuuuuuu.
Goodbye

you displayed:
...
The letter B occurred 2 times in the sentence.

The letter C occurred 2 times in the sentence.

The letter E occurred 7 times in the sentence.

The letter F occurred 1 times in the sentence.

...
instead of:
...
The letter B occurred 2 times in the sentence.
The letter C occurred 2 times in the sentence.
The letter E occurred 7 times in the sentence.
The letter F occurred 1 times in the sentence.
The letter G occurred 1 times in the sentence.
The letter H occurred 1 times in the sentence.
The letter I occurred 5 times in the sentence.
The letter L occurred 6 times in the sentence.
The letter N occurred 5 times in the sentence.
...

     ⇒     Failed 4 out of 4 test runs.

Failed Test Run #1

     ⇒     The contents of your standard output is incorrect.
     ⇒     There is an error in your prompts.

Hide Invisibles
Expected Result:

Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:

The·letter·A·occurred·4·times·in·the·sentence.↵
      The·letter·B·occurred·1·times·in·the·sentence.↵
      The·letter·C·occurred·1·times·in·the·sentence.↵
      The·letter·E·occurred·9·times·in·the·sentence.↵
      The·letter·H·occurred·3·times·in·the·sentence.↵
      The·letter·I·occurred·1·times·in·the·sentence.↵
      The·letter·N·occurred·4·times·in·the·sentence.↵
      The·letter·O·occurred·2·times·in·the·sentence.↵
      The·letter·R·occurred·4·times·in·the·sentence.↵
      The·letter·S·occurred·4·times·in·the·sentence.↵
      The·letter·T·occurred·1·times·in·the·sentence.↵
      The·letter·U·occurred·1·times·in·the·sentence.↵
      The·letter·V·occurred·2·times·in·the·sentence.↵
      The·letter·W·occurred·1·times·in·the·sentence.↵ Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:
      The·letter·A·occurred·15·times·in·the·sentence.↵
      The·letter·B·occurred·5·times·in·the·sentence.↵
      The·letter·C·occurred·10·times·in·the·sentence.↵ Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:
      The·letter·Z·occurred·5·times·in·the·sentence.↵ Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:
      The·letter·G·occurred·8·times·in·the·sentence.↵
      The·letter·R·occurred·9·times·in·the·sentence.↵ Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:
      The·letter·A·occurred·1·times·in·the·sentence.↵
      The·letter·C·occurred·1·times·in·the·sentence.↵
      The·letter·D·occurred·1·times·in·the·sentence.↵
      The·letter·E·occurred·4·times·in·the·sentence.↵
      The·letter·G·occurred·2·times·in·the·sentence.↵
      The·letter·H·occurred·3·times·in·the·sentence.↵
      The·letter·I·occurred·2·times·in·the·sentence.↵
      The·letter·L·occurred·4·times·in·the·sentence.↵
      The·letter·M·occurred·1·times·in·the·sentence.↵
      The·letter·N·occurred·4·times·in·the·sentence.↵
      The·letter·O·occurred·5·times·in·the·sentence.↵
      The·letter·P·occurred·1·times·in·the·sentence.↵
      The·letter·R·occurred·3·times·in·the·sentence.↵
      The·letter·S·occurred·4·times·in·the·sentence.↵
      The·letter·T·occurred·5·times·in·the·sentence.↵
      The·letter·U·occurred·2·times·in·the·sentence.↵
      The·letter·Y·occurred·1·times·in·the·sentence.↵ Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:
      The·letter·A·occurred·9·times·in·the·sentence.↵
      The·letter·B·occurred·2·times·in·the·sentence.↵
      The·letter·C·occurred·3·times·in·the·sentence.↵
      The·letter·E·occurred·24·times·in·the·sentence.↵
      The·letter·F·occurred·3·times·in·the·sentence.↵
      The·letter·G·occurred·7·times·in·the·sentence.↵
      The·letter·H·occurred·14·times·in·the·sentence.↵
      The·letter·I·occurred·12·times·in·the·sentence.↵
      The·letter·K·occurred·1·times·in·the·sentence.↵
      The·letter·L·occurred·7·times·in·the·sentence.↵
      The·letter·M·occurred·2·times·in·the·sentence.↵
      The·letter·N·occurred·10·times·in·the·sentence.↵
      The·letter·O·occurred·9·times·in·the·sentence.↵
      The·letter·P·occurred·4·times·in·the·sentence.↵
      The·letter·Q·occurred·1·times·in·the·sentence.↵
      The·letter·R·occurred·5·times·in·the·sentence.↵
      The·letter·S·occurred·9·times·in·the·sentence.↵
      The·letter·T·occurred·22·times·in·the·sentence.↵
      The·letter·U·occurred·8·times·in·the·sentence.↵
      The·letter·V·occurred·1·times·in·the·sentence.↵
      The·letter·W·occurred·3·times·in·the·sentence.↵
      The·letter·X·occurred·1·times·in·the·sentence.↵
      The·letter·Y·occurred·5·times·in·the·sentence.↵ Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:
      The·letter·A·occurred·6·times·in·the·sentence.↵
      The·letter·B·occurred·1·times·in·the·sentence.↵
      The·letter·C·occurred·1·times·in·the·sentence.↵
      The·letter·D·occurred·2·times·in·the·sentence.↵
      The·letter·E·occurred·7·times·in·the·sentence.↵
      The·letter·G·occurred·2·times·in·the·sentence.↵
      The·letter·H·occurred·5·times·in·the·sentence.↵
      The·letter·I·occurred·6·times·in·the·sentence.↵
      The·letter·L·occurred·2·times·in·the·sentence.↵
      The·letter·M·occurred·2·times·in·the·sentence.↵
      The·letter·N·occurred·5·times·in·the·sentence.↵
      The·letter·O·occurred·5·times·in·the·sentence.↵
      The·letter·P·occurred·2·times·in·the·sentence.↵
      The·letter·R·occurred·4·times·in·the·sentence.↵
      The·letter·S·occurred·2·times·in·the·sentence.↵
      The·letter·T·occurred·12·times·in·the·sentence.↵
      The·letter·U·occurred·3·times·in·the·sentence.↵
      The·letter·W·occurred·2·times·in·the·sentence.↵
      The·letter·Y·occurred·1·times·in·the·sentence.↵ Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:↵

Your Code's Actual Result:

Enter·a·sentence·ending·with·a·period·or·anything·not·ending·in·a·period·to·end:
      The·letter·A·occurred·4·times·in·the·sentence.↵
      ↵
      The·letter·B·occurred·1·times·in·the·sentence.↵
      ↵
      The·letter·C·occurred·1·times·in·the·sentence.↵
      ↵
      The·letter·E·occurred·9·times·in·the·sentence.↵
      ↵
      The·letter·H·occurred·3·times·in·the·sentence.↵
      ↵
      The·letter·I·occurred·1·times·in·the·sentence.↵
      ↵
      The·letter·N·occurred·4·times·in·the·sentence.↵
      ↵
      The·letter·O·occurred·2·times·in·the·sentence.↵
      ↵
      The·letter·R·occurred·4·times·in·the·sentence.↵
      ↵
      The·letter·S·occurred·4·times·in·the·sentence.↵
      ↵
      The·letter·T·occurred·1·times·in·the·sentence.↵
      ↵
      The·letter·U·occurred·1·times·in·the·sentence.↵
      ↵
      The·letter·V·occurred·2·times·in·the·sentence.↵
      ↵
      The·letter·W·occurred·1·times·in·the·sentence.↵
      ↵
      ↵

Here is my code:

import java.util.Scanner;
public class LetterFreq
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        String input = "";
        int a[] = new int[26];
        System.out.print("Enter a sentence ending with a period or anything not ending in a period to end:");
        input = sc.nextLine();
        char[] c = input.toCharArray();
        for(int i = 0; i < c.length; i++)
        {
            if(Character.isDigit(c[i]))
            {
                System.out.println();
                System.exit(0);
            }
            if(Character.isLetter(c[i]))
            {
                if(Character.isLowerCase(c[i]))
                    c[i] = Character.toUpperCase(c[i]);
                int index = c[i] - 'A';
                int b = a[index];
                b++;
                a[index] = b;
            }
        }
        for(int i = 0; i  0)
            {
                System.out.println("The letter " + (char)(i + 'A') + " occurred " + a[i] + " times in the sentence.");
                System.out.println();
            }
        }
        System.out.println();
    }
}

UPDATE:
When I remove the 'System.out.println();' that appears after the one with '"The letter "', I get another output error:
    CODELAB ANALYSIS: LOGICAL ERROR(S)

Problems Detected:
     ⇒     The contents of your standard output is incorrect.

Given the following was entered from the keyboard:
!!!!!If you built your letter counter properly it will not count anything

but proper letters@@@@@@.
    AlsO The DegRee OF captilization SHOULD NOT AFFECT YOUR COUNTER in any way shape or form.
    Multiple sentences on one line are fine. As long as the line ends with a period.
    aaaaa bbbbb ttttt uuuuuuuuuu.
    Goodbye

you displayed:
...

instead of:
...
Enter a sentence ending with a period or anything not ending in a period to
end:The letter A occurred 7 times in the sentence.
The letter C occurred 3 times in the sentence.
The letter D occurred 2 times in the sentence.
The letter E occurred 7 times in the sentence.
The letter F occurred 4 times in the sentence.
The letter G occurred 1 times in the sentence.
The letter H occurred 3 times in the sentence.
The letter I occurred 4 times in the sentence.
The letter L occurred 3 times in the sentence.
...

     ⇒     Failed 4 out of 4 test runs.

     ⇒     The contents of your standard output is incorrect.
     ⇒     There is an error in your prompts.

The output for my code shows up far down the page on the test runs, but the double-spacing has been corrected. I'm not sure how to fix the error mentioned above. Thoughts?

Body:
Look at your code:

System.out.println("The letter " + (char)(i + 'A') + " occurred " + a[i] + " times in the sentence.");
System.out.println();

What do you think that second System.out.println() is doing?

You're getting "double-spaced" because that's what you're explicitely declaring with the line:

System.out.println();

Remove it, and you'll remove the double-spacing.


来源: stackexchange

问:
In Datastage, in oracle connector stage can I use parameters in external sql file?
I am using oracle connector stage and I have selected "Read select statement from file" option.

In the sql file I am using a parameter like where eff_start_date = #eff_start_date#. I have defined eff_start_date parameter in the job and I am also giving its value at run-time, but it is not populating the values and showing invalid character error.

I read somewhere that we can't use parameters in a sql file, so I want to ask is there any workaround for it?

答:
Use a Sequence and two job.

The first job, receive the eff_star_date parameter, and do:

Read the sql file (file1), with a Sequential File Stage

Replace the variable string on a Transformer, with the parameter value

Write a new sql file (file2) with replaced string, on Sequential File Stage

On the second job, there is the Oracle connector with "Read select statement from file" option, that read the complete file (file2)

ContentLicense: CC BY-SA 3.0


问:
For what should I use the Aspect Ratio NSLayoutConstraint?
When I first started working with AutoLayout, I couldn't find any example which helps understanding for what stands the Aspect Ratio NSLayoutConstraint.

Does someone have an example of usage? Thanks!

答:
I have a demo example of keeping a square view centered in all devices and orientations here.

The constraints are set up in IB, but you could just as easily set them up in code. Most of this was meant to explain how to prioritize margin constraints to let the auto layout engine know what to break and when, but what makes the view square is the aspect ration - it's 1:1. If you want a rectangle, you make it 2:1 (or 1:2 depending).

Once you understand these two pieces (prioritization and aspect ratio), the last piece is the actual margins values - I set them for 10 points, meaning the square will have 10 point margins on the smallest axis. If the device is an iPad Pro 12.9 inch, you get a very large square. If it's an iPhone SE, you get a very small one. No matter what, you get the 10 point margin. Set the margin values up for 50, and the square view is relatively smaller. The important thing is with an aspect ratio of 1:1, it will always be a square.


问:
When is a factory appropriate?
Taken from wikipedia:

In object-oriented computer
  programming, a factory is an object
  for creating other objects. It is an
  abstraction of a constructor, and can
  be used to implement various
  allocation schemes.

Could anyone please explain when a factory class is required or beneficial?

I am currently working on a project where I have a class and use the constructor to initialize an object (duh!) but it can fail and not initialize at all. I have a Success property to check if it was created properly. Is this a good example for when a factory class should be implemented? This way the Create() method can return null and I can get rid of the Success property. Do I have the right idea?

答:
The textbook example for a Factory situation is when you have an interface and several implementations, but you don't want to expose the implementations. You implement a factory (method or class) that produces instances of different implementations based on the parameters you pass it; however, since it returns them by the interface type, the caller will not be burdened with implementation details.

Real-world example: Suppose you have defined an interface for a stream reader, and implementations to read from a local file, a network resource, and stdin. You then write a factory method that takes a single parameter (the URI), and returns a suitable reader. The caller doesn't need to know about implementation details. The best part is, when you decide you want to support another input method, say, data: URIs, you just add another implementation and add it to the factory - you won't need to change anything in the calling code.

ContentLicense: CC BY-SA 2.5

Title: When is a factory appropriate?


问:
Execute mac command from Python
Im trying to execute a MAC command from Python but get the following error:-

Command

```<code>from subprocess import call
call(["""osascript -e 'tell app "System Events" to display dialog "Hello World" ' """])
</code>```

Error

```<code>Traceback (most recent call last):
  File "/Users/premanandlakshmanan/Documents/psilon/quantopian/mac_popup.py", line 2, in <module>
    call(["""osascript -e 'tell app "System Events" to display dialog "Hello World" ' """])
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 522, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in __init__
    errread, errwrite)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1335, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory
[Finished in 0.3s with exit code 1]
</code>```

答:
subprocess.call(), with shell=False (the default) takes a list of arguments.

Try:

import subprocess

args = []
args.append('osascript')
args.append('-e')
args.append('tell app "System Events" to display dialog "Hello World"')
subprocess.call(args)
```

You are trying to execute a file called osascript -e 'tell ap..., which doesn't exist.

You want to execute osascript, with some arguments.

Title: Execute mac command from Python

Body:
Im trying to execute a MAC command from Python but get the following error:-

Command

from subprocess import call
call(["""osascript -e 'tell app "System Events" to display dialog "Hello World" ' """])

Error

Traceback (most recent call last):
  File "/Users/premanandlakshmanan/Documents/psilon/quantopian/mac_popup.py", line 2, in <module>
    call(["""osascript -e 'tell app "System Events" to display dialog "Hello World" ' """])
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 522, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in __init__
    errread, errwrite)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1335, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory
[Finished in 0.3s with exit code 1]

Body:
subprocess.call(), with shell=False (the default) takes a list of arguments.

Try:

import subprocess

args = []
args.append('osascript')
args.append('-e')
args.append('tell app "System Events" to display dialog "Hello World"')
subprocess.call(args)

You are trying to execute a file called osascript -e 'tell ap..., which doesn't exist.

You want to execute osascript, with some arguments.


问:
How to accept a file and then store it in cloud storage
I am using expressjs (all newest versions of express, node, and npm). I have create a route such as this:

```<code>router.post("/", function(req, res, next) {
});
</code>```

This route will need to be able to have a file (image/video/docx,etc) uploaded and needs to then be stored on a cloud storage service (Google Storage). I do not want to store anything on the server that express is running on, just want to receive the file and pass it on over to Google Cloud Storage. I see there are some libraries which do this in addition to express, but I couldn't not find how to do it using just express.

答:
I think your clients might be able to upload directly to GCS by constructing a HTML form. Basically you can create a signed url and embed it in the form and then on submit, the upload goes straight to GCS and your app doesn't need to handle it at all.

See: https://cloud.google.com/storage/docs/xml-api/post-object

Body:
I am using expressjs (all newest versions of express, node, and npm). I have create a route such as this:

router.post("/", function(req, res, next) {
});

This route will need to be able to have a file (image/video/docx,etc) uploaded and needs to then be stored on a cloud storage service (Google Storage). I do not want to store anything on the server that express is running on, just want to receive the file and pass it on over to Google Cloud Storage. I see there are some libraries which do this in addition to express, but I couldn't not find how to do it using just express.


问:
How to add text on a image in html5 and css3
Enclosing the code and how can i add the text on image  how write the code for it.as im working on it</p>

```<code><div class="content">
                <div class="section">
                <div class="box">
                    <a href="#">

                    <img src="./images/pc.jpg" alt style="height: 210px; width: 215px; border: 1px solid black; margin-left: -13px; border-bottom: 10px solid blue;"></a>

                    <a href="#"><img src="./images/pc.jpg" style="height: 210px; width: 215px; border: 1px solid black; margin-left: 25px;border-bottom: 10px solid blue;"></a>

                    <a href="#"><img src="./images/pc.jpg" style="height: 210px; width: 215px; border: 1px solid black; margin-left: 25px;border-bottom: 10px solid blue;"></a>
                    <br>
                    <a href="#"><img src="./images/pc.jpg" style="height: 210px; width: 215px; border: 1px solid black; margin-left: -13px;border-bottom: 10px solid blue;"></a>

                    <a href="#"><img src="./images/pc.jpg" style="height: 210px; width: 215px; border: 1px solid black; margin-left: 25px;border-bottom: 10px solid blue;"></a>

                    <a href="#"><img src="./images/pc.jpg" style="height: 210px; width: 215px; border: 1px solid black; margin-left: 25px;border-bottom: 10px solid blue;"></a>

                </div>

                </div>

                </div>
</code>```

答:
Three steps:

Give the div a position: relative

Set the image as a background-image of the div

Give the text inside the div a position: absolute so you can position it wherever you need to

Working Example:

div {
position: relative;
background-image: url('http://placekitten.com/340/180');
width: 340px;
height: 180px;
}

div p {
position: absolute;
top: 108px;
right: 6px;
color: rgb(255, 255, 255);
background-color: rgba(0, 0, 0, 0.4);
font-size: 24px;
line-height: 36px;
font-weight: bold;
padding: 4px 12px;
border-radius: 9px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<p>I am a little kitten</p>
</div></code>```

Body:
Three steps:

Give the div a position: relative

Set the image as a background-image of the div

Give the text inside the div a position: absolute so you can position it wherever you need to

Working Example:

div {
position: relative;
background-image: url('http://placekitten.com/340/180');
width: 340px;
height: 180px;
}

div p {
position: absolute;
top: 108px;
right: 6px;
color: rgb(255, 255, 255);
background-color: rgba(0, 0, 0, 0.4);
font-size: 24px;
line-height: 36px;
font-weight: bold;
padding: 4px 12px;
border-radius: 9px;
}

<div>
<p>I am a little kitten</p>
</div>


问:
Oracle: Need help on a parent-child scenario
Need help on the below scenario.

Table Structure:

ACCT_XREF

```<code>CREATE TABLE ACCT_XREF
(
 ACCT_NO VARCHAR2(10),
 PRNT_ACCT_NO VARCHAR2(10),
 PRTY_ROWID VARCHAR2(10),
 ACCT_ROWID VARCHAR2(10)
);
</code>```

INPUT_ACCTROWID

```<code>CREATE TABLE INPUT_ACCTROWID
(
 ACCT_ROWID VARCHAR2(10)
);
</code>```

Sample Data:

```<code>INSERT INTO ACCT_XREF VALUES('1000',NULL,'100','1');
INSERT INTO ACCT_XREF VALUES('1001','1003','NULL','2');
INSERT INTO ACCT_XREF VALUES('1003',NULL,'102','3');

INSERT INTO INPUT_ACCTROWID VALUES('1');
INSERT INTO INPUT_ACCTROWID VALUES('2');
</code>```

ACCT_XREF

i/p data:

```<code>ACCT_NO    PRNT_ACCT_NO    PRTY_ROWID      ACCT_ROWID
-----------------------------------------------------
1000       NULL            100             1
1001       1003            NULL            2
1003       NULL            102             3
</code>```

INPUT_ACCTROWID

```<code> ACCT_ROWID
 ----------
 1
 2
</code>```

EXPECTED OUTPUT

```<code>ACCT_NO   PRTY_ROWID
--------------------
1000      100
1001      102
</code>```

The issue here is:

ACCT_XREF is hierarchy based,

So, When PRNT_ACCT_NO is NOT NULL,PRTY_ROWID will be NULL,

In such cases, Pick the PRNT_ACCT_NO and    query the same table with
ACCT_NO as a match conditon and fetch the    Party linked to that
account i.e PRTY_ROWID

I have made an effort to achieve the same and below is my query:

```<code>SELECT ALL_INP.ACCT_NO,COALESCE(ALL_INP.PRTY_ROWID,C.PRTY_ROWID)
FROM
(
 SELECT A.*
 FROM
 ACCT_XREF A
 JOIN
 INPUT_ACCTROWID B
 ON A.ACCT_ROWID=B.ACCT_ROWID
)ALL_INP
LEFT OUTER JOIN
ACCT_XREF C
ON ALL_INP.PRNT_ACCT_NO=C.ACCT_NO;
</code>```

Not sure this is the best way, So wanted to know if there are better options.Thanks in Advance.

答:
To resolve this create a subquery in select, like the next query:</p>

```<code>    select AX.ACCT_NO, AX.PRNT_ACCT_NO, AX.ACCT_ROWID,
           COALESCE(AX.PRTY_ROWID, (SELECT AX2.PRTY_ROWID
                                    FROM ACCT_XREF AX2
                                    WHERE AX2.ACCT_NO=AX.PRNT_ACCT_NO)
                   ) PRTY_ROWID
    from ACCT_XREF AX INNER JOIN INPUT_ACCTROWID IA ON (IA.ACCT_ROWID=AX.ACCT_ROWID)
</code>```

Body:
Need help on the below scenario.

Table Structure:

ACCT_XREF

CREATE TABLE ACCT_XREF
(
 ACCT_NO VARCHAR2(10),
 PRNT_ACCT_NO VARCHAR2(10),
 PRTY_ROWID VARCHAR2(10),
 ACCT_ROWID VARCHAR2(10)
);

INPUT_ACCTROWID

CREATE TABLE INPUT_ACCTROWID
(
 ACCT_ROWID VARCHAR2(10)
);

Sample Data:

INSERT INTO ACCT_XREF VALUES('1000',NULL,'100','1');
INSERT INTO ACCT_XREF VALUES('1001','1003','NULL','2');
INSERT INTO ACCT_XREF VALUES('1003',NULL,'102','3');

INSERT INTO INPUT_ACCTROWID VALUES('1');
INSERT INTO INPUT_ACCTROWID VALUES('2');

ACCT_XREF

i/p data:

ACCT_NO    PRNT_ACCT_NO    PRTY_ROWID      ACCT_ROWID
-----------------------------------------------------
1000       NULL            100             1
1001       1003            NULL            2
1003       NULL            102             3

INPUT_ACCTROWID

 ACCT_ROWID
 ----------
 1
 2

EXPECTED OUTPUT

ACCT_NO   PRTY_ROWID
--------------------
1000      100
1001      102

The issue here is:

ACCT_XREF is hierarchy based,

So, When PRNT_ACCT_NO is NOT NULL,PRTY_ROWID will be NULL,

In such cases, Pick the PRNT_ACCT_NO and    query the same table with
ACCT_NO as a match conditon and fetch the    Party linked to that
account i.e PRTY_ROWID

I have made an effort to achieve the same and below is my query:

SELECT ALL_INP.ACCT_NO,COALESCE(ALL_INP.PRTY_ROWID,C.PRTY_ROWID)
FROM
(
 SELECT A.*
 FROM
 ACCT_XREF A
 JOIN
 INPUT_ACCTROWID B
 ON A.ACCT_ROWID=B.ACCT_ROWID
)ALL_INP
LEFT OUTER JOIN
ACCT_XREF C
ON ALL_INP.PRNT_ACCT_NO=C.ACCT_NO;

Not sure this is the best way, So wanted to know if there are better options.Thanks in Advance.

Body:
To resolve this create a subquery in select, like the next query:

    select AX.ACCT_NO, AX.PRNT_ACCT_NO, AX.ACCT_ROWID,
           COALESCE(AX.PRTY_ROWID, (SELECT AX2.PRTY_ROWID
                                    FROM ACCT_XREF AX2
                                    WHERE AX2.ACCT_NO=AX.PRNT_ACCT_NO)
                   ) PRTY_ROWID
    from ACCT_XREF AX INNER JOIN INPUT_ACCTROWID IA ON (IA.ACCT_ROWID=AX.ACCT_ROWID)


问:
What should my Objective-C singleton look like?
My singleton accessor method is usually some variant of:

```<code>static MyClass *gInstance = NULL;

+ (MyClass *)instance
{
    @synchronized(self)
    {
        if (gInstance == NULL)
            gInstance = [[self alloc] init];
    }

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

What could I be doing to improve this?

答:
I've rolled singleton into a class, so other classes can inherit singleton properties.

Singleton.h :

```<code>static id sharedInstance = nil;

#define DEFINE_SHARED_INSTANCE + (id) sharedInstance {  return [self sharedInstance:&sharedInstance]; } \
                               + (id) allocWithZone:(NSZone *)zone { return [self allocWithZone:zone forInstance:&sharedInstance]; }

@interface Singleton : NSObject {

}

+ (id) sharedInstance;
+ (id) sharedInstance:(id*)inst;

+ (id) allocWithZone:(NSZone *)zone forInstance:(id*)inst;

@end
</code>```

Singleton.m :

```<code>#import "Singleton.h"

@implementation Singleton

+ (id) sharedInstance {
    return [self sharedInstance:&sharedInstance];
}

+ (id) sharedInstance:(id*)inst {
    @synchronized(self)
    {
        if (*inst == nil)
            *inst = [[self alloc] init];
    }
    return *inst;
}

+ (id) allocWithZone:(NSZone *)zone forInstance:(id*)inst {
    @synchronized(self) {
        if (*inst == nil) {
            *inst = [super allocWithZone:zone];
            return *inst;  // assignment and return on first allocation
        }
    }
    return nil; // on subsequent allocation attempts return nil
}

- (id)copyWithZone:(NSZone *)zone {
    return self;
}

- (id)retain {
    return self;
}

- (unsigned)retainCount {
    return UINT_MAX;  // denotes an object that cannot be released
}

- (void)release {
    //do nothing
}

- (id)autorelease {
    return self;
}

@end
</code>```

And here is an example of some class, that you want to become singleton.

```<code>#import "Singleton.h"

@interface SomeClass : Singleton {

}

@end

@implementation SomeClass

DEFINE_SHARED_INSTANCE;

@end
</code>```

The only limitation about Singleton class, is that it is NSObject subclass. But most time I use singletons in my code they are in fact NSObject subclasses, so this class really ease my life and make code cleaner.

OwnerDisplayName: schwa

Body:
My singleton accessor method is usually some variant of:

static MyClass *gInstance = NULL;

+ (MyClass *)instance
{
    @synchronized(self)
    {
        if (gInstance == NULL)
            gInstance = [[self alloc] init];
    }

    return(gInstance);
}

What could I be doing to improve this?

LastEditorDisplayName: Ned Batchelder

Body:
I've rolled singleton into a class, so other classes can inherit singleton properties.

Singleton.h :

static id sharedInstance = nil;

#define DEFINE_SHARED_INSTANCE + (id) sharedInstance {  return [self sharedInstance:&sharedInstance]; } \
                               + (id) allocWithZone:(NSZone *)zone { return [self allocWithZone:zone forInstance:&sharedInstance]; }

@interface Singleton : NSObject {

}

+ (id) sharedInstance;
+ (id) sharedInstance:(id*)inst;

+ (id) allocWithZone:(NSZone *)zone forInstance:(id*)inst;

@end

Singleton.m :

#import "Singleton.h"

@implementation Singleton

+ (id) sharedInstance {
    return [self sharedInstance:&sharedInstance];
}

+ (id) sharedInstance:(id*)inst {
    @synchronized(self)
    {
        if (*inst == nil)
            *inst = [[self alloc] init];
    }
    return *inst;
}

+ (id) allocWithZone:(NSZone *)zone forInstance:(id*)inst {
    @synchronized(self) {
        if (*inst == nil) {
            *inst = [super allocWithZone:zone];
            return *inst;  // assignment and return on first allocation
        }
    }
    return nil; // on subsequent allocation attempts return nil
}

- (id)copyWithZone:(NSZone *)zone {
    return self;
}

- (id)retain {
    return self;
}

- (unsigned)retainCount {
    return UINT_MAX;  // denotes an object that cannot be released
}

- (void)release {
    //do nothing
}

- (id)autorelease {
    return self;
}

@end

And here is an example of some class, that you want to become singleton.

#import "Singleton.h"

@interface SomeClass : Singleton {

}

@end

@implementation SomeClass

DEFINE_SHARED_INSTANCE;

@end

The only limitation about Singleton class, is that it is NSObject subclass. But most time I use singletons in my code they are in fact NSObject subclasses, so this class really ease my life and make code cleaner.


问:
How to place transparent image over camera view in codename one
First of all, thanks to everything of codenameone.

I would like to customize camera view, simply overlaying PNG image on the full camera view screen.

Any way how to do it?

Here is code snippet.

```<code>Form mainForm = new Form();
ImageViewer iv = new ImageViewer();

mainForm.getToolbar().addMaterialCommandToRightBar("",
    FontImage.MATERIAL_CAMERA_ALT, 4, (ev) -> {
        filePath = Capture.capturePhoto();
        setImage(filePath, iv);
});
</code>```

I couldn't any view component of camera view, because Capture.capturePhoto() works automatically.

Or is there any way to build custom camera component in codename one?
I googled and got about PeerComponents, however don't know how to use it.
Just please provide some small sample code for me.
Best regards.

答:
Currently Capture.capturePhoto() opens its own "window" over the app so you can't customize it.  In the future we will likely add a more flexible API to embed the camera into your UI, especially now that we have Z-layering (we can draw over top of native widgets).

If you need this functionality right now, you would need to write a native interface and make your own capture component.

Body:
First of all, thanks to everything of codenameone.

I would like to customize camera view, simply overlaying PNG image on the full camera view screen.

Any way how to do it?

Here is code snippet.

Form mainForm = new Form();
ImageViewer iv = new ImageViewer();

mainForm.getToolbar().addMaterialCommandToRightBar("",
    FontImage.MATERIAL_CAMERA_ALT, 4, (ev) -> {
        filePath = Capture.capturePhoto();
        setImage(filePath, iv);
});

I couldn't any view component of camera view, because Capture.capturePhoto() works automatically.

Or is there any way to build custom camera component in codename one?
I googled and got about PeerComponents, however don't know how to use it.
Just please provide some small sample code for me.
Best regards.


问:
Class set to time out
I want a pop up to show onMouseOver which I can do below. But how can I then remove the class onMouseOut?</p>

```<code>// Get the snackbar DIV
var x = document.getElementById("snackbar2")

// Add the "show" class to DIV
x.className = "show";
</code>```

答:
To add a class:

```<code>x.classList.add('show');
</code>```

To remove a class:

```<code>x.classList.remove('show');
</code>```

To toggle a class on and off:

```<code>x.classList.toggle('show');
</code>```

To check if an element has a class or not:

```<code>if (x.classList.contains('show'))
</code>```

MDN Reference

Title: Class set to time out

Body:
I want a pop up to show onMouseOver which I can do below. But how can I then remove the class onMouseOut?

// Get the snackbar DIV
var x = document.getElementById("snackbar2")

// Add the "show" class to DIV
x.className = "show";

Body:
To add a class:

x.classList.add('show');

To remove a class:

x.classList.remove('show');

To toggle a class on and off:

x.classList.toggle('show');

To check if an element has a class or not:

if (x.classList.contains('show'))

MDN Reference


问:
sorting objects with multiple conditions
I'm currently trying to sort an array of objects that is being returned in my reducer. I want to sort the apps based off of their name that is being returned, and where there are still currently some names that are null I want to list the null names at the end. Currently when I try to add an additional condition I am getting an error Cannot read property 'toLowerCase' of null which i'm expecting null items just need to move them to the end.

```<code>// Actions
export const FETCH_MYAPPS_PENDING = 'widgets/apps/FETCH_PENDING';
export const FETCH_MYAPPS_FULFILLED = 'widgets/apps/FETCH_FULFILLED';

// Reducer
const appsSort = (a, b) => {
  if (a.name != null && b.name != null) {
   if (a.name.toLowerCase() > b.name.toLowerCase()) return 1;
   if (a.name.toLowerCase() < b.name.toLowerCase()) return -1;
  }
  return 0;
};

export default function reducer(state = { data: [], pending: false }, action) {
switch (action.type) {
case FETCH_MYAPPS_FULFILLED:
  return {
    data: action.apps.sort(appsSort),
    pending: false,
    retrievedAt: Date.now(),
  };
case FETCH_MYAPPS_PENDING:
  return {
    ...state,
    pending: true,
  };
default:
  return state;
 }
}
</code>```

答:
You could use the check for null as sort value and sort later with localeCompare with a chained approach with logical OR ||.

const appsSort = (a, b) =>
        (a.name === null) - (b.name === null) ||
        ('' + a.name).localeCompare(b.name);

var obj = [{ name: 'apples', id: 1 }, { name: null, id: 3 }, { name: 'Banana', id: 2 }, { name: null, id: 4 }];

obj.sort(appsSort);

console.log(obj)```

Body:
I'm currently trying to sort an array of objects that is being returned in my reducer. I want to sort the apps based off of their name that is being returned, and where there are still currently some names that are null I want to list the null names at the end. Currently when I try to add an additional condition I am getting an error Cannot read property 'toLowerCase' of null which i'm expecting null items just need to move them to the end.

// Actions
export const FETCH_MYAPPS_PENDING = 'widgets/apps/FETCH_PENDING';
export const FETCH_MYAPPS_FULFILLED = 'widgets/apps/FETCH_FULFILLED';

// Reducer
const appsSort = (a, b) => {
  if (a.name != null && b.name != null) {
   if (a.name.toLowerCase() > b.name.toLowerCase()) return 1;
   if (a.name.toLowerCase() < b.name.toLowerCase()) return -1;
  }
  return 0;
};

export default function reducer(state = { data: [], pending: false }, action) {
switch (action.type) {
case FETCH_MYAPPS_FULFILLED:
  return {
    data: action.apps.sort(appsSort),
    pending: false,
    retrievedAt: Date.now(),
  };
case FETCH_MYAPPS_PENDING:
  return {
    ...state,
    pending: true,
  };
default:
  return state;
 }
}


问:
Google Script Video Upload Fails
I am very new to Google Scripts - like I just started learning how to use it yesterday. I have put together a google drive dropzone based on code from this answer. I have my script working, and it uploads photos to the correct folder. The problem is, I am not able to upload files larger than 10mb, and I need to be able to upload video. I did a little research, and I found other questions addressing the same issue, but none of them had a solution to the problem.

Sorry for the messy code since this is another projet I modified.

Here is form.html:

  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootswatch/3.3.7/flatly/bootstrap.min.css">
  <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.3.0/min/dropzone.min.css">
  <link href="https://fonts.googleapis.com/css?family=Catamaran:900" rel="stylesheet">

Media Dropzone

          <form class="dropzone" id="myForm" action="#">

              <input name="file" type="file" multiple/>

          </form>

```
</div>
</div>
</p>

<p>And here is <code>server.gs</code>:</p>

```function doGet() {
  return HtmlService.createHtmlOutputFromFile('form')
    .setSandboxMode(HtmlService.SandboxMode.IFRAME);
}

function uploadFileToDrive(base64Data, fileName) {
  try{
    var splitBase = base64Data.split(','),
        type = splitBase[0].split(';')[0].replace('data:','');

    var byteCharacters = Utilities.base64Decode(splitBase[1]);
    var ss = Utilities.newBlob(byteCharacters, type);
    ss.setName(fileName);

    var folder;

    try{
      folder = DriveApp.getFolderById(""); //removed this for security
    } catch(e){
      folder = DriveApp.createFolder("social-media-dropzone");
    }

    var file = folder.createFile(ss);
    return file.getName();
  } catch(e){
    return 'Error: ' + e.toString();
  }
}
```

<p>Is there any way to increase the limit, or should I scrap this method and try something other than Google scripts?</p>

<p>And here is <code>server.gs</code> using the Advanced Drive API:</p>

```function doGet() {
  var output = HtmlService.createHtmlOutputFromFile('form').setSandboxMode(HtmlService.SandboxMode.IFRAME);
  output.addMetaTag('viewport', 'width=device-width, initial-scale=1');
  return output;
}

function uploadFileToDrive(base64Data, fileName) {
    var splitBase = base64Data.split(','),
        type = splitBase[0].split(';')[0].replace('data:','');

    var byteCharacters = Utilities.base64Decode(splitBase[1]);
    var ss = Utilities.newBlob(byteCharacters, type);
    ss.setName(fileName);

    //var file = folder.createFile(ss);
    var folderId = ""; //removed for security
    var file = {
      title: fileName,
      mimeType: ss.type,
      parents: [{id: folderId }]
    };
    Drive.Files.insert(file, ss);

    return null;
}
```

Even with the advanced API, uploads fail when they get too big. I tested it with an 8mb video and a 15mb video, and the latter failed.

答:
Apps Script wouldn't be my first choice. It depends a little on your use case, but I would probably go with a pure client-side JavaScript approach.

Whatever client you go with, you will need to use resumable upload. I believe this is available to Apps Script via the Advanced Drive Service. See https://developers.google.com/apps-script/advanced/drive and https://developers.google.com/drive/v2/reference/files/update

Title: Google Script Video Upload Fails

Body:
I am very new to Google Scripts - like I just started learning how to use it yesterday. I have put together a google drive dropzone based on code from this answer. I have my script working, and it uploads photos to the correct folder. The problem is, I am not able to upload files larger than 10mb, and I need to be able to upload video. I did a little research, and I found other questions addressing the same issue, but none of them had a solution to the problem.

Sorry for the messy code since this is another projet I modified.

Here is form.html:

  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootswatch/3.3.7/flatly/bootstrap.min.css">
  <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.3.0/min/dropzone.min.css">
  <link href="https://fonts.googleapis.com/css?family=Catamaran:900" rel="stylesheet">

Media Dropzone

          <form class="dropzone" id="myForm" action="#">

              <input name="file" type="file" multiple/>

          </form>

And here is server.gs:

function doGet() {
  return HtmlService.createHtmlOutputFromFile('form')
    .setSandboxMode(HtmlService.SandboxMode.IFRAME);
}

function uploadFileToDrive(base64Data, fileName) {
  try{
    var splitBase = base64Data.split(','),
        type = splitBase[0].split(';')[0].replace('data:','');

    var byteCharacters = Utilities.base64Decode(splitBase[1]);
    var ss = Utilities.newBlob(byteCharacters, type);
    ss.setName(fileName);

    var folder;

    try{
      folder = DriveApp.getFolderById(""); //removed this for security
    } catch(e){
      folder = DriveApp.createFolder("social-media-dropzone");
    }

    var file = folder.createFile(ss);
    return file.getName();
  } catch(e){
    return 'Error: ' + e.toString();
  }
}

Is there any way to increase the limit, or should I scrap this method and try something other than Google scripts?

And here is server.gs using the Advanced Drive API:

function doGet() {
  var output = HtmlService.createHtmlOutputFromFile('form').setSandboxMode(HtmlService.SandboxMode.IFRAME);
  output.addMetaTag('viewport', 'width=device-width, initial-scale=1');
  return output;
}

function uploadFileToDrive(base64Data, fileName) {
    var splitBase = base64Data.split(','),
        type = splitBase[0].split(';')[0].replace('data:','');

    var byteCharacters = Utilities.base64Decode(splitBase[1]);
    var ss = Utilities.newBlob(byteCharacters, type);
    ss.setName(fileName);

    //var file = folder.createFile(ss);
    var folderId = ""; //removed for security
    var file = {
      title: fileName,
      mimeType: ss.type,
      parents: [{id: folderId }]
    };
    Drive.Files.insert(file, ss);

    return null;
}

Even with the advanced API, uploads fail when they get too big. I tested it with an 8mb video and a 15mb video, and the latter failed.


问:
Sending data via sockets from c# to a node socket.io server
I am currently trying to feed my socket.io server with data from my C# client. But I am not sure how to receive the message on the server.

My server code:

```<code>const io = require('socket.io')(9000);

io.on('connection', (socket) => {
     console.log('Connected');
}
</code>```

First of all I don't know which event I have to listen to, but nevertheless I am unable to send data to my server using the following client (which uses Websocket-sharp) code:

```<code>private void init()
        {
            // start socket connection
            using (var ws = new WebSocket("ws://localhost:9000/socket.io/?EIO=2&transport=websocket"))
            {
                ws.OnMessage += (sender, e) =>
                    API.consoleOutput("Message: " + e.Data);

                ws.OnError += (sender, e) =>
                    API.consoleOutput("Error: " + e.Message);

                ws.Connect();
                ws.Send("server");
            }
        }
</code>```

The connection works, but how do I receive the message of the server? The sending does not fire an error, therefore I think it does work.

答:
I've gotten this working for a UWP app that connects to a node.js server. Basically what I do is connect to a URL that looks like ws://localhost:4200/socket.io/?EIO=3&transport=websocket

the port number being something we chose.

once that is set I connect to the node.js socket io library via the following lines of code.

```<code>private async Task ConnectWebsocket() {
        websocket = new MessageWebSocket();
        Uri server = new Uri(WebSocketURI); //like ws://localhost:4300/socket.io/?EIO=3&transport=websocket

        websocket.Control.MessageType = SocketMessageType.Utf8;
        websocket.MessageReceived += Websocket_MessageReceived;
        websocket.Closed += Websocket_Closed;
        try {
            await websocket.ConnectAsync(server);
            isConnected = true;
            writer = new DataWriter(websocket.OutputStream);
        }
        catch ( Exception ex ) // For debugging
        {
            // Error happened during connect operation.
            websocket.Dispose();
            websocket = null;
            Debug.Log("[SocketIOComponent] " + ex.Message);

            if ( ex is COMException ) {
                Debug.Log("Send Event to User To tell them we are unable to connect to Pi");
            }
            return;
        }
    }
</code>```

`

at this point your socket io on "connection" should fire on your server

then you can emit events to it like normal. except the C# socket code does not discriminate various channels so you must do so on your own. below is how we do it (aka SocketData and SocketIOEvent are classes we have defined)

```<code>private void Websocket_MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args) {
        try {
            using ( DataReader reader = args.GetDataReader() ) {
                reader.UnicodeEncoding = UnicodeEncoding.Utf8;

                try {
                    string read = reader.ReadString(reader.UnconsumedBufferLength);
                    //read = Regex.Unescape(read);
                    SocketData socc = SocketData.ParseFromString(read);
                    if (socc != null ) {
                        Debug.Log(socc.ToString());
                        SocketIOEvent e = new SocketIOEvent(socc.channel, new JSONObject( socc.jsonPayload));
                        lock ( eventQueueLock ) { eventQueue.Enqueue(e); }
                    }
                }
                catch ( Exception ex ) {
                    Debug.Log(ex.Message);
                }
            }
        } catch (Exception ex ) {
            Debug.Log(ex.Message);
        }

    }
</code>```

in our specific application we did not need to send messages to our server, so for that I do not have a good answer.

Body:
I am currently trying to feed my socket.io server with data from my C# client. But I am not sure how to receive the message on the server.

My server code:

const io = require('socket.io')(9000);

io.on('connection', (socket) => {
     console.log('Connected');
}

First of all I don't know which event I have to listen to, but nevertheless I am unable to send data to my server using the following client (which uses Websocket-sharp) code:

private void init()
        {
            // start socket connection
            using (var ws = new WebSocket("ws://localhost:9000/socket.io/?EIO=2&transport=websocket"))
            {
                ws.OnMessage += (sender, e) =>
                    API.consoleOutput("Message: " + e.Data);

                ws.OnError += (sender, e) =>
                    API.consoleOutput("Error: " + e.Message);

                ws.Connect();
                ws.Send("server");
            }
        }

The connection works, but how do I receive the message of the server? The sending does not fire an error, therefore I think it does work.

Body:
I've gotten this working for a UWP app that connects to a node.js server. Basically what I do is connect to a URL that looks like ws://localhost:4200/socket.io/?EIO=3&transport=websocket

the port number being something we chose.

once that is set I connect to the node.js socket io library via the following lines of code.

private async Task ConnectWebsocket() {
        websocket = new MessageWebSocket();
        Uri server = new Uri(WebSocketURI); //like ws://localhost:4300/socket.io/?EIO=3&transport=websocket

        websocket.Control.MessageType = SocketMessageType.Utf8;
        websocket.MessageReceived += Websocket_MessageReceived;
        websocket.Closed += Websocket_Closed;
        try {
            await websocket.ConnectAsync(server);
            isConnected = true;
            writer = new DataWriter(websocket.OutputStream);
        }
        catch ( Exception ex ) // For debugging
        {
            // Error happened during connect operation.
            websocket.Dispose();
            websocket = null;
            Debug.Log("[SocketIOComponent] " + ex.Message);

            if ( ex is COMException ) {
                Debug.Log("Send Event to User To tell them we are unable to connect to Pi");
            }
            return;
        }
    }

`

at this point your socket io on "connection" should fire on your server

then you can emit events to it like normal. except the C# socket code does not discriminate various channels so you must do so on your own. below is how we do it (aka SocketData and SocketIOEvent are classes we have defined)

private void Websocket_MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args) {
        try {
            using ( DataReader reader = args.GetDataReader() ) {
                reader.UnicodeEncoding = UnicodeEncoding.Utf8;

                try {
                    string read = reader.ReadString(reader.UnconsumedBufferLength);
                    //read = Regex.Unescape(read);
                    SocketData socc = SocketData.ParseFromString(read);
                    if (socc != null ) {
                        Debug.Log(socc.ToString());
                        SocketIOEvent e = new SocketIOEvent(socc.channel, new JSONObject( socc.jsonPayload));
                        lock ( eventQueueLock ) { eventQueue.Enqueue(e); }
                    }
                }
                catch ( Exception ex ) {
                    Debug.Log(ex.Message);
                }
            }
        } catch (Exception ex ) {
            Debug.Log(ex.Message);
        }

    }

in our specific application we did not need to send messages to our server, so for that I do not have a good answer.


问:
New data is not getting created if it is not present on the autocomplete dropdown on rails app
I am trying to implement jquery autocomplete on a field in rails app. I am following Railscasts video. I have successfully implemented the autocomplete feature. But I am also trying to add new data if it is not present on the autocomplete dropdown. I spent a lot of time on this but not able to overcome this issue. Following is my code:

equipment.rb

```<code>def manufacturer_name
    manufacturer.try(:name)
end

def manufacturer_name=(name)
    self.manufacturer = Manufacturer.find_or_create_by(:name => params[:other][:manufacturer_name], :status => 1)
end
</code>```

js

```<code>$('#equipment_manufacturer_name').autocomplete({
    source: function(req, res) {
    var arraySource = $('#equipment_manufacturer_name').data('autocomplete-source');
    var results = $.ui.autocomplete.filter(arraySource, req.term);
    res(results.slice(0, 10));
    }
});
</code>```

html.erb field

```<code><label for="select">Manufacturer * :</label>
<%= f.text_field :manufacturer_name, data: {autocomplete_source: Manufacturer.order(:name).map(&:name)} %>
</code>```

答:
If you wan to add data you can use source block with ajax request or if you want to use existing data you can select block.Like this:

```<code>$('#equipment_manufacturer_name').autocomplete({
    minLength: 1,
    source: function(req, res) {
      var arraySource = $('#equipment_manufacturer_name').data('autocomplete-source');
      var results = $.ui.autocomplete.filter(arraySource, req.term);
      res(results.slice(0, 10));
    },
    response: function(event, ui) {
      // ui.content is the array that's about to be sent to the response callback.
      if (ui.content.length == 0) {
        $.ajax({
          url : "/set_manufacturer",
          data: {name: $(this).val()},
          type: 'POST',
          dataType: 'json',
          success: function(response){

          }
        });
      }
    },

    select: function(event, ui){
      console.log(ui);
    }
  });
</code>```

Body:
I am trying to implement jquery autocomplete on a field in rails app. I am following Railscasts video. I have successfully implemented the autocomplete feature. But I am also trying to add new data if it is not present on the autocomplete dropdown. I spent a lot of time on this but not able to overcome this issue. Following is my code:

equipment.rb

def manufacturer_name
    manufacturer.try(:name)
end

def manufacturer_name=(name)
    self.manufacturer = Manufacturer.find_or_create_by(:name => params[:other][:manufacturer_name], :status => 1)
end

js

$('#equipment_manufacturer_name').autocomplete({
    source: function(req, res) {
    var arraySource = $('#equipment_manufacturer_name').data('autocomplete-source');
    var results = $.ui.autocomplete.filter(arraySource, req.term);
    res(results.slice(0, 10));
    }
});

html.erb field

Manufacturer * :
<%= f.text_field :manufacturer_name, data: {autocomplete_source: Manufacturer.order(:name).map(&:name)} %>

Body:
If you wan to add data you can use source block with ajax request or if you want to use existing data you can select block.Like this:

$('#equipment_manufacturer_name').autocomplete({
    minLength: 1,
    source: function(req, res) {
      var arraySource = $('#equipment_manufacturer_name').data('autocomplete-source');
      var results = $.ui.autocomplete.filter(arraySource, req.term);
      res(results.slice(0, 10));
    },
    response: function(event, ui) {
      // ui.content is the array that's about to be sent to the response callback.
      if (ui.content.length == 0) {
        $.ajax({
          url : "/set_manufacturer",
          data: {name: $(this).val()},
          type: 'POST',
          dataType: 'json',
          success: function(response){

          }
        });
      }
    },

    select: function(event, ui){
      console.log(ui);
    }
  });


问:
How can I add fastlane builds to Xcode's archive organizer?
After setting up fastlane with mostly default settings I got an automated build and upload to iTunes Connect using gym's export_method: "app-store". This uploads files to iTunes connect, and leaves in the current directory *.app.dSYM.zip and *.ipa files. However, when I open Xcode's organizer I don't see a build archive for the uploaded files.

Is it somehow possible to convert the files left by fastlane into an Xcode archive and have it appear in the organizer? Gym parameter documentation mentions alternatives for the export_method parameter: ad-hoc, package, enterprise, development, developer-id, but I have no idea what they mean or do.

EDIT: Since Fastlane is placing files in a hardcoded path I opened an issue about this.

答: If you don't pass a build_path or archive_path to gym it should default to placing your archive into ~/Library/Developer/Xcode/Archives/[date]. That is where Xcode looks for archives, so they should then be visible in the Organizer!


问:
Chat via WIFI platform independent
I'm thinking of creating a chat app which is similar like firechat. which needs no internet for communication and depends only on BT or WIFI to communicate and also have an advantage of platform independent.
      I've seen many sites referring some sites like open garden for firechat and alljoyn framework. I really don't understand what this things are for. Its really hard to find a solution for this.

I tried alljoyn initially, but the last update was about 3 years ago. the sample apps crashes in devices.
      So any one who worked in this kinda project or or sharing some knowledge will be more helpful!

Thanks in advance!

答: The official website is outdated, use git repo (git clone https://git.allseenalliance.org/gerrit/core/alljoyn.git), a chat is one of the samples. </p>

Title: Chat via WIFI platform independent


问:
GLIBCXX version error on AWS
This is an extension on a previous question asked here:  libstdc++ GLIBCXX version errors

I have a Node.js app which runs fine locally (Ubuntu 16.04), but when I upload the bundle to AWS Elastic Beanstalk, I get an error related to my DLLs. The app uses the ffi node-module to call C++ functions in the form of a DLL (.so). When the app is run on AWS, I get a GLIBCXX version error which results in failed dynamic linking calls.

While posts on previous questions have suggested to use static linking instead of dynamic linking, this is not an option for me since the C++ add-on must be a dll. It seems then that I need to compile my dll such that it uses an earlier version GLIBCXX.

My questions are then:

How do I know which version of GLIBCXX is running on my AWS instance?

How do I compile my dll to use an earlier version of GLIBCXX?

Is there anyway to solve these issues on the AWS instance itself (i.e. doesn't require recompiling the dll to an earlier version of GLIBCXX)

For reference, here is the exact error I am getting:

Error: Dynamic Linking Error: /usr/lib64/libstdc++.so.6: version
  `GLIBCXX_3.4.20' not found (required by
  Code/C++/mathreco/TRUNK/src/lib/libsmath.so)
      at new DynamicLibrary (/var/app/current/node_modules/ffi/lib/dynamic_library.js:74:11)

答:
Answer found here: How to fix: /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

Link statically to libstdc++ with -static-libstdc++ gcc option.

For some reason I didn't think I could statically link libstc++ since my library was dynamically linked. Happy it worked!

Title: GLIBCXX version error on AWS


问:
Can we customize the message back to gerrit in jenkins with variable?
In Jenkins gerrit-trigger plugin, we are able to customize the build message, I wonder whether we can use variable inside ?

Like below for ${PORT} ?

Update in 2017.03.31, it looks there is issue already JENKINS-37885

答:
I think you can use any job parameter in the format <PARAMETER> and any build environment variable in the format $VARIABLE.

In the Gerrit plugin help ("?") is written:

```<code>The following standard <PARAMETER> values are available:

GERRIT_NAME: The Gerrit project name.
CHANGE_ID: The Gerrit Change-Id (SHA-1).
BRANCH: The branch of the project.
CHANGE: The change number.
PATCHSET: The patchset number.
PATCHSET_REVISION: The patchset revision.
REFSPEC: The ref-spec. (refs/changes/xx/xxxx/z).
BUILDURL: The URL to the build.
VERIFIED: The verified vote.
CODE_REVIEW: The code review vote.
NOTIFICATION_LEVEL: The notification level. (always ALL)
The following special <PARAMETER> values are available:

STARTED_STATS: The number of builds started out of the total triggered like "(1/3)". If there is only one build triggered then the value is empty.

You can also use any environment variable from the build that was started with the $ENV_VAR syntax.
</code>```

Body:
I think you can use any job parameter in the format <PARAMETER> and any build environment variable in the format $VARIABLE.

In the Gerrit plugin help ("?") is written:

The following standard <PARAMETER> values are available:

GERRIT_NAME: The Gerrit project name.
CHANGE_ID: The Gerrit Change-Id (SHA-1).
BRANCH: The branch of the project.
CHANGE: The change number.
PATCHSET: The patchset number.
PATCHSET_REVISION: The patchset revision.
REFSPEC: The ref-spec. (refs/changes/xx/xxxx/z).
BUILDURL: The URL to the build.
VERIFIED: The verified vote.
CODE_REVIEW: The code review vote.
NOTIFICATION_LEVEL: The notification level. (always ALL)
The following special <PARAMETER> values are available:

STARTED_STATS: The number of builds started out of the total triggered like "(1/3)". If there is only one build triggered then the value is empty.

You can also use any environment variable from the build that was started with the $ENV_VAR syntax.


问:
Parse XML files in folder and rename them with values from three nodes
I'm new to winbatch scripting. I would like to pares XML files in folder and rename them with values from three nodes.
    Ex: in C drive I have three files:

```<code>1.xml
2.xml
3.xml
</code>```

Batch script should rename files as follows:

```<code>1.xml = AB_D_HR.xml
2.xml = ZZ_PK_IT.xml
3.xml = TS_MR_IT.xml
</code>```

I reached till the point where i can get the values of two nodes however not sure about further steps. please suggest:

XML1:
<company name="AAA">
    <department>
        <depname>HR</depname>
    </department>
    <Employee>
        <lastname>D</lastname>
        <firstname>AB</firstname>
    </Employee>
</company>

XML2:
<company name="AAA">
    <department>
        <depname>IT</depname>
    </department>
    <Employee>
        <lastname>PK</lastname>
        <firstname>ZZ</firstname>
    </Employee>
</company>

XML3:
<company name="AAA">
    <department>
        <depname>IT</depname>
    </department>
    <Employee>
        <lastname>MR</lastname>
        <firstname>TS</firstname>
    </Employee>
</company>
```

<pre class="lang-bat prettyprint-override"><code>@echo off

for /f "delims=" %%T in ('dir /b *.xml') do (
   for /f "tokens=3 delims=<>" %%A in (
     'find /i "<lastname>" ^< "%%T"'
    )do set K=%%A

for /f "tokens=3 delims=<>" %%B in (
     'find /i "<firstname>" ^< "%%T"'
    )do set L=%%B

)

echo %K%_%L%

pause
</code>```

答:
check xpath.bat:

```<code>@echo off

setlocal enableDelayedExpansion
for  %%T in (*.xml) do (
   for /f "tokens=* delims=" %%A in (
     'xpath.bat "%%T" "//lastname"'
    ) do set "K=%%A"

   for /f "tokens=* delims=" %%A in (
     'xpath.bat "%%T" "//firstname"'
    ) do set "L=%%B"

Echo !L! !K!

)
</code>```

Im not sure how direct renaming will work.May be you should first rename the files with different extension in order to avoid collisions.

Body:
I'm new to winbatch scripting. I would like to pares XML files in folder and rename them with values from three nodes.
    Ex: in C drive I have three files:

1.xml
2.xml
3.xml

Batch script should rename files as follows:

1.xml = AB_D_HR.xml
2.xml = ZZ_PK_IT.xml
3.xml = TS_MR_IT.xml

I reached till the point where i can get the values of two nodes however not sure about further steps. please suggest:

XML1:
<company name="AAA">
    <department>
        <depname>HR</depname>
    </department>
    <Employee>
        <lastname>D</lastname>
        <firstname>AB</firstname>
    </Employee>
</company>

XML2:
<company name="AAA">
    <department>
        <depname>IT</depname>
    </department>
    <Employee>
        <lastname>PK</lastname>
        <firstname>ZZ</firstname>
    </Employee>
</company>

XML3:
<company name="AAA">
    <department>
        <depname>IT</depname>
    </department>
    <Employee>
        <lastname>MR</lastname>
        <firstname>TS</firstname>
    </Employee>
</company>

@echo off

for /f "delims=" %%T in ('dir /b *.xml') do (
   for /f "tokens=3 delims=<>" %%A in (
     'find /i "<lastname>" ^< "%%T"'
    )do set K=%%A

for /f "tokens=3 delims=<>" %%B in (
     'find /i "<firstname>" ^< "%%T"'
    )do set L=%%B

)

echo %K%_%L%

pause

Body:
check xpath.bat:

@echo off

setlocal enableDelayedExpansion
for  %%T in (*.xml) do (
   for /f "tokens=* delims=" %%A in (
     'xpath.bat "%%T" "//lastname"'
    ) do set "K=%%A"

   for /f "tokens=* delims=" %%A in (
     'xpath.bat "%%T" "//firstname"'
    ) do set "L=%%B"

Echo !L! !K!

)

Im not sure how direct renaming will work.May be you should first rename the files with different extension in order to avoid collisions.


问:
Step Functions for tens or hundreds of executions per second?
I'm considering to use step functions for scenarios like retrieving data from a few sources, composing a mail with it and sending that mail - with appropriate retries.
The step function is triggered from API Gateway, so by calling "StartExecution".

It works great, but I notice that the soft limit for StartExecution is set to 2 executions/second, with a bucket size of 100.
I'm expecting tens or maybe hundreds of requests per second...

Am I right to understand that every call to the API counts towards that Start Execution soft limit?
Does this low default limit indicate that Step Functions may not be the right tool for the job?

答:
You are correct that each API call counts towards this limit. The fact that the bucket size is 100 leads me to believe that higher rates can be supported, but I do not work on the Step Function team.

It is a soft limit, so I would encourage you to request a limit increase. The Step Functions team will be able to tell you if they can support your use case.


问:
jquery select any dom element on page
Does anyone know how to select any element (possibly on click) on page like body is selected, div is selected, div#foo etc... so i can place it to some variable and edit it later on.

i've tried

```<code>$("*", document.body).click(function (e) {
 e.stopPropagation();
 var domEl = $(this).get(0);
 alert("Clicked on - " + domEl.tagName);
});
</code>```

but it's not working for all elements

答:
Try this.</p>

```<code>$(function(){
    $("*").click(function () {
         console.log($(this));
         return false;
        }
    );
});
</code>```

Title: jquery select any dom element on page

Body:
Does anyone know how to select any element (possibly on click) on page like body is selected, div is selected, div#foo etc... so i can place it to some variable and edit it later on.

i've tried

$("*", document.body).click(function (e) {
 e.stopPropagation();
 var domEl = $(this).get(0);
 alert("Clicked on - " + domEl.tagName);
});

but it's not working for all elements

Body:
Try this.

$(function(){
    $("*").click(function () {
         console.log($(this));
         return false;
        }
    );
});


问:
Using bean property parameter in bean validation message template
I'm trying to use a feature in bean-validation that I already used in the past, but I don't rembember how and i can't find any documentation.

```<code>import org.hibernate.validator.constraints.NotBlank;

public class User {

    protected String id;

    @NotBlank(message = "Name is mandatory for user {id}")
    protected String name;

    public String getId() {
        return id;
    }

}
</code>```

In this example, {id} is not remplaced by instance id.

Is there any way to use any current bean property in message template ?

Regards.

答:
You could use custom javax.validation.MessageInterpolator to achieve it.

Please see..
How do I dynamically resolve message parameters with Hibernate Validator?

Body:
I'm trying to use a feature in bean-validation that I already used in the past, but I don't rembember how and i can't find any documentation.

import org.hibernate.validator.constraints.NotBlank;

public class User {

    protected String id;

    @NotBlank(message = "Name is mandatory for user {id}")
    protected String name;

    public String getId() {
        return id;
    }

}

In this example, {id} is not remplaced by instance id.

Is there any way to use any current bean property in message template ?

Regards.


问:
manage drawing entities Inside Forge ambience
i am using VB6 using the autocad API.
is it possible to move insert rotate blocks with the autodesk-designautomation api?
Also extract block attributes and change them?
Create new drawings changing DWG block attributes and save them?

if yes. How?

Best Regards

Luis

答: No, sorry, VB6 is not supported in Forge Design Automation. You'll have to use VB.NET (define an autocad command).</p>


问:
Laravel 5.0 Undefined variable result
I have a form that a user enters and takes the entry and queries the database and returns to a view. I have managed to get one query working but when trying to work on another query it returns an undefined variable error in the view. See below:

Routes

```<code>Route::get('/shopsales', 'shopsalescontroller@index');
</code>```

Controller

```<code>class shopsalescontroller extends Controller
</code>```

{

```<code> public function index()
{
    $storeNum = request('storeNum');

   $result = shopsales::where('StoreNumber','=',$storeNum)
        ->get();

    return view('shopsales',compact('result'));

}
</code>```

}

shopsales view

```<code><section>
  <center><h1><STRONG>Query Data</STRONG></h1></center>
    <ul>
      @foreach ($result as $results)
        <li>Report Name = {{ $results->ReportName}} | Report ID = {{ $results->ReportID}} | Store Number = {{ $results->StoreNumber}} | Store Name = {{ $results->StoreName}} | Week Number = {{ $results->WeekNumber}} |
            Year = {{ $results->Year}} | PerfumeName = {{ $results->PerfumeName}} | Units Sold = {{ $results->UnitsSold}} | Sales = {{ $results->Sales}}
        </li>
        <br>
      @endforeach
    </ul>

</section>
</code>```

I have used the exact code for the query that is working, struggling to understand why this is not.

答:
Try something like this</p>

```<code>public function storeCheckout(Request $request) {
$storeNum=$request->get('storeNum');
$result = shopsales::where('StoreNumber','=',$storeNum)
        ->get();

    return view('shopsales',compact('result'));

}
</code>```

Title: Laravel 5.0 Undefined variable result

Body:
I have a form that a user enters and takes the entry and queries the database and returns to a view. I have managed to get one query working but when trying to work on another query it returns an undefined variable error in the view. See below:

Routes

Route::get('/shopsales', 'shopsalescontroller@index');

Controller

class shopsalescontroller extends Controller

{

 public function index()
{
    $storeNum = request('storeNum');

   $result = shopsales::where('StoreNumber','=',$storeNum)
        ->get();

    return view('shopsales',compact('result'));

}

}

shopsales view

Query Data

      @foreach ($result as $results)

Report Name = {{ $results->ReportName}} | Report ID = {{ $results->ReportID}} | Store Number = {{ $results->StoreNumber}} | Store Name = {{ $results->StoreName}} | Week Number = {{ $results->WeekNumber}} |
            Year = {{ $results->Year}} | PerfumeName = {{ $results->PerfumeName}} | Units Sold = {{ $results->UnitsSold}} | Sales = {{ $results->Sales}}

      @endforeach

I have used the exact code for the query that is working, struggling to understand why this is not.

Body:
Try something like this

public function storeCheckout(Request $request) {
$storeNum=$request->get('storeNum');
$result = shopsales::where('StoreNumber','=',$storeNum)
        ->get();

    return view('shopsales',compact('result'));

}


问:
OpenQA.Selenium.ElementNotVisibleException' in WebDriver.dll while trying to click on the link
I am trying to create a simple automation script in C# which will load google homepage then type something in the search box, list the results and then click on the "Images" link and show possible images of the searched item.

I was able to get to the point when Selenium Webdriver is able to locate the Images link by LinkText but when I want to perform a Click() operation I get error message Exception thrown: 'OpenQA.Selenium.ElementNotVisibleException' in WebDriver.dll and I am not able to move further.

I am placing my code below.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;

namespace WebDriverDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            IWebDriver driver = new FirefoxDriver();
            driver.Url = "http://www.google.com";

           var searchBox = driver.FindElement(By.Id("lst-ib"));
           searchBox.SendKeys("apple");
           searchBox.SendKeys(Keys.Enter);

           driver.Manage().Timeouts().ImplicitWait = (TimeSpan.FromSeconds(10));

            try
            {
                var imageLink = driver.FindElement(By.LinkText("Images"));
                Console.Write("Element found by a LinkText");
                imageLink.Click();
            }
            catch(Exception e)
            {
                Console.WriteLine(e);
            }
            Console.Read();

        }
    }
}
</code>```

I am looking forward to your feedback and possible solutions :)

Best regards and thank you,

答:
Sorry for a long delay, however I was able to solve the problem myself. Instead of driver.FindElement(By.LinkText("Images")) I used the Xpath, to show me the exact location of the image link :)

Thank you for the support!

Body:
I am trying to create a simple automation script in C# which will load google homepage then type something in the search box, list the results and then click on the "Images" link and show possible images of the searched item.

I was able to get to the point when Selenium Webdriver is able to locate the Images link by LinkText but when I want to perform a Click() operation I get error message Exception thrown: 'OpenQA.Selenium.ElementNotVisibleException' in WebDriver.dll and I am not able to move further.

I am placing my code below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;

namespace WebDriverDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            IWebDriver driver = new FirefoxDriver();
            driver.Url = "http://www.google.com";

           var searchBox = driver.FindElement(By.Id("lst-ib"));
           searchBox.SendKeys("apple");
           searchBox.SendKeys(Keys.Enter);

           driver.Manage().Timeouts().ImplicitWait = (TimeSpan.FromSeconds(10));

            try
            {
                var imageLink = driver.FindElement(By.LinkText("Images"));
                Console.Write("Element found by a LinkText");
                imageLink.Click();
            }
            catch(Exception e)
            {
                Console.WriteLine(e);
            }
            Console.Read();

        }
    }
}

I am looking forward to your feedback and possible solutions :)

Best regards and thank you,


问:
Espresso does not wait for animation to finish assertion faills
I am asserting some views which will be displayed after some animation or loads slowly

Ex:- Search button on the action bar is delayed to display on the action bar, before its displayed assertion fails, it should wait?

And in lollipop we have a ripple blow animation and after that some views are displayed but assertion fails before animation is finished, espresso should wait for all views and animation to become idle right?
When I used custom idling resource and waiting for 2 sec's that time it worked, but thats not the right way.

```<code>//Its my custom idling resource which wait for 2000 millisec
EspressoSolo.sleep(200);
    RecordingTest.getDefault().customTests(1, 1);
</code>```

答:
I'm copying in what the Google tutorial instructs us to do:

On your device, under Settings->Developer options disable the following 3 settings:

Window animation scale

Transition animation scale

Animator duration scale

This turns off the animations and allows your tests to run.

Body:
I am asserting some views which will be displayed after some animation or loads slowly

Ex:- Search button on the action bar is delayed to display on the action bar, before its displayed assertion fails, it should wait?

And in lollipop we have a ripple blow animation and after that some views are displayed but assertion fails before animation is finished, espresso should wait for all views and animation to become idle right?
When I used custom idling resource and waiting for 2 sec's that time it worked, but thats not the right way.

//Its my custom idling resource which wait for 2000 millisec
EspressoSolo.sleep(200);
    RecordingTest.getDefault().customTests(1, 1);


问:
Retrieve all inputs belonging to a certain array name into a jquery variable
Suppose I have this html:

```<code><td>
  <input type="hidden" name="params[test][index]" value="0">
  <input type="hidden" name="params[test][name]" value="2">
  <input type="hidden" name="params[other][]" value="0">
  <input type="hidden" name="params[test2]" value="0">
</td>
</code>```

And I want to grab all the inputs of the params array into my jquery as an array or as a json:

(not sure of the syntax but something like that)

```<code>var $params = { test => {index =>0, name=>2},other=>[0],test2=>0};
</code>```

What should I do?

答:
You can create a plain object, iterate input elements using $.each(), use .split() with RegExp

var params = {};

$.each($("td input"), function(_, el) {
  var param = el.name.split(/^\w+(?=\[)|\[|\]/).filter(Boolean).pop();
  params[param] = el.value;
});

console.log(params);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
  <input type="hidden" name="params[test][index]" value="0">
  <input type="hidden" name="params[test][name]" value="2">
  <input type="hidden" name="params[other][]" value="0">
  <input type="hidden" name="params[test2]" value="0">
</td>
</tr>
</table></code>```

Edit, Updated

You can use if, if..else conditions and statements, RegExp to parse .name attributes to get expected result described at OP

var params = {};
var re = /\[|\]/g;

$.each($("td input"), function(_, el) {
  var param = el.name.match(/\[\]|\[\w+\]/g);
  var prop = param.shift().replace(re, "");
  if (param.length) {
    if (!(prop in params) && param[0] !== "[]") {
      params[prop] = {};
    }
    if (prop in params) {
      params[prop][param.shift().replace(re, "")] = el.value;
    } else if (param[0] === "[]") {
      params[prop] = [el.value];
    }
  } else {
    params[prop] = el.value;
  }
});

console.log(params);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<table>
  <tr>
    <td>
      <input type="hidden" name="params[test][index]" value="0">
      <input type="hidden" name="params[test][name]" value="2">
      <input type="hidden" name="params[other][]" value="0">
      <input type="hidden" name="params[test2]" value="0">
    </td>
  </tr>
</table></code>```

Body:
Suppose I have this html:

  <input type="hidden" name="params[test][index]" value="0">
  <input type="hidden" name="params[test][name]" value="2">
  <input type="hidden" name="params[other][]" value="0">
  <input type="hidden" name="params[test2]" value="0">

And I want to grab all the inputs of the params array into my jquery as an array or as a json:

(not sure of the syntax but something like that)

var $params = { test => {index =>0, name=>2},other=>[0],test2=>0};

What should I do?

Body:
You can create a plain object, iterate input elements using $.each(), use .split() with RegExp

var params = {};

$.each($("td input"), function(_, el) {
  var param = el.name.split(/^\w+(?=\[)|\[|\]/).filter(Boolean).pop();
  params[param] = el.value;
});

console.log(params);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
  <input type="hidden" name="params[test][index]" value="0">
  <input type="hidden" name="params[test][name]" value="2">
  <input type="hidden" name="params[other][]" value="0">
  <input type="hidden" name="params[test2]" value="0">
</td>
</tr>
</table>

Edit, Updated

You can use if, if..else conditions and statements, RegExp to parse .name attributes to get expected result described at OP

var params = {};
var re = /\[|\]/g;

$.each($("td input"), function(_, el) {
  var param = el.name.match(/\[\]|\[\w+\]/g);
  var prop = param.shift().replace(re, "");
  if (param.length) {
    if (!(prop in params) && param[0] !== "[]") {
      params[prop] = {};
    }
    if (prop in params) {
      params[prop][param.shift().replace(re, "")] = el.value;
    } else if (param[0] === "[]") {
      params[prop] = [el.value];
    }
  } else {
    params[prop] = el.value;
  }
});

console.log(params);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<table>
  <tr>
    <td>
      <input type="hidden" name="params[test][index]" value="0">
      <input type="hidden" name="params[test][name]" value="2">
      <input type="hidden" name="params[other][]" value="0">
      <input type="hidden" name="params[test2]" value="0">
    </td>
  </tr>
</table>


问:
SwiftySKScrollView working perfectly until I try to change its size or move it
First - apologies for starting a new question but I don't yet have the required reputation to comment on the original.

I have implemented the scroll view from here https://github.com/crashoverride777/SwiftySKScrollView and this question ScrollView in SpriteKit. Everything works great, until I try to resize it or move it. I'm hoping to have two separate scroll views next to each other (which doesn't seem like it should be too difficult) but i cannot move the first SwiftySKScrollView to one side.

I've worked out that the issue happens as soon as I change any of the frame parameters in

scrollView = SwiftySKScrollView(frame: CGRect(x: 0, y: 0, width: CGFloat(frame.width), height: frame.height), moveableNode: moveableNode, direction: .vertical)

After I change the parameters (and that's all I'm doing - even just dividing the height parameter by two alone causes the problem), the scroll view shows up exactly how I want it but the children no longer respond to touch.

Thanks for any help, I really appreciate it.

答:
Thanks for using my helper. Here are my thoughts

1) This helper is actually quite old and I personally no longer use it for my own projects. I still maintain the GitHub repository but its not the most elegant solution or something I would recommend unless its for the simplest of menus. I did mention this in the instructions.

2) It is not designed to have 2 smaller scroll views next to each other. So I would not even bother trying to continue. Your end result would also be clunky and involve a lot of error prone code.

3) In general you would want to avoid using UIKit in SpriteKit.

4) UICollectionViews are now pretty much the only UIKit stuff I might use in my SpriteKit projects (e.g large level select menus) because they offer certain conveniences (scrolling, cell reuse etc) that would be very hard to recreate in SpriteKit.

5) First try doing it all with SpriteKit APIs (SKLabelNodes, SKSpriteNodes, SKNodes etc).

Have a look at this for an example

https://codedump.io/share/etvt4SwQI6iR/1/how-to-create-a-vertical-scrolling-menu-in-spritekit

6) If point 5 is not an option you will probably have to implement 2 UICollectionViews. The problem here is that

a) you will have to learn about UICollectionViews if you haven't used them before

b) You have to either create them via Storyboards which can be tricky if you haven't used Storyboards before. It is also than quite difficulty to implement them in your SpriteKit scene.

c) Create them in code like SwiftySKScrollView which can also be quite tricky if you haven't used them before.

Hope this helps


问:
Delete from multiple tables in sql
Hello can someone help me here.

I would like to delete from multiple tables.

I want to delete id_grupo = 6 from grupos.
But when I delete it I would like to delete from gerir_posts where id_grupo = 6. But from posts, id_post = 4, that's the same id from gerir_posts id_post; I want delete it too.

So what i realy want is when i remove a grup , the posts that are in that grup most be deleted too.

This is a example of my db.

```<code>   CREATE TABLE Utilizadores
(
    id_utilizador int auto_increment not null primary key,
    Nome varchar(50)
);

INSERT INTO utilizadores VALUES (1,'Admin');

CREATE TABLE Grupos
(
    id_grupo int auto_increment not null primary key,
    Nome_grupo varchar(50)
);
INSERT INTO grupos VALUES (1,'Grupo');

CREATE TABLE Gerir_grupos
(
    id_gerir_grupo int auto_increment not null primary key,
    id_grupo int,
    id_utilizador int,
    FOREIGN KEY (id_utilizador) references Utilizadores(id_utilizador),
    FOREIGN KEY (id_grupo) references Grupos(id_grupo) on delete cascade
);

INSERT INTO gerir_grupos VALUES (1,1,1);

CREATE TABLE Posts
(
    id_post int auto_increment not null primary key,
    id_utilizador int,
    Titulo_do_post varchar(50),
    Corpo_do_post varchar(500),
    FOREIGN KEY (id_utilizador) references Utilizadores (id_utilizador)

);
INSERT INTO posts VALUES (1,1,"teste","grupo teste");

CREATE TABLE Gerir_posts
(
    id_gerir_post int auto_increment not null primary key,
    id_post int,
    id_grupo int,
    FOREIGN KEY (id_post) references Posts (id_post) on delete cascade,
    FOREIGN KEY (id_grupo) references Grupos (id_grupo)on delete cascade
);

INSERT INTO gerir_posts VALUES (1,1,1);
</code>```

If this can help

答:
You cannot specify many tables in a single delete statement.

Use a transaction

```<code>begin;
delete posts where post_id in (select post_id from gerir_posts where ...);
delete gerir_posts where ... ;
delete grupos where ... ;
commit;
</code>```

This way, everything is either deleted together, or stays intact.

Use ON DELETE CASCADE in your constraints

```<code>create table posts (
  post_id integer primary key,
  ...
);

create table gerir_posts (
  ...
  post_id integer;
  constraint gerir_posts_fk
    foreign key(post_id) references(posts.post_id)
    on delete cascade,
);
</code>```

Now if you delete a record from posts, all records in gerir_posts that refer to the same post_id are also deleted.

You can use alter table to add / modify constraints of the existing tables.

Title: Delete from multiple tables in sql

Body:
Hello can someone help me here.

I would like to delete from multiple tables.

I want to delete id_grupo = 6 from grupos.
But when I delete it I would like to delete from gerir_posts where id_grupo = 6. But from posts, id_post = 4, that's the same id from gerir_posts id_post; I want delete it too.

So what i realy want is when i remove a grup , the posts that are in that grup most be deleted too.

This is a example of my db.

   CREATE TABLE Utilizadores
(
    id_utilizador int auto_increment not null primary key,
    Nome varchar(50)
);

INSERT INTO utilizadores VALUES (1,'Admin');

CREATE TABLE Grupos
(
    id_grupo int auto_increment not null primary key,
    Nome_grupo varchar(50)
);
INSERT INTO grupos VALUES (1,'Grupo');

CREATE TABLE Gerir_grupos
(
    id_gerir_grupo int auto_increment not null primary key,
    id_grupo int,
    id_utilizador int,
    FOREIGN KEY (id_utilizador) references Utilizadores(id_utilizador),
    FOREIGN KEY (id_grupo) references Grupos(id_grupo) on delete cascade
);

INSERT INTO gerir_grupos VALUES (1,1,1);

CREATE TABLE Posts
(
    id_post int auto_increment not null primary key,
    id_utilizador int,
    Titulo_do_post varchar(50),
    Corpo_do_post varchar(500),
    FOREIGN KEY (id_utilizador) references Utilizadores (id_utilizador)

);
INSERT INTO posts VALUES (1,1,"teste","grupo teste");

CREATE TABLE Gerir_posts
(
    id_gerir_post int auto_increment not null primary key,
    id_post int,
    id_grupo int,
    FOREIGN KEY (id_post) references Posts (id_post) on delete cascade,
    FOREIGN KEY (id_grupo) references Grupos (id_grupo)on delete cascade
);

INSERT INTO gerir_posts VALUES (1,1,1);

If this can help

Body:
You cannot specify many tables in a single delete statement.

Use a transaction

begin;
delete posts where post_id in (select post_id from gerir_posts where ...);
delete gerir_posts where ... ;
delete grupos where ... ;
commit;

This way, everything is either deleted together, or stays intact.

Use ON DELETE CASCADE in your constraints

create table posts (
  post_id integer primary key,
  ...
);

create table gerir_posts (
  ...
  post_id integer;
  constraint gerir_posts_fk
    foreign key(post_id) references(posts.post_id)
    on delete cascade,
);

Now if you delete a record from posts, all records in gerir_posts that refer to the same post_id are also deleted.

You can use alter table to add / modify constraints of the existing tables.